How are the bits arranged in int8_t

Question: The signed int8_t type is less intuitive than uint8_t.
For example: -36 decimal is coded 11011100 binary (220 decimal if read unsigned)
In other words how to manually convert from int8_t to its absolute value?

Sometimes the easy things are not so easy found

EDIT
How are the bits arranged in int8_t?
I want to understand the int8_t and the steps to get its absolute value
Comment: @Sean: Why not? [This is encouraged.](https://stackoverflow.com/help/self-answer) In fact it's _so_ encouraged that there's literally a feature to do that on the Ask Question page... Did you perhaps forget that Stack Overflow is a Q&A repository for general use, not a personal helpdesk?
Comment: @Sean Because it took me some time to find the answer. It may be useful for others
Comment: That being said, I don't really understand the question/problem. Is this asking how to comprehend two's complement representation? Or how to cast a `int8_t` to some other type? Or what? Reading the OP's answer leaves me none the wiser.
Comment: Why are you posting a question and then immediately answering it yourself?
Comment: @Sean [Can I answer my own question?](https://stackoverflow.com/help/self-answer)
Comment: @Sean What difference does it make if OP answers it or someone else?
Comment: What do you mean by "manually"?
Comment: What do you mean by _"the steps to get its absolute value"_? You already have its "absolute value", right there. Unless you mean mathematically, i.e. 36? So just `* -1`? You do not need to know anything about the representation or the bits... that's exactly why we have a nice high level language to do it for you.
Comment: @AsteroidsWithWings, if you apply `* -1` to `std::uint8_t`, you'll get a value of another type.
Comment: The best way to get the absolute value is something like this: `int8_t x = -3; uint8_t y = abs(x);`
Comment: @AsteroidsWithWings Thanks for helping me getting better in writing questions. I mean that I want to understand *two's complement representation* but without knowing its name.
Comment: @klutt Yes, that's a good way :) but I wanted to understand how it works
Comment: @Evg Just as you will with any of the bitwise operations.
Comment: @Guglie, you might want to take a look at the generated [assembly code](https://godbolt.org/z/AUaoer).
Comment: @Evg Thanks! Surely that's useful even if I was searching for something more like the int8_t spec
Answer: From the C99 draft used as reference from C+11:

18.104.22.168 Exact-width integer types
  The typedef name intN_t designates a signed integer type with width N, no padding bits, and a
  two's complement representation. Thus, int8_t denotes a signed integer
  type with a width of exactly 8 bits.

From Wikipedia Two's complement:

The two's complement of an N-bit number is defined as its complement
  with respect to 2N. For instance, for the three-bit number 010, the
  two's complement is 110, because 010 + 110 = 1000. The two's
  complement is calculated by inverting the digits and adding one.

So from the above example (signed to absolute)
(-36 decimal) = 11011100

(inverting)  -> 00100011

(+1)         -> 00100100

              = (36 decimal)

-36 decimal to int8_t
(36 decimal) = 00100100

(-1)        -> 00100011

(invert)    -> 11011100

            = (-36 decimal)

Comment: Note that for signed integer types other than the fixed width `intN_t` types, in C as well as C++ (until C++20), the sign representation depends on implementation, and could in theory be other than 2's complement. That said, non 2's complement hardware is becoming quite rare these days.
Comment: I'm curious why this answer has so many downvotes. What's wrong with it?
Comment: @AsteroidsWithWings Thanks, I didn't mean to reinvent the wheel. Surely there are a lot of wonderful tools that do the job for us, but **sometimes it's enlightening to understand how they work**. Sometimes not knowing what's under the hood leads even to problems like *Leaky Abstraction*
Comment: @eerorika Does that mean that on a platform with 32 bit `int` that isn't two's complement, the type `int` and `int32_t` are different types?
Comment: @FrançoisAndrieux Such platform probably wouldn't define any of `intN_t`. The fixed width type aliases are optional. If it did define it, then it would have to be different from a type that isn't 2's complement.
Comment: @eerorika thanks for the clarification! By the way I was searching only for fixed width integer types :)
Comment: This is a very roundabout way of multiplying by -1 or using `std::abs`. Just get the language & compiler to do it for you; that's literally why we have them. You do not need to know anything about the representation or the bits.
Comment: @Guglie Absolutely - and if you'd phrased your question like that, it would have been understood that way ;)
Comment: @FrançoisAndrieux Some people have problems with people self answering their questions.

How are the bits arranged in int8_t


Debug C++ code (add two very big numbers)

Question: This code is supposed to get two very big numbers and add them together. Just iostream and string library allowed.
Example input:
132163162986831298132869132968213689316298613298681329689312682136312621382931628613286831286921968312698312698132682136893162986832168312698132
8312961362983126893162986312986832196893126813268932169831268912869621386893126893126891326831268361298621398631286831269813268312698132689312683612986892136813268312698312698321686312986312986893216831268921368321698132689312698132689321683126893216986893216893126813268931286931629886312

Example output:
8312961362983126893162986312986832196893126813268932169831268912869621386893126893126891326831268361298621398631286831269813268312698132689312683745150055123644566445567445666535375629284926285574546520581603504634319515620941311419520608605095205915299591349575263706431918119099942584444

#include <iostream>
#include <string>

using namespace std;

int main (){
    string num1 , num2 ,sum;
    getline(cin,num1);
    getline(cin,num2);
    if (num2.length() > num1.length())
    {
        num2.swap(num1);
    }
    std::reverse(num1.begin(), num1.end());
    std::reverse(num2.begin(), num2.end());
    while(num2.length() < num1.length())
        num2.push_back('0');
    size_t lnth = num1.length();
    unsigned tmp , holder=0;
    for (size_t i = 0;i < lnth ; i++){
        tmp = (num1[i] - '0') + (num2[i] - '0') + holder;
        sum.push_back(tmp % 10 + '0');
        holder = tmp / 10;
    }
    if(holder > 0){
        sum.push_back('0' + holder);
    }
    while(!sum.empty()){
        if (sum[sum.length() - 1] == '0'){
            sum.pop_back();
        }
        else{
            break;
        }
    }
    std::reverse(sum.begin(), sum.end());
    cout << sum;
}

I' getting some correct and some wrong answers;
Comment: what error do you get?
Answer: To begin with, given size_t i, the condition i >= 0 is always true by definition.
This is because size_t yields a 2s-complement unsigned representation.
Therefore, the loop for (size_t i = whatever; i >= 0; i--) will just run forever, or until "something bad happens".
Answer: Did you know std::string has a wonderful feature called "reverse iterators"?
It makes your life a whole lot easier:
auto it1 = str1.crbegin(), it2 = str2.crbegin();
int carry = 0;
std::string result;
while (it1 != str1.crend() && it2 != str2.crend()) {
  int sum = (*it1 - '0') + (*it2 - '0') + carry;
  result.push_back('0' + (sum % 10));
  carry = sum / 10;
  it1++; it2++;
}

// We assume str1 is the longest, so copy digits from str1
while (it1 != str1.crend()) {
  int sum = (*it1 - '0') + carry;
  result.push_back('0' + (sum % 10));
  carry = sum / 10;
  it1++;
}

// This is an edge case: if str1.length == str2.length, carry might be 1
if (carry) {
  result.push_back('1');
}

// Reverse result
result = std::string(result.crbegin(), result.crend());

Comment: i used your idea (not copying), but getting some wrong answers. could you have a look?
Comment: I don't see anything obviously wrong. Edit your question with some inputs and wrong outputs


How should I handle secret values in a project in source control?

Question: My question is essentially the same as this one but for a Windows Store App, c# and Visual Studio. I want to have an easy way to keep secret values in the project, in a file that can be ignored in (not checked in to) source control. How should I structure my project to store the app secret in a way that makes building/source control easy?
My first idea was to store it in an XML file (not checked in), and load it at runtime, but this leaves it available to the user who installs it, so it should be done at build time. How can I store a couple secret values and have visual studio replace them in my code when my project is built?
Comment: I would never put secrets in source control -- manually add them when a new user comes on to the project.
Comment: It's not clear to me why the user who "installs it" has access to the XML file that is not in source control. Is it bundled in your installer? If so, take it out and make it a run-time dependency.
Comment: @PeterRitchie That's exactly what I'm saying. My question means how can I make project build process easy *without* having that value in source control. I.e, "check out the project, then do x with your app secret". I edited for clarity.
Comment: @Kohanz if the value is stored in an xml file, for example, and it's copied as a content file, and read at run-time, then a user who installs the app would have access to that file/value, just like any image assets included in the package.
Comment: @roiuser Right, so I'm suggesting that you don't include that XML file as content and just read it from a pre-determined location. You should probably refactor it such that the XML file excluded from the build contains ONLY the secret fields that you do not want to share (e.g. passwords)
Comment: @Kohanz yes, and my question is where/when is that xml file read? pre-build event? Environment variable? Do I need a batch file? If so, how do I replace text in a source file from XML in the batch file?
Comment: How about build a one-time crypto dll? save encrypted values in xml files and obtain them back using decrypt method of that crypto dll. Every developer will have the DLL and the encrypted data.
Comment: @roviuser: we used to run a NAnt job to do stuff like this. You'd put the NAnt job into a script which gets called in the post-build event. NAnt is good not just for building, but also for pulling from source control & updating files.
Answer: In my company we decide to you following solution. In config file we link sections with "secret" values in external configs.
External configs are on source control. First it wasn't but after a problem when our build server lost a disk we decide it it safer to store it on a place which has backup. The folder in source control (can be also on file server) is really restricted to read and write to only people who needs this. Build process checkouts "project" folder plus "configuration" folder and do build. After build "configuration" folder is deleted. Access to build server is also restricted.
Comment: I'm really looking for more of a technical solution within visual studio of how to store/replace these values. I'm not worried about backing up or checking in the app secret anywhere.
Comment: So store copy config file somewhere where almost nobody has access and on build server checkout project and this config file. You can also use a tool like SnowCheetach and keep only transfarmations in "safe" place. More about tool here:  http://www.hanselman.com/blog/SlowCheetahWebconfigTransformationSyntaxNowGeneralizedForAnyXMLConfigurationFile.aspx
Comment: This isn't helpful. I never mentioned a build server, and that still doesn't tell me anything about how or when to read that file. My question is *technical* about reading and using the values, not *semantic* about securing it.
Answer: One option is to store the secrets in source control, but store them in an encrypted form. In your development or build environments, use a environment variable to store the key, and decrypt on the fly. That way you get the benefits of source control while keeping your info safe.
It is possible to do this even if you are using app.config or web.config, you just need to modify the configuration from code at startup.
Erick
Answer: Updated
If you put a secret in an untrusted area (e.g. public source control), it is vulnerable. Even if it's encrypted, with enough diligence it can be retrieved.
The only way to really keep it out of reach is to have an external service that interacts with the 3rd party API. That has its own trade-offs (e.g. user authentication as you mentioned in comments). Especially if your developers need to utilize the 3rd party API when testing, I see no other alternative that will limit the secret's exposure.
Comment: This has nothing to do with the app itself. It's a secret for authenticating against a third party API. I never said it was for the app's configuration.
Comment: The Live Connect integration is 3rd party integration, but it is setup at the Windows Store level instead of the app level. The sub-optimal work-around is to have an intermediate service that answers requests from your app and forwards them to the 3rd party API with the secret. Depending on who controls server security, the server-side secret could be in a config file on the server, and nowhere else.
Comment: What you're suggesting is adding an extra server to prevent an API secret? I would still have to authenticate the user somehow, but now I've got an extra hop. That seems superfluous and doesn't provide anything better than having the value encrypted. This is besides the fact that this is related to protecting the key from the end user, instead of my question, which relates to protecting the key from source control/other developers.
Comment: External service protects against discovery from both user and developer. If you put it out there in source, encrypted or not, it is vulnerable. Are you just trying to prevent public source control surfers from getting it?
Comment: Also note if you store it encrypted in source, I assume you still have to decrypt it before sending it to the 3rd party API. So now the problem has shifted to securing the decryption key instead of the secret.
Answer: Create a new class file in your project that has slots for all of your secret values, and holds dummy/test values for all of them. Check that into source control with the rest of your project, so that anybody building it without access to the secrets will get some sort of test version.
Then, create a copy of that class file with the real secret values, and put it somewhere outside of source control. Write a batch script in the pre-build event that looks for this class file, and if found, replaces the dummy file that is included in the project with it.
This way, your project can still be in source control and anybody can check it out, build it, and run it in the test mode. Your secret file/values are stored on your build server only, so only when you build the project there will it have the real values.
Do remember to back up your secrets file somewhere. And also remember that .NET code can be decompiled easily, so your secrets may not be as secret as you hope them to be - any user with a .NET reflector can see all of the code in your release assembly, including your secret class.


Front page as link in Views

Question: This is pretty straight forward. How do I print a link to the homepage as field in Views?
I have added a global text field with html code Home but this is just the path to the root & my website is installed in a subdomain.
Using D7 and latest Views module.
Comment: @NishantP I'm sure he meant `print l('front','',array('absolute'=>true));` - but I don't remember how to do it in views field easily.
Comment: @Mołot I think OP not being able to clear that how to explain there issue. First we need surety from OP.
Comment: Did you read the edited question?
Comment: Try to check the [LINK](https://www.drupal.org/node/1234862). I hope you are talking about this & you will get help from this url.
Comment: Thanks for your effort. Unfortunately, that is not what I'm looking for. I'm looking for a way to display a field as a link to frontpage in views (as mentioned in the question above, the "/" href does not take me to the frontpage, it is taking me to root domain).
Comment: @designarti if you installed Drupal into your sub-domain(something.maindomain.com), then the sub-domain root is your home page. You need the absolute url for any outside the sub-domain, something like `Home`
Comment: I had installed Drupal in a subdomain and the / href would've taken me to root domain. Maybe because I'm working on Xampp, localhost. The answer was given down the page. Thank you though.
Answer: it should work this way:

create the global text field, with the text as the link text -

then rewrite the results, and output as a link using <front> as the path -
Comment: Thank you so much! Didn't know it is that simple. And a very important asset - now I know  could be used as a token in Views.

Front page as link in Views


Converting this MySQL query to SQL Server

Question: This is the query that i would like to be converted into MSSQL. I really tried so hard on searching online to convert everything line by line. I really do hope someone can help me :(
CREATE DEFINER=`root`@`localhost` PROCEDURE `EmployeesLOG`(IN `vIDNumber` varchar(20), IN `vMonth` varchar(20), IN `EmployeesGroup` varchar(50))
BEGIN
SELECT logtime.IDNumber, concat(Last_Name,', ' ,First_Name,' ',left(Middle_Name,1),'.') AS Employee, profile.Employees_Group,
IFNULL( group_concat( case when logtime.InOutMode In ('IN-AM') then STR_TO_DATE(EmployeesLog.LogTime,'%T') end Order By case when EmployeesLog.InOutMode In ('IN-AM') then STR_TO_DATE(EmployeesLog.LogTime,'%T') end ASC SEPARATOR ',  ' ),'') AS IN_AM,
IFNULL( group_concat( case when EmployeesLog.InOutMode In ('OUT-AM') then STR_TO_DATE(EmployeesLog.LogTime,'%T') end Order By case when EmployeesLog.InOutMode In ('OUT-AM') then STR_TO_DATE(EmployeesLog.LogTime,'%T') end DESC SEPARATOR ',  ' ),'') AS OUT_AM,
STR_TO_DATE(EmployeesLog.LogDate,'%m/%d/%Y') AS iDate FROM EmployeesLog Inner Join profile ON EmployeesLog.IDNumber = profile.IDNumber where   DATE_FORMAT(STR_TO_DATE(EmployeesLog.LogDate,'%m/%d/%Y'),'%M%Y')=vMonth and EmployeesLog.IDNumber like vIDNumber
and TRIM( Profile.Employees_Group) like (CONCAT('%', TRIM(EmployeesGroup))) GROUP BY IDNumber, iDate Order by  Employee ASC, iDate ASC;
END

Thank you in advance
EmployeeID  Employee             Employees_Group  IN_AM      OUT_AM     iDate
1001        Agustin, Mirasol D.  COA OFFICE       04:46:47,  11:02:01,        10/01/2020
                                                  04:46:54,  11:02:43
                                                  04:47:05
1001        Agustin, Mirasol D.  COA OFFICE       05:01:04   12:11:01, 10/02/2020
                                                             12:11:41
1001        Agustin, Mirasol D.  COA OFFICE       04:58:12   12:03:23  10/03/2020
                                                  04:58:44

Comment: Please have a go, making use of the official docs, and google, and only post a question when stuck on a specific problem.
Comment: I really did sir @DaleK but i am currently low on experience since i am currently a 3rd year college student :( i'm just hoping someone could help me and make it my experience for constructing a MSSQL query
Comment: There are loads and loads of resources out there to assist with this. These days the main skill of a developer is googling resources on how to do stuff. You'll learn it much better than if someone just does it for you.
Comment: Thanks for the motivation @DaleK. I'm just having a hard time learning MSSQL stored procedure.
Answer: Conversion
If you decide to go for the most literal conversion, then you will find some pointers below:

Create stored procedure syntax
concat => concat
group_concat => string_agg
ifnull => isnull, nullif, coalesce
trim => trim
date_format, str_to_date => convert

Rebuild
An alternative would be to build a new solution from the ground up. That is what I have done below.
Sample data
create table EmployeeProfile
(
    IDNumber int,
    FirstName nvarchar(20),
    MiddleName nvarchar(20),
    LastName nvarchar(20),
    EmplGroup nvarchar(10)
);
insert into EmployeeProfile (IDNumber, FirstName, MiddleName, LastName, EmplGroup) values
(1001, 'Mirasol', 'Dirk', 'Agustin', 'COA OFFICE');

create table EmployeeLog
(
    IDNumber int,
    InOutMode nvarchar(6),
    LogDate date,
    LogTime time
);
insert into EmployeeLog (IDNumber, InOutMode, LogDate, LogTime) values
(1001, 'IN-AM',  '2020-10-01', '04:46:47'),
(1001, 'OUT-AM', '2020-10-01', '11:02:01'),
(1001, 'IN-AM',  '2020-10-01', '04:46:54'),
(1001, 'OUT-AM', '2020-10-01', '11:02:43'),
(1001, 'IN-AM',  '2020-10-01', '04:47:05'),
(1001, 'IN-AM',  '2020-10-02', '05:01:04'),
(1001, 'OUT-AM', '2020-10-02', '12:11:01'),
(1001, 'OUT-AM', '2020-10-02', '12:11:41'),
(1001, 'IN-AM',  '2020-10-03', '04:58:12'),
(1001, 'OUT-AM', '2020-10-03', '12:03:23'),
(1001, 'IN-AM',  '2020-10-03', '04:58:44');

Selection
You can spot some elements from my pointers above making an appearance. Additionally the solution contains case, common table expression and pivot.
with cte as
(
    select  el.IDNumber as 'EmployeeID',
            ep.LastName + ', ' + ep.FirstName + ' ' + left(ep.MiddleName, 1) + '.' as 'Employee',
            ep.EmplGroup,
            el.InOutMode,
            el.LogDate,
            el.LogTime,
            row_number() over(partition by el.LogDate, el.InOutMode order by el.LogTime) as 'RowNum'
    from EmployeeLog el
    join EmployeeProfile ep
        on ep.IDNumber = el.IDNumber
)
select  case when p.RowNum = 1 then convert(nvarchar, p.EmployeeID) else '' end as 'EmployeeID',
        case when p.RowNum = 1 then p.Employee else '' end as 'Employee',
        case when p.RowNum = 1 then p.EmplGroup else '' end as 'Employees_Group',
        isnull(convert(nvarchar, p.[IN-AM], 108), '') as 'IN_AM',
        isnull(convert(nvarchar, p.[OUT-AM], 108), '') as 'OUT_AM',
        case when p.RowNum = 1 then convert(nvarchar, p.LogDate, 101) else '' end as 'iDate'
from cte c
pivot (max(c.LogTime) for c.InOutMode in ([IN-AM], [OUT-AM])) p;

Result
EmployeeID Employee            Employees_Group IN_AM    OUT_AM   iDate
---------- ------------------- --------------- -------- -------- ----------
1001       Agustin, Mirasol D. COA OFFICE      04:46:47 11:02:01 10/01/2020
                                               04:46:54 11:02:43
                                               04:47:05
1001       Agustin, Mirasol D. COA OFFICE      05:01:04 12:11:01 10/02/2020
                                                        12:11:41
1001       Agustin, Mirasol D. COA OFFICE      04:58:12 12:03:23 10/03/2020
                                               04:58:44

Stored procedure
Some notes:

The date parameters (year and month) are passed as separate integers to avoid string conversions and matching a string pattern.
The trim() from around the field EmplGroup was removed, clean up the data in the database or add the trim() back.

Create procedure:
create procedure proc_EmployeeReport
    @vIDNumber int,
    @vMonth int,
    @vYear int,
    @EmployeesGroup nvarchar(50)
as
with cte as
(
    select  el.IDNumber as 'EmployeeID',
            ep.LastName + ', ' + ep.FirstName + ' ' + left(ep.MiddleName, 1) + '.' as 'Employee',
            ep.EmplGroup,
            el.InOutMode,
            el.LogDate,
            el.LogTime,
            row_number() over(partition by el.LogDate, el.InOutMode order by el.LogTime) as 'RowNum'
    from EmployeeLog el
    join EmployeeProfile ep
        on ep.IDNumber = el.IDNumber
    where el.IDNumber = @vIDNumber
      and month(el.LogDate) = @vMonth
      and year(el.LogDate) = @vYear
      and ep.EmplGroup like concat('%',trim(@EmployeesGroup),'%')
)
select  case when p.RowNum = 1 then convert(nvarchar, p.EmployeeID) else '' end as 'EmployeeID',
        case when p.RowNum = 1 then p.Employee else '' end as 'Employee',
        case when p.RowNum = 1 then p.EmplGroup else '' end as 'Employees_Group',
        isnull(convert(nvarchar, p.[IN-AM], 108), '') as 'IN_AM',
        isnull(convert(nvarchar, p.[OUT-AM], 108), '') as 'OUT_AM',
        case when p.RowNum = 1 then convert(nvarchar, p.LogDate, 101) else '' end as 'iDate'
from cte c
pivot (max(c.LogTime) for c.InOutMode in ([IN-AM], [OUT-AM])) p;

Call procedure (results are the same as from selection):
exec proc_EmployeeReport @vIDNumber=1001, @vMonth=10, @vYear=2020, @EmployeesGroup='COA';

Comment: Thank you so much sir!!! You are a savior. This will make my stepping stone on learning MSSQL. I really do appreciate it sir. Thank you again sir and more power!! ^^


Uppercase and Lowercase in MySQL query condition

Question: I am writing a SQL query which uses WHERE statement to find the record. The problem is MySQL seems not care about uppercase and lowercase string in the condition. My both bellow queries have same result.
SELECT * FROM mytable WHERE url = 'http://domain.com/aaa'
=> http://domain.com/aaa record (CORRECT)
SELECT * FROM mytable WHERE url = 'http://domain.com/AAA'
=> http://domain.com/aaa record (INCORRECT)
I searched on the Internet and tried to use BINARY and COLLATE utf8_bin but it didn't help. How can I make it work? Thank you in advance.
Comment: This http://alvinalexander.com/sql/sql-select-case-insensitive-query-queries-upper-lower may help shed some light on the subject. Also `Select Title from FooName where binary Title like '%foo%'` from http://technikhil.wordpress.com/2007/09/17/case-sensitive-matches-in-mysql/
Comment: What is the collate of that table?
Comment: Hi @frlan, it is `utf8_general_ci`
Comment: or `WHERE BINARY url = '....'` if you can't/won't change the collation.
Comment: utf8_general_ci...the ci means case insensitive...so change the collation to one that is case sensitive.
Comment: you tried `SELECT * FROM mytable WHERE url = 'http://domain.com/AAA' COLLATE utf8_bin` correct?
Comment: Check this answer http://stackoverflow.com/questions/153944/is-sql-syntax-case-sensitive
Comment: @Rudolfwm I tried both `BINARY` and `COLLATE utf8_bin` but it does not work when I use the phpmyadmin querybox. Then I used the mysql command-line, and it work correctly. It is quite strange and I don't know why.
Comment: @Ngo Duy Khanh : from what I remember, phpmyadmin adds collation automatically so that may override your query. Not sure.
Answer: ok, you wants to have case sensitive comparison than you BINARY is the only best choice
SELECT * FROM mytable WHERE BINARY url = 'http://domain.com/aaa'
Answer: You can use the MySQL's built-in string functions
SELECT * FROM mytable WHERE url = LOWER('http://domain.com/AAA')

REF: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html
Answer: Mysql query is not case sensitive by default but you can try binary operator to make it case sensitive. Here is the code which should work for you
For URL http://domain.com/aaa
SELECT * FROM table WHERE BINARY url = http://domain.com/aaa

For URL http://domain.com/AAA
SELECT * FROM table WHERE BINARY url = http://domain.com/AAA

I hope this helps you


Android : Content Provider : Uri Type Wrong on Jellybean 4.2.2

Question: I am having problems with acquiring proper uriType on Jellybean 4.2.2.
The code given below works fine on other versions.
package com.karacraft.security;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.karacraft.data.ItemsContract;
import com.karacraft.data.MasterSahabDatabaseHelper;
import com.karacraft.data.MerchandisesContract;
import com.karacraft.data.OrdersContract;
import com.karacraft.data.StaffContract;
import com.karacraft.data.StatsContract;
import com.karacraft.data.SuitsContract;
import com.karacraft.data.TailorsContract;
import com.karacraft.utils.Constants;

public class MasterSahabProvider extends ContentProvider
{
public static final String AUTHORITY ="com.karacraft.security.mastersahab";
public static final String KEY_URI = "/#";

//database
private MasterSahabDatabaseHelper database;

//Table Names
private static final String ITEMS_TABLE         = "/" + ItemsContract.TABLE_ITEMS;
private static final String MERCHANDISES_TABLE  = "/" + MerchandisesContract.TABLE_MERCHANDISES;
private static final String ORDERS_TABLE        = "/" + OrdersContract.TABLE_ORDERS;
private static final String SUITS_TABLE         = "/" + SuitsContract.TABLE_SUITS;
private static final String TAILORS_TABLE       = "/" + TailorsContract.TABLE_TAILORS;
private static final String STAFF_TABLE         = "/" + StaffContract.TABLE_STAFF;
private static final String STATS_TABLE         = "/" + StatsContract.TABLE_STATS;

//Uri for Multiple Tables
public static final Uri CONTENT_URI_ITEMS           = Uri.parse("content://" + AUTHORITY + ITEMS_TABLE);
public static final Uri CONTENT_URI_MERCHANDISES    = Uri.parse("content://" + AUTHORITY + MERCHANDISES_TABLE);
public static final Uri CONTENT_URI_ORDERS          = Uri.parse("content://" + AUTHORITY + ORDERS_TABLE);
public static final Uri CONTENT_URI_SUITS           = Uri.parse("content://" + AUTHORITY + SUITS_TABLE);
public static final Uri CONTENT_URI_TAILORS         = Uri.parse("content://" + AUTHORITY + TAILORS_TABLE);
public static final Uri CONTENT_URI_STAFF           = Uri.parse("content://" + AUTHORITY + STAFF_TABLE);
public static final Uri CONTENT_URI_STATS           = Uri.parse("content://" + AUTHORITY + STATS_TABLE);

public static final Uri CONTENT_URI_ORDERS_BY_MERC  = Uri.parse("content://" + AUTHORITY + ORDERS_TABLE);

//Return value setup for Uri Matchers
private static final int ITEMS          = 10;
private static final int ITEM_ID        = 20;
private static final int MERCHANDISES   = 30;
private static final int MERCHANDISE_ID = 40;
private static final int ORDERS         = 50;
private static final int ORDERS_ID      = 60;
private static final int SUITS          = 70;
private static final int SUITS_ID       = 80;
private static final int TAILORS        = 90;
private static final int TAILORS_ID     = 100;
private static final int STAFF          = 110;
private static final int STAFF_ID       = 120;
private static final int STATS          = 130;
private static final int STATS_ID       = 140;

private static final int ORDERS_BY_MERC = 200;

//Custom Method
private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
    uriMatcher.addURI(AUTHORITY, ITEMS_TABLE,ITEMS);
    uriMatcher.addURI(AUTHORITY, ITEMS_TABLE + KEY_URI,ITEM_ID);
    uriMatcher.addURI(AUTHORITY, MERCHANDISES_TABLE,MERCHANDISES);
    uriMatcher.addURI(AUTHORITY, MERCHANDISES_TABLE + KEY_URI,MERCHANDISE_ID);
    uriMatcher.addURI(AUTHORITY, ORDERS_TABLE,ORDERS);
    uriMatcher.addURI(AUTHORITY, ORDERS_TABLE + KEY_URI,ORDERS_ID);
    uriMatcher.addURI(AUTHORITY, SUITS_TABLE,SUITS);
    uriMatcher.addURI(AUTHORITY, SUITS_TABLE + KEY_URI,SUITS_ID);
    uriMatcher.addURI(AUTHORITY, TAILORS_TABLE,TAILORS);
    uriMatcher.addURI(AUTHORITY, TAILORS_TABLE + KEY_URI,TAILORS_ID);
    uriMatcher.addURI(AUTHORITY, STAFF_TABLE , STAFF);
    uriMatcher.addURI(AUTHORITY, STAFF_TABLE + KEY_URI, STAFF_ID);
    uriMatcher.addURI(AUTHORITY, STATS_TABLE , STATS);
    uriMatcher.addURI(AUTHORITY, STATS_TABLE + KEY_URI, STATS_ID);

    uriMatcher.addURI(AUTHORITY,ORDERS_TABLE ,ORDERS);
}

public boolean onCreate()
{
    //Create Database
    database = new MasterSahabDatabaseHelper(getContext());
    return false;
}

/**
URI         uri         The URI of the object(s) to access. This is the only argument that must not be null
String[]    projection  This String array indicates which columns/attributes of the objects you want to access
String      selection   With this argument you can determine which records to return
String[]    selectionArgs   The binding parameters to the previous selection argument
String      sortOrder   If the result should be ordered you must use this argument to determine the sort order
*/
@Nullable
@Override
public Cursor query(Uri uri
        , String[] projection
        , String selection
        , String[] selectionArgs
        , String sortOrder)
{
    //Using SQLiteQueryBuilder instead of query() method
    SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
    SQLiteDatabase db = database.getWritableDatabase();
    Cursor cursor=null;

    int uriType = uriMatcher.match(uri);
    Log.d(Constants.APP_TAG,"URIType is : " + uriType);
    Log.d(Constants.APP_TAG,"URI is : " + uri.toString());

    switch (uriType){
        case ITEMS:
            //Set the table
            builder.setTables(ItemsContract.TABLE_ITEMS);
            //adding the ID to original Query
            cursor = builder.query(db,projection,selection,selectionArgs,null,null,sortOrder);
            // make sure that potential listeners are getting notified
            cursor.setNotificationUri(getContext().getContentResolver(),uri);
            break;
        case ITEM_ID:
            //Set the table
            builder.setTables(ItemsContract.TABLE_ITEMS);
            //adding the ID to original Query
            builder.appendWhere(ItemsContract.ITEM_ID + "=" + uri.getLastPathSegment());
            cursor = builder.query(db,projection,selection,selectionArgs,null,null,sortOrder);
            // make sure that potential listeners are getting notified
            cursor.setNotificationUri(getContext().getContentResolver(), uri);
            break;
        case MERCHANDISES:
            //Set the table
            builder.setTables(MerchandisesContract.TABLE_MERCHANDISES);
            //adding the ID to original Query
            cursor = builder.query(db,projection,selection,selectionArgs,null,null,sortOrder);
            // make sure that potential listeners are getting notified
            cursor.setNotificationUri(getContext().getContentResolver(),uri);
            break;
        case MERCHANDISE_ID:
            //Set the table
            builder.setTables(MerchandisesContract.TABLE_MERCHANDISES);
            //adding the ID to original Query
            builder.appendWhere(MerchandisesContract.MERCHANDISE_ID + "=" + uri.getLastPathSegment());
            cursor = builder.query(db,projection,selection,selectionArgs,null,null,sortOrder);
            // make sure that potential listeners are getting notified
            cursor.setNotificationUri(getContext().getContentResolver(),uri);
            break;
        case ORDERS:
            //Set the table
            builder.setTables(OrdersContract.TABLE_ORDERS);
            //adding the ID to original Query
            cursor = builder.query(db,projection,selection,selectionArgs,null,null,sortOrder);
            // make sure that potential listeners are getting notified
            cursor.setNotificationUri(getContext().getContentResolver(),uri);
            break;
        case ORDERS_ID:
            //Set the table
            builder.setTables(OrdersContract.TABLE_ORDERS);
            //adding the ID to original Query
            builder.appendWhere(OrdersContract.ORDER_ID + "=" + uri.getLastPathSegment());
            cursor = builder.query(db,projection,selection,selectionArgs,null,null,sortOrder);
            // make sure that potential listeners are getting notified
            cursor.setNotificationUri(getContext().getContentResolver(),uri);
            break;
        case TAILORS:
            //Set the table
            builder.setTables(TailorsContract.TABLE_TAILORS);
            //adding the ID to original Query
            cursor = builder.query(db,projection,selection,selectionArgs,null,null,sortOrder);
            // make sure that potential listeners are getting notified
            cursor.setNotificationUri(getContext().getContentResolver(),uri);
            break;
        case TAILORS_ID:
            //Set the table
            builder.setTables(TailorsContract.TABLE_TAILORS);
            //adding the ID to original Query
            builder.appendWhere(TailorsContract.TAILOR_ID + "=" + uri.getLastPathSegment());
            cursor = builder.query(db,projection,selection,selectionArgs,null,null,sortOrder);
            // make sure that potential listeners are getting notified
            cursor.setNotificationUri(getContext().getContentResolver(),uri);
            break;
        case SUITS:
            //Set the table
            builder.setTables(SuitsContract.TABLE_SUITS);
            //adding the ID to original Query
            cursor = builder.query(db,projection,selection,selectionArgs,null,null,sortOrder);
            // make sure that potential listeners are getting notified
            cursor.setNotificationUri(getContext().getContentResolver(),uri);
            break;
        case SUITS_ID:
            //Set the table
            builder.setTables(SuitsContract.TABLE_SUITS);
            //adding the ID to original Query
            builder.appendWhere(SuitsContract.SUITS_ID + "=" + uri.getLastPathSegment());
            cursor = builder.query(db,projection,selection,selectionArgs,null,null,sortOrder);
            // make sure that potential listeners are getting notified
            cursor.setNotificationUri(getContext().getContentResolver(),uri);
            break;
        case STAFF:
            //Set the table
            builder.setTables(StaffContract.TABLE_STAFF);
            //adding the ID to original Query
            cursor = builder.query(db,projection,selection,selectionArgs,null,null,sortOrder);
            // make sure that potential listeners are getting notified
            cursor.setNotificationUri(getContext().getContentResolver(),uri);
            break;
        case STAFF_ID:
            //Set the table
            builder.setTables(StaffContract.TABLE_STAFF);
            //adding the ID to original Query
            builder.appendWhere(StaffContract.STAFF_ID + "=" + uri.getLastPathSegment());
            cursor = builder.query(db,projection,selection,selectionArgs,null,null,sortOrder);
            // make sure that potential listeners are getting notified
            cursor.setNotificationUri(getContext().getContentResolver(),uri);
            break;
        case STATS:
            //Set the table
            builder.setTables(StatsContract.TABLE_STATS);
            //adding the ID to original Query
            cursor = builder.query(db,projection,selection,selectionArgs,null,null,sortOrder);
            // make sure that potential listeners are getting notified
            cursor.setNotificationUri(getContext().getContentResolver(),uri);
            break;
        case STATS_ID:
            //Set the table
            builder.setTables(StatsContract.TABLE_STATS);
            //adding the ID to original Query
            builder.appendWhere(StatsContract.STATS_ID + "=" + uri.getLastPathSegment());
            cursor = builder.query(db,projection,selection,selectionArgs,null,null,sortOrder);
            // make sure that potential listeners are getting notified
            cursor.setNotificationUri(getContext().getContentResolver(),uri);
            break;
        case ORDERS_BY_MERC:
            //Set the table
            //builder.setTables("orders LEFT OUTER JOIN staff ON (orders.staff_id = staff._id)");
            builder.setTables("orders LEFT OUTER JOIN staff ON orders.staff_id = staff._id");
            //builder.setTables("orders,staff");
            //adding the ID to original Query
            cursor = builder.query(db,projection,selection,selectionArgs,null,null,sortOrder);
            // make sure that potential listeners are getting notified
            cursor.setNotificationUri(getContext().getContentResolver(),uri);
        default:
            throw new IllegalArgumentException("Unknown URI: " + uri);
    }
    return cursor;
}

@Nullable
@Override
public String getType(Uri uri)
{
    return null;
}

@Nullable
@Override
public Uri insert(Uri uri
        , ContentValues values)
{
    int uriType = uriMatcher.match(uri);
    SQLiteDatabase db = database.getWritableDatabase();
    Log.d(Constants.APP_TAG,"URIType is : " + uriType);
    Log.d(Constants.APP_TAG,"URI is : " + uri.toString());

    long id = 0;
    switch (uriType){
        case ITEMS:
            id = db.insert(ItemsContract.TABLE_ITEMS, null, values);
            getContext().getContentResolver().notifyChange(uri,null);
            return Uri.parse(ITEMS_TABLE + "/" + id);

        case MERCHANDISES:
            id = db.insert(MerchandisesContract.TABLE_MERCHANDISES,null,values);
            getContext().getContentResolver().notifyChange(uri,null);
            return Uri.parse(MERCHANDISES_TABLE + "/" + id);

        case ORDERS:
            id = db.insert(OrdersContract.TABLE_ORDERS,null,values);
            getContext().getContentResolver().notifyChange(uri,null);
            return Uri.parse(ORDERS_TABLE + "/" + id);

        case SUITS:
            id = db.insert(SuitsContract.TABLE_SUITS,null,values);
            getContext().getContentResolver().notifyChange(uri,null);
            return Uri.parse(SUITS_TABLE + "/" + id);

        case STAFF:
            id = db.insert(StaffContract.TABLE_STAFF,null, values);
            getContext().getContentResolver().notifyChange(uri,null);
            return Uri.parse(STAFF_TABLE + "/" + id);

        case TAILORS:
            id = db.insert(TailorsContract.TABLE_TAILORS,null,values);
            getContext().getContentResolver().notifyChange(uri,null);
            return Uri.parse(TAILORS_TABLE + "/" + id);

        case STATS:
            id = db.insert(StatsContract.TABLE_STATS,null,values);
            getContext().getContentResolver().notifyChange(uri,null);
            return Uri.parse(STATS_TABLE + "/" + id);
        default:
            throw new IllegalArgumentException("Unknown URI: " + uri);
    }
}

@Override
public int delete(Uri uri
        , String selection
        , String[] selectionArgs)
{
    int uriType = uriMatcher.match(uri);
    SQLiteDatabase sqlDB = database.getWritableDatabase();
    int rowsDeleted = 0;
    String id ="";

    Log.d(Constants.APP_TAG,"URIType is : " + uriType);
    Log.d(Constants.APP_TAG,"URI is : " + uri.toString());

    switch (uriType) {
        case ITEMS:
            rowsDeleted = sqlDB.delete(ItemsContract.TABLE_ITEMS, selection, selectionArgs);
            break;
        case ITEM_ID:
            id = uri.getLastPathSegment();
            if (TextUtils.isEmpty(selection)) {
                rowsDeleted = sqlDB.delete(ItemsContract.TABLE_ITEMS, ItemsContract.ITEM_ID + "=" + id, null);
            } else {
                rowsDeleted = sqlDB.delete(ItemsContract.TABLE_ITEMS, ItemsContract.ITEM_ID + "=" + id + " AND " + selection, selectionArgs);
            }
            break;
        case MERCHANDISES:
            rowsDeleted = sqlDB.delete(MerchandisesContract.TABLE_MERCHANDISES, selection, selectionArgs);
            break;
        case MERCHANDISE_ID:
            id = uri.getLastPathSegment();
            if (TextUtils.isEmpty(selection)) {
                rowsDeleted = sqlDB.delete(MerchandisesContract.TABLE_MERCHANDISES, MerchandisesContract.MERCHANDISE_ID+ "=" + id, null);
            } else {
                rowsDeleted = sqlDB.delete(MerchandisesContract.TABLE_MERCHANDISES, MerchandisesContract.MERCHANDISE_ID + "=" + id + " AND " + selection, selectionArgs);
            }
            break;
        case TAILORS:
            rowsDeleted = sqlDB.delete(TailorsContract.TABLE_TAILORS, selection, selectionArgs);
            break;
        case TAILORS_ID:
            id = uri.getLastPathSegment();
            if (TextUtils.isEmpty(selection)) {
                rowsDeleted = sqlDB.delete(TailorsContract.TABLE_TAILORS, TailorsContract.TAILOR_ID + "=" + id, null);
            } else {
                rowsDeleted = sqlDB.delete(TailorsContract.TABLE_TAILORS, TailorsContract.TAILOR_ID + "=" + id + " AND " + selection, selectionArgs);
            }
            break;
        case STAFF:
            rowsDeleted = sqlDB.delete(StaffContract.TABLE_STAFF, selection, selectionArgs);
            break;
        case STAFF_ID:
            id = uri.getLastPathSegment();
            if (TextUtils.isEmpty(selection)) {
                rowsDeleted = sqlDB.delete(StaffContract.TABLE_STAFF, StaffContract.STAFF_ID + "=" + id, null);
            } else {
                rowsDeleted = sqlDB.delete(StaffContract.TABLE_STAFF, StaffContract.STAFF_ID + "=" + id + " AND " + selection, selectionArgs);
            }
            break;
        case SUITS:
            rowsDeleted = sqlDB.delete(SuitsContract.TABLE_SUITS, selection, selectionArgs);
            break;
        case SUITS_ID:
            id = uri.getLastPathSegment();
            if (TextUtils.isEmpty(selection)) {
                rowsDeleted = sqlDB.delete(SuitsContract.TABLE_SUITS, SuitsContract.SUITS_ID + "=" + id, null);
            } else {
                rowsDeleted = sqlDB.delete(SuitsContract.TABLE_SUITS, SuitsContract.SUITS_ID + "=" + id + " AND " + selection, selectionArgs);
            }
            break;
        case ORDERS:
            rowsDeleted = sqlDB.delete(OrdersContract.TABLE_ORDERS, selection, selectionArgs);
            break;
        case ORDERS_ID:
            id = uri.getLastPathSegment();
            if (TextUtils.isEmpty(selection)) {
                rowsDeleted = sqlDB.delete(OrdersContract.TABLE_ORDERS, OrdersContract.ORDER_ID + "=" + id, null);
            } else {
                rowsDeleted = sqlDB.delete(OrdersContract.TABLE_ORDERS, OrdersContract.ORDER_ID + "=" + id + " AND " + selection, selectionArgs);
            }
            break;
        case STATS:
            rowsDeleted = sqlDB.delete(StatsContract.TABLE_STATS, selection, selectionArgs);
            break;
        case STATS_ID:
            id = uri.getLastPathSegment();
            if (TextUtils.isEmpty(selection)) {
                rowsDeleted = sqlDB.delete(StatsContract.TABLE_STATS, StatsContract.STATS_ID + "=" + id, null);
            } else {
                rowsDeleted = sqlDB.delete(StatsContract.TABLE_STATS, StatsContract.STATS_ID + "=" + id + " AND " + selection, selectionArgs);
            }
            break;
        default:
            throw new IllegalArgumentException("Unknown URI: " + uri);
    }
    getContext().getContentResolver().notifyChange(uri, null);
    return rowsDeleted;
}

@Override
public int update(Uri uri
        , ContentValues values
        , String selection
        , String[] selectionArgs)
{
    int uriType = uriMatcher.match(uri);
    SQLiteDatabase db = database.getWritableDatabase();
    int rowsUpdated=0;
    Log.d(Constants.APP_TAG,"URIType is : " + uriType);
    Log.d(Constants.APP_TAG,"URI is : " + uri.toString());

    switch (uriType){
        case ITEMS:
            rowsUpdated = db.update(ItemsContract.TABLE_ITEMS,values,selection,selectionArgs);
            break;
        case ITEM_ID:
            String id = uri.getLastPathSegment();
            if(TextUtils.isEmpty(selection)){
                rowsUpdated = db.update(ItemsContract.TABLE_ITEMS,values, ItemsContract.ITEM_ID + "=" + id,null);
            }else{
                rowsUpdated = db.update(ItemsContract.TABLE_ITEMS,values, ItemsContract.ITEM_ID + "=" + id + " AND " + selection,selectionArgs);
            }
            break;
        default:
            throw new IllegalArgumentException("Unknown URI: " + uri);
    }
    getContext().getContentResolver().notifyChange(uri,null);
    return rowsUpdated;
    }
}

I've checked the above content provider code with Emulators and physical sets, and all are working fine (I've tried it on 5.0, 5.1 and 6.0 emulator).
And here is the Logcat For (JellyBean 4.2.2):
02-20 21:12:27.480 1796-1808/? D/PTI: URIType is : -1
02-20 21:12:27.480 1796-1808/? D/PTI: URI is : content://com.karacraft.security.mastersahab/items
02-20 21:12:27.480 1796-1808/? E/DatabaseUtils: Writing exception to parcel
    java.lang.IllegalArgumentException: Unknown URI: content://com.karacraft.security.mastersahab/items
at com.karacraft.security.MasterSahabProvider.query(MasterSahabProvider.java:260)
at android.content.ContentProvider.query(ContentProvider.java:652)
at android.content.ContentProvider$Transport.query(ContentProvider.java:189)
at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:113)
at android.os.Binder.execTransact(Binder.java:351)
at dalvik.system.NativeStart.run(Native Method)

On other systems, URI always comes out as intended.
Here is Logcat for KitKat 4.4.4:
02-21 01:06:51.591 1872-1884/? D/PTI: URIType is : 10
02-21 01:06:51.591 1872-1884/? D/PTI: URI is : content://com.karacraft.security.mastersahab/items
02-21 01:06:51.631 1872-1883/? D/PTI: URIType is : 50
02-21 01:06:51.631 1872-1883/? D/PTI: URI is : content://com.karacraft.security.mastersahab/orders
02-21 01:06:51.631 1872-1884/? D/PTI: URIType is : 70
02-21 01:06:51.631 1872-1884/? D/PTI: URI is : content://com.karacraft.security.mastersahab/suits
02-21 01:06:51.631 1872-1883/? D/PTI: URIType is : 90
02-21 01:06:51.631 1872-1883/? D/PTI: URI is : content://com.karacraft.security.mastersahab/tailors
02-21 01:06:51.631 1872-1884/? D/PTI: URIType is : 130
02-21 01:06:51.631 1872-1884/? D/PTI: URI is : content://com.karacraft.security.mastersahab/stats
02-21 01:06:51.641 1872-1883/? D/PTI: URIType is : 110
02-21 01:06:51.641 1872-1883/? D/PTI: URI is : content://com.karacraft.security.mastersahab/staff
02-21 01:06:51.641 1872-1884/? D/PTI: URIType is : 30
02-21 01:06:51.641 1872-1884/? D/PTI: URI is : content://com.karacraft.security.mastersahab/merchandises

It's showing proper URI's on Kitkat.
Solution found, thanks to @MARTEN answer
Changing the Leading Slash from Table Name to URI solved the problem.
//Table Names
private static final String ITEMS_TABLE         = "/" + ItemsContract.TABLE_ITEMS;
private static final String MERCHANDISES_TABLE  = "/" + MerchandisesContract.TABLE_MERCHANDISES;
private static final String ORDERS_TABLE        = "/" + OrdersContract.TABLE_ORDERS;
private static final String SUITS_TABLE         = "/" + SuitsContract.TABLE_SUITS;
private static final String TAILORS_TABLE       = "/" + TailorsContract.TABLE_TAILORS;
private static final String STAFF_TABLE         = "/" + StaffContract.TABLE_STAFF;
private static final String STATS_TABLE         = "/" + StatsContract.TABLE_STATS;

//Uri for Multiple Tables
public static final Uri CONTENT_URI_ITEMS           = Uri.parse("content://" + AUTHORITY + ITEMS_TABLE);
public static final Uri CONTENT_URI_MERCHANDISES    = Uri.parse("content://" + AUTHORITY + MERCHANDISES_TABLE);
public static final Uri CONTENT_URI_ORDERS          = Uri.parse("content://" + AUTHORITY + ORDERS_TABLE);
public static final Uri CONTENT_URI_SUITS           = Uri.parse("content://" + AUTHORITY + SUITS_TABLE);
public static final Uri CONTENT_URI_TAILORS         = Uri.parse("content://" + AUTHORITY + TAILORS_TABLE);
public static final Uri CONTENT_URI_STAFF           = Uri.parse("content://" + AUTHORITY + STAFF_TABLE);
public static final Uri CONTENT_URI_STATS           = Uri.parse("content://" + AUTHORITY + STATS_TABLE);

This
  //Table Names
private static final String ITEMS_TABLE         =  ItemsContract.TABLE_ITEMS;
private static final String MERCHANDISES_TABLE  =  MerchandisesContract.TABLE_MERCHANDISES;
private static final String ORDERS_TABLE        =  OrdersContract.TABLE_ORDERS;
private static final String SUITS_TABLE         =  SuitsContract.TABLE_SUITS;
private static final String TAILORS_TABLE       =  TailorsContract.TABLE_TAILORS;
private static final String STAFF_TABLE         =  StaffContract.TABLE_STAFF;
private static final String STATS_TABLE         =  StatsContract.TABLE_STATS;

//Uri for Multiple Tables
public static final Uri CONTENT_URI_ITEMS           = Uri.parse("content://" + AUTHORITY + "/" + ITEMS_TABLE);
public static final Uri CONTENT_URI_MERCHANDISES    = Uri.parse("content://" + AUTHORITY + "/" +MERCHANDISES_TABLE);
public static final Uri CONTENT_URI_ORDERS          = Uri.parse("content://" + AUTHORITY + "/" +ORDERS_TABLE);
public static final Uri CONTENT_URI_SUITS           = Uri.parse("content://" + AUTHORITY + "/" +SUITS_TABLE);
public static final Uri CONTENT_URI_TAILORS         = Uri.parse("content://" + AUTHORITY + "/" +TAILORS_TABLE);
public static final Uri CONTENT_URI_STAFF           = Uri.parse("content://" + AUTHORITY + "/" +STAFF_TABLE);
public static final Uri CONTENT_URI_STATS           = Uri.parse("content://" + AUTHORITY + "/" +STATS_TABLE);

Comment: How are you certain it's a problem with the android version? Perhaps it's a problem with a specific device or manufacturer, or that particular build of the apk could have a problem, etc...
Comment: just updated my question with 4.4.4 logcat. I've checked this on several handsets as well as on emulator. -1 is only coming up on 4.2.2.
Answer: Support for paths with leading slashes has been added in Android 4.3. See the description of addUri, which states

Starting from API level JELLY_BEAN_MR2, this method will accept a leading slash in the path.

So just remove the leading slashes in your paths.
i.e. replace
uriMatcher.addURI(AUTHORITY, ITEMS_TABLE,ITEMS);

by
uriMatcher.addURI(AUTHORITY, ItemsContract.TABLE_ITEMS);

btw. the last case statement in your query method is missing a break; which means that Uri will always throw an exception.
Comment: I was pretty sure that there is something wrong with my uri, so i reworked a bit, and solution was changing the the place of LEADING SLASH. Please check my question.
Comment: Of course your changes solve it too, but I would ditch the redundant static fields.
Comment: thats what i did in the end. But kept the solution close to original problem :)
Comment: don't forget to add the missing `break;`
Comment: it was the first thing which i did. Thanks Again


How to compare the performance of different SVMs and CNNs?

Question: I'm a beginner in machine learning und I have a problem to find the best way to compare the performance (accuracy) of different SVMs and CNNs (Jupyter Notebook)?
The CNNs I train in Google Colab with GPU.
So far I've tried to make the models reproducible by setting seeds und train each model architecture several times.
The reproducibility works with the SVMs, but not with the CNNs in Google Colab.
But generally I'm not sure if reproducibility is really helpful in this case.
Wouldn't it be better not to put any seeds and train each model several times and then
compare the models by using the calculated mean and standard deviation?
I hope and would be very grateful when you can explain me how to do it right.
Many thanks in advance
Answer: If CNN returns random results, there must be the part related to RNG. If it's hard to locate where exactly they are, you can just try several times and compare them with mean and STD.
However, I wouldn't recommend you to do that b/c it might take a long time to train CNN. Rather, I recommend you to read the documents of ML module that you are using (i.e. Tensorflow, PyTorch, Keras, ...) to find out where the RNG is coming from.
Comment: I use Keras with Tensorflow backend and Jupyter notebook for the CNNs. My problem seems to be already a big topic of discussion. So far there seems to be no solution for my ML modules.
Comment: The only clue I keep coming across is to use the CPU instead of the GPU. But this solution would really take a lot of time for the CNNs.


Help in creating Enum extension helper

Question: Take this enum for example:
public enum PersonName : short
{
    Mike = 1,
    Robert= 2
}

I wnat to have en extension method like this:

PersonName person = PersonName.Robert;
short personId = person.GetId();
//Instead of:
short personId = (short)person;

Any idea how to implement this?
it need to be generic to int, short etc..., and to generic enums as well, not limited to PersonName.
Comment: This is not possible to do.  (You cannot constain a method based on an `enum`'s underlying type)
Comment: Why would you need an extension method to do this? Casting to the underlying type is already as easy as `(int) SomeEnum.SomeValue`
Answer: This is completely impossible.
You cannot constrain a method based on an enum's underlying type.
Explanation:
Here is how you might try to do this:
public static TNumber GetId<TEnum, TNumber>(this TEnum val)
       where TEnum : Enum
       where TEnum based on TNumber

The first constraint is unfortunately not allowed by C#, and the second constraint is not supported by the CLR.
Comment: You can "sort of" (well, you create the effect) - http://msmvps.com/blogs/jon_skeet/archive/2009/09/10/generic-constraints-for-enums-and-delegates.aspx
Comment: See also: http://stackoverflow.com/questions/7244/anyone-know-a-good-workaround-for-the-lack-of-an-enum-generic-constraint
Answer: Well, its sort of possible, but on the flip side you will have to specify what the underlying type is:
public static T GetId<T>(this Enum value)
                        where T : struct, IComparable, IFormattable, IConvertible
{
    return (T)Convert.ChangeType(value, typeof(T));
}

since System.Enum is the base class of all enum types. Call it:
PersonName person = PersonName.Robert;
short personId = person.GetId<short>();

Since you can cast almost anything to long, you could even have this:
public static long GetId(this Enum value)
{
    return Convert.ToInt64(value);
}

and call:
PersonName person = PersonName.Robert;
long personId = person.GetId();

What is otherwise possible is to get an object instance returned, like this or so:
public static object GetId(this Enum value)
{
    return Convert.ChangeType(task, Enum.GetUnderlyingType(value.GetType()));
}

PersonName person = PersonName.Robert;
var personId = (short)person.GetId();
// but that sort of defeats the purpose isnt it?

All of which involves some sort of boxing and unboxing. The second approach looks better (you could even make it int, the standard type) and then the first.
Answer: I believe you should be able to define an extension method on the PersonName class:
public static class PersonExtensions // now that sounds weird...
{
    public static short GetID (this PersonName name)
    {
        return (short) name;
    }
}

Side node: I somehow hope that the code in your question is overly simplified, as it does not seem quite right to implement a person repository as an enum :)
Comment: I want it to be a generic. and of course this was an example :)
Comment: Sorry, didn't catch that in your question. I am afraid I am not sure what you mean by "generic" in this context, but it seems like others have figured it out :)
Answer: Is there any reason you can't turn it into a class?  It would probably make more sense in context of a class.
Comment: Good point. And how get the person-property name, using reflation? or each one should return dictionary? I'll think about it. bu the question still interesting to me.
Answer: I would just use something like IEnumerable<KeyValuePair<string,short>> or Dictionary<string,short>... you can add your extensions to IDictionary or IEnumerable if you want.
Comment: That what I'm going to use by now. But about the question, this behavior I wanted a lot of time, but from my knowledge it not possible to achieve.

