text:
Q: redefinition; previous definition was 'typedef' error I got the following error:

error C2365: 'DECIMAL' : redefinition; previous definition was 'typedef'

for the following definition in the header file:
enum DATA_TYPE {DECIMAL, HEXA, STRING};

I understood that this error occur by duplicate definitions, but there isn't another known defintion like that, and there aren't including files in this header file.
Which other reasons can cause that error?

A: Somewhere in your included header files, or the files they include ad infinitum, there is a definition of DECIMAL as a typedef.
Do not go looking for it! Well, do if you really want to but you aren't going to be able to do anything about it. Just rename your enum to something sensible like DT_DECIMAL.
If you really want to keep using DECIMAL and avoid this error there are two strategies. One is to use namespaces, to put your names into a different namespace from that other pesky definition.
The other (old school) way is to use a masking macro definition.


text:
Q: ExcelLibrary.DataSetHelper.CreateWorkbook("MyExcelFile.xls", ds); Line gives an error, Why? I want to export my database to an Excel worksheet. I'm using Visual Studio 2017.
I tried Microsoft.Office.Interop.Excel;
        SqlConnection conDataBase = new SqlConnection(conString);
        SqlCommand cmdDatabase = new SqlCommand("Select * from Table_2 ;",conDataBase);

        try
        {
            SqlDataAdapter sda = new SqlDataAdapter();
            sda.SelectCommand = cmdDatabase;
            DataTable dbdataset = new DataTable();
            sda.Fill(dbdataset);
            BindingSource bsource = new BindingSource();

            /*  bsource.DataSource = dbdataset;
            dataGridView1.DataSource = bsource;
            sda.Update(dbdataset);
            */

            DataSet ds = new DataSet("New_DataSet");
            ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
            sda.Fill(dbdataset);
            ds.Tables.Add(dbdataset);
            ExcelLibrary.DataSetHelper.CreateWorkbook("MyExcelFile.xls", ds);
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

A: I would recommend using SSMS to do this rather than Visual Studio. You can use the Wizard tool within SQL Server to export data to an excel file and you can create an SSIS package if you need to do this on an ongoing basis. See this article for additional info How to import and Export SQL Server data to an Excel File
If you really do want to use Interop it may be better to explicitly export each table.
//Launch an Excel session
        Application excelapp = new Application();
        excelapp.Visible = true;

        _Workbook workbook = (_Workbook)(excelapp.Workbooks.Add(Type.Missing));
        _Worksheet worksheet = (_Worksheet)workbook.ActiveSheet;

        //Create Worksheet Headers
        worksheet.Cells[1, 1] = "Order number";
        worksheet.Cells[1, 2] = "Delivery carrier";
        worksheet.Cells[1, 3] = "Shipper arrive early";
        worksheet.Cells[1, 4] = "Shipper city";
        worksheet.Cells[1, 5] = "Shipper state";
        worksheet.Cells[1, 6] = "Consignee arrive early";
        worksheet.Cells[1, 7] = "Consignee city";
        worksheet.Cells[1, 8] = "Consignee state";
        worksheet.Cells[1, 9] = "BOL";
        worksheet.Cells[1, 10] = "Consignee reference";
        worksheet.Cells[1, 11] = "Shipper actual arrival";
        worksheet.Cells[1, 12] = "Shipper actual departure";
        worksheet.Cells[1, 13] = "Status";
        worksheet.Cells[1, 14] = "Consignee actual arrival";
        worksheet.Cells[1, 15] = "Consignee actual departure";

        int row1 = 1;

        //Format text type in excel
        worksheet.Cells[1, 1].EntireColumn.NumberFormat = "@";

        //Write Data to Each Row of Worksheet
        foreach (DB_DataSet.Row row in report_Data)
        {
            row1++;

            worksheet.Cells[row1, 1] = row.Order_number;
            worksheet.Cells[row1, 2] = row.Delivery_Carrier;
            worksheet.Cells[row1, 3] = row.Shipper_arrive_early;
            worksheet.Cells[row1, 4] = row.Shipper_city;
            worksheet.Cells[row1, 5] = row.Shipper_state;
            worksheet.Cells[row1, 6] = row.Consignee_arrive_early;
            worksheet.Cells[row1, 7] = row.Consignee_city;
            worksheet.Cells[row1, 8] = row.Consignee_state;
            worksheet.Cells[row1, 9] = row.BOL;
            worksheet.Cells[row1, 10] = row.Consignee_reference;
            worksheet.Cells[row1, 11] = row.Shipper_Actual_Arrival;
            try { worksheet.Cells[row1, 12] = row.Shipper_Actual_departure; } catch { }
            try { worksheet.Cells[row1, 13] = row.status; } catch { }
            try { worksheet.Cells[row1, 14] = row.Consignee_actual_arrival; } catch { }
            try { worksheet.Cells[row1, 15] = row.Consignee_actual_departure; } catch { }

            //Format Worksheet
            worksheet.Cells[row1, 15].EntireRow.Font.Name = "Arial";
        }

Thank you,
Joseph

redpajama_set_name: RedPajamaStackExchange


text:
Q: while loop and getchar() I have the simple program below that I wrote for a college course. I know it doesn't really do anything, but it's just an assignment for a course.
The part that I can't figure out, is why doesn't the outer loop work?
The user needs to press '1' to continue, and any other key the program exits.
However, it still doesn't continue if the user presses '1' and instead exits anyway.
I tried adding a cin.clear() before cin >> repeat, but that doesn't work.
I also tried playing around with cin.ignore(), but that didn't seem to help either.
Any ideas?
Thanks
int main()
{
    int repeat = '1';
    stack<char> cstr;
    char c;

    while (repeat == '1')
    {
        cout << "Enter in a name: ";

        while (cin.get(c) && c != '\n')
        {
            cstr.push(c);
        }

        cout << "\n Enter another name? 1 = Continue, any other key to exit the program";
        cin >> repeat;
        repeat = getchar();
   }
}

A: There is nothing at all wrong with your code. It seems to be working fine for me.
EDIT: Sorry it doesn't work until you remove the getchar. Forgot to mention that. Simple way of finding out the error is to just display the value of the variable repeat to see what the value is and where it is going wrong.
Screenshot to show you that your codes work

Everything seems to be working fine. I would like to comment on your program structure though. For small programs like this it's ok but always best to practice the logical way. For questions like this you should implement the do while loop instead of the while loop so that it goes in without checking and then accepts the user input and checks with the post condition. Example below.
    char  repeat;

    do
    {
        //Your codes in here
    }while (repeat == '1');

It is more logical to use this method instead unless your question specifies you to use while loop. Anyhow hope this helps.

A:    cin >> repeat;

it reads repeat as int. (1 is not equal '1')
repeat = getchar();

It reads int code of special char '\n' - symbol end of line.
You must use
char repeat = '1';

Or write
int repeat = 1;

and not use getchar()

A: Run this . it will solve your problem somehow repeat=getchar was making repeat=10.
 int main()
    {
    char  repeat = '1';
    stack<char> cstr;
    char c;

    while (repeat == '1')
    {
        cout << "Enter in a name: ";
        cin.ignore();
        while (cin.get(c) && c != '\n')
        {
            cstr.push(c);
        }

        cout << "\nEnter another name ? \nPress 1 to Continue : ";
        cin >> repeat;
        cout << endl;
    }
    system("pause");
    }

A: The line cin >> repeat is tring to read an integer from the keyboard because repeat is a variable of type int. However, you are verifying if the integer read from the keyboard is equal to 49 (the ASCII code for the character '1'), which is not what you want. A solution would be to replace the line
int repeat = '1';

with
int repeat = 1;

and also replace
while (repeat == '1')

with
while (repeat == 1)

because then you are comparing the integer read from the keyboard with the integer 1 (rather than the character '1'). Also, at the end of the loop you read input from the keyboard and store it in repeat but then you immediately read input again and store that value in repeat, replacing its previous value. To solve this, replace the line
repeat = getchar();

with
getchar();

and that should do it.


text:
Q: Android service when device restarted not working Is any way that when device be turned off and turned on again
our android service be active again without activity
(Does not have to call an activity)?


text:
Q: jquery create html add javascript event not working I created html using jquery and added a javascript event command in tag html. Compile is invalid
ex.
var text = 'abc';
var id = 1;
html = "

";

Compile

How do I fix it?

A: It looks like your second single quote is closing the onclick value, replace the single quotes around text with escaped double quotes.
Try replacing this line
html = "

";

Or since attribute values will end up with double quotes anyway,
html = '

';

A: You can use Template literals like the following way:

var text = 'abc';
var id = 1;
var html = `<tr onclick="test(${id},'${text}')"><td>Sample Data</td></tr>`;
document.querySelector('table tbody').insertAdjacentHTML('beforeend', html);

function test(elId, elText){
  console.log(elId + '::' + elText);
}

A: create element and add event using jquery

var text = 'abc';
var id = 1;

html = $('
click Me!
').click(function() {
  test(id, text);
})

$('table').append(html);

function test(id, txt) {
  console.log(id, txt);
}


text:
Q: Sending documents with API and setting SignHere AnchorString vs Field Locators I am new to Docusign so I'm testing the API.  I can send a document and ask for signatures in the places I need using the SignHere data structure and setting the AnchorString as defined in the guide in tab placement method 2.
I also read about Field Locators here and I thought they were for this purpose but they don't seem to work with the SignHere data structure so what is the purpose of them?
Thanks for any help.

A: The two things are you are referring to are related to two different products and two different APIs and cannot be mixed.
If you are going to use the DocuSign eSignature API, you can use the AhcorString, or you can specify X/Y coordinates for the SignHere tags.
The second link you had posted talking about the DSA, which is DocuSign Appliance and is a different technology (Digital Signature instead of Electronic Signature) and is not related to the SignHere tags


text:
Q: css is not loading even path of css is correct I have written
<link media="all" type="text/css"
href="www.nysci.org.php53-14.ord1-1.websitetestlink.com/wp-content/themes/nysci/custom.css"
rel="stylesheet">

in my header but it is not loading css
can any body please give me a solution?
url is http://www.nysci.org.php53-14.ord1-1.websitetestlink.com/

A: change your code
from this
  href="www.nysci.org.php53-14.ord1-1.websitetestlink.com/wp-content/themes/nysci/custom.css"

to
 href="http://www.nysci.org.php53-14.ord1-1.websitetestlink.com/wp-content/themes/nysci/custom.css"

A: Try to www.nysci.org.php53-14.ord1-1.websitetestlink.com/wp-content/themes/nysci/custom.css, because in your given URL it it takes http://www.nysci.org.php53-14.ord1-1.websitetestlink.com/www.nysci.org.php53-14.ord1-1.websitetestlink.com/wp-content/themes/nysci/custom.css

A: The issue is that your CSS file is getting a 404 HTTP error. So you need to change the link from
href="www.nysci.org.php53-14.ord1-1.websitetestlink.com/wp-content/
themes/nysci/custom.css"

to this:
href="//www.nysci.org.php53-14.ord1-1.websitetestlink.com/wp-content/
themes/nysci/custom.css"