Help in creating Enum extension helper


Crocco's Equation Problem

Question:
For $2$-D steady, incompressible inviscid flow, subject to a conservative body force $\underline{X} = -\nabla\chi$, show that Crocco's equation reduces to
  $$-\Omega\underline{\nabla}\psi = \underline{\nabla}H\quad\text{where}\quad \underline{\omega} = \underline{\nabla}\times\underline{u} = \Omega\underline{\hat k},\quad H = \frac{1}{\rho}p + \frac{1}{2}||\underline{u}||^2 + \chi$$
  where $\psi$ is the $2$-D stream function, $\underline{u} = \underline{\nabla}\psi\times\underline{\hat k}$. Hence show that
  $$\frac{\mathrm{d}H}{\mathrm{d}\psi} = -\Omega(\psi)$$

I am truly completely confused about all of this. All I have is that
$$\underline{\omega} = \underline{\nabla}\times\underline{u} = \underline{\omega} = \underline{\nabla}\times(\underline{\nabla}\psi\times\underline{\hat k}) = \underline{\nabla}\psi(\underline{\nabla}\cdot\underline{\hat k}) - \underline{\hat k}(\underline{\nabla}\cdot\underline{\nabla}\psi) = \Omega\underline{\hat k}$$
But I don't know what else to dod from here or even if this is right. I struggle with vector calculus so much...
For incompressible flow with a conservative body-force $\underline{X}=-\underline{\nabla}\chi$, the equation of motion (1) reduces to the incompressible form of Crocco's equation.
$$\frac{\partial\underline{u}}{\partial t}-\underline{u}\times\underline{\omega}=-\underline{\nabla}\left[\frac{1}{\rho}p+\frac{1}{2}||\underline{u}||^2 + \chi\right]-\nu\underline{\nabla}\times\underline{\omega}$$
where $\underline{\omega} = \underline{\nabla}\times\underline{u}$ is the vorticity vector.
Comment: Do you mind writing down Crocco's equation? This is the first time I heard about it.
Comment: @CheeHan I've included what I can see in my online notes but I am totally lost. If you need to know more I'll do my best. I really appreciate your help
Answer: The Crocco's equation is
$$ \frac{du}{dt} - u\times\omega = -\nabla H - \nu\nabla\times\omega. $$
Suppose $u = (u_1,u_2,0)$ is the 2D steady, incompressible, inviscid flow field. With $\nu = 0$, $\frac{du}{dt} = 0$ and $\omega = (0,0,\Omega)$, Crocco's equation reduces to
$$ -u\times\omega = -\nabla H $$
or
$$ u\times\omega = \nabla H. $$
We only need to show that $u\times\omega = -\Omega\nabla\psi$, where $\psi$ is the 2D stream function. First,
$$ u\times\omega = \begin{pmatrix} u_1 \\ u_2 \\ 0 \end{pmatrix}\times\begin{pmatrix} 0 \\ 0 \\ \Omega \end{pmatrix} = \begin{pmatrix} \Omega u_2 \\ -\Omega u_1 \\ 0 \end{pmatrix}. $$
From the definition of stream function, we find that
$$ u = \nabla\psi\times\hat{k} = \begin{pmatrix} \partial_x\psi \\ \partial_y\psi \\ 0 \end{pmatrix}\times\begin{pmatrix} 0 \\ 0 \\ 1 \end{pmatrix} = \begin{pmatrix} \partial_y\psi \\ -\partial_x\psi \\ 0 \end{pmatrix} = \begin{pmatrix} u_1 \\ u_2 \\ 0 \end{pmatrix}. $$
The desired result follows from combining these two computations:
$$ \nabla H = u\times\omega = \Omega\begin{pmatrix} -\partial_x\psi \\ -\partial_y\psi \\ 0 \end{pmatrix} = -\Omega\nabla\psi. $$
Comment: Gosh you're good at this. Thank you, you have a great way of breaking things down to a speed that I can inderstand that isn't the case in my lectures

Crocco's Equation Problem


Como diferenciar um EditText com o mesmo nome e o mesmo id?

Question: public void criaForm(){
    for (int i = 0; i < 5; i++) {
        EditText et = new EditText(this);
        linearLayout.addView(et);
        TextView tv = new TextView(this);
        linearLayout.addView(tv);
    }
}

Criei vários EditTexts dentro de um for, com isso eles têm o mesmo nome e id, existe alguma forma onde eu possa diferenciá-los? Agradeço desde já!
Comment: Cara... Não ta claro sua pergunta... Tente se expressar melhor e coloque alguns pedaços de código pra que possamos ajudar você!
Comment: Olá, eu só queria diferenciar um EditText do outro sem ser pelo nome dele ou pelo id. Coloquei um pedaço do meu código onde eu crio ele. No meu código eu tenho 5 et. Eu queria por exemplo, quando clicar no segundo et, saber que cliquei nele.
Answer: Qualquer View Android tem um atributo chamado tag ao qual pode ser usando para adicionar informação extra em uma View.
Um exemplo de sua utilização é o seguinte:
View view = new View(contexto);
Object objeto = new Object();
view.setTag(objeto);

Object objectDaTag = view.getTag();

E, já que EditText é filho de View também pode se aproveitar desse recurso. Como por exemplo:
EditText et = new EditText(this);
et.setTag(objeto);
Object objetoDaTag = et.getTag(); // se atribuído outra classe deve ser feito o cast