When you have the initial link, you will see that the resource file is empty. But once you add // and then open the file, you will see the styling tech in the Inspector's Style tab.


text:
Q: add Exists operator in a union sql query I have two tables that am using union to combine the result-set of them my problem here is Each SELECT statement within UNION must have the same number of columns and data types, I don't have the same number of columns so am creating null columns
select
d.deal_id as order_id,
EXISTS(select * from table1 c where d.user_id = c.user_id) as IsUser, --this returns boolean value
from table 1 c
union
select
cast(o.id as varchar) as order_id,
coalesce('No_user'::text,'0'::text) as IsUser, --i get an error :UNION types boolean and character varying cannot be matched
from table2 o

how can I create a null column in table2 that matches the boolean data type of the table1

A:
how can I create a null column in table2 that matches the boolean data type of the table1

By putting NULL into the SELECT list of the second query.
Generally (in SQL) the datatype for the column is dictated by the first query in the union set and other queries must match. You don't need column aliases for subsequent queries either, but they may help make a query more readable:
select
  d.deal_id as order_id,
  EXISTS(select * from table1 c where d.user_id = c.user_id) as IsUser, --this returns boolean value
from table 1 c
union
select
  cast(o.id as varchar) as order_id,
  null --IsUser
from table2 o

If you have a case where the type of the column in the first query is different to what you want in the output, you cast the first column:
select 1::boolean as boolcol
UNION
select true

This will ensure that the column is boolean, rather than giving a "integer and bool cannot be matched". Remember also that, should you need to, NULL can be cast to a type, e.g. select null::boolean as bolcol


text:
Q: there is no unique constraint matching given keys for referenced table PostgreSQL I have created an ER diagram by using PostgreSQL and try to create tables according to exported .sql file but I get an error. I might do a structural fault. If you notice a structural mistake about Entity Relationship Diagram can you explain me?
Error:
Error image
Here is my ER diagram:
ER DIAGRAM IMAGE
Here is my exported SQL Script:
BEGIN;

CREATE TABLE public."Persons"
(
    id bigserial NOT NULL,
    name character varying(30) NOT NULL,
    surname character varying(30) NOT NULL,
    email character varying(30),
    PRIMARY KEY (id)
);

CREATE TABLE public."System_Personals"
(
    id bigserial NOT NULL,
    PRIMARY KEY (id)
);

CREATE TABLE public."Job_Seekers"
(
    id bigserial NOT NULL,
    ssn character(11) NOT NULL,
    birth_date date NOT NULL,
    password character varying(30) NOT NULL,
    PRIMARY KEY (id)
);

CREATE TABLE public."Employers"
(
    id bigserial NOT NULL,
    company_name character varying(30) NOT NULL,
    website character varying(40) NOT NULL,
    phone_number character(11) NOT NULL,
    password character varying(30) NOT NULL,
    PRIMARY KEY (id)
);

CREATE TABLE public."Jobs"
(
    id bigserial NOT NULL,
    role character varying(30) NOT NULL,
    definition character varying(500) NOT NULL,
    PRIMARY KEY (id)
);

CREATE TABLE public."Job_Announcements"
(
    id bigserial NOT NULL,
    title character varying(100) NOT NULL,
    company_name character varying(30) NOT NULL,
    role character varying(30) NOT NULL,
    city_name character varying(30) NOT NULL,
    salary bigint NOT NULL,
    job_definition character varying(300) NOT NULL,
    PRIMARY KEY (id)
);

CREATE TABLE public."Cities"
(
    id bigserial NOT NULL,
    name character varying(30) NOT NULL,
    PRIMARY KEY (id)
);

CREATE TABLE public."Activations"
(
    id bigserial NOT NULL,
    email character varying(30) NOT NULL,
    PRIMARY KEY (id)
);

CREATE TABLE public."Employer_Activations"
(
    id bigserial NOT NULL,
    PRIMARY KEY (id)
);

CREATE TABLE public."Job_Seeker_Activations"
(
    id bigserial NOT NULL,
    ssn character(11) NOT NULL,
    PRIMARY KEY (id)
);

ALTER TABLE public."System_Personals"
    ADD FOREIGN KEY (id)
    REFERENCES public."Persons" (id)
    NOT VALID;

ALTER TABLE public."Job_Seekers"
    ADD FOREIGN KEY (id)
    REFERENCES public."Persons" (id)
    NOT VALID;

ALTER TABLE public."Employers"
    ADD FOREIGN KEY (id)
    REFERENCES public."Persons" (id)
    NOT VALID;

ALTER TABLE public."System_Personals"
    ADD FOREIGN KEY (id)
    REFERENCES public."Jobs" (id)
    NOT VALID;

ALTER TABLE public."Employers"
    ADD FOREIGN KEY (id)
    REFERENCES public."Cities" (id)
    NOT VALID;

ALTER TABLE public."Job_Announcements"
    ADD FOREIGN KEY (city_name)
    REFERENCES public."Cities" (name)
    NOT VALID;

ALTER TABLE public."Job_Announcements"
    ADD FOREIGN KEY (role)
    REFERENCES public."Jobs" (role)
    NOT VALID;

ALTER TABLE public."Job_Announcements"
    ADD FOREIGN KEY (job_definition)
    REFERENCES public."Jobs" (definition)
    NOT VALID;

ALTER TABLE public."Employer_Activations"
    ADD FOREIGN KEY (id)
    REFERENCES public."Activations" (id)
    NOT VALID;

ALTER TABLE public."Job_Seeker_Activations"
    ADD FOREIGN KEY (id)
    REFERENCES public."Activations" (id)
    NOT VALID;

ALTER TABLE public."Job_Seeker_Activations"
    ADD FOREIGN KEY (ssn)
    REFERENCES public."Persons" (id)
    NOT VALID;

ALTER TABLE public."Activations"
    ADD FOREIGN KEY (email)
    REFERENCES public."Persons" (email)
    NOT VALID;

END;

Why I get that error? Any help?

A: All of these are in violation:
ALTER TABLE public."Job_Announcements"
    ADD FOREIGN KEY (city_name)
    REFERENCES public."Cities" (name)
    NOT VALID;

ALTER TABLE public."Job_Announcements"
    ADD FOREIGN KEY (role)
    REFERENCES public."Jobs" (role)
    NOT VALID;

ALTER TABLE public."Job_Announcements"
    ADD FOREIGN KEY (job_definition)
    REFERENCES public."Jobs" (definition)
    NOT VALID;

ALTER TABLE public."Activations"
    ADD FOREIGN KEY (email)
    REFERENCES public."Persons" (email)
    NOT VALID;

The manual:

A foreign key must reference columns that either are a primary key or form a unique constraint.


text:
Q: Remove spaces when amending a text file using Python Good Day,
I am a new here an new to coding so worry if this a silly question.
I need some help! I have the following Python code that amends a line in a text file. However, every time I run it, it adds spaces before each word in the text file. Does anyone know why?
with open ("sheepfile.txt",'r') as My_Sheep:
    data = My_Sheep.readlines()

with open ("sheepfile.txt",'w') as My_Sheep: # opens the text file as 'w'
    for I, line in enumerate(data, 1):
        if I == Line_num:
        My_Sheep.writelines( '%s, %s, %s, %s' % (Update_Sheep))
    else:
        My_Sheep.writelines(line)

My_Sheep.close() # close the file

So the text file as the following original text
Matt,1,A,Blue
Katy,34,B,Pink
Isobel,32,C,Yellow

But when I run the code and say change age of Matt to 2, I get:
Matt,2, A, Blue
Katy,34,B,Pink
Isobel,32,C,Yellow

There is now a space before the 'A' and a space before 'Blue'
A further space will appear ever time run the code. Does anyone know how I can get rid of them or stop them from appearing?


text:
Q: Linear Independence I've come across a question in Linear Algebra that I can't quite figure out. I've tried a multitude of things that either don't work or aren't sufficient enough to convince me I understand linear independence well enough.
I know a set of vectors, S, in vector space V are linearly independent if their linear combination, that is,
$\lambda_1 \mathbf{v}_1 + ... + \lambda_n \mathbf{v}_n = \mathbf{0}$
means all scalars are equal to each other and 0,
$\lambda_1 = ... = \lambda_n = 0.$
I can also show a set of vectors S is linearly independent if I'm given a set of vectors with numerical values - by creating a matrix and reducing it to row echelon form. However, my understanding isn't great enough that I can expand on this and answer questions such as the following:
Assume the vectors u, v and w are linearly independent elements of a vector space V.
For each of the following sets decide whether it is linearly independent.
A. {u + v + w,  v - 2w,  2u + 3w}
B. {u + 2w, v + 2w, 2w}
C. {x, y, z}
where,
x = u + 2v - w,
y = 2x + u + 2v - w,
z = 3x - 2y.
If anyone can explain to me the connection between this type of question and the definition of linear independence by answering A or providing a guideline of how to answer A then hopefully I can tackle B and C and any related questions. Thanks.

A: Hint: In both cases, write the coordinates of the vectors in the set with respect to the original set as rows in a matrix. Row reduce this matrix.

A: You basically need to write the definition of linear independence. Suppose that
$$
\alpha(u+v+w)+\beta(v-2w)+\gamma(2u+3w)=0.
$$
We can rewrite this as
$$
(\alpha+2\gamma)\,u+(\alpha+\beta)\,v+(\alpha-2\beta+3\gamma)\,w=0.
$$
Since $u,v,w$ are linearly independent, we get the equalities
$$
\alpha+2\gamma=0,\ \ \alpha+\beta=0,\ \ \alpha-2\beta+3\gamma=0.
$$
Now you can analyze this system. If the only solution is $\alpha=\beta=\gamma=0$, you'll know that the three vectors in A are linearly independent. If you produce a nonzero solution, you'll know that they are linearly dependent.

A: You just need to use the definition. For the first case you can write:
$$\lambda_1(u+v+w)+\lambda_2(v-2w)+\lambda_3(2u+3w)=0$$
now rewrite like:
$$(\lambda_1+2\lambda_3)u+(\lambda_1+\lambda_2)v+(\lambda_1-2\lambda_2+3\lambda_3)w=0$$
Now use that $u,v,w$ are independent, solve the system and find $\lambda_1,\lambda_2,\lambda_3$.
Can you finish?

A: for A: we have
$$\alpha(u+v+w)+\beta(v-2w)+\gamma(2u+3w)=0$$
this is equivalant to
$$u(\alpha+2\gamma)+v(\alpha+\beta)+w(\alpha-2\beta+3\gamma)=0$$
can you finish?
for B: we get
$$u\alpha=0,v\beta=0,w(2\alpha+2\beta+2\gamma)=0$$


text:
Q: Do email pattern check for md-chips tag I want to check email pattern to Angular-Material md-chips tag given below, type="email" not working.
<md-chips ng-model="ctrl.emails" md-separator-keys="ctrl.customKeys" type="email" ></md-chips>