Documentação oficial
Comment: Obrigado pela respostas, mas já tentei com Tag e tive o mesmo problema do id, o EditText "pega" somente o valor da última Tag.
Comment: E se gerar IDs únicos para esses EditText resolve seu problema?
Comment: Perguntei isso porque creio que você não está atribuindo IDs incrementados para prevenir conflito com os IDs da classe R.
Comment: Eu gerei, usei o contador do for concatenado com outro número "(i+5)", o id fica único que testei isso colocando todos dentro de um ArrayList, o problema que estou tendo é para usar o textWatcher, eu tentei colocando todos os editTexts dentro de um ArrayList de EditText mas só funciona se eu setar o valor do editText na mão "listaEditText.get(posicao)" ,eu precisaria de clicar no editText e ele me retornar algum valor que pudesse diferencia-lo dos outros
Comment: Estou criando tudo dinamicamente, não estou usando xml para nada.
Comment: Não conheço outra forma de identificar uma View de maneira única e eficiente senão com id.
Answer: Se o seu problema é diferenciar dois EditTexts e nem id nem tag te satisfazem, tire proveito do mecanismo de herança e polimorfismo de Java e crie uma classe com um atributo a mais
public class MyEditText extends EditText {
    ...

}


Is there an analogue of the Hille Yosida theorem for abstract Cauchy problems of the type $ \frac{du(x,t)}{dt}=A(t)u(t,x)+Cu(t,x)$

Question: I have the following abstract Cauchy problem on a Banach space $X$:
$$ \frac{du(x,t)}{dt}=A(t)u(t,x)+Cu(t,x)$$
where $A(t)$ is a closed, densely defined, linear, bounded operator for every $t \in [0,T]$.
Moreover, all the operators of the family $\{A(t): t \in [0,T]\}$ have the same domain $D(A) \subset X $, hence all the operators go from $D(A)$ to $X$.
Also $C$ is a linear bounded operator from $D(C)$ to $X$.
I would like to know if the operator $A(t)+C$ generates a strongly continuous semigroup.
I know that this holds if $A$ does not depend by the time, but I do not find the analogue result in the case of $A$ depending by time.
Someone knows where this kind of problems are treated in literature ?
Thank you
Comment: What are the properties of $\{A(t)\}$ and $D(C)$? Well, the answer is "yes" if $\{A(t)\}$ is stable and $D(C)=X$. See my post for more details and some references.
Answer: As $A$ depends on $t$, we have to talk about "family" of infinitesimal generators. In this context, your question can be formulated as follows:
Does a family of generators retain the properties of a family of generators if subjected to perturbations? (This is a version of Kato, p. 497)
Of course, the answer depends on the properties of the family and the perturbations. We have, for example, the following result in Pazy's book (p. 132):