text:
Q: Changing Screen Resolution and Scaling in one Batch file, and Launch a .exe file as well I wanna set the screen resolution of screen 1 to a predetermined value of 1872 x 1248 then set scaling to 100% then launch a .exe file from a folder, and once the exe is closed revert the screen automatically back to 3240 x 2160 and 200% scaling.
EDIT1:
Batch command to change the resolution of a computer
this one helped me set the resolution and it works fine:
  ChangeScreenResolution.exe /w=1872 /h=1248 /d=0

allFiles.exe

/wait allFiles.exe
ChangeScreenResolution.exe /w=3240 /h=2160 /d=0

But I couldn't find any resources on how to set resolution scaling at all, that's the missing bit, I'm fairly sure it can be done, but I don't know how.
How can it be done?
Thanks

A: So thanks to @Compo I figured out how it can be done:
https://github.com/imniko/SetDPI
https://tools.taubenkorb.at/change-screen-resolution/
And these 2 can do the trick for anyone interested:
::This bit changes Screen Resolution of Display1 to 1872 x 1248
::ChangeScreenResolution.exe [/w=1872 Horizontal Pixels] [/h=1248 Vertical Pixels] [/d=0 Means Display1]
ChangeScreenResolution.exe /w=1872 /h=1248 /d=0

::This bit changes this bit changes the scaling for Display1 to 125%
:: SetDPI.exe [Display Number 1 - means Display1] [Scaling %]
SetDPI.exe 1 125

::This bit starts allFiles.exe and goes on to the next line ONLY AFTER IT'S CLOSED
allFiles.exe /wait

::This bit sets resolution back to original
::ChangeScreenResolution.exe [/w=3240 Horizontal Pixels] [/h=2160 Vertical Pixels] [/d=0 Means Display1]
ChangeScreenResolution.exe /w=3240 /h=2160 /d=0

::This bit sets scaling back to original
:: SetDPI.exe /[Display Number 1 - means Display1] /[Scaling %]
SetDPI.exe 1 200

Thanks guys, it works like a charm now!


text:
Q: URL redirecting to wrong place when urls are similar Here is part of my .htaccess file.
RewriteEngine On
RewriteBase /example/

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^\.]+)$ $1.php [NC,L]

RewriteRule tilaukset home.php?page=orders
RewriteRule tilaustenhallinta home.php?page=ordersManage
RewriteRule jarjestelmaraportit home.php?page=ordersReports
RewriteRule kaikki-tilaukset home.php?page=allOrders
RewriteRule keskeneraiset-tilaukset home.php?page=inProgressorders
RewriteRule valmiit-tilaukset home.php?page=completedOrders
RewriteRule tuotannossa-tilaukset home.php?page=inProductionorders
RewriteRule lahetetyt-tilaukset home.php?page=shippedOrders

By clicking this element Tilaukset it redirects to correct place (which is orders.php), but when I click another link with different properties Kaikki tilaukset it still opens the same file. When I remove "tilaukset" from "Kaikki tilaukset" and just leave it as "Kaikki". Like so:
RewriteRule kaikki home.php?page=allOrders

It works correctly and nothing bad happens. For some reason it doenst check the whole argument. It finds same word and then uses that. How to fix this?

A: This line :
RewriteRule tilaukset home.php?page=orders

means any URI contains tilaukset it will capture a kaikki-tilaukset as well
change it to :
RewriteRule ^tilaukset home.php?page=orders

This ^ means start with tilaukset .
The other Rule:
RewriteRule kaikki-tilaukset home.php?page=allOrders

Should work fine right now.


text:
Q: Search repos with GitHub API using date query If I make the following GET request to the GitHub API, I get about 58 entries:
https://api.github.com/search/repositories?&per_page=250&sort=updated&order=asc&q=%22github-octocat%22

However, the following with any date parameters return 0 entries:
Created since date: ( created:>=2010-09-01 )
https://api.github.com/search/repositories?&per_page=250&sort=updated&order=asc&q=%22github-octocat+created:>=2010-09-01%22

Date range: ( created:2012-08-13..2020-08-14 )
https://api.github.com/search/repositories?&per_page=250&sort=updated&order=asc&q=%22github-octocat+created:2012-08-13..2020-08-14%22

In the GitHub docs, under the section Constructing a search query, the syntax is outlined as such:
SEARCH_KEYWORD_1 SEARCH_KEYWORD_N QUALIFIER_1 QUALIFIER_N
Thei GitHub docs at Search by when a repository was created or last updated outlines date formats like the two above, and Query for values between a range outlines valid combinations of them. I suspect these examples are not meant for this use, as the examples use URLs intended for browsers, such as https://github.com/search?q=case+pushed%3A%3E%3D2013-03-06+fork%3Aonly&type=Repositories, instead of api.github.com, which is confusing too.
I'm trying to apply the patterns shown in the following resources in order to get a range of dates filter:

*

*Github API call: filter by committer-date, answer by Poonacha

*Get issues on a date range from Github enterprise API, answer by Al Neill
Any pointers greatly appreciated.

A: Even though the GitHub docs outlines the syntax as such:
SEARCH_KEYWORD_1 SEARCH_KEYWORD_N QUALIFIER_1 QUALIFIER_N

the parameters for date or similar, are not valid unless placed outside the q parameter. Instead of including date qualifier inside of the double quotes (shown as %22 below):
q=%22mysearch+pushed%3A2017-09-01..2020-10-01+sort:updated%22

Pull them out, and add them after the closing quote of the q parameter:
q=%22mystring%22+pushed%3A2017-09-01..2020-10-01+sort:updated


text:
Q: Get id of a checkbox? - jQuery Hey, I am wondering how to get the id of a checkbox when it is checked.
This is what my HTML would probably look like at first:

        <input type="checkbox" id="check1" />Marketing
        <input type="checkbox" id="check2" />Automotive
        <input type="checkbox" id="check3" />Sports

I'm assuming the jQuery would look something like this:
$(document).ready(function() {
    $(":checkbox").click(function(){
        var id = $(this).attr('id');

        $.post("index.php", { id: id });
       //return false to ensure the page doesn't refresh
       return false;
    });
});

I'm trying to get the checked item id and then post that id in a mysql query to grab the results of the id from the database.
Thanks for any help on this.

A: The jQuery you provided works fine? You should probably remove the return false to show that the checkbox has been checked.
EDIT: $.post() is for an async request (AJAX technique) so there will be no page refresh.
EDIT 2: You may also want to see if the checkbox is checked (not just that it has been clicked):
$(document).ready(function() {
  $(":checkbox").click(function(){
        var id = $(this).attr('id');
        var isChecked = $(this).attr('checked'));
        $.post("index.php", { id: id, isChecked: isChecked });
    });
});

A: You can use the :checkbox selector and then check the id and checked properties of the DOM element like so:
var id = $(this).find(":checkbox")[0].id;
var isChecked = $(this).find(":checkbox")[0].checked;

A: You probably want the change event here, like this:
$(function() {
  $(":checkbox").change(function(){
    $.post("index.php", { id: this.id, checked: this.checked });
  });
});

This posts whenever a checkbox changes, and lets the PHP side know the ID and whether it's checked or not.

A: You can better use jQuery get instead of post. It allows you to handle the output of your request: http://api.jquery.com/jQuery.get/
Example:
$(document).ready(function() {
  $(':checkbox').click(function(){
        var id = $(this).attr('id');
        var isChecked = $(this).attr('checked'));
        $.get(
          'getcheckbox.php',
          { id: id, isChecked: isChecked },
          function(data) {
            //return value in getcheckbox.php and use it in on complete function
            var result = data;
          }
        );
    });
});

A: Why do I only need this for the name of a checkbox, but $(this) in order to access the value
$('input:checkbox').change( function() {
        console.log("here i am: " + this.name + " value = " + $(this).val() );
        }
    );


text:
Q: R (RShiny) equivalent of layer_data function for other types of plots I am building an RShiny-app where I am creating a plot based on a data table which I can edit and another data table which I cannot. I eventually want to save all data points on the plot in a data table which I can display and export.
I have seen many ways to do this using ggplot (ie layer_data, ggplot_build), but no efficient ways when just using plot and lines. My plots will be getting quite complicated so it would be really helpful to find an easy way to do this rather than hardcoding everything in.
A very simple example of my code is below (Note: plots will be getting much more complicated than this. They will be line graphs, but I will just need the y values at each x value marked with a number on the x axis):
x <- data.frame('col_1' = c(1,2,3,4,5), 'col_2' = c(4,5,6,7,8))
y <- data.frame('col_1' = c(5,4,3,6,7), 'col_2' = c(1,2,3,4,5))

#import necessary libraries
library(shiny)
library(DT)
library(shinythemes)
library(rhandsontable)

#ui
ui <- fluidPage(theme = shinytheme("flatly"),
                titlePanel("Test"),
                sidebarLayout(
                  sidebarPanel(

                    #display data
                    rHandsontableOutput('contents'),
                    #update plot button
                    actionButton("go", "Plot Update"),
                    width=4

                  ),
                mainPanel(

                  tabsetPanel(
                    #plot
                    tabPanel("Plot", plotOutput("plot_1")) )
                ))
)

#server
server <- function(input, output, session) {

  #data table
  output$table_b <- renderTable(x)

  indat <- reactiveValues(data=y)

  observe({
    if(!is.null(input$contents))
      indat$data <- hot_to_r(input$contents)

  })

  output$contents <- renderRHandsontable({
    rhandsontable(indat$data)
  })

  #save updated data
  test <- eventReactive(input$go, {
    live_data = hot_to_r(input$contents)
    return(live_data)
  })

  #plot
  output$plot_1 <- renderPlot({

    plot(x[,1],x[,2],col='red',type = 'l')
    lines(test()[,1],x[,2], col='black', type='l')

    # need a way to grab data from plot a create a table
  })
}

shinyApp(ui, server)


text:
Q: how to query nested array mongodb I'm new to mongodb, and I'm trying to make a database that has posts and tags, where each post can have numerous tags, something like this (simplified)
posts: [
 post:{
   id: dkdkd,
   title: hello,
   body: hello world,
   tags: [1,2,3]
 },
 post:{
   id: ccc,
   title: hello2,
   body: hello world2,
   tags: [3,4,5]
 }
]

how can I get a list of all the tags? (i.e. returns [1,2,3,4,5])

A: You may use something like this to get all tags per document:
db.collection.aggregate([
{
  $project: {
    _id: 0,
    tags: {
      $reduce: {
        input: "$posts.post.tags",
        initialValue: [],
        in: {
          "$setUnion": [
            "$$value",
            "$$this"
          ]
        }
      }
    }
  }
}
])

Explained:
Project the array posts.post.tag and apply reduce operation with $setUnion between all documents tag array elements to receive distinct list of tags
playground
And something like this to take distinct tags per collection:
db.collection.aggregate([
{
$project: {
  _id: 0,
  tags: {
    $reduce: {
      input: "$posts.post.tags",
      initialValue: [],
      in: {
        "$setUnion": [
          "$$value",
          "$$this"
          ]
        }
      }
    }
  }
},
{
  $group: {
  _id: "Total",
  tags: {
    "$push": "$tags"
    }
  }
},
{
$project: {
  _id: 0,
  tags: {
    $reduce: {
      input: "$tags",
      initialValue: [],
      in: {
        "$setUnion": [
          "$$value",
          "$$this"
          ]
        }
      }
    }
  }
}
])

Explained:
1.project all tags per document.
2. Group all tags from collection.
3. setUnion to all tags arrays in collection.
playground2


text:
Q: Screen Scraping with Ruby on Rails Am a newbie in RoR. I want to develop a rails app, which could search flight info from my rails app, fetch the flight informations from various airlines sites(for example; airasia and malaysia airlines).  display those results back in my rails app.
My search module should include the following textfields:
From: Kuala Lumpur
To: Dubai
Departure Date:2/11/2009
Return date: 19/11/2009
Departure Time: 12:00
Number of tickets: 2

user gets to enter the information above on my site and
a script should search flights according to that information on various airlines sites and
display the results with the tag of which airlines is providing this flight.
Can either use "Scrapi" or "Scrubyt"

A:
can anyone offer an assistance?

Don't. Find another get rich quick scheme. Or at least don't rely on screen scraping.
There's so much potential for it to go wrong. Find another way to get the information to aggregate. Use API's if they exist and store the schedules in the databases (they rarely change on a week to week basis). Storing things locally makes things faster for your customers, it also allows you to provide more services.
Here are just a few of the potential problems with screen scraping:

*

*Minor updates to the sites you're scraping can break your tool.

*Scraping attempts from your server's IP can be denied.

*Depending on the information, you could possibly even get sued.

A: To start with scraping, you can refer to the post -
http://rorguide.blogspot.com/2011/04/simple-ruby-screen-scraper-using.html
(Simple Ruby Screen Scraper using Mechanize, Hpricot and XPath )
http://rorguide.blogspot.com/2011/04/simple-ruby-screen-scraper-in-just-5.html
(Simple Ruby Screen Scraper in just 5 lines without using XPath )
This is just for understanding

A: cough cough watir-webdriver (gem)
the DOM cannot hide


text:
Q: From react-admin v3 to v4 I am new to react-admin, and i'd like to implement custom forms for related records.
I found this on the doc but the code doesn't seem to work for version 4 anymore.
I'd like to do the same. Open a modal for the related record.
Is there any v4 example ?

A: React-admin v4 has built-in support for related record creation, see the Creating new choices documentation.
import { SelectInput, Create, SimpleForm, TextInput } from 'react-admin';

const PostCreate = () => {
    const categories = [
        { name: 'Tech', id: 'tech' },
        { name: 'Lifestyle', id: 'lifestyle' },
    ];
    return (
        <Create>
            <SimpleForm>
                <TextInput source="title" />
                <SelectInput
                    onCreate={() => {
                        const newCategoryName = prompt('Enter a new category');
                        const newCategory = { id: newCategoryName.toLowerCase(), name: newCategoryName };
                        categories.push(newCategory);
                        return newCategory;
                    }}
                    source="category"
                    choices={categories}
                />
            </SimpleForm>
        </Create>
    );
}


text:
Q: Why does label need sizeToFit? If sizeToFit is not called, the label is invisible. Why is this?
class RootViewController: UIViewController {

    override func loadView() {

        let v = UIView()

        v.backgroundColor = .green

        self.view = v

        let label = UILabel()
        v.addSubview(label)
        label.text = "Hello, World!"

        label.autoresizingMask = [
            .flexibleTopMargin,
            .flexibleLeftMargin,
            .flexibleBottomMargin,
            .flexibleRightMargin]
        label.sizeToFit()
        label.center = CGPoint(v.bounds.midX, v.bounds.midY)
        label.frame = label.frame.integral
    }

}

A: UIView() is the same thing as UIView(frame: CGRect.zero). So the default size of your label is zero. You're using manual layout, which means that the system won't automatically resize your label. So whatever size you assign to it is the size it will have. Your code isn't assigning a size anywhere except for the call to sizeToFit(). So if you don't call sizeToFit(), your label will retain the zero size that you created it with. sizeToFit() changes its size to fit its contents, so you can actually see it.


text:
Q: How to add this multidimensional matrix? i am totally new guy to javascript.I dont know how to add these two varible that  are in multidimensional array in matrix way.Would you pls suggest any npm module with
an example or the manual algorithm would be appreciated.
these are my two varibles
var MatrixA = [[13,5,0][11,6,4][10,7,2][9,8,0]]
var MatrixB =  [[103,50,0][11,60,40][10,70,20][90,80,0]]

A: Not sure what exactly you want
I am considering you want to add up all the numbers of these arrays
If so ,consider the following code snippet

var MatrixA = [[13,5,0],[11,6,4],[10,7,2],[9,8,0]];
var MatrixB =  [[103,50,0],[11,60,40],[10,70,20],[90,80,0]];
var sum=0;
for(var i=0;i<3;i++){
    for(var j=0;j<3;j++){
        sum+=MatrixA[i][j]+MatrixB[i][j];
    }

}
console.log(sum);

Hope this helps

A: Check the following code snippet

var MatrixA = [[13, 5, 0], [11, 6, 4], [10, 7, 2], [9, 8, 0]];
var MatrixB = [[103, 50, 0], [11, 60, 40], [10, 70, 20], [90, 80, 0]];
var sumMatrix = [[], [], []];
var j = 0
  , k = 0;
l = 0;
for (var i = 0; i < 3; i++) {
  for(var j=0;j<3;j++){
    sumMatrix[i][j]=MatrixA[i][j]+MatrixB[i][j];
  }
}for (var i = 0; i < 3; i++) {
  for(var j=0;j<3;j++){
    console.log(sumMatrix[i][j]);
    }
  }

Hope this helps

A: First of all you need to declare another 2d array, lets say sum=[[],[],[]] to store the sum in. Then all you need to do is simply add the the two matrices.
C code:
for(i=0;i<r;++i)
    for(j=0;j<c;++j)
    {
        sum[i][j]=a[i][j]+b[i][j];
    }

I have actually never really coded much in Javascript but was able to put together a program on an online compiler I am getting NaN. But still works, and gives output.
var MatrixA = [[13,5,0],[11,6,4],[10,7,2],[9,8,0]];
var MatrixB =  [[103,50,0],[11,60,40],[10,70,20],[90,80,0]];
var sum=[[],[],[],[]];

for (var i=0 ; i<MatrixA.length; i++ )

    for (var j=0;j<MatrixB.length; j++)
        {
             sum[i][j]=MatrixA[i][j]+MatrixB[i][j];
        }

for (var i=0 ; i<MatrixA.length; i++ )

    for (var j=0;j<MatrixB.length; j++)
        {
             console.log(sum[i][j]);
        }

A: May be you can do as follows;

var m1 = [[13,5,0],[11,6,4],[10,7,2],[9,8,0]],
    m2 = [[103,50,0],[11,60,40],[10,70,20],[90,80,0]],
result = m1.map((a,i) => a.map((n,j) => n + m2[i][j]));

console.log(JSON.stringify(result));


text:
Q: How to return different kind of values in a column in one record I have a table dict (id,dict_name,dict_id,dict_type) and table record(fruit_id,tool_id,lan_id).I need to query it and return three dict_name for the three given ids in record in one record.
For example
It will return three dict_name(apple,car,lisp when fruit_id = 100, tool_id = 1000, lan_id = 22222) when I use limit 1 in the query,
I have tried lots ways to query, like
 SELECT GROUP_CONCAT(DISTINCT(dict.dict_name))
 FROM dict
 JOIN record
 WHERE dict.dict_id IN (record.fruit_id, record.tool_id, record.lan_id)
 GROUP BY dict.type" //

But I only get one dict_name in every record,and dict_names in
{'group_concat(DISTINCT(dict.dict_name))': apple},

and thress dict_names  but in more than one records
{'group_concat(DISTINCT(dict.dict_name))': apple},
{'group_concat(DISTINCT(dict.dict_name))': car},
{'group_concat(DISTINCT(dict.dict_name))': lisp}

Thank you.
dict:
dict_name  //  dict_id  //  type

    apple  //      100  // fruit
     pear  //      101  // fruit
      car  //     1000  //  tool
      bus  //     1001  //  tool
     lisp  //    22222  //   lan
     perl  //    22223  //   lan

id_record
 fruit_id  //  tool_id  // lan_id

      100 //      1000  //  22222
      100  //     1000  //  22222
      100  //     1000  //  22223
      101  //     1001  //  22223
      101  //     1001  //  22223
      101  //     1001  //  22223

It seems One-to-Many SQL SELECT into single row may help.


text:
Q: Adding items to ListView repeats same XML element I have a listView box and I'm adding items into it. But it's giving me the same text/item for the idAtt and applicIDAtt elements in every row. The desc does update to a new value for every row.
Code
Public Sub loadFile()
    Dim doc As New XmlDocument()
    doc.Load(fileName)
    Dim LItem As New ListViewItem

    For Each node As XmlNode In doc.SelectNodes("/dmodule/content/faultIsolation/faultIsolationProcedure/faultDescr/descr")
        Dim idAtt = node.SelectSingleNode("//faultIsolationProcedure/@id").InnerText
        Dim desc As String = node.InnerText
        Dim applicIDAtt = node.SelectSingleNode("/dmodule/content/faultIsolation/faultIsolationProcedure/@applicRefId").InnerText

        Dim lv As ListViewItem = ListView1.Items.Add(idAtt)
        lv.SubItems.Add(desc)
        lv.SubItems.Add(applicIDAtt)
    Next
End Sub

Example XML
<dmodule>
<content>
    <faultIsolation>
        <faultIsolationProcedure applicRefId="Software" id="tree1">
            <fault faultCode=" "/>
            <faultDescr>
                <descr>This nodes description</descr>
            </faultDescr>
        </faultIsolationProcedure>
    </faultIsolation>
</content>

A: Your xpaths are a bit wonky; you're not really treating the document like a set of hierarchical nodes. If it helps, think of it like file paths and folders. Get the "folder" at a particular path and pull out its attributes/innertexts (files) but address it relatively from where you are
For Each node As XmlNode In doc.SelectNodes("/dmodule/content/faultIsolation/faultIsolationProcedure")
    Dim idAtt = node.Attributes("id").Value
    Dim desc As String = node.SelectSingleNode("faultDescr/descr").InnerText
    Dim applicIDAtt = node.Attributes("applicRefId").Value

Now, you didn't really post a usefully large XML document sample for me to work out exactly at what hierarchy level the nodes repeat themselves, so I assumed it's like this:
<dmodule>
    <content>
        <faultIsolation>
            <faultIsolationProcedure applicRefId=""Software"" id=""tree1"">
                <fault faultCode="" ""/>
                <faultDescr>
                    <descr>This nodes description</descr>
                </faultDescr>
            </faultIsolationProcedure>

            <faultIsolationProcedure applicRefId=""Software2"" id=""tree2"">
                <fault faultCode="" ""/>
                <faultDescr>
                    <descr>This nodes description2</descr>
                </faultDescr>
            </faultIsolationProcedure>
        </faultIsolation>
    </content>
</dmodule>