If $\{A(t)\}_{t\in[0,T]}$ is a stable family of infinitesimal generators of $C_0$-semigroups and $\{B(t)\}_{t\in[0,T]}$ is a family of bounded linear operators from $X$ to $X$ such that $\sup_{t\in[0,T]}\|B(t)\|<\infty$, then $\{A(t)+B(t)\}_{t\in[0,T]}$ is a stable family of infinitesimal generators.

You can find more results in the paper Stability of CD-Systems Under Perturbations in the Favard class (there are other references in the third paragraph).


The Myth of Long-Horizon Predictability

Question: I recently came across a fascinating article about predicting future stock market returns. The author presents the graph below and cites an R^2 of 0.913. This would make the author's method far superior to anything I have ever seen on the subject (most argue that the stock market is unpredictable).

The author describes his method in great detail and provides substantial theory to back up the results. Then I read a second, critiquing article that referenced this paper: The Myth of Long-Horizon Predictability. Apparently people have been falling for this illusion for decades. Unfortunately, I don't really understand the paper.
This leads me to the following questions:

Does the false confidence of long-term predictions arise due to using the same data set for both training and model validation? Would the problem go away if training and validation data were pulled from separate, non-overlapping time periods?
Aside from validating on the training set, why does this problem become more pronounced over longer horizons?
In general, how can I overcome this problem when training models that must make long-term predictions?
Comment: Not sure if you came across this thread on CV, where I referenced a couple of papers on this topic. https://stats.stackexchange.com/questions/294489/is-autocorrelation-in-a-supervised-learning-dataset-a-problem/294991#294991
Answer: I think a simple answer is that one doesn't want to measure R^2 on original scale of the timeseries. If one's forecast is purely a copy of the last seen timeseries value, the R^2 would be huge. Example:

This could be called a spurious case. I am getting the value 0.96, while this forecast is totally bullshit-ish.
R^2 is going to give an honest value if it has been measured using stationary timeseires, for example, first differences of y and y-hat.
Answer: The problem does not arise because we are using the same dataset for training and validation. It arises because of the effect of the persistence of the variables on magnifying sampling errors and small effects at longer time horizons. As stated in the article, even if you cannot predict future stock market returns from your variable of interest, we expect $R^2$ as well as regression coefficients to be roughly proportional to the time horizon if the variables are persistent. This is because (pg. 1584):
a) any unusual draw from the returns at time $t$ will influence the returns for $k$ periods, where $k$ is the time horizon.
b) a persistant regressor will have very similar values for $t$, $t-1$, $t-2$, .., $t-k$
and thus "The impact of the unusual draw will be roughly $k$ times larger in the long-horizon regression than in the one-period regression." In the linked article citing the very high $R^2$, the time horizon is ten years, data is available quarterly, so a time horizon of 10 years (time horizon $k = 40$) the inflation in $R^2$ will likely be very substantial.

The Myth of Long-Horizon Predictability


Is sqrt still slow in Delphi 2009?