1 faultIsolation node has multiple faultIsolationprocedure nodes
Here's a complete code you can paste into some vb.net fiddle site and run to highlight the problem. Read the full code, including my comments. I put my code above and then your code, with a commentary on each, in comments in the VB:
Imports System
Imports System.Xml

Public Module Module1

    Public Sub Main()

        Dim doc As New XmlDocument()
        doc.LoadXml("<dmodule>
    <content>
        <faultIsolation>
            <faultIsolationProcedure applicRefId=""Software"" id=""tree1"">
                <fault faultCode="" ""/>
                <faultDescr>
                    <descr>This nodes description</descr>
                </faultDescr>
            </faultIsolationProcedure>

            <faultIsolationProcedure applicRefId=""Software2"" id=""tree2"">
                <fault faultCode="" ""/>
                <faultDescr>
                    <descr>This nodes description2</descr>
                </faultDescr>
            </faultIsolationProcedure>
        </faultIsolation>
    </content>
</dmodule>")

        '#####################################
        '                 my way
        '#####################################

        'treat /dmodule/content/faultIsolation/faultIsolationProcedure as a collection of nodes, do each one
        For Each node As XmlNode In doc.SelectNodes("/dmodule/content/faultIsolation/faultIsolationProcedure")

            'pull attribute by name
            Dim idAtt = node.Attributes("id").Value

            'pull a sub node relative to the current node, not the document root
            Dim desc As String = node.SelectSingleNode("faultDescr/descr").InnerText

            'pull attribute by name
            Dim applicIDAtt = node.Attributes("applicRefId").Value

            Console.WriteLine(idAtt)
            Console.WriteLine(desc)
            Console.WriteLine(applicIDAtt)

        Next

        Console.WriteLine("##############")

        '#####################################
        '              your way
        '#####################################
        For Each node As XmlNode In doc.SelectNodes("/dmodule/content/faultIsolation/faultIsolationProcedure/faultDescr/descr")

            'well it sort of works for the first one, because // is always the document root
            'in xpath, not the current node. The node you're looking at still knows of the
            'document and if you ask it to search for an xpath starting with // you're NOT
            'searching from the current node as a start point, but the doc root. this is why
            'you keep getting the same node, because the code goes back to the doc root and
            'pulls the first child node, which is always the same node!
            Dim idAtt = node.SelectSingleNode("//faultIsolationProcedure/@id").InnerText

            'this is OK - it works relative to the node you're currently on in the foreach
            'and it does return different descriptions each time
            Dim desc As String = node.InnerText

            'Again, this xpath starts with / which is "from the doc root" not "from the current node"
            '-because this doesn't have a double slash it has to be an exact path from the doc root
            'which is IS - it's a valid path and it might well be that there are lots of nodes
            'in the document with this path, but your call to selectsinglenode will only
            'give you the first encountered node in the document, so its always the same node..
            Dim applicIDAtt = node.SelectSingleNode("/dmodule/content/faultIsolation/faultIsolationProcedure/@applicRefId").InnerText
            Console.WriteLine(idAtt)
            Console.WriteLine(desc)
            Console.WriteLine(applicIDAtt)

        Next
    End Sub

End Module

Remember. If you have a file system like this:
c:\temp\my\path\file.txt

You can do this:
CD c:\temp\my

And you'll be in the my folder, and you can either refer to the file relatively or absolutely:
notepad path\file.txt
notepad c:\temp\my\path\file.txt

XPath is no different; if you start a path with a slash it's "from the doc root" no matter what the current node is, just like if you start a file path with c:\ it's from the drive root, no matter what the current directory is


text: Q: How to retrieve a list of registered geofences from Google Play services? I am building an app that can easily access all the resources used by other apps. For that I require a list of all the registered geofences in the play services of a particular device ? Is there a particular way to do this ?


text:
Q: codility challenge, test case OK , Evaluation report Wrong Answer the aluminium 2014 gives me wrong answer [3 , 9 , -6 , 7 ,-3 , 9 , -6 , -10] got 25 expected 28
but when i repeated the challenge with the same code and make case test it gives me the correct answer
Your test case [3, 9, -6, 7, -3, 9, -6, -10] : NO RUNTIME ERRORS (returned value: 28)
what is the wrong with it ???
the challenge :-

A non-empty zero-indexed array A consisting of N integers is given. A
  pair of integers (P, Q), such that 0 ≤ P ≤ Q < N, is called a slice of
  array A. The sum of a slice (P, Q) is the total of A[P] + A[P+1] + ...
  + A[Q]. The maximum sum is the maximum sum of any slice of A. For example, consider array A such that:    A[0] = 3
      A[1] = 2
      A[2] = -6
      A[3] = 3
      A[4] = 1 For example (0, 1) is a slice of A that has sum A[0] + A[1] = 5. This is the maximum sum of A. You can perform a single swap
  operation in array A. This operation takes two indices I and J, such
  that 0 ≤ I ≤ J < N, and exchanges the values of A[I] and A[J]. To goal
  is to find the maximum sum you can achieve after performing a single
  swap. For example, after swapping elements 2 and 4, you will get the
  following array A:    A[0] = 3
      A[1] = 2
      A[2] = 1
      A[3] = 3
      A[4] = -6 After that, (0, 3) is a slice of A that has the sum A[0] + A[1] + A[2] + A[3] = 9. This is the maximum sum of A after a single swap. Write a function: class Solution { public int solution(int[] A);
  } that, given a non-empty zero-indexed array A of N integers, returns
  the maximum sum of any slice of A after a single swap operation. For
  example, given:    A[0] = 3
      A[1] = 2
      A[2] = -6
      A[3] = 3
      A[4] = 1 the function should return 9, as explained above.

and my code is :-
import java.math.*;

class Solution {
    public int solution(int[] A) {
        if(A.length == 1)
            return A[0];
        else if (A.length==2)
            return A[0]+A[1];

        else{
            int finalMaxSum = A[0];

            for (int l=0 ; l<A.length ; l++){
                for (int k = l+1 ; k<A.length ; k++ ){

                    int [] newA = A;
                    int temp = newA[l];
                    newA [l] = newA[k];
                    newA[k]=temp;

                    int maxSum = newA[0];
                    int current_max = newA[0];
                    for(int i = 1; i < newA.length; i++)
                    {
                        current_max = Math.max(A[i], current_max + newA[i]);
                        maxSum = Math.max(maxSum, current_max);
                    }

                    finalMaxSum = Math.max(finalMaxSum , maxSum);

                }
            }

            return finalMaxSum;
        }
    }
}

i don't know what's the wrong with it ??

A: It was a bug in the website and this is the reply from the support team
the evaluation system run your program not only on the test case it presented to you, but also on the mirrored test case B = [-10, -6, 9, -3, 7, -6, 9, 3]. On test case B your program indeed returned 22, when it should have returned 28.

A: public static int findMaxSumOfArray(int[] A) {
    int[] T = new int[A.length];
    int sum = 0;

    int max1 = Integer.MIN_VALUE;
    int max2 = Integer.MIN_VALUE;
    int max3 = Integer.MIN_VALUE;
    int max1index = 0;
    int max2intex = 0;

    for (int i = 0; i < A.length; i++) {
        if (A[i] < 0) {
            T[i] = sum;
            sum = 0;
        } else if (i == A.length - 1) {
            sum += A[i];
            T[i] = sum;
            sum = 0;
        } else {
            sum += A[i];
        }
    }

    for (int i = 0; i < T.length; i++) {
        if (max3 < T[i]) {
            if (max2 < T[i]) {
                if (max1 < T[i]) {
                    max2intex = max1index;
                    max3 = max2;
                    max2 = max1;
                    max1 = T[i];
                    max1index = i;
                } else {
                    max3 = max2;
                    max2 = T[i];
                    max2intex = i;
                }
            } else {
                max3 = T[i];
            }
        }
    }
    return max1 + max2 + (Math.abs(max1index - max2intex) == 1 ? max3 : 0);
}


text:
Q: Execute same query with different table names I have an array with some table names and a predefined SQL query.
I want the execute the same query on all of the tables in that array. My approach was to traverse the table array and to replace the current table name with the next one (+1):
$tabs = array("abc", "def", "ghi", "jkl"); // array of tables

$query = "SELECT `col1`, `col2` FROM `abc`"; // example query

for($i=0; $i<sizeof($tabs); $i++){
    // ... execute ...

    echo $query; // for debugging

    $query = str_replace ( $tabs [$i], $tabs [$i+1], $query ); // replacing table names
}

This is the output:
SELECT `col1`, `col2` FROM `abc`
SELECT `col1`, `col2` FROM `def`
SELECT `col1`, `col2` FROM `ghi`
SELECT `col1`, `col2` FROM `jkl`

But in that case, it comes to that situation, where it tries to access an index that doesn't exist (in this case it' s 4).
So this error (or notice) occurs:
Notice:  Undefined offset: 4 in [...][...] on line 11

Is there a better approach?

A: You can try to put a marker in your query and replace it for each tables, like this :
<?php

$tabs = array("abc", "def", "ghi", "jkl"); // array of tables
$query = "SELECT `col1`, `col2` FROM `%my_table%` "; // example query

foreach($tabs as $tab) {
    $query = str_replace("%my_table%", $tab, $query);
    echo $query;
}

A: Work with an template query.
$tabs = array("abc", "def", "ghi", "jkl"); // array of tables

$tmp_query = "SELECT `col1`, `col2` FROM `%table%`"; // template query

echo $tmp_query ; // for debugging

foreach($tabs as $tab){

    $query = str_replace ('%table%', $tab, $tmp_query  ); // replacing table names

    echo $query ; // for debugging

    // ... execute ...
}

A: $tabs = array('abc', 'def', 'ghi', 'jkl'); // array of tables

foreach($tabs as $tab) {
    $query = sprintf('SELECT `col1`, `col2` FROM `%s`', $tab);

    // do something with $query
}

Explanation:

*

*Single quotes are faster than double quotes.

*sprintf is faster than str_replace and more flexible because you can add extra parameters.

*foreach iterates over every item in the array and you don't need to worry about the array index. If you wish to use the array index, just change foreach($array as $value) to foreach($array as $index => $value) and you can use the $index.

*This method is the most efficient & easiest to read solution to the problem of those provided so far - and solves the answer in the fewest lines of code.

A: Run this
$tabs = array("abc", "def", "ghi", "jkl"); // array of tables

$basequery = "SELECT `col1`, `col2` FROM "; // example query
foreach ($tabs as $tab){
   $query = $basequery." `".$tab."`";
}

A: first, instead of sizeof(), use count()
You probably noticed its the $i+1 within your str_replace that causes the error.  I would have written the code more like:

$tabs = array('abc', 'def', 'ghi', 'jkl');
$query = 'SELECT col1, col2 FROM :table:';
foreach($tabs as $i => $tab) {
    $sql = str_replace(':table:', $tab, $query);
    echo $sql; // for debugging
    // ... execute ...
}

This avoids any issue with array indexes by using a foreach and a second variable to store the desired query string ($sql).

A: I'd do two things in your code: first i'd use count since sizeof is an alias for count and i'd assign it to a variable since as per Php manual this will lead to a better performance. Then I'd use an if to prevent the error. this not to rewrite your code but keep using the for
$query = "SELECT `col1`, `col2` FROM `abc`"; // example query
$max = count($tabs);
for($i=0; $i<$max; $i++){
    // ... execute ...

    echo $query; // for debugging
    if($tabs[$i+1]<$max){
        $query = str_replace ( $tabs [$i], $tabs [$i+1], $query ); // replacing table names
    }
}


text:
Q: Easiest way to see that $\mathcal{C}$ is cocomplete? Let $\mathcal{C}$ be a category that has all coproducts and coequalizers. My question is, what is the easiest way to see that $\mathcal{C}$ is cocomplete?

A: As the initial comments on the question make clear, the first response to the question is "It's a one-line proof by duality!".
For the result that a category that has all coproducts and coequalizers is cocomplete is of course an immediate corollary by duality of the standard result that a category that has all products and  equalizers is complete.
So is the question really about is what is the easiest way to prove either the standard result or its dual? Again, as the comments make clear,  essentially the same line of proof of the standard result crops up in many texts.
But if you are finding presentations of it in standard texts too quick, you could try the slow-motion, three-stage, version in Ch. 14 of these online notes.


text:
Q: C# Capture Highlited Text From Another Program In C# with VS 2012 is it possible to "read" what a user highlights in another program?
For instance if a user is running Firefox, and uses the mouse to select (or highlight) a piece of text, can a program built with C# be "aware" of this selected text?
I have searched around, but I have come up empty.

A: I think the easiest way to do this is copying the text to the clipboard. For example, call CTRL+C programmatically. It will work for almost every program. If you need a certain program, you can do it using the UI Automation.


text:
Q: Is there a way to seperate the description for the first image and the second image using django? so for my website is there is 2 part to uploading an images, one is to upload images for the box and the other is to upload an images of the equipment but when it is uploaded the first image description is together with the second image description. Example shown below.
Picture of what happens when it is uploaded (not I wanted)

picture of what I wanted in my database.

views.py
@login_required()
def ReceptionUnserviceable(request):
    descriptionbox = Photo.objects.all()

    if request.method == 'POST':
        data = request.POST
        images = request.FILES.getlist('images')
        for image in images:
            photo = Photo.objects.create(

                descriptionbox=data['descriptionbox'],
                image=image,
                serialno=data['serialno'],
                partno=data['partno'],
                reception=data['reception'],
                customername=data['customername'],
                descriptionequipment=data['descriptionequipment'],

            )

        return redirect('success')

    context = {}
    return render(request, 'ReceptionUnserviceable.html', context)

models.py
class Photo(models.Model):
    class Meta:
        verbose_name = 'Photo'
        verbose_name_plural = 'Photos'

    image = models.ImageField(null=False, blank=False)
    descriptionbox = models.TextField()
    serialno = models.TextField()
    partno = models.TextField()
    reception = models.TextField()
    customername = models.TextField()
    descriptionequipment = models.TextField()

    def __str__(self):
        return self.descriptionbox

Receptionunservicable.html
     <form method='POST' action="" enctype="multipart/form-data">
                        {% csrf_token %}

                            Description Of The Box
                            <input required name="descriptionbox" type="text" placeholder="Enter a description" style="width:300px" class="form-control">

                            Upload Box Photo
                            <input required name="images" type="file" multiple class="form-control-file">

                 Part Number
                 <input required name="partno" type="text" placeholder="Enter part number" style="width:300px" class="form-control">

                 Serial Number
                 <input required name="serialno" type="text" placeholder="Enter serial number" style="width:300px" class="form-control">

                 Reception
                 <input name="reception" type="text" placeholder="Enter reception number" style="width:300px" class="form-control">

                 Customer Name
                 <input required  name="customername" type="text" placeholder="Enter customer name" style="width:300px" class="form-control">

                 Description Of The Equipment
                 <input required name="descriptionequipment" type="text" placeholder="Enter a description" style="width:300px" class="form-control">

                  Upload Equipment Photo
                  <input required name="images" type="file" multiple class="form-control-file">

             <button type='submit' style="width: 100px" class="btn btn-primary">Submit</button>
         </form>

How it looks on my website

A: One way is by naming the images differently so that we know which one is for the box and which one is for the equipment:
Receptionunservicable.html
...
<input required name="image_box" type="file" multiple class="form-control-file">
...
<input required name="image_equipment" type="file" multiple class="form-control-file">
...

Once renamed, we can access them separately and put the appropriate description:
views.py
...
data = request.POST

file_descriptions = [  # This assumes that both images are tagged with <required>
    {
        "image": request.FILES["image_box"],
        "descriptionbox": data['descriptionbox'],
        "descriptionequipment": "",  # Or better yet make the field <Photo.descriptionequipment> as <null=True> in the model
    },
    {
        "image": request.FILES["image_equipment"],
        "descriptionbox": "",  # Or better yet make the field <Photo.descriptionbox> as <null=True> in the model
        "descriptionequipment": data['descriptionequipment'],
    },
]

for file in file_descriptions:
    photo = Photo.objects.create(
        serialno=data['serialno'],
        partno=data['partno'],
        reception=data['reception'],
        customername=data['customername'],
        **file,
    )
...


text:
Q: Is it possible to combine strtok() and substr()? I've recently started working with PHP and am trying to make a list from a .txt BUT removing all the unnecessary components.
a line got this
item = 0    egg    came_from_chicken

I want to remove the item = and the came_from_chicken which leaves me with 0 egg.
Now after some searching I've found substr() to remove the first 5 characters of each of my lines. Later I've also found that strtok() can remove the rest of the unwanted text after the second tab. Unfortunately I cannot combine these. So my question is: How to remove the first 5 chars from each line and remove everything after the second tab from each line?
I've got this so far:
<?php
$lines = file('../doc/itemlist.txt');
$newf = array();
foreach ($lines as $line) {
    $newf[] = strtok($line, "\t") . "\t" . strtok("\t");
}
var_dump($newf);
?>

This works like a charm to remove everything after egg but still have to remove item =.

A: This approach will work with any string preceeding the = symbol.
foreach ($lines as $line) {
  $newf[] = implode("\t", array_slice(explode("\t", trim(explode('=', $line, 2)[1])), 0, 2));
}

A: The quick-and-dirty way is to just wrap it all:
$newf[] = substr(strtok($line, "\t") . "\t" . strtok("\t"), 5);

But, I personally have a dislike for strtok() (can't explain why, I just don't like it). If you don't need to strip everything off from the second tab, but from the last tab (in your example the second tab is the last tab), I would use strrpos() to find the location of the last tab, and dump that into substr():
$newf[] = substr($line, 5, strrpos($line, "\t")-5);

That -5 is to compensate for the 5 characters you strip off from the beginning. If you need to start at character 6 instead of 5, you should also subtract 6 from whatever strrpos() returns.
Edit Never mind that whole last part, I just saw the example format you posted and you really need the second tab instead of the last tab.

A: You can use a regular expression:
<?php
$lines = file('./file.txt');
$newf = array();
foreach ($lines as $line) {
    $newf[] = preg_replace('/.*=\s*(.*)\t.*/s', '$1', $line);
}

var_dump($newf);

Output:
array(1) {
  [0]=>
  string(5) "0  egg"
}

A: Assuming that you will be receiving similar patterns to the example you gave.
You can just do a simple line of:
$str = "item = 0    egg    came_from_chicken";
$parts = preg_split('/\s+/', $str);
echo $parts[2] . $parts[3];

A: I know this is not the answer you are looking for using strtok but I believe it would be much easier to do the following code below:
<?php
    $lines  = '../doc/itemlist.txt';

    // array to store all data
    $newf   = array();

    foreach ($lines as $line) {
        // you can do an explode which will turn it into an array and you can then get any values you want
        // $newf [] = strtok ($line, "\t") . "\t" . strtok("\t"); // throw away

        // lets say we use [item = 0    egg    came_from_chicken] as our string
        // we split it into an array for every tab or spaces found
        $values     = preg_split ('/\s+/', $line);
        //returns
        //  Array
        //  (
        //      [0] => item
        //      [1] => =
        //      [2] => 0
        //      [3] => egg
        //      [4] => came_from_chicken
        //      [5] =>
        //  )

        // lastly store your values which would be sub 2 and sub 4
        $newf []    = $values [2] . ' ' . $values [3];
    }

    var_dump($newf);

    // return
    // array (size=3)
    // 0 => string '0 aaa' (length=5)
    // 1 => string '1 bbb' (length=5)
    // 2 => string '2 ccc' (length=5)
?>


text:
Q: Git Authentication Failure Spring Cloud config store We are configuring spring cloud config server and below is how my application properties look:
server.port=8080
spring.cloud.config.server.git.uri=https://github.com/myorganization/config-store.git
spring.cloud.config.server.git.searchPaths={application}
spring.cloud.config.server.git.clone-on-start=true
spring.cloud.config.server.git.skipSslValidation=true
spring.cloud.config.server.git.ignore-local-ssh-settings=true
spring.cloud.config.server.git.username=MyUser
spring.cloud.config.server.git.password=MyPassword
spring.cloud.config.server.git.default-label=develop
spring.application.name=config-server
spring.security.user.name=root
spring.security.user.password=password

I am able to login to the github url i.e. https://github.com/myorganization/config-store.git using the username MyUser and password MyPassword as per above properties but when i am trying to start my config server using: ./mvnw spring-boot:run i am getting the below error:
Caused by: org.eclipse.jgit.errors.TransportException: https://github.com/myorganization/config-store.git: not authorized

i have tried out many things but running out of any ideas now, would appreciate any help in advance.

A: The use of username and password to do git operations on GitHub is deprecated and it no longer works, as described here.
You should generate a Personal Access Token, follow the official documentation to do it. Then you can add the token to the spring configuration as it was you password:
spring.cloud.config.server.git.username=<yourusername>
spring.cloud.config.server.git.password=<yourtoken>

A:
Beginning August 13, 2021, we will no longer accept account passwords when authenticating Git operations on GitHub.com.

From : https://github.blog/2020-12-15-token-authentication-requirements-for-git-operations/
Thx to: https://stackoverflow.com/a/70443213/592355
For Github Enterprise Server, our options (also) are limited, but considered secure & well documented:

Authenticating with the API
You can authenticate with the API in different ways.
...

*