Question: Is sqrt still slow in Delphi 2009?
Are the old tricks (lookup table, approx functions) still useful?
Comment: i am guessing Delphi? language please
Comment: "...still...": Compared to which version of Delphi?
Comment: Actually I was talking about c.
The answers are however interesting, so I'll post a separate C version
Comment: @Mykelyk: Do you think maybe asking the question and including the language you are talking about might help? Perhaps at least editing the answer after people have asked for the language?
Answer: If you are dealing with a small set of really large numbers then a lookup table will most always be faster.  While if you are dealing with a large set of small numbers then even a slow routine may be faster then maintaining a large table.
I looked in System.pas (where SQRT is located) and while there are a number of blocks marked as licensed from the Fastcode project, SQRT is not.  In fact, it just makes an assembly call to FSQRT, so it most likely hasn't changed.  So if it was comparatively slow at one point then it most likely still is as slow (although your CPU may be a lot faster and optimized for that now . . . .)
My recommendation is to look at your usage and test.
Comment: Right.  I don't believe there are any optimizations over using FSQRT or a look-up table.
Comment: My usage is a physic simulation game
Comment: You are really going to need to optimize it for your usage.  If you see that you are calculating the same large square roots repeatedly then you might consider caching them, but that will probably only be faster if you are dealing with large numbers.  Small numbers will probably be faster to just calculate each time.  Of course you will need to test and see.
Answer: Many moons ago I had an app that computed distance to sort vectors. I realized sorting by the un-sqrt-ed values was the same so I skipped it altogether. Sorted by distance^2 and saved some time.
Comment: Yes, I've done this sort of thing more than once.  Very often you can work with distance^2 instead of distance.
Comment: exactly. comparing dot products are just as good as comparing magnitudes. (sadly, it doesn't work with ratios.)
Answer: My answer to questions of efficiency is to just apply the simplest method first, then optimize later.  Making an operation faster when there's no need for it to be all that fast in the first place seems silly.
I digress, however, since my answer is about efficiency, not the historical aspects of your question.
Comment: So, basically, this isn't an answer at all.
Comment: There are two parts to his question, one is about efficiency and the other is about the historical nature of the function.  He obviously isn't looking to optimize an existing implementation, so why not try it first then see if the performance is tolerable.

Is sqrt still slow in Delphi 2009?


The data is not registered to the database

Question: I want to make a student registration form.  I get no error messages, but the data is not entered into the database.
INDEX is for INDEX NUMBER
USERNAME is for USER
EMAIL is for EMAIL
I had trouble with index variable it said that it is undefined, I am not sure if I defined the variable properly.
<!doctype html>

<meta charset="utf-8">

<title>Untitled Document</title>

<?php
    session_start();
    $_SESSION["message"] = "";

    $mysqli = new MySQLi("localhost","root","","accounts");

    if ($_SERVER['REQUEST_METHOD'] == "POST"){
        $username = $mysqli->real_escape_string($_POST["username"]);
        $email = $mysqli->real_escape_string($_POST["email"]);

        $index = ($_POST["email"]);

        $_SESSION["username"] = $username;
        $_SESSION["email"] = $email;

        $sql = "INSERT INTO users (index, email, name) "
    . "VALUES ('$index', '$email', '$username')";

        //check if mysql query is successful
if ($mysqli->query($sql) === true)
{
    $_SESSION[ 'message' ] = "Registration succesful! Added $username to the database!";
    //redirect the user to welcome.php
    header( "location: welcome.php" );
}
        else{
            $_SESSION["message"] = "user could not be added to the database";
        }

    }
    else{
            $_SESSION["message"] = "could not initiate session";
        }

    ?>

<link href="//db.onlinewebfonts.com/c/a4e256ed67403c6ad5d43937ed48a77b?family=Core+Sans+N+W01+35+Light" rel="stylesheet" type="text/css"/>
<link rel="stylesheet" href="form.css" type="text/css">

Create an account

    <form class="form" action="form.php" method="post" enctype="multipart/form-data" autocomplete="off">

      <input type="text" placeholder="User Name" name="username" required />
<input type="email" placeholder="Email" name="email" required />

      <input type="text" placeholder="Index Number" name="index" required />

      <input type="submit" value="Register" name="register" class="btn btn-block btn-primary" />
    </form>

Comment: Possible duplicate of [Syntax error due to using a reserved word as a table or column name in MySQL](https://stackoverflow.com/questions/23446377/syntax-error-due-to-using-a-reserved-word-as-a-table-or-column-name-in-mysql)
Comment: `index` is a MySQL reserved word - https://dev.mysql.com/doc/refman/5.5/en/keywords.html#keywords-5-5-detailed-I. In order to use it as a column name, you must escape it - `INSERT INTO users (\`index\`, email, ...`
Comment: Than.k you very much. It works now .
Comment: Welcome to StackOverflow.  Please don't use ALL CAPS in your questions in future.
Comment: @Graham: Please try to use exception or error handling so it will easy to find out received error.
I.e Just simply add or die(mysqli_error($db)); at the end of your query, this will print the mysqli error.

 mysqli_query($db, $inserQuery) or die(mysqli_error($db));
Thank you
Comment: @Dipti I just edited the question from the "Help & Improvement" queue, it's not me you need to tag.
Answer: Change this line :
$sql = "INSERT INTO users (index, email, name) "
. "VALUES ('$index', '$email', '$username')";

To this :
$sql = 'INSERT INTO users (index, email, name) '
. 'VALUES ("$index", "$email", "$username")';

Hope to solve your problem.


Can a triangle be constructed by right edge and compass when its base, median to the base and the sum of other sides are known?

Question: Can a triangle be constructed by right edge and compass when its base, median and the sum of other sides are known?
I found this problem in the book "An introduction to the modern geometry of the triangles and the circles" by Nathan Altshiller Court. This is my effort:
Case 1: The measure of median is greater than half base:

We have base AB and median EC; first we do following calculations:
$BE^2=CE^2-BC^2$
$AE^2=BE^2+AB^2$
$AE+EB=\sqrt{BE^2+AB^2}+\sqrt{CE^2-BC^2}$
therefore the sum of two other sides given must be competent with this calculation, it will not be necessary to know it. Now for construction of triangle we have to draw an ellipse, its intersection with a circle center at C and radius equal to median will be the third vertex. For drawing the ellipse we may use ancient method; using a rope length equal to $l=AB + BE+AE$ and a pen which make a triangle with A and B. Moving this pen give us the ellipse. I have no idea how to do this using a compass.
Case 2- The measure of median is less than half base:

First we draw ellipse using three center arc which is called ellipse like arc. First we divide AB in three equal segments. Construct an equilateral triangle CDF on middle part CD. Draw two circle on centers E and D, with radii $EB=DA$, then draw third circle center on F , radius $2 EB=\frac 23 AB$. This arc is tangent on previous two arcs at points I and K and the arc AIKB is approximately a part of an ellipse passing  points A and B. Now we draw a circle center on C and radius equal to the measure of median. The intersection of this circle and the ellipse will be the third vertex of triangle.  As can be seen in figure , the third vertex is intersection of median circle with circle center of F and $r=\frac 23 AB $if median $m<\frac 13 BC$ (point L in figure) and it is with circle center on E and radius $r=\frac 13 AB$ if median $BC>m>\frac 12 BC$ (point N in the figure).
Again the sum of two other sides, if given, is not used.
Question: How about if the the sum of measures of other sides is given? any idea for constructing the triangle with straight edge and compass?
Note: the original problem was the difference of two other sides is given. In this case the third vertex can be the intersection of the circles g and h with a hyperbola. I tried to solve a simpler form; sum instead of difference.
Comment: The circle with center in A and radius AB intersect the circle with center in M and radius the median in C; if the intersection is not empty.
Answer:
The problem can be formulated so:

Let $M$ be the midpoint of the side $AB$ in the triangle $ABC$. Let
$CX$ be perpendicular drawn from $C$ to $AB$. Is it possible to
construct $x=MX$ with right edge and compass if $AB$, $CM$ and $AC+BC$
are known?

Let $CM=m$, $AB=2a$, $AC+BC=2l$.
Then the last equation can be written (see figure):
$$
\sqrt{(a+x)^2+(m^2-x^2)}+\sqrt{(a-x)^2+(m^2-x^2)}=2l.
$$
Squaring the equation one obtains:
$$\begin{align}
&2a^2+2m^2+2\sqrt{(a^2+2ax+m^2)(a^2-2ax+m^2)}=4l^2\\
\implies&(2l^2-a^2-m^2)^2=(a^2+2ax+m^2)(a^2-2ax+m^2)=(a^2+m^2)^2-4a^2x^2\\
\iff&4a^2x^2=(a^2+m^2)^2-(2l^2-a^2-m^2)^2=2l^2(2a^2+2m^2-2l^2)\\
\iff& a|x|=l\sqrt{a^2+m^2-l^2}\tag1
\end{align}$$
Given $a,m,l$ the equation $(1)$ obviously can be solved for $x$ with compass and right edge, provided that $l>a$ and $\sqrt{l^2-a^2}\le m<l$.
Comment: Of course $x=MX$, not $CX$.
Comment: Of course. Thank you for pointing this out!
Comment: $user, Perfect. thank you.


socket.emit inside socket.on not working on client side Socket.io

Question: Client side code:-

...snip...

var socket = io.connect( 'http://localhost:5000' );

socket.on('text_msg', function (data) {
    socket.emit('message', {txt:"test"});  //this is not working
    alert( data.msg );
});

Server Side Code looks like:-
const io = require('socket.io').listen(5000);
   io.emit('text_msg', {msg: 'Welcome you are now connected.'}); //this is working good

    // plain message - this never works
    io.on('message', function(data){
        console.log("message : " + data.txt);   //No msg on console!
    });
});

Please help me in sending message from client script to the server.
Answer: You are emitting the text_msg event right as you start your socket server, and not when a connection is made. You should listen for the connection event on the server, and then emit the welcome message to the connected socket.
The message that the client sends to the server also won't be seen because you are not listening for it. You need to listen on each individual socket.
Your server-sided code should look like this:
const io = require('socket.io').listen(5000);

io.on('connection', function (socket) {
    socket.emit('text_msg', {
        msg: 'Welcome you are now connected.'
    });

    socket.on('message', function(data) {
        console.log('message : ' + data.txt);
    });
});

Comment: After replacing the server code with above code... Neither io.emit nor io.on is working now..Please help!
Comment: I solved my issue as I'm using socket inside another callback of Mosca.js `moscaServer.on('published', function(client) {` . Anyone facing similar issue please define your socket code outside these types of callbacks. Thanks!


binary and floating point representation

Question: suppose that we have following  binary digits
$00011001.110 $,we can do following thing
$00011001.110=1\cdot2^4+1\cdot2^3+1\cdot2^0+1\cdot2^{-1}+1\cdot2^{-2}=25.75$
then  what does means?
We then "float" the binary point:
$00011001.110 \Rightarrow 1.1001110 \cdot 2^4 $
mantissa = 1.1001110, exponent = 4
i did not understand this part,generally for sign  we have  $1$ bit,for exponent we have $8$ bit and for mantissa we need   $23$ bit,so i can't understand last part,from floating to binary point,please help me
Comment: IEEE-754 format i meant
Comment: Are you referring to IEEE format for floating point numbers?
Comment: Does this answer help?  http://math.stackexchange.com/a/305901/23353  (I don't know a lot about IEEE-754, but that answer looked pretty nice.)
Comment: a bit explanation please,in my case how it would be
Comment: Please: Using an asterisk for ordinary multiplication in MathJax is vulgar.  I edited it.
Answer: I'm not sure I really get your question, but are you confused about what "mantissa" really means - it should be a 2-complement integer, but in normalized representation it has a leading "1."? In the standard, the leading "1." is implied: the mantissa bits represent, in your case, only 100111. If this isn't your point of confusion, kindly elaborate more.
Comment: yes it is related to mantissa and exponent,in my example how it is calculated  last part?
Comment: You have a typo in your translation which I thought was just that: do you see that 11001.11 = 1.100111 times $2^{4}$? (You have 24) then you just forget the 1., and 100111 is your m, and $2^{4}$ is your exponent.
Comment: You can think of $2^n$ as rotating n times to the left.
Comment: sorry i am lost now
Comment: @datodatuashvili: Me too probably. :) If you have 11.01 = 5.25, then it is the same as 1.101 * 2 = $2.625_d$ * $2_d$. Or think of it as the position left to any position is twice the value of that position; so $6_d$ = 110 = 11 * 2 = $3_d$ * $2_d$; $12_d$ = 1100 = 11 * $2^2$ = $3_d$ times $4_d$. I'm not quite sure where you're stuck.
Comment: And again in other words, if in a (binary) representation you move the dot from xx.yyy to xxx.yy, you multiply by 2 for each such shift; so as in your original case you moved the dot 4 times to the right, you multiply the resulting number by $2^4$.
Comment: i will work on this problem tomorrow,i can't think now
Answer: You start with the binary number $11001.110_2$  We want to express it as something between $1$ and $2_{10}=10_2$ times the appropriate power of two.  So $11001.110_2=1.1001110 \cdot 2^4$  Note that this is the same as your expression except that you used $x$ for times and lost the exponent sign.  The mantissa is the value between $1$ and $10_2$, so is $1.100111$.  The exponent is the exponent of $2$ in the expression, so $4$.  We have not yet packed it into the $32$ bit representation.  Now if we want to go to IEEE single precision floating point, the sign bit is $0$ (positive), the exponent is $4+127=131=10000011_2$ and the significand is $11001110000000000000000$, so the whole number is $1\ 10000011\ 11001110000000000000000$ where I put the spaces in to show where the pieces go.