*Personal access tokens (-> 1. https://stackoverflow.com/a/69663073/592355, 2. https://stackoverflow.com/a/70580891/592355 ?)

*OAuth Apps...

*GitHub Apps...

Authenticating with the command line
...

*

*HTTPS ...

*SSH ...

When SSH, for the spring-cloud-end:
Use "local ssh environment" or see: https://docs.spring.io/spring-cloud-config/docs/current/reference/html/#_git_ssh_configuration_using_properties


text:
Q: I want to get this CSS shape and have a background puicture inside it How to create this shape using CSS and HTML only?

A: You can achieve similar shapes to this using the border-radius property. You can play around with the values until you get the perfect shape you want.
HTML:

CSS:
.shape{
  width:500px;
  height:400px;
  margin:50px auto;
  overflow:hidden;
  border-radius:0 0 10% 50%;
}
.shape img{
  max-height:100%;
}

Here's a fiddle: https://jsfiddle.net/p80b7fp6/


text:
Q: Symfony2 ObjectNormalizer denormalize callbacks Is it possible to use setCallbacks on Symfony\Component\Serializer\Normalizer\ObjectNormalizer which are invoked when calling Symfony\Component\Serializer\Serializer.deserialize() to convert a  normalized value back to an object?
I know the reverse is possible in that a object can be normalized when calling Symfony\Component\Serializer\Serializer.serialize().  I just don't how to do the reverse normalization.
Example of serialization on entity with setCallbacks converting Foo to an Id:
    $encoder = new JsonEncoder();
    $normalizer = new ObjectNormalizer();
    $normalizer->setCallbacks(array(
        'foo' => function ($foo) {
            return $foo instanceof Foo
                ? $foo->getId()
                : null;
        },
    ));
    $serializer = new Serializer(array($normalizer), array($encoder));

    $json = $serializer->serialize($entity, 'json');

The reverse I would Like to do:
$em = static::getEntityManager();

    $encoder = new JsonEncoder();
    $normalizer = new ObjectNormalizer();
    $normalizer->setCallbacks(array(
        'foo' => function ($foo) use($em) {
            return !is_null($foo)
                ? $em->getReference('\Entity\Foo', $foo)
                : null;
        },
    ));
    $serializer = new Serializer(array($normalizer), array($encoder));

    return $serializer->deserialize($entity, $classname, 'json');

The error I get:
Catchable fatal error: Argument 1 passed to \Entity\Bar::setFoo() must be an instance of \Entity\Foo, integer given

Or is there a pre step that can be carried out before deserialize?

A: Please check here to see what do exact getReference.

There is no way to make getReference() check the database for the existence of the referenced object.

If you want to work your deserealize you must use $em->getRepository('\Entity\Foo')->find($foo)


text:
Q: How to get url params while bootstrapping angular app I have an angular app that I am manually bootstrap so I can get config data from the server before the app starts up. The problem is I need an id param from the url to pass to the server in order to get the config data.
Is there a way to use angular to harvest some url params while I bootstrap the app? I need a param for the $http.get url.
fetchData().then(bootstrapApplication);

function fetchData() {
    var initInjector = angular.injector(["ng"]);
    var $http = initInjector.get("$http");

    return $http.get("/path/to/data.json").then(function (response) {
        angular.module('app').constant("config", response.data);
    }, function (errorResponse) {
        // Handle error case
    });
}

function bootstrapApplication() {

    // manually bootstrap the app
    angular.element(document).ready(function () {
        var reportingApp = document.getElementById('ClaimSummaryApp');
        angular.bootstrap(reportingApp, ['app']);

    });

}


text:
Q: Why copy the same value to rax that he already has? can someone explain to me why we moved the value in rax to rdi in the main function @0x6f5, then copy the value at rdi to the stack of the  get_vand then moved it back to rax @0x6c8?. Perhaps it is a convention of x86-64, but I didn't understand its logic.
 main:
   0x00000000000006da <+0>:     push   rbp
   0x00000000000006db <+1>:     mov    rbp,rsp
   0x00000000000006de <+4>:     sub    rsp,0x10
   0x00000000000006e2 <+8>:     mov    rax,QWORD PTR fs:0x28
   0x00000000000006eb <+17>:    mov    QWORD PTR [rbp-0x8],rax
   0x00000000000006ef <+21>:    xor    eax,eax
   0x00000000000006f1 <+23>:    lea    rax,[rbp-0xc]
 =>0x00000000000006f5 <+27>:    mov    rdi,rax
   0x00000000000006f8 <+30>:    call   0x6c0 <get_v>
   0x00000000000006fd <+35>:    mov    eax,0x0
   0x0000000000000702 <+40>:    mov    rdx,QWORD PTR [rbp-0x8]
   0x0000000000000706 <+44>:    xor    rdx,QWORD PTR fs:0x28
   0x000000000000070f <+53>:    je     0x716 <main+60>
   0x0000000000000711 <+55>:    call   0x580
   0x0000000000000716 <+60>:    leave
   0x0000000000000717 <+61>:    ret

 get_v
   0x00000000000006c0 <+0>:     push   rbp
   0x00000000000006c1 <+1>:     mov    rbp,rsp
   0x00000000000006c4 <+4>:     mov    QWORD PTR [rbp-0x8],rdi
 =>0x00000000000006c8 <+8>:     mov    rax,QWORD PTR [rbp-0x8]
   0x00000000000006cc <+12>:    mov    DWORD PTR [rax],0x2
   0x00000000000006d2 <+18>:    mov    rax,QWORD PTR [rbp-0x8]
   0x00000000000006d6 <+22>:    mov    eax,DWORD PTR [rax]
   0x00000000000006d8 <+24>:    pop    rbp
   0x00000000000006d9 <+25>:    ret

A: This is unoptimized code. There are a lot of instructions here that are redundant and make very little sense, so I'm not sure why you've fixed on the particular indicated one. Consider the instructions immediately preceding it:
xor    eax,eax
lea    rax,[rbp-0xc]

First, RAX is cleared (instructions that operate on the lower 32-bits of a 64-bit register implicitly clear the upper bits, so xor reg32, reg32 is equivalent and slightly more optimal than xor reg64, reg64), then RAX is loaded with a value. There was absolutely no reason to clear RAX first, so the first instruction could have been altogether elided.
In this code:
lea    rax,[rbp-0xc]
mov    rdi,rax

RAX is loaded, and then its value is copied into RDI. This makes sense if you need the same value in both RAX and RDI, but you don't. The value just needs to be in RDI in preparation for the function call. (The System V AMD64 calling convention passes the first integer parameter in the RDI register.) So this could have simply been:
lea   rdi, [rbp-0xc]

but, again, this is unoptimized code. The compiler is prioritizing fast code generation and the ability to set breakpoints on individual (high-level language) statements over the generation of efficient code (which takes longer to produce and is harder to debug).
The cyclical spill-reload from the stack in get_v is another symptom of unoptimized code:
mov    QWORD PTR [rbp-0x8],rdi
mov    rax,QWORD PTR [rbp-0x8]

None of this is required. It's all just busy work, a common calling card of unoptimized code. In an optimized build, or hand-written assembly, it would have been written simply as a register-to-register move, e.g.:
mov    rax, rdi

You'll see that GCC always follows the pattern you've observed in unoptimized builds. Consider this function:
void SetParam(int& a)
{
    a = 0x2;
}

With -O0 (optimizations disabled), GCC emits the following:
SetParam(int&):
    push    rbp
    mov     rbp, rsp
    mov     QWORD PTR [rbp-8], rdi
    mov     rax, QWORD PTR [rbp-8]
    mov     DWORD PTR [rax], 2
    nop
    pop     rbp
    ret

Look familiar?
Now enable optimizations, and we get the more sensible:
SetParam(int&):
    mov     DWORD PTR [rdi], 2
    ret

Here, the store is done directly into the address passed in the RDI register. No stack frame needs to be set up or torn down. In fact, the stack is bypassed altogether. Not only is the code much simpler and easier to understand, it is also much faster.
Which serves as a lesson: when you are trying to analyze a compiler's object-code output, always enable optimization. Studying unoptimized builds is largely a waste of time, unless you are actually interested in how the compiler generates unoptimized code (e.g., because you're writing or reverse-engineering the compiler itself). Otherwise, what you care about is optimized code because it is simpler to understand and much more real-world.
Your entire get_v function could be simply:
mov   DWORD PTR [rdi], 0x2
mov   eax, DWORD PTR [rdi]
ret

There's no reason to use the stack, shuffling values back and forth. There's no reason to reload the data from the address RBP-8, since we already have that value loaded into RDI.
But actually, we can do even better than this, since we are moving a constant into the address stored in RDI:
mov   DWORD PTR [rdi], 0x2
mov   eax, 0x2
ret

In fact, this is exactly what GCC generates for what I imagine is your get_v function:
int get_v(int& a)
{
    a = 0x2;
    return a;
}

Unoptimized:
get_v(int&):
    push    rbp
    mov     rbp, rsp
    mov     QWORD PTR [rbp-8], rdi
    mov     rax, QWORD PTR [rbp-8]
    mov     DWORD PTR [rax], 2
    mov     rax, QWORD PTR [rbp-8]
    mov     eax, DWORD PTR [rax]
    pop     rbp
    ret

Optimized:
get_v(int&):
    mov     DWORD PTR [rdi], 2
    mov     eax, 2
    ret


text:
Q: What does this syntax mean? Is it plain jQuery? I found on codeply an example having the following line:
$('[id^=carousel-selector-]').click( function(){

I think it is related to the line in html:

But what does exactly '[id^=carousel-selector-]' mean?

A: It is the attribute starts with selector.
It will select all the elemets whose id starts with carousel-selector-
Consider the html,
one
one
one
one

Then $('[id^=carousel-selector-]'). will return first 3 anchor elements, as its id starts with carousel-selector-

*

*^ is starts with selector

*$ is ends with selector

** is contains selector

A: It means; select element with an ID that begins with carousel-selector-
You may also come across a similar selector id*=carousel-selector- which means; select elements with an ID that contains carousel-selector-

A: the query is going to click all the element whose id is going to start with carousel-selector- . for example

click me

click me

click me

There are three different html element with random id but starting with the same id name. so this will find them all and do the event what you want to do
or you can also hide the all item on page load or do whatever you want
$('[id^=carousel-selector-]').hide();

So this will going to search all the item whose id is starting with carousel-selector- and do the stuff


text:
Q: Does jQuery event.stopPropagation() stop all callbacks for that event, or just the one it's declared in? I have a question about jQuery's event.stopPropagation(). Does event.stopPropagation() prevent all callback functions for that event on that target element (not necessarily the same target but same parent) from bubbling to the parent or just the one it's declared in? To elaborate, say I have this:
$('#someId').on('mousedown touchstart MSPointerDown', function(e){
    e.preventDefault();
    e.stopPropagation();
    $(e.target).toggleClass('blue');
});
$('#someId').on('mousedown touchstart MSPointerDown', function(e){
    $(e.target).toggleClass('blue');
});

or
$('#someId').children()[0].on('mousedown touchstart MSPointerDown', function(e){
    e.preventDefault();
    e.stopPropagation();
    $(e.target).toggleClass('blue');
});
$('#someId').children()[1].on('mousedown touchstart MSPointerDown', function(e){
    $(e.target).toggleClass('blue');
});

Or would I need to have e.stopPropagation() in both to prevent the callback form bubbling up?

A: In your second example, the two events are not related at all, so you will have to treat them as such; they will both need to be prevented.
stopPropagation will stop the event from propagating up the dom, but it will not stop other event handlers bound to the same element and event. For that, you would need stopImmediatePropagation.


text:
Q: Accessing same database from different desktop applications I want to ask your opinion.
for example:
Restaurant A is a new restaurant in location B. Usually i manage the information just by book and maybe some excel formula to calculate. The information that i manage is about staff schedule, staff payroll, staff attendance, income, and storehouse.
After a two years, i want to expand my business. I build the same restaurant, but in location C. and now, i realize. Using a book and excel is helpless. Just wasting time for me. i got an idea, how about if all the information store in the computer? Then, I planning to build a system that can help me  to manage the information. Actually is a desktop app. Then i bought two computer. one is for restaurant A in B. the other one is for restaurant A in C. i plan to install the desktop app in both of the computer and also install the desktop app in my personal laptop so that i can manage the restaurant eventhough i'm at home.
my question is :
1. which kind of database should i use? because i need to retrieve the data quickly.
2. where should i store the database? in both of computer for each restaurant? if yes, how can i access the data if i'm at home?
can you give me your opinion?

A: This sounds like a problem that will have an out-of-the-box solution.  Have you taken a look at an existing cloud solution?  I did a quick search and something like this looks like it could work for what you need.
If you must create your own solution (which will probably be a lot more expensive) then I would definitely make use of a cloud database like SQL Azure.  That way it will be accessible from anywhere with no synching/merging required.

A: Web application is more likely to solve your problem but if you still want to have a desktop application you can buy an hosting for a database and connect to it. IF this will be costly and you wont have internet access just use an accessdb with your application.Put the application and the database file in a usb drive and put it to any computer you want. The exe files may stay the same but you should move the database file to get the updated data in different locations.

A: Yes. there are different solutions to your problem.

*

*If you have ur own network connection between your restaurants, then you can have a SQL Server installed at one Server(centralized) , and you can connect to it through windows app.

*Developing a Web app which can be accessed through browser. U can  have all kinda info you need in click. That should be hosted in a server.

A: In my opinion you should go for Shared Web hosting that will give you database and web application hosting service.
e.g. Something that give Sql Express or Server with .Net web application host on IIS etc
Reason I am advising you to go for web application because it will be available 24/7 via the internet for you to access and update you data from anywhere and will give you more time to focus on managing restaurants rather than maintaining software.
Another advantage is you don't need to worry about installation of software and apps on every computer because you will be able to use your web application via a web browser


text:
Q: Make title of plots in for loop the column name of dataframe I have a dataframe that looks like this:
points  time             Antwerp    Busan       Colombo     Dalian      Guangzhou   Hamburg Hong Kong   Jebel Ali/Dubai Kaohsiung   ... Qingdao Rotterdam   Shanghai    Shenzhen    Singapore   Tanjung Pelepas Tanjung Priok/Jakarta   Tianjin Xiamen  Yingkou
0   1990-01-01 00:00:00 273.70395   279.31912   298.03195   268.42200   285.93228   271.31534   290.31357   289.83023   292.94135   ... 273.34103   274.18726   279.60450   288.37366   298.10950   298.23816   299.37143   272.06094   285.92570   265.19046
1   1990-01-01 01:00:00 273.72702   279.94266   298.02042   268.18445   286.04940   271.18503   290.59730   289.69333   292.95950   ... 273.52084   274.12128   280.13235   288.59967   298.21176   298.40808   299.59576   272.04776   286.36612   265.10303

I just want to run a bunch of different types of plots using a for loop.
For example:
for i in data.columns[1:]:
    plt.figure()
    plt.plot(data[i]-273)

This creates a bunch of line plots for all 25 locations that I have. Now, I want to assign the plot title to be the city name, which is every column name. I know how to do this with a dictionary, but am unsure if there is an easier way to do this without converting everything to a dictionary.

A: Column labels are an attribute of a dataframe in pandas. So here, your variable "i" is in fact the column name, and you can title your plot with plt.title(i). No need to use a dictionary to convert indexes to names here.


text:
Q: Using rabbitmq-c as static library gives error: fatal error: amqp.h: No such file or directory I am trying to build rabbitmq-c as a static library so I can use in AWS lambda.
I am able to build the examples following the documentation and those are working fine.
But now I am trying to use in my own project.
Below are the steps I took:

*

*Cloned https://github.com/alanxz/rabbitmq-c inside third-party directory.

*Inside my source directory, I am building using cmake.

Below is my CMakeLists.txt
cmake_minimum_required(VERSION 3.1)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_BUILD_TYPE "Release")
project(executable LANGUAGES CXX)

SET(CMAKE_FIND_LIBRARY_SUFFIXES ".a")
SET(BUILD_SHARED_LIBS OFF)

set(RABBITMQ_TARGET "<absolute_path_to_third_party_dir>/third_party/rabbitmq-c/")
add_definitions(-DAMQP_STATIC)
add_subdirectory(${RABBITMQ_TARGET})

include_directories(${LIBRABBITMQ_INCLUDE_DIRS})

add_executable(${PROJECT_NAME} execute_code.cpp)
target_link_libraries(executable PRIVATE ${RMQ_LIBRARY_TARGET})

*I run cmake .. -DBUILD_EXAMPLES=OFF -DBUILD_SHARED_LIBS=OFF (which works without any issue).

*But when I am executing make, it gives following error:

fatal error: amqp.h: No such file or directory
compilation terminated.
CMakeFiles/executable.dir/build.make:62: recipe for target 'CMakeFiles/executable.dir/execute_code.cpp.o' failed
make[2]: *** [CMakeFiles/executable.dir/execute_code.cpp.o] Error 1
CMakeFiles/Makefile2:169: recipe for target 'CMakeFiles/executable.dir/all' failed
make[1]: *** [CMakeFiles/executable.dir/all] Error 2
Makefile:129: recipe for target 'all' failed
make: *** [all] Error 2

Here is my execute_code.cpp (I am removing unnecessary code just for here)
#include<iostream>
#include <amqp.h>
#include <amqp_tcp_socket.h>

using namespace std;

int main(int argc, char** argv) {
  char const *hostname;
  int port, status;
  char const *exchange;
  char const *bindingkey;
  amqp_socket_t *socket = NULL;
  amqp_connection_state_t conn;

  amqp_bytes_t queuename;

  conn = amqp_new_connection();
  socket = amqp_tcp_socket_new(conn);
  return 0;
}

when I am not using
#include <amqp.h>
#include <amqp_tcp_socket.h>

I am able to build rabbitmq-static, below is the make response
Scanning dependencies of target rabbitmq-static
[ 35%] Building C object third_party/rabbitmq-c/librabbitmq/CMakeFiles/rabbitmq-static.dir/amqp_framing.c.o
[ 37%] Building C object third_party/rabbitmq-c/librabbitmq/CMakeFiles/rabbitmq-static.dir/amqp_api.c.o
[ 40%] Building C object third_party/rabbitmq-c/librabbitmq/CMakeFiles/rabbitmq-static.dir/amqp_connection.c.o
[ 42%] Building C object third_party/rabbitmq-c/librabbitmq/CMakeFiles/rabbitmq-static.dir/amqp_mem.c.o
[ 44%] Building C object third_party/rabbitmq-c/librabbitmq/CMakeFiles/rabbitmq-static.dir/amqp_socket.c.o
[ 46%] Building C object third_party/rabbitmq-c/librabbitmq/CMakeFiles/rabbitmq-static.dir/amqp_table.c.o
[ 48%] Building C object third_party/rabbitmq-c/librabbitmq/CMakeFiles/rabbitmq-static.dir/amqp_url.c.o
[ 51%] Building C object third_party/rabbitmq-c/librabbitmq/CMakeFiles/rabbitmq-static.dir/amqp_tcp_socket.c.o
[ 53%] Building C object third_party/rabbitmq-c/librabbitmq/CMakeFiles/rabbitmq-static.dir/amqp_time.c.o
[ 55%] Building C object third_party/rabbitmq-c/librabbitmq/CMakeFiles/rabbitmq-static.dir/amqp_consumer.c.o
[ 57%] Building C object third_party/rabbitmq-c/librabbitmq/CMakeFiles/rabbitmq-static.dir/amqp_openssl.c.o
[ 60%] Building C object third_party/rabbitmq-c/librabbitmq/CMakeFiles/rabbitmq-static.dir/amqp_openssl_hostname_validation.c.o
[ 62%] Building C object third_party/rabbitmq-c/librabbitmq/CMakeFiles/rabbitmq-static.dir/amqp_hostcheck.c.o
[ 64%] Building C object third_party/rabbitmq-c/librabbitmq/CMakeFiles/rabbitmq-static.dir/amqp_openssl_bio.c.o
[ 66%] Linking C static library librabbitmq.a
[ 66%] Built target rabbitmq-static

It is able to generate librabbitmq.a, so it is able to build statically.
I tried with https://github.com/alanxz/rabbitmq-c/releases/tag/v0.10.0 which is the latest stable version. But still the same error.
I tried searching regarding the issue, but couldn't find anything helpful.
I am pretty much newbie to cmake, Can you please tell me what I am doing wrong or am I missing something?

A: The rabbitmq-c repository sets the LIBRABBITMQ_INCLUDE_DIRS variable in the rabbitmq-c/librabbitmq sub-directory, then also sets it using PARENT_SCOPE so it is also available in the top-level rabbitmq-c directory. See that code here:

set(LIBRABBITMQ_INCLUDE_DIRS
    ${CMAKE_CURRENT_BINARY_DIR}
    ${CMAKE_CURRENT_SOURCE_DIR}
    ${SOCKET_IMPL}
    ${MSINTTYPES_INCLUDE}
    )

include_directories(${LIBRABBITMQ_INCLUDE_DIRS})

set(LIBRABBITMQ_INCLUDE_DIRS
    ${LIBRABBITMQ_INCLUDE_DIRS}
    PARENT_SCOPE)

However, when you include the rabbitmq-c repo in your project via add_subdirectory, it introduces an additional scope, and the LIBRABBITMQ_INCLUDE_DIRS variable is not available in this parent-parent scope. You will have to either:

*

*Re-organize your CMake project such that your project sits within
the rabbitmq-c repository (although this is not scalable, and probably not what you want to do).

*Modify the top-level rabbitmq-c
CMake file to further extend the scope of this variable.

*Install rabbitmq-c on your machine, and use a CMake Find Module
or a CMake configuration file (e.g. rabbitmq-c-config.cmake)
furnished by rabbitmq-c to locate the installed software.

A: A bit late to the party, I stumbled onto the same issue today.
None of the 3 solutions proposed by Kevin would suit my needs (the lib is declared as a submodule so I can't modify it, won't install on the production machines)
The solution for me was to add rabbitmq include directories to the target that links the lib :
target_include_directories("${PROJECT_NAME}" PUBLIC include/ path/to/rabbitmq-c/librabbitmq)


text:
Q: Prove $\sum_{k=1}^{\infty} P(X \geq k) = E[X]$ for any discrete random variable with nonnegative values. The hint for this problem that is given in the book is to write $P(X \geq k)$ as $\sum_{i=k}^{\infty} P(X = i)$ and then switch the order of summation but I have no idea how to continue from there. This would leave me with $$ \sum_{i=k}^{\infty} \sum_{k=1}^{\infty} P(X = i)$$.

A: Great, now try to rearrange terms in your last expression to equate that sum to the definition of expectation for such random variables.
$$E[X] = \sum_{j=1}^\infty j P(X=j).$$