Update R Commands from Bash

Question: My problem is simple: is there a way to update R packages from the BASH command line? Something like r cmd "update.packages(ask=FALSE)", except one that works?
Thanks.
Comment: can't you just put the `update.packages` line in an R script and use R CMD BATCH myUpdateScript.R?
Answer: Use Rscript with -e option to run a specific expression and just change your repos as necessary:
Rscript -e "update.packages(ask=F, repos='http://r-forge.r-project.org')"

Update R Commands from Bash


strange results from density plot

Question: I am getting some very weird results. I have created a density plot for various continuous response variables, which are independent of each other.

I have noticed that the Density value seems to be very small. I know the height is meaningless and what needs to be interpreted is the area under the curve. Therefore I have tried to check the area under my curve, but I have obtained value much smaller than 1 -  namely -15411.15:
strassenverkehr.densities <-plot(density.gs8m, ylim = c(0, 0.03), col = 9, lty = 1,
                                 xlab = "Abweichung in %", xlim = c(-100,100) )
lines(density.ks12m, col=1, col = 7, lty = 8)
lines(density.bruecke4m, col = 2,lty = 3)
lines(density.bruecke8m, col = 3,lty = 4)
lines(density.bruecke12m, col = 4,lty = 5)
lines(density.FeldwegKies, col = 5,lty = 6)
lines(density.FeldwegAsph, col = 6,lty = 7)

> density.bruecke4m <- density (diff.bruecke4m)
> trapz(density.bruecke4m$x[density.bruecke4m$x < -40])
[1] -15411.45

I am afraid there is something seriously wrong with my analysis. Any ideas?
Comment: That should indeed not happen. Then again, it's hard to help you if we can't recreate your problem. Can you please edit your post to contain a minimum (!) working (!) example? Thanks!
Comment: Most of your curves have a base about 100 units long and typical densities about 0.01. That checks: 100 * 0.01 = 1. The height units are not meaningless at  all: density is probability per unit deviation. That is no more meaningless than density in physical science being mass per unit volume or population density being people per unit area.
Comment: Please *describe* the calculation you're trying to do, so we can see that makes sense, and then (if it does) you can ask on a site that takes programming questions whether your code actually does that.
Answer: I guess it is because you wrote
trapz(density.bruecke4m$x[density.bruecke4m$x < -40])

In trapz, x and y should be supplied. Maybe try something like
index <- (density.bruecke4m$x < -40)
trapz(x=density.bruecke4m$x[index], y=density.bruecke4m$y[index])

strange results from density plot


Not implemented Error for reports with Charts (Graphs) on Azure

Question: I installed Crystal Reports on Windows Azure, and most reports work just fine.  However, none of the reports with charts work.  I get Operation not yet implemented error from my web page.
Any help greatly appreciated.
Thanks.
Comment: Do you have a url to such a non working report? Which operation does it state is not implemented?
Comment: I cannot really publish the URL.  It just says Operation Not Implemented, not additional info provided.  I know now it is "not suported" on Azure, which makes no sense to me.  http://scn.sap.com/thread/3236182
Answer: If you can install all the needed SAP, I understood that from the thread you mentioned, on a server on premises you could try one of the following options:

Start up a webrole, rdp into it and install what's needed
Create a startup task that installs the needed material. See this for example.
Make use of the new IaaS capabilities in Azure. Create a new server from one of the images in the gallery or upload a sys prepped image with the stuff you need on it to Azure.
Comment: I have everything working in a web role, except charts.  SAP is using a third party charting, and that is what does not work.  I was trying really hard to avoid a VM role (IaaS) as it take more effort.
Comment: An alternative would be SQL Server Reporting Services which also works on Azure.


Soap xml is passing reference in php

Question: I am calling a webservice using soap in php but I am getting the error in xml as response from the server.
The problem is that when creating the xml for the request Php introduces the id in the xml and then wherever it finds the same node it just passes the id as the reference.
Eg:-
<ns1:ChargeBU id=\"ref1\">
<ns1:ChargeBreakUp>
<ns1:PriceId>0</ns1:PriceId>
<ns1:ChargeType>TboMarkup</ns1:ChargeType>
<ns1:Amount>35</ns1:Amount>
</ns1:ChargeBreakUp><ns1:ChargeBreakUp>
<ns1:PriceId>0</ns1:PriceId>
<ns1:ChargeType>OtherCharges</ns1:ChargeType>
<ns1:Amount>0.00</ns1:Amount>
</ns1:ChargeBreakUp>
</ns1:ChargeBU>

and then when it finds the same node it does this
<ns1:ChargeBU href=\"#ref1\"/>

So how can i prevent this so that it includes the full node again instead of just passing the reference ??
Answer: I had the same issue but couldn't figure out anything to do differently within SoapClient to fix it. i ended up overriding __doRequest() to modify the xml before sending to remove the reference id's from the elements and replace the reference elements with the elements they reference. if you do this, be sure to fix __getLastRequest() as shown here.
Edit: Using unserialize(serialize($input)) before sending seems to have fixed this for me.
Answer: you can create a new copy (instance) of that array to prevent php to use refs for the same values.
for example, we have:
$item = array(
    "id" => 1,
    "name" => "test value"
);

and our request/response:
$response = array(
    "item1" => $item,
    "item2" => $item
);

by default, php will replace item2 value with reference to item1 (both items point to the same array)
in order to prevent such behaviour, we need to create two different items with the same structure, something like:
function copyArray($source){
    $result = array();

    foreach($source as $key => $item){
        $result[$key] = (is_array($item) ? copyArray($item) : $item);
    }

    return $result;
}

and request/response:
$response = array(
    "item1" => copyArray($item),
    "item2" => copyArray($item)
);

the same by structure items are in fact different arrays in memory and php will not generate any refs in this case
Answer: I did some research, and SOAP extension, nuSOAP, WSO2 are not supported since 2010. They are full of unfixed bugs, I don't recommend to use them.
Use Zend 2 SOAP instead which does not use any unsupported extension, or if you are a Symfony fan, then try out the BeSimple SOAP boundle, which tries to fix the bugs of the SOAP extension. Don't reinvent the wheel!
Answer: I have changed the function a little bit because. if the $source is not an array ,we have a small problem in the foreach
function copyArray(Array $source){
    $result = array();
    if($source) { // not for empty arrays
        foreach($source as $key => $item){
            $result[$key] = (is_array($item) ? copyArray($item) : $item);
        }
    }
    return $result;
}

Soap xml is passing reference in php


Time data does not match format python odoo11

Question: I have an issue with odoo 11 default "sales channel report".
Trying to generate the report I get the following error message:
<code> Traceback (most recent call last):   File "C:\Program Files (x86)\Odoo
 11.0\server\odoo\fields.py", line 936, in __get__
     value = record.env.cache.get(record, self)   File "C:\Program Files (x86)\Odoo 11.0\server\odoo\api.py", line 960, in get
     value = self._data[field][record.id][key] KeyError: <odoo.api.Environment object at 0x061B1C50>

 During handling of the above exception, another exception occurred:

 Traceback (most recent call last):   File "C:\Program Files (x86)\Odoo
 11.0\server\odoo\http.py", line 647, in _handle_exception
     return super(JsonRequest, self)._handle_exception(exception)   File "C:\Program Files (x86)\Odoo 11.0\server\odoo\http.py", line 307,
 in _handle_exception
     raise pycompat.reraise(type(exception), exception, sys.exc_info()[2])   File "C:\Program Files (x86)\Odoo
 11.0\server\odoo\tools\pycompat.py", line 87, in reraise
     raise value   File "C:\Program Files (x86)\Odoo 11.0\server\odoo\http.py", line 689, in dispatch
     result = self._call_function(**self.params)   File "C:\Program Files (x86)\Odoo 11.0\server\odoo\http.py", line 339, in
 _call_function
     return checked_call(self.db, *args, **kwargs)   File "C:\Program Files (x86)\Odoo 11.0\server\odoo\service\model.py", line 97, in
 wrapper
     return f(dbname, *args, **kwargs)   File "C:\Program Files (x86)\Odoo 11.0\server\odoo\http.py", line 332, in checked_call
     result = self.endpoint(*a, **kw)   File "C:\Program Files (x86)\Odoo 11.0\server\odoo\http.py", line 933, in __call__
     return self.method(*args, **kw)   File "C:\Program Files (x86)\Odoo 11.0\server\odoo\http.py", line 512, in response_wrap
     response = f(*args, **kw)   File "C:\Program Files (x86)\Odoo 11.0\server\odoo\addons\web\controllers\main.py", line 872, in search_read
     return self.do_search_read(model, fields, offset, limit, domain, sort)   File "C:\Program Files (x86)\Odoo
 11.0\server\odoo\addons\web\controllers\main.py", line 894, in do_search_read
     offset=offset or 0, limit=limit or False, order=sort or False)   File "C:\Program Files (x86)\Odoo 11.0\server\odoo\models.py", line
 4169, in search_read
     result = records.read(fields)   File "C:\Program Files (x86)\Odoo 11.0\server\odoo\models.py", line 2535, in read
     values[name] = field.convert_to_read(record[name], record, use_name_get)   File "C:\Program Files (x86)\Odoo
 11.0\server\odoo\models.py", line 4688, in __getitem__
     return self._fields[key].__get__(self, type(self))   File "C:\Program Files (x86)\Odoo 11.0\server\odoo\fields.py", line 940, in
 __get__
     self.determine_value(record)   File "C:\Program Files (x86)\Odoo 11.0\server\odoo\fields.py", line 1051, in determine_value
     self.compute_value(recs)   File "C:\Program Files (x86)\Odoo 11.0\server\odoo\fields.py", line 1007, in compute_value
     self._compute_value(records)   File "C:\Program Files (x86)\Odoo 11.0\server\odoo\fields.py", line 998, in _compute_value
     getattr(records, self.compute)()   File "C:\Program Files (x86)\Odoo 11.0\server\odoo\addons\sales_team\models\crm_team.py",
 line 92, in _compute_dashboard_graph
     team.dashboard_graph_data = json.dumps(team._get_graph())   File "C:\Program Files (x86)\Odoo
 11.0\server\odoo\addons\crm\models\crm_team.py", line 205, in _get_graph
     graph_datas = super(Team, self)._get_graph()   File "C:\Program Files (x86)\Odoo
 11.0\server\odoo\addons\sales_team\models\crm_team.py", line 214, in _get_graph
     graph_data = self._graph_data(start_date, end_date)   File "C:\Program Files (x86)\Odoo
 11.0\server\odoo\addons\pos_sale\models\crm_team.py", line 90, in _graph_data
     result.append({'x_value': fields.Date.to_string((fields.datetime.strptime(data_point.get('date:day'),
 "%d %b %Y"))), 'y_value': data_point.get('price_total')})   File
 "C:\Program Files (x86)\Odoo 11.0\python\lib\_strptime.py", line 565,
 in _strptime_datetime
     tt, fraction = _strptime(data_string, format)   File "C:\Program Files (x86)\Odoo 11.0\python\lib\_strptime.py", line 362, in _strptime
     (data_string, format)) ValueError: time data '31 Oct 2018' does not match format '%d %b %Y'
</code>
It seems like a data issue or locale configuration, but this is the only report going in exception and it is not clear how to check data on db (on which entity) any suggestion will be appreciated.
Answer: As of suggestion I would like you to look in following things,

Use type(fields.Date.to_string((fields.datetime.strptime(data_point.get('date:day')) to know what datatype your are getting & does it match with your field 'x_value' datatype?
Use like this fields.datetime.strptime(str(date), dayformat).date()