text:
Q: Fill masked array column-wise I seem to miss a fast way of filling a masked region in column-major ordering in Python.
Here is an example that works, but is very inefficient:
def fill_masked_array_colmajor(arr_to_fill, mask, fill_values):
    c = 0
    for h in range(arr_to_fill.shape[1]):
        for v in range(arr_to_fill.shape[0]):
            if mask[v,h]:
                arr_to_fill[v,h] = fill_values[c,0]
                c+=1
    return arr_to_fill

test_arr = np.arange(1,65).reshape(8,8)
test_mask = np.zeros((8,8))
test_mask[2:6,3:5] = 1
test_mask = test_mask.astype(bool)
test_vals = np.arange(1,9)[..., np.newaxis]  # added axis because my data looks like that

test_res = fill_masked_array_colmajor(test_arr, test_mask, test_vals)

The correct output then becomes:
 [ 1  2  3  4  5  6  7  8]
 [ 9 10 11 12 13 14 15 16]
 [17 18 19  1  5 22 23 24]
 [25 26 27  2  6 30 31 32]
 [33 34 35  3  7 38 39 40]
 [41 42 43  4  8 46 47 48]
 [49 50 51 52 53 54 55 56]
 [57 58 59 60 61 62 63 64]

If i try something like:
test_arr2 = np.arange(1,65).reshape(8,8)
test_mask2 = np.zeros((8,8))
test_mask2[2:6,3:5] = 1
test_mask2 = test_mask2.astype(bool)
test_vals = np.arange(1,9)[..., np.newaxis] # added axis because my data looks like that

test_arr2[test_mask2] = test_vals[:,0]

then the wrong row-major output becomes:
[ 1  2  3  4  5  6  7  8]
[ 9 10 11 12 13 14 15 16]
[17 18 19  1  2 22 23 24]
[25 26 27  3  4 30 31 32]
[33 34 35  5  6 38 39 40]
[41 42 43  7  8 46 47 48]
[49 50 51 52 53 54 55 56]
[57 58 59 60 61 62 63 64]

It is important to note that the masked region is not necessarily rectangular as shown here, but can be spread in odd shapes and multiple blobs. The length of test_vals is always equal to the number of masked elements. I just need to fill them in column-major ordering.
I understand the behavior since Python is row-major. I can perhaps see a solution using .flatten(order="f") and making some copies, and then reshaping - but there must be a fast and simple implementation of this? I feel I am missing something obvious. Thanks.
New failed attempt
So I tried my own suggestion of doing a flattened array and reshaping. As expected, it turns out to generally be slower than my loop-function above. So hopefully this is not the best approach.
idx = np.argwhere(test_mask2.ravel("F"))
tmp = test_arr2.ravel("F")
tmp[idx] = test_vals
out = tmp.reshape(test_arr2.shape).T


text:
Q: How to integrate axios api in react js with async and await using react hooks I have the following code in signin.js and I am using Axios API to integrate it with the code so that it redirects to the dashboard. I have the following URL for API (https://9d6e-110-44-127-177.ngrok.io/auth/login/) and email that is verified is "m@m.com" and password is admin@123 but I don't know how to integrate with the code. The code for signin.jsx is as below:
signin.jsx
import React, {useState} from 'react'
import styled from 'styled-components'
import StyledInput from './StyledInput'
import StyledButton from './StyledButton'
import { Link } from 'react-router-dom'
import './Signin.css'
import axios from 'axios'

const Container = styled.div`

display: flex;
flex-direction: column;
justify-content:center;
align-items: center;
height: 80vh;
width: 30vw;
background: #E8E8E8;

`;

const Welcome = styled.h2`

   margin: 3rem 0 2rem 0;
   box-sizing: border-box;
   background-color: #00009c;
   border: 2px solid #00009c;
   border-radius: 2rem;
   padding: 15px;
   text-transform: uppercase;
   color: white;
   letter-spacing: 0.4rem;
`;

const Form = styled.form`
width: 100%;
  height: 100vh;

  justify-content: center;
  align-items: flex-start;
`;

const Input = styled.div`
display: flex;
flex-direction: column;
justify-content: space-around;
align-items: center;
height:20%;
width: 100%;
` ;

const Button = styled.div`
margin: 1rem 0 2rem 0;
width: 90%;
display: flex;
align-items: center;
justify-content: center;

`;

const Paragraph = styled.p`
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
`;

const Check = styled.input`
font-size: 15px;
margin-left: -400px;
box-sizing: border-box;
`;

const Label = styled.label`
margin-top: -120px;
margin-left: -270px;

`;

const Signin = () => {
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");

    const  handleSubmit = (e) => {
        e.preventDefault()
        axios.post("https://9d6e-110-44-127-177.ngrok.io/auth/login/", {
            email: "m@m.com",
            password: "admin@123"
        })
            .await((response) => {
                console.log(response)

            })

            .catch((err) => {
                console.log(err)
                alert(err.response.data.error.message)
         })
    }

   const handleEmail = (e) => {
        setEmail(e.target.value)
    }

  const  handlePassword = (e) => {
        setPassword(e.target.value)
    }

    return (
        <Container>
            <Welcome>
                Welcome
            </Welcome>
            <Form onSubmit= {handleSubmit}>

                <Input>

redpajama_set_name: RedPajamaStackExchange


text:
Q: After install Google Chrome in EC2 won't open from Ubuntu Server 14.04 LTS (HVM) command line I have installed Google Chrome with following command line:
$ wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -
$ sudo sh -c 'echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list'
$ sudo apt-get update
$ sudo apt-get install google-chrome-stable

When try to open Google Chrome from command line ($ google-chrome), I am getting following error:
[5426:5426:0808/041800:ERROR:browser_main_loop.cc(209)] Gtk: cannot open display:

How can I fix this issue to open the Google browser?

A: Connecting from Ubuntu and other Unix-like systems with X11-based GUIs
If I understand the situation correctly, you are connecting to a remote EC2 instance (perhaps a "cloud server"). You are probably using ssh.
Installing an X server on the EC2 instance won't help, because you need this application's graphical interface to appear on your end, not on the screen attached to the server. (There probably is no such screen, but even if there were, it wouldn't help you.)
Assuming the machine you're connecting from (i.e., the computer you're physically using) is running Ubuntu or some other operating system that uses the X window system for its GUI, you can use X11 forwarding (ssh -X).
Right now, you're probably connecting to the EC2 server with a command like:
ssh username@hostname

(Where hostname is either the domain name or IP address of the EC2 instance, or perhaps its "simple name" if you're connecting through a VPN.)
To forward X11, change this to:
ssh -X username@hostname

In my experience, remotely controlled GUI applications run via ssh -X often lag perceptibly. You may be able to improve performance by using the blowfish cipher:
ssh -c blowfish -X username@hostname

And unless your connection to the EC2 instance is extremely fast, you may be able to improve responsiveness further with data compression:
ssh -C -c blowfish -X username@hostname

(These can be used in any combination; for example, you could use ssh -C -X username@hostname if you wanted.)
If ssh -X doesn't work, it might be disabled on the server. In that case, open /etc/ssh/sshd_config on the server. Search for a line that says X11Forwarding no and change it to X11Forwarding yes. (If there is no such line, simply add X11Forwarding yes.)
Further reading: How to forward X over SSH from Ubuntu machine?
Connecting from Windows using PuTTY
If you are using PuTTY on Windows (which now appears to be the case, based on the screenshot you've uploaded), then this is still an SSH connection, but you're not using the ssh command so the above client-side syntax won't help you.
Instead, you'll have to:

*

*Configure PuTTY to forward X11.

*Install an run an X11 server on your Windows system.

(Note that while your Windows system is the SSH client and the EC2 instance is the SSH server, it's the other way around for X11: the SSH client runs the X server and the SSH server runs the X client.)
X11 Forwarding using Xming and PuTTY explains how to install the Xming X server on your Windows system and configure PuTTY to forward X11. In short:

*

*Download Xming from its project page.

*Install Xming and Xming-fonts (both are included in what you downloaded).

*Run Xming.

*Run PuTTY, find X11 (it's in the left panel, under SSH, which itself is under Connection). Click on X11.

*Make sure the "Enable X11 forwarding" checkbox is checked, the contents of the textbox labeled "X display location" are localhost:0, and the option button under "Remote X11 authentication protocol" is set to MIT-Magic-Cookie-1.

*Then connect with PuTTY to your EC2 instance, as normal.

Optionally (and not taken from that source):

*

*If you want to use the blowfish cipher, click SSH on the left panel, select Blowfish in the "Encryption cipher selection policy" listbox, and click the Up button until it's at the top of the list. That's essentially the equivalent of -c blowfish if you were using the ssh command.

*If you want to use compression, then also after clicking SSH on the left panel, make sure the "Enable compression" checkbox, under "Protocol options," is checked.

See also:

*

*How to use X11 forwarding with putty

*Nathan Osman's answer to How to run GUI applications remotely on a headless server?


text:
Q: Parsing recursive hashes into data records in Ruby I've struggled with this problem for a while, and I'm finally going to ask here for help.
Take a very straightforward hash that represents some event:
{
  :eventkey=>"someeventkey",
  :web_id=>"77d5f434-5a40-4582-88e8-9667b7774c7d",
  :apikey=>"eaf3b6e1-b020-41b6-b67f-98f1cc0a9590",
  :details=>  {
    :phone=>"1-936-774-6886",
    :email=>"dasia_schuster@wisokytrantow.com",
    :pageUrl=>"http://ortiz.info/joe"
    }
}

My goal is to create a 'master record' for the entire hash, with the fields in the record being all the keys that do not contain values that are also hashes.  When I run into a value that is a hash (in this case 'details'), I need to create a separate record for each k/v pair in that hash bearing the same record id as the parent master record.
I'm not getting the recursion right somehow.  Ideally I would get back a single primary record:
{
  :recordid=>"some-generated-record-id",
  :web_id=>"77d5f434-5a40-4582-88e8-9667b7774c7d",
  :apikey=>"eaf3b6e1-b020-41b6-b67f-98f1cc0a9590",
  :details=>nil
}

And a distinct entry for each key in the nested hash:
{
  :recordid=>"some-generated-detail-record-id",
  :parentid=>"the-parent-id-from-the-master-record",
  :phone=>"1-936-774-6886"
}

{
  :recordid=>"another-generated-detail-record-id",
  :parentid=>"the-same-parent-id-from-the-master-record",
  :email=>"dasia_schuster@wisokytrantow.com"
}

And so on.  I'm trying to get this set of records back as an array of hashes.
I've gotten as far as being able to generate the master record, as well as a detail record, but the detail record contains all the keys in the detail.
def eventToBreakout(eventhash,sequenceid = -1, parentrecordid = nil, records = [])
    recordid = SecureRandom.uuid
    sequenceid += 1

    recordstruc = {:record_id => recordid, :parent_record_id => parentrecordid, :record_processed_ts => Time.now, :sequence_id => sequenceid}
    eventhash.each_pair do |k,v|
        if recurse?(v)

          eventToBreakout(v,sequenceid,recordid,records)

        else
          if !recordstruc.keys.include?(k)
            recordstruc[k]=v
          end
        end

    end
    records << recordstruc
    records
end

I've included my code and here is the output I'm currently getting from it.
[{:record_id=>"ed98be89-4c1f-496e-beb4-ede5f38dd549",
  :parent_record_id=>"fa77299b-95b0-429d-ad8a-f5d365f2f357",
  :record_processed_ts=>2016-04-25 16:46:10 -0500,
  :sequence_id=>1,
  :phone=>"1-756-608-8114",
  :email=>"hipolito_wilderman@morar.co",
  :pageUrl=>"http://haag.net/alexie.marvin"},
 {:record_id=>"fa77299b-95b0-429d-ad8a-f5d365f2f357",
  :parent_record_id=>nil,
  :record_processed_ts=>2016-04-25 16:46:10 -0500,
  :sequence_id=>0,
  :eventts=>2016-04-25 22:10:32 -0500,
  :web_id=>"a61c57ae-3a01-4994-8803-8d8292df3338",
  :apikey=>"9adbc7a4-03ff-4fcc-ac81-ae8d0ee01ef0"}]

A: Maybe you want something along these lines?
input = { id: 'parent', value: 'parent value', child: { child_value: 1}}

record = {}
input.each do |k,v|
  if v.is_a? Hash
    v[:parent_id] = input[:id]
    (record[:children] ||= []) << v
  else
    record[k] = v
  end
end

puts record
# {:id=>"parent", :value=>"parent value", :children=>[{:child_value=>1, :parent_id=>"parent"}]}

By the way this is a good example to get started with "spec" or "test" frameworks like minitest or rspec (both can be used for both). You have defined input and expected output already and "just" need to code until all test/spec-runs are green.


text:
Q: Multitasking how to keep track of what you're doing I'm in a long debugging task, I need to figure out where to hook up some extra functionality I need.
It's cumbersome work, and I've been debugging 2 whole days, and I'm on my third, but I work in multiple projects, and I'm returning to this after almost a week, and it's been hard to get back to the point I left at, and remember what was all this about, and what conclusions had I already arrived at.
How do you keep track of what you were doing/thinking in this kind of scenario where comments aren't actually the "right thing" to do? I do some comments in my testing code, plus some informative git/hg commit messages but that's kind of dirty.. written paper might be the answer...

A: I'm not sure for you, but for me Automatic Tests (Unit tests if possible) are a good way of discovering how the code works, and knowing that it doesn't work as expected.
Automatic Tests replaces debugging, changing a memory-backed developer-checked knowledge and verification, to a file-backed explicitely-checked one.
When coming back to your work later on, you will be at the same point after a few seconds executing your tests, instead of trying to retrieve your context from old memories and replaying a long debug sequence (these last two activities may require written communication anyway as memory might not suffice ; then Automatic Tests would have no overhead).
I know, some projects are not easily testable automatically. We use TDD to solve that problem, gaining also many other advantages ....
If you already write some automatic tests, the same tests you write automatically track what you are thinking and verifying, so you probably need nothing else. When you finally found your bug, you can keep your test sequence ... or refactor it ;-)

Edit after comment :
Testing how a library works ! I call that learning tests.
Good that you do them :

*

*they let you know exactly how the library is working.

*they document that knowledge, for you later or for your team members

*they may document the uses of that library, how it is used in your project
(in my Aeronautics experiences, the company policy mandated that each external code is controlled, knowing precisely what features are used, and documenting what would be the effect on our software if the library would stop working !)

*they serve as a non-regression test when you upgrade your library

A: I setup a task with a reminder for two reasons:

*

*I need a prompt to return to the code.

*I can enter any notes or link to important documents, web pages, files, etc..

It's difficult to switch tasks if you're in constant fear of forgetting to back to that original bug. You do need to have some idea of when it is best to set the reminder. I also do this when leaving things over the weekend.

A: for working on multiple, complex projects, regardless of whether they involve developing software, there's no substitute for writing things down.
I've used bug tracking software, spreadsheets, personal wikis, a self-developed database, and probably a dozen other methods I've forgotten over the years. Writing things down helps you recall not only what you did, but why you did it.
When it comes specifically to debugging, there's no reason you can check code-in-progress into your own personal version control system. You can clean it up before committing to the central source repository.


text:
Q: Define a map that looks like a solid Let $S$ be a solid in $\mathbb{R}^3$. If we are viewing it from the x-axis, in the front, it looks like a circle, a rectangle from the side, and equilateral triangle from above, all centered at the origin.
I'm not even sure what a solid like this will look like, so how can we define the map $f : \mathbb{R}^3 \to \mathbb{R}^2$ by $f(x,y,z) = (y,z)$?
And how can we describe $f(S)$ using sets?

A: Not exactly to your scale, but your figure looks like a toothpaste tube.

And $f$ is just the projection on the $yz$ plane


text:
Q: The result is expected to be 25 but why does the program produce 0 instead? I am practicing calculations in Java. I decided to convert room temperature in Fahrenheit to temperature in Celsius. I made different programs and found the answer but I want to learn more. The result is expected to be 25 but the first program produces 0 instead.  Could you tell me why is the first program is wrong?
The first program
int room_temp_f = 77;
int room_temp_c =  (room_temp_f - 32)* 5/9;
System.out.println(room_temp_c);

The second program
int room_temp_f = 77;
int room_temp_c = 5/9 * (room_temp_f - 32);
System.out.println(room_temp_c);


text:
Q: Is it possible to combine the results of multiple SEPARATED select statements? I'm new to SQL in general,
I don't know if this is already answered or just common knowledge, but I've failed to find similar question.
Is it possible to append multiple select statements when there's other processes between it?
For example,
set @a = 1;
#first select
select @a as alphabet;

#random code
set @a = 2;
insert into `dummy`(`iddummy`) values @a;

#second select
select @a as alphabet;

and get results like
alphabet
--------
1
2

I want appended result like that because I'm working with for my front end program, using select to return error message or insert results (for review). This becomes a problem when one of my stored procedure calls other similar procedure, resulting in multiple select results with just one call

A: Save the results of the first query in a temporary table, then select from it in your final query:
set @a = 1;
create temporary table query1
select @a as alphabet;
set @a = 2;
insert into dummy(iddummy) values (@a);
select alphabet from query1
union all
select @a;

Produces:

alphabet

1

2

See live demo (also showing dummy was inserted into).


text:
Q: Flutter CI with cirrusci/flutter I am trying to make CI for a Flutter app in GitLab. I set up a docker container with cirrusci/flutter:2.8.1. When I run my .gitlab-ci.yml it fails because flutter can't find lib/main.dart:3:8: Error: Error when reading 'lib/Screens/maps.dart': No such file or directory import 'package:navitank/Screens/maps.dart';. This is nonsense because the file exists and it works when I try it on my machine. But it won't work in docker.
My .gitlab-ci.yml looks like this:
image: cirrusci/flutter:2.8.1

stages:
  - build
  - test

doctor:
  stage: build
  script:
    - flutter doctor

build:
  stage: build
  script:
    - flutter build appbundle

widget-test:
  stage: test
  script:
    - flutter test

Does someone have an idea or a solution?


text:
Q: Objective C NSFetch Request I'm trying to understanding using fetch requests in core data. I would like to make a fetch request to select a Chord entity from core data.
@interface ChordViewController ()

@property NSFetchRequest* fetchRequest;
@property NSEntityDescription* entityDescription;
@property NSManagedObjectContext* managedObjectContext;

@end

self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
    self.managedObjectContext = [[NSManagedObjectContext alloc] init];
    self.fetchRequest = [[NSFetchRequest alloc] init];
    self.entityDescription = [NSEntityDescription entityForName:@"Chord" inManagedObjectContext:self.managedObjectContext];
    [self.fetchRequest setEntity:self.entityDescription];
}
return self;

Is the fetch request reusable, and if so, is it good practice to reuse the same fetch request between fetches such that is it a class member property? I would also like to know if the entityDescription should be a class member property too.
Thank you!

A: Fetch requests and entity descriptions can be reused, but the cost of creation is relatively low so recreating isn't much of an issue. Predicates are more costly to recreate if you use any.
I assume your code is just typed in as creating a managed object context like that won't work (it has no connection to a persistent store...).


text:
Q: Organising and examining a complicated CSV file I am being sent data in CSV files. The sender is providing helpful comments and lots of headings so that it is fine to look at in a spreadsheet environment. However, when I import it into Mathematica it becomes difficult to read using  TableForm mostly because many of the cells contain comments that are very long.
How do I restrict the length of TableForm entries?
Here is a minimum working example of the results of using Import[] on the CSV file.
ip = {{{"", "", ""}, {"", "", ""}, {"",
     "Data for tests on the 14th April 2021", ""}, {"", "", ""}, {"",
     "Here is a very long line. Only the start of the line needs to \
be seen since an overview of the spreadsheet is required. ", ""}, {"",
      "", ""}, {"",
     "The data is in 4 four sheets this sheet is the summary",
     ""}, {"", "", ""}, {"", "Start ", "End"}, {"Data 1", 2.`,
     5.`}, {"Data 2", 5.`, 9.`}, {"Data 3", 20.`, 25.`}, {"Data 4",
     12.`, 17.`}}, {{"x vals", "y vals"}, {2.`,
     0.3330287479237922`}, {3.`, 0.19273318644865778`}, {4.`,
     0.2689069410951601`}, {5.`, 0.08207429250157161`}}, {{"x vals",
     "y vals"}, {5.`, 0.45418961829920845`}, {6.`,
     0.571585992020961`}, {7.`, 0.2085062721975699`}, {8.`,
     0.4228854382612791`}, {9.`, 0.8204853099017002`}}, {{"x vals",
     "y vals"}, {20.`, 0.004555883050753273`}, {21.`,
     0.9461665188994238`}, {22.`, 0.5266492863708679`}, {23.`,
     0.993247994762222`}, {24.`, 0.40219540885589733`}, {25.`,
     0.7634085960638198`}}, {{"x vals", "y vals"}, {12.`,
     0.15418438184183136`}, {13.`, 0.6223264477185402`}, {14.`,
     0.9009276274909394`}, {15.`, 0.6832380927198871`}, {16.`,
     0.16021536248120283`}, {17.`, 0.27399014026061996`}}};
Dimensions[ip]

The Dimensions[] tells me that there are 5 sheets. So I look at the first sheet using TableForm.
TableForm[ip[[1]], TableSpacing -> {0, 1}]

As you can see the long comments in some CSV cells make some entries in the table much longer than others. I just want an overview of the contents so I don't want to see all the details in each entry. I probably need to do some form of converting to strings and then limiting the number of characters in each string.  I am sure there are other possibilities as well. Thanks for helping.

A: Maybe something like this? The following function will divide the available screen width into equally sized columns and then uses scrollbars to display content when it becomes too tall:
readableGrid[content_List, maxRowHeight : _ : 50, gridOpts : OptionsPattern[]] := Grid[
  Map[
   Pane[#, ImageSize -> {Full, UpTo[maxRowHeight]},
     Scrollbars -> {False, Automatic}, AppearanceElements -> None] &,
   content,
   {2}
   ],
  gridOpts,
  ItemSize -> Scaled[0.99/Max[Length /@ content]],
  Alignment -> Left
  ]
TabView[readableGrid /@ ip]

Alternatively, you can use ImageSize -> {UpTo[200], UpTo[maxRowHeight]} (or however wide you want your columns to be at most) in the Pane and leave out the ItemSize option in Grid. You can similarly also put a Pane with a scrollbar around the whole Grid to make sure the output cell itself remains manageable in size.

A: Using Grid and selecting text to display
grid[data_] := Grid[data, Background -> {None, 1 -> LightYellow}, Dividers -> Center]

heading = (ip[[1, 1 ;; 8]] // Map[Select[# != "" &]]) //. {} -> Nothing // Flatten // First

Grid[{{heading, SpanFromLeft},
  {grid@ip[[1, 9 ;;]], Splice@Table[grid[ip[[i]]], {i, 2, Length@ip}]}},
 Alignment -> Top,
 Frame -> All,
 ItemStyle -> {Automatic, 1 -> {Bold}}]

Could add a header to each of the sub-grids, "Summary", "Sheet 1", etc.


text:
Q: What's the best way to compute the coefficients of a polynomial from its roots? The poly function takes the roots of a polynomial as the input and returns the polynomial's coefficients. What is the underlying algorithm?
Is there a better way to compute the coefficients of a polynomial from its roots?

A: Note that:

*

*To obtain the polynomial p(x) (with leading coefficient 1) you need to multiply all terms of the form x−r, where r is a root. (Multiple roots should be considered several times according to their multiplicities.)

*Multiplication of polynomials is equivalent to convolution. In fact, the documentation of conv says

w = conv(u,v) returns the convolution of vectors u and v. If u and v are vectors of polynomial coefficients, convolving them is equivalent to multiplying the two polynomials.

So:
roots = [1 -2 3]; %// input (roots)
result = 1;  %// initiallize
for r = roots
    result = conv(result, [1 -r]);
end

In this example the result is
result =
     1    -2    -5     6

which is the same vector that poly returns.
Alternatively, you can do the convolution manually:
roots = [1 -2 3]; %// input (roots)
result = 1;  %// initiallize
for r = roots
    result = [result 0] + [0 -r*result];
end

This is equivalent to the following code with explicit loops, which should be closer to a C++ implementation:
roots = [1 -2 3]; %// input (roots)
result = nan(1,numel(roots)+1);  %// preallocate. Values will be overwritten
result(1) = 1; %// initiallize
for n = 1:numel(roots)
    result(n+1) = -roots(n)*result(n); %// update from right to left, due to overwriting
    for k = n:-1:2
        result(k) = result(k) - roots(n)*result(k-1);
    end
end

A: Since you solicited for a c++ answer.
A typical implementation would look like.
std::vector<int> poly( std::vector<int> roots )
{
    std::vector<int> result{1};
    for( size_t i = 0 ; i < roots.size() ; ++i)
    {
        std::vector<int> temp{result.begin(),result.end()};

        for(auto & item : temp )
            item *= ( -roots[i] );

        result.push_back(0);
        for( size_t j = 1 ; j < result.size() ; ++j)
        {
            result[j] += temp[j-1];
        }
    }
    return result;
}

Hope that helps


text:
Q: vector vs unique_ptr to c style function When I am interacting with a c-style function which style should I use.
I do plan on storing the data in a vector after it comes back from the c function. What are advantageous of one over the other?
{
  auto test = std::make_unique<double[]>(10);
  fooCstyle(test);
}

or
{
  auto test = std::vector<double>;
  test.reserve(10);
  fooCstyle(test);
}

A: In this case it makes no difference, it depends on what you want to do with that data later in cpp-styled code.
However your examples are wrong, it should look like this:
std::vector<char> buffer(10);
cstyle(buffer.data());

or
std::unique_ptr<char[]> test { new char[10] };
cstyle(test.get());


text:
Q: How do i check whether my list contains any symbols or numbers on python I am making a code breaker game on python and need to make a if statement that checks whether the list contains any symbols or numbers.
So it would tell me that:
list=[hello, bonjour, 4 , hola]`

contains a number.  And:
list2=[hello, bonjour, hola]

does not contain a number

A: Just use:
>>> test = 'abc123%def'
>>> any(not x.isalpha() for x in test)
True
>>> test2 = 'abc'
>>> any(not x.isalpha() for x in test2)
False


text:
Q: sem_open - valgrind complains about uninitialised bytes I have a trivial program:

int main(void)
{
  const char sname[]="xxx";
  sem_t *pSemaphor;
  if ((pSemaphor = sem_open(sname, O_CREAT, 0644, 0)) == SEM_FAILED) {
    perror("semaphore initilization");
    exit(1);
  }
  sem_unlink(sname);
  sem_close(pSemaphor);
}

When I run it under valgrind, I get the following error:
==12702== Syscall param write(buf) points to uninitialised byte(s)
==12702==    at 0x4E457A0: __write_nocancel (syscall-template.S:81)
==12702==    by 0x4E446FC: sem_open (sem_open.c:245)
==12702==    by 0x4007D0: main (test.cpp:15)
==12702==  Address 0xfff00023c is on thread 1's stack
==12702==  in frame #1, created by sem_open (sem_open.c:139)

The code was extracted from a bigger project where it ran successfully for years, but now it is causing segmentation fault.
The valgrind error from my example is the same as seen in the bigger project, but there it causes a crash, which my small example doesn't.

A: I see this with glibc 2.27-5 on Debian.  In my case I only open the semaphores right at the start of a long-running program and it seems harmless so far - just annoying.
Looking at the code for sem_open.c which is available at:
https://code.woboq.org/userspace/glibc/nptl/sem_open.c.html
It seems that valgrind is complaining about the line (270 as I look now):
if (TEMP_FAILURE_RETRY (__libc_write (fd, &sem.initsem, sizeof (sem_t)))
      == sizeof (sem_t)

However sem.initsem is properly initialised earlier in a fairly baroque manner, firstly by explicitly setting fields in the sem.newsem (part of the union), and then once that is done by a call to memset (L226-228):
  /* Initialize the remaining bytes as well.  */
  memset ((char *) &sem.initsem + sizeof (struct new_sem), '\0',
          sizeof (sem_t) - sizeof (struct new_sem));

I think that this particular shenanigans is all quite optimal, but we need to make sure that all of the fields of new_sem have actually been initialised... we find the definition in https://code.woboq.org/userspace/glibc/sysdeps/nptl/internaltypes.h.html and it is this wonderful creation:
struct new_sem
{
#if __HAVE_64B_ATOMICS
  /* The data field holds both value (in the least-significant 32 bytes) and
     nwaiters.  */
# if __BYTE_ORDER == __LITTLE_ENDIAN
#  define SEM_VALUE_OFFSET 0
# elif __BYTE_ORDER == __BIG_ENDIAN
#  define SEM_VALUE_OFFSET 1
# else
# error Unsupported byte order.
# endif
# define SEM_NWAITERS_SHIFT 32
# define SEM_VALUE_MASK (~(unsigned int)0)
  uint64_t data;
  int private;
  int pad;
#else
# define SEM_VALUE_SHIFT 1
# define SEM_NWAITERS_MASK ((unsigned int)1)
  unsigned int value;
  int private;
  int pad;
  unsigned int nwaiters;
#endif
};

So if we __HAVE_64B_ATOMICS then the structure has a data field which contains both the value and the nwaiters, otherwise these are separate fields.
In the initialisation of sem.newsem we can see that these are initialised correctly, as follows:
#if __HAVE_64B_ATOMICS
      sem.newsem.data = value;
#else
      sem.newsem.value = value << SEM_VALUE_SHIFT;
      sem.newsem.nwaiters = 0;
#endif
      /* pad is used as a mutex on pre-v9 sparc and ignored otherwise.  */
      sem.newsem.pad = 0;
      /* This always is a shared semaphore.  */
      sem.newsem.private = FUTEX_SHARED;

I'm doing all of this on a 64-bit system, so I think that valgrind is complaining about the initialisation of the 64-bit sem.newsem.data with a 32-bit value since from:
  value = va_arg (ap, unsigned int);

We can see that value is defined simply as an unsigned int which will usually still be 32 bits even on a 64-bit system (see What should be the sizeof(int) on a 64-bit machine?), but that should just be an implicit cast to 64-bits when it is assigned.
So I think this is not a bug - just valgrind getting confused.


text:
Q: bootstrap para margin spacing I just started bootstrap and I had an issue which I am not able to resolve
when I give margin to my section in code the third section comes down although I have given width to be col-md-4 I'm not able to give margin in order to separate the sections also there is one small issue when the browserwidth goes less than 768px the section stack (which I want) but a scroll bar to view from left to right also comes which I don't won't can you please help me and sorry for posting code like this I'm new to stackoverflow.

    body {
     background: #F13421;
     font-size: 16px;
     margin: 0;
    }

    #header-nav {
     border-radius: 0;
    }
    .container {
     border: none;
     margin-left: auto;
     margin-right: auto;
     margin-top: 10px;
     margin-bottom: 0;

     padding: 10px 10px 0 10px;

    }

    .navbar-brand h1 {
       font-size: 2em;
       margin-top: -5px;
       margin-bottom: 40px;
       line-height: 0.65;
    }

    #nav-list {
     margin-top: 0;
     margin-bottom: 0;
     background: #F1F021;
    }

    #nav-list hr {

    width: 90%;
    }
    .row {
     margin: 10px;
    }
    #tiles section {
     background: #D3D3D3 ;
        margin: 5px;

    }
 <!DOCTYPE html>

        <meta charset="utf-8">
     <meta name="viewport" content="width=device-width, initial-scale=1">

     <link rel="stylesheet" href="css/bootstrap.min.css">
        <link rel="stylesheet" href="css/styles.css">

     <title>Module 3 Solution</title>

Food, LLC

               <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#collapsable-nav" aria-expanded="false">

                          Toggle navigation

               </button>

Chicken

                       Beef

                       Sushi

Our Menu

Chicken

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus dignissimos aut quasi quibusdam aspernatur possimus officia nulla consectetur velit! At, asperiores dolorem. Et iure assumenda, repudiandae laudantium, voluptatibus ex dignissimos, eum quaerat ducimus cupiditate corporis totam. Illo, alias voluptatem accusamus ut natus consequuntur quis laboriosam doloribus porro vero assumenda quo temporibus quos quam quisquam, libero quod, itaque eius sit ducimus totam iste possimus architecto debitis? Commodi ut minima maiores consequuntur voluptates unde deleniti error vero tempora, eligendi blanditiis, deserunt aliquam nobis porro dolores tenetur amet eius! Aspernatur, vitae. Suscipit, dolores quos doloribus. Velit repudiandae provident a, in ad id aspernatur dolor ratione eos placeat, ex temporibus ipsum eligendi sequi reprehenderit cupiditate perferendis eaque, explicabo blanditiis nemo dolorem aperiam minima deleniti. Tempore, rem, quam? Totam non reiciendis amet, at reprehenderit inventore, adipisci nesciunt itaque dolorum asperiores, ducimus corrupti quam impedit quaerat autem quod officia tempora. Itaque dicta deleniti fugit, laudantium rerum sint consectetur asperiores, quia veritatis dignissimos esse in nesciunt distinctio facere iure facilis voluptatibus placeat voluptate voluptatum expedita animi a veniam nulla ea. Enim aliquid, non. Necessitatibus nam fugiat autem quae qui quam consequatur repudiandae quidem ipsam impedit distinctio, sequi doloribus, quaerat quod ab maxime. Harum facilis sed commodi reprehenderit?
(End of Chicken Section) Back to Top

Beef

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus dignissimos aut quasi quibusdam aspernatur possimus officia nulla consectetur velit! At, asperiores dolorem. Et iure assumenda, repudiandae laudantium, voluptatibus ex dignissimos, eum quaerat ducimus cupiditate corporis totam. Illo, alias voluptatem accusamus ut natus consequuntur quis laboriosam doloribus porro vero assumenda quo temporibus quos quam quisquam, libero quod, itaque eius sit ducimus totam iste possimus architecto debitis? Commodi ut minima maiores consequuntur voluptates unde deleniti error vero tempora, eligendi blanditiis, deserunt aliquam nobis porro dolores tenetur amet eius! Aspernatur, vitae. Suscipit, dolores quos doloribus. Velit repudiandae provident a, in ad id aspernatur dolor ratione eos placeat, ex temporibus ipsum eligendi sequi reprehenderit cupiditate perferendis eaque, explicabo blanditiis nemo dolorem aperiam minima deleniti. Tempore, rem, quam? Totam non reiciendis amet, at reprehenderit inventore, adipisci nesciunt itaque dolorum asperiores, ducimus corrupti quam impedit quaerat autem quod officia tempora. Itaque dicta deleniti fugit, laudantium rerum sint consectetur asperiores, quia veritatis dignissimos esse in nesciunt distinctio facere iure facilis voluptatibus placeat voluptate voluptatum expedita animi a veniam nulla ea. Enim aliquid, non. Necessitatibus nam fugiat autem quae qui quam consequatur repudiandae quidem ipsam impedit distinctio, sequi doloribus, quaerat quod ab maxime. Harum facilis sed commodi reprehenderit?
(End of Beef Section) Back to Top

Sushi

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus dignissimos aut quasi quibusdam aspernatur possimus officia nulla consectetur velit! At, asperiores dolorem. Et iure assumenda, repudiandae laudantium, voluptatibus ex dignissimos, eum quaerat ducimus cupiditate corporis totam. Illo, alias voluptatem accusamus ut natus consequuntur quis laboriosam doloribus porro vero assumenda quo temporibus quos quam quisquam, libero quod, itaque eius sit ducimus totam iste possimus architecto debitis? Commodi ut minima maiores consequuntur voluptates unde deleniti error vero tempora, eligendi blanditiis, deserunt aliquam nobis porro dolores tenetur amet eius! Aspernatur, vitae. Suscipit, dolores quos doloribus. Velit repudiandae provident a, in ad id aspernatur dolor ratione eos placeat, ex temporibus ipsum eligendi sequi reprehenderit cupiditate perferendis eaque, explicabo blanditiis nemo dolorem aperiam minima deleniti. Tempore, rem, quam? Totam non reiciendis amet, at reprehenderit inventore, adipisci nesciunt itaque dolorum asperiores, ducimus corrupti quam impedit quaerat autem quod officia tempora. Itaque dicta deleniti fugit, laudantium rerum sint consectetur asperiores, quia veritatis dignissimos esse in nesciunt distinctio facere iure facilis voluptatibus placeat voluptate voluptatum expedita animi a veniam nulla ea. Enim aliquid, non. Necessitatibus nam fugiat autem quae qui quam consequatur repudiandae quidem ipsam impedit distinctio, sequi doloribus, quaerat quod ab maxime. Harum facilis sed commodi reprehenderit?
(End of Sushi Section) Back to Top

A: There are basic HTML issues. First you need close paragraphs and then start new divs. Secondly, there are fundamental designing issues. Anyways. Here is the updated code for responsive navbar layout ;-).

body {
    background: #F13421;
    font-size: 16px;
    margin: 0;
}

#main-content{
padding-top: 50px;
}

.chicken, .beef, .sushi {
background-color: #D3D3D3 ;
    padding: 10px;
}

  Food LLC
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">

  </button>

        Chicken (current)

        Beef

        Sushi

Our Menu

Chicken

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus dignissimos aut quasi quibusdam aspernatur possimus officia nulla consectetur velit! At, asperiores dolorem. Et iure assumenda, repudiandae laudantium, voluptatibus ex dignissimos, eum quaerat ducimus cupiditate corporis totam. Illo, alias voluptatem accusamus ut natus consequuntur quis laboriosam doloribus porro vero assumenda quo temporibus quos quam quisquam, libero quod, itaque eius sit ducimus totam iste possimus architecto debitis? Commodi ut minima maiores consequuntur voluptates unde deleniti error vero tempora, eligendi blanditiis, deserunt aliquam nobis porro dolores tenetur amet eius! Aspernatur, vitae. Suscipit, dolores quos doloribus. Velit repudiandae provident a, in ad id aspernatur dolor ratione eos placeat, ex temporibus ipsum eligendi sequi reprehenderit cupiditate perferendis eaque, explicabo blanditiis nemo dolorem aperiam minima deleniti. Tempore, rem, quam? Totam non reiciendis amet, at reprehenderit inventore, adipisci nesciunt itaque dolorum asperiores, ducimus corrupti quam impedit quaerat autem quod officia tempora. Itaque dicta deleniti fugit, laudantium rerum sint consectetur asperiores, quia veritatis dignissimos esse in nesciunt distinctio facere iure facilis voluptatibus placeat voluptate voluptatum expedita animi a veniam nulla ea. Enim aliquid, non. Necessitatibus nam fugiat autem quae qui quam consequatur repudiandae quidem ipsam impedit distinctio, sequi doloribus, quaerat quod ab maxime. Harum facilis sed commodi reprehenderit?

(End of Chicken Section) Back to Top

Beef

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus dignissimos aut quasi quibusdam aspernatur possimus officia nulla consectetur velit! At, asperiores dolorem. Et iure assumenda, repudiandae laudantium, voluptatibus ex dignissimos, eum quaerat ducimus cupiditate corporis totam. Illo, alias voluptatem accusamus ut natus consequuntur quis laboriosam doloribus porro vero assumenda quo temporibus quos quam quisquam, libero quod, itaque eius sit ducimus totam iste possimus architecto debitis? Commodi ut minima maiores consequuntur voluptates unde deleniti error vero tempora, eligendi blanditiis, deserunt aliquam nobis porro dolores tenetur amet eius! Aspernatur, vitae. Suscipit, dolores quos doloribus. Velit repudiandae provident a, in ad id aspernatur dolor ratione eos placeat, ex temporibus ipsum eligendi sequi reprehenderit cupiditate perferendis eaque, explicabo blanditiis nemo dolorem aperiam minima deleniti. Tempore, rem, quam? Totam non reiciendis amet, at reprehenderit inventore, adipisci nesciunt itaque dolorum asperiores, ducimus corrupti quam impedit quaerat autem quod officia tempora. Itaque dicta deleniti fugit, laudantium rerum sint consectetur asperiores, quia veritatis dignissimos esse in nesciunt distinctio facere iure facilis voluptatibus placeat voluptate voluptatum expedita animi a veniam nulla ea. Enim aliquid, non. Necessitatibus nam fugiat autem quae qui quam consequatur repudiandae quidem ipsam impedit distinctio, sequi doloribus, quaerat quod ab maxime. Harum facilis sed commodi reprehenderit?

(End of Beef Section) Back to Top

Sushi

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus dignissimos aut quasi quibusdam aspernatur possimus officia nulla consectetur velit! At, asperiores dolorem. Et iure assumenda, repudiandae laudantium, voluptatibus ex dignissimos, eum quaerat ducimus cupiditate corporis totam. Illo, alias voluptatem accusamus ut natus consequuntur quis laboriosam doloribus porro vero assumenda quo temporibus quos quam quisquam, libero quod, itaque eius sit ducimus totam iste possimus architecto debitis? Commodi ut minima maiores consequuntur voluptates unde deleniti error vero tempora, eligendi blanditiis, deserunt aliquam nobis porro dolores tenetur amet eius! Aspernatur, vitae. Suscipit, dolores quos doloribus. Velit repudiandae provident a, in ad id aspernatur dolor ratione eos placeat, ex temporibus ipsum eligendi sequi reprehenderit cupiditate perferendis eaque, explicabo blanditiis nemo dolorem aperiam minima deleniti. Tempore, rem, quam? Totam non reiciendis amet, at reprehenderit inventore, adipisci nesciunt itaque dolorum asperiores, ducimus corrupti quam impedit quaerat autem quod officia tempora. Itaque dicta deleniti fugit, laudantium rerum sint consectetur asperiores, quia veritatis dignissimos esse in nesciunt distinctio facere iure facilis voluptatibus placeat voluptate voluptatum expedita animi a veniam nulla ea. Enim aliquid, non. Necessitatibus nam fugiat autem quae qui quam consequatur repudiandae quidem ipsam impedit distinctio, sequi doloribus, quaerat quod ab maxime. Harum facilis sed commodi reprehenderit?

(End of Sushi Section) Back to Top

</div

The JS Fiddle Link as follows:
https://jsfiddle.net/hilalrehan/s2kezpgq/
If you want nav bar to be not responsive. Please follow this link
https://jsfiddle.net/hilalrehan/Lwkm1zdc/51/
I believe this will solve your problem.


text:
Q: "App not installed" error when trying to install signed APK with V2 signature on Android 6.0 device I have finished coding the latest update for my android app. So once I did this, I generated the signed apk and installed it on one of my devices having Android 7.0 OS. The installation worked fine.
But when I tried installing it on two of my other devices running on Android 6.0, I got the "App not installed error". I googled a lot, tried many of the solutions, even factory reset my device, and tried again, it still showed same error when installing the apk.

I have updated to Android Studio 2.3.3 and I found that when generating signed apk, there were some new options that weren't there in previous versions of android studio. By default, it was set to V2 signature. So I checked both V1 and V2 and generated the apk.
When I tried to install this apk on my device running on Android 6.0, it worked!!.
Can someone explain the significance of these V1 and V2 signatures? Will I encounter some issues when publishing this update on Google Play, since my previous versions of the app (currently on Google Play) were signed with a lower version of Android Studio which did not present these V1 and V2 options when signing?
My app would be running on wide range of devices from Android 4.4 to current Android OS 7.1. Is signing with both V1 and V2 signatures the right way to go for me, to publish the update on Google Play (once I test the apk on my devices), or should I enable only V1 signature (enabling only V2 signature caused this issue in the first place)?


text:
Q: When does autoexec.sas execute In this SAS tutorial
AUTOEXEC.SAS is processed once, when the SAS application is started

I am confused about the term SAS application. When I installed SAS, it came with many components like Di studio, OLAP studio , Management console, SAS enterprise guide. Will the autoexec.sas execute when any of these components start up?

A: It is talking about the sas.exe process; when that runs. autoexec.sas is processed.  That may occur multiple times if you have a server that spawns multiple processes (or even you instruct Enterprise Guide to do so locally).


text:
Q: The page isn't redirecting properly I used RewriteOptions to add "/" to end all urls, but when publishing to the iis server I get a "page does not redirect correctly" error.
i using this
var options = new RewriteOptions() //add '/' to end of url
        .AddRedirect("(.*[^/])$", "$1/")
        .AddRedirectToHttpsPermanent();
            app.UseRewriter(options);

A:
Can you suggest a suitable pattern?

Well, assuming you have already installed URL Rewrite Modulefrom the below official site. Here is the reference for you.

Configure URL Rewrite Pattern and Rules:
As, so far your requirement is to add additional slash / of your website, Thus,you can set this (.*[^/])$ pattern on your URL Rewrite module in IIS as below:

Steps for configuration:

*

*Select your site in IIS

*Double Click on URL Rewrite under HTTP Features Table

*Click On Add Rules(s) top right

*Select Append Or remove the trainin slash symbol

*Select Appended if does not exist from the dropdown

*Click OK

Note: You can customize your rules as well. If you encounter any concern on this you can have a look below screen capture how to do it.
Output:

If you still need more further assistance, you could have look on our official document here


text:
Q: Upload File to Quickbooks online with IDS V3 I would like to upload a file to QuickBooks Online using IDS V3.
I followed the steps described here
https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/020_key_concepts/attachments.
Here is my source code
 URL url = new URL("https://quickbooks.api.intuit.com/v3/company/My_company_ID/upload");
    HttpURLConnection request = (HttpURLConnection) url.openConnection();
    request.setDoOutput(true);
    request.setRequestMethod("POST");
    HttpParameters para = new HttpParameters();
    //String status = URLEncoder.encode("中 文","utf-8").replaceAll("\\+", "%20");
    //para.put("status", status);
    String boundary = "---------------------------37531613912423";
    //String content = "--"+boundary+"\r\nContent-Disposition: form-data; name=\"status\"\r\n\r\n";
    String pic = "\r\n--"+boundary+"\r\nContent-Disposition: form-data; name=\"pic\"; filename=\"postpic.gif\"\r\nContent-Type: image/gif\r\n\r\n";
    byte[] end_data = ("\r\n--" + boundary + "--\r\n").getBytes();
    File f = new File("/Users/cnanfack/Documents/oml_map1.gif");
    FileInputStream stream = new FileInputStream(f);
    byte[] file = new byte[(int)f.length()];
    stream.read(file);
    String lineEnd = "\r\n";
    String header =   "Content-Disposition: form-data; name=\"file_metadata_0\""+lineEnd
    +"Content-Type: application/xml; charset=UTF-8"+lineEnd
    +"Content-Transfer-Encoding: 8bit"+lineEnd;

   String attachable =  header+"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Attachable xmlns=\"http://schema.intuit.com/finance/v3\" domain=\"QBO\" sparse=\"false\">"
    +"<EntityRef type=\"Bill\">285</EntityRef>"
    +"<Size>4099</Size>"
    +"<ContentType>image/gif</ContentType>"
    +"<FileName>postpic.gif</FileName>"
    +"</Attachable>";

    request.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
    //request.setRequestProperty("Content-Length", String.valueOf(boundary.getBytes().length+"test".getBytes().length+pic.getBytes().length+f.length()+end_data.length));
    //consumer.setAdditionalParameters(para);
      consumer.sign(request);
      OutputStream ot = request.getOutputStream();
      ot.write(end_data);
      ot.write(attachable.getBytes());
      ot.write(end_data);
      //ot.write(status.getBytes());
      ot.write(pic.getBytes());
      ot.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());
      ot.write(file);
      ot.write(end_data);
      ot.flush();
      ot.close();
    System.err.println("Sending request...");
    request.connect();
    System.err.println("Response: " + request.getResponseCode() + " "
          + request.getResponseMessage());
    BufferedReader reader =new BufferedReader(new InputStreamReader(request.getInputStream()));
    String b = null;
    while((b = reader.readLine())!=null){
       System.err.println(b);
    }

The returned result:
Response: 200 OK
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><IntuitResponse xmlns="http://schema.intuit.com/finance/v3" time="2013-11-10T20:24:27.823-08:00"/>

But I don't see the file on Quickbooks Online.
Maybe I miss something. Can someone help me?
Thank you in advance

A: I had tried this Upload endpoint call using Java Devkit. It is working fine. PFB details.
 -  Request URI : https://quickbooks.api.intuit.com/v3/company/688779980/upload? Http
 -  Method : POST Content-Disposition: form-data; name="file_metadata_2bddf"
 -  Content-Type: application/xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Attachable xmlns="http://schema.intuit.com/finance/v3">
    <FileName>images.jpg</FileName>
    <ContentType>image/jpeg</ContentType>
    <Lat>25.293112341223</Lat>
    <Long>-21.3253249834</Long>
    <PlaceName>Fake Place</PlaceName>
    <Note>Attachable note 900a49e1</Note>
    <Tag>Attachable tag 900a49e1</Tag>
</Attachable>

Response XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<IntuitResponse xmlns="http://schema.intuit.com/finance/v3" time="2013-11-12T05:58:25.296-08:00">
    <AttachableResponse>
        <Attachable domain="QBO" sparse="false">
            <Id>100000000000543524</Id>
            <SyncToken>0</SyncToken>
            <MetaData>
                <CreateTime>2013-11-12T05:58:26-08:00</CreateTime>
                <LastUpdatedTime>2013-11-12T05:58:26-08:00</LastUpdatedTime>
            </MetaData>
            <FileName>images.jpg</FileName>
            <FileAccessUri>/v3/company/688779980/download/100000000000543524</FileAccessUri>
            <TempDownloadUri>https://intuit-qbo-prod-19.s3.amazonaws.com/688779980%2Fattachments%2Fimages-1384264705362.jpg?Expires=1384265606&AWSAccessKeyId=AKIAJEXDXKNYCBUNCCCQ&Signature=ESZPzeO%2B5YWxw8VOWMVMBRnvIdw%3D</TempDownloadUri>
            <Size>58616</Size>
            <ContentType>image/jpeg</ContentType>
            <Lat>25.293112341223</Lat>
            <Long>-21.3253249834</Long>
            <PlaceName>Fake Place</PlaceName>
            <Note>Attachable note 8219e79a</Note>
            <Tag>Attachable tag 8219e79a</Tag>
            <ThumbnailFileAccessUri>/v3/company/688779980/attachable-thumbnail/100000000000543524</ThumbnailFileAccessUri>
        </Attachable>
    </AttachableResponse>
</IntuitResponse>

From the ThumnailFileAccessUri property I got the following attachment URI which I had used for Download endpoint.
/v3/company/688779980/attachable-thumbnail/100000000000543524
Download Endpoint(GET)-
https://quickbooks.api.intuit.com/v3/company/688779980/download/100000000000543521

JAVA/.Net SDK download link - https://developer.intuit.com/docs/0025_quickbooksapi/0055_devkits
Hope it will be useful.
EDIT- Adding Java code snippet
public static void executeUploadForImageFilePoc(DataService service) throws ParseException, FMSException, FileNotFoundException {
    System.out.println("executeUploadForImageFile");
    String uuid = UUID.randomUUID().toString().substring(0, 8);
    Attachable attachable1 = new Attachable();
    //attachable.setSize(new Long("34234"));
    attachable1.setLat("25.293112341223");
    attachable1.setLong("-21.3253249834");
    attachable1.setPlaceName("Fake Place");
    attachable1.setNote("Attachable note " + uuid);
    attachable1.setTag("Attachable tag " + uuid);
    Attachable attachable = attachable1;
    attachable.setFileName("images.jpg");
    attachable.setContentType("image/jpeg");
    File file = new File("C:\\images_new.jpg");
    InputStream in = new FileInputStream(file);

    //Upload endpoint call
    Attachable attachableOutput = service.upload(attachable, in);

    //Check return XML
    attachable.getFileAccessUri();
    System.out.println(attachableOutput.getFileAccessUri());
    System.out.println(attachableOutput.getFileName());

    //Download endpoint call
    InputStream output = service.download(attachableOutput);
    try {
        BufferedImage bImageFromConvert = ImageIO.read(output);

        ImageIO.write(bImageFromConvert, "jpg", new File("C:\\images_new_manas.jpg"));

    } catch (IOException e) {
        throw new FMSException("Error while reading the upload file.", e);
    }
}

Thanks

A: I have a working code in dotnet. See if it works for you:
DataService.DataService commonServiceQBO= new DataService.DataService(qboContextoAuth);
      string imagePath = string.Concat(AppDomain.CurrentDomain.BaseDirectory, "\\", "Services\\Resource\\image.jpg");
                        System.IO.FileInfo file = new System.IO.FileInfo(imagePath);
                        Attachable attachable = new Attachable();
                        attachable.AttachableRef = new AttachableRef[1];
                        attachable.AttachableRef[0].EntityRef = new ReferenceType();
                        attachable.AttachableRef[0].EntityRef.type = "Bill";
                        attachable.AttachableRef[0].EntityRef.Value = "12";
                        attachable.Lat = "25.293112341223";
                        attachable.Long = "-21.3253249834";
                        attachable.PlaceName = "Fake Place";
                        attachable.Note = "Attachable note123 ";
                        attachable.Tag = "Attachable tag123 ";
                        using (System.IO.FileStream fs = file.OpenRead())
                                {
                                    attachable.ContentType = "image/jpeg";
                                    attachable.FileName = file.Name;
                                    Attachable attachableUploaded = commonServiceQBO.Upload(attachable, fs);
                                }

For download use:
    byte[] responseByte = service.Download(attachableUploaded);


text:
Q: How to avoid redundant module naming for Single struct modules in rust? Maybe this just bothers me, but in certain cases I'd like to have one struct per module file.
Let's say I have a struct named User like this:
struct User {
    name: String
}

And let's say I have a file structure like where the User struct code is located in src/models/user.rs like this:
src/
    models/
           user.rs

And now I'd like to be able to use the User struct like this:
use crate::models::User;

Of course that's not possible. Instead it needs to be referred with:
use crate::models::user::User;

To me this looks quite ugly and I consider it redundant if both words, user and User, are part of the module path.
Is there any solution that doesn't seem to be as "clumsy" as the one just described?
It might as well be the case that I missed something regarding how the rust module naming system works.

A: You can re-export the User struct in the models module with pub use user::User; and optionally make the user submodule private (so that no one outside of models can access it). Externally, the User struct can then be referred to as a member of the models module with crate::models::User.
See also:

*

*The Rust Reference: use Visibility


text:
Q: Where can I modify my model to fix this error when I make a join with doctrine? I am using symfony 1.4 and doctrine, I currently created the structure on the schema.yml for my 2 tables, but when I make the query I get this exception

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'o.id' in 'on clause'. Failing Query: "SELECT o.id_aditional_details AS o__id_aditional_details, o.name AS o_name, o.type AS o_type, o.group AS o__group FROM ohrm_aditional_details o INNER JOIN ohrm_details_info o2 ON o.id = o2.ohrm_aditional_details_id WHERE (o2.user = 4)"

I have to tables, details_info and aditional_details, aditional details requires in one of the fields the id of one entry in details_info , I dont know this error because Ive done it with other tables, but this time I have no idea whats going on...
My schema.yml is like this
OhrmAditionalDetails:
  connection: doctrine
  tableName: ohrm_aditional_details
  columns:
    id_aditional_details:
      type: integer(11)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: true
    name:
      type: string(100)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    type:
      type: integer(4)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    group:
      type: integer(4)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
OhrmDetailsInfo:
  connection: doctrine
  tableName:  ohrm_details_info
  columns:
    id_details_info:
      type: integer(11)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: true
    aditional_info:
      type: integer(11)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    result:
      type: string(200)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    user:
      type: integer(11)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
  relations:
    OhrmAditionalDetails:
    local: aditional_info
    foreign: id_aditional_details
    type: one
    HsHrEmployee:
    local: user
    foreign: emp_number
    type: one

and my query, quite simple
try
{
    $q = Doctrine_Query::create()
        ->select('*')
        ->from('OhrmAditionalDetails D')
        ->innerJoin('D.OhrmDetailsInfo I')
        ->where("I.user = $id");

    $result = $q->execute();
    return $result;
}
catch(Exception $e)
{
    print_r ($e->getMessage());
    return null;
}

in the case $id = 4
Any idea? Ive tried
php symfony cc
php symfony doctrine:build-model
php symfony orangehrm:publish-assets
php symfony cc

but nothing...

A: It's trying to guess the name of the column to join on, e.g. looking for id instead of id_aditional_details.
It looks like you have defined it properly in your schema.yml, but it's interpreting it as empty because you haven't indented your yaml properly. Try:
  relations:
    OhrmAditionalDetails:
      local: aditional_info
      foreign: id_aditional_details
      type: one
    HsHrEmployee:
      local: user
      foreign: emp_number
      type: one


text:
Q: "getActiveSheet" gets and changes the value of cell. I want to select a cell from a different sheet but I don't know the syntax for it Basically, getActiveSheet changes the value within the same sheet. How do I select another sheet within the same Google Sheet?
Thank You!
function getData() {
  var queryString = Math.random();

  var cellFunction1 = '=IMPORTXML("' + SpreadsheetApp.getActiveSheet().getRange('A1').getValue() + '?' + queryString + '","'+ SpreadsheetApp.getActiveSheet().getRange('A2').getValue() + '")';
  SpreadsheetApp.getActiveSheet().getRange('C1').setValue(cellFunction1);
}

A: You can use getSheetByName("sheetname") to get a specific sheet.
For example:
function getData() {
  var queryString = Math.random();

  var cellFunction1 = '=IMPORTXML("' + SpreadsheetApp.getSheetByName("sheetname").getRange('A1').getValue() + '?' + queryString + '","'+ SpreadsheetApp.getSheetByName("sheetname").getRange('A2').getValue() + '")';
  SpreadsheetApp.getSheetByName("sheetname").getRange('C1').setValue(cellFunction1);
}

You can find the full reference documentation for the spreadsheet class here
Finally if you don't know the sheet names you may also be find the getSheets() method useful, which will return an array of all sheets in the spreadsheet

A: Change
SpreadsheetApp.getActiveSheet()
to
SpreadsheetApp.getSheetByName("Name_of_the_sheet/tab")

Reference
getSheetByName()


text:
Q: How can I simply return objects in PDO? Trying out PDO for the first time.
$dbh = new PDO("mysql:host=$hostname;dbname=animals", $username, $password);

$stmt = $dbh->query("SELECT * FROM animals");
$stmt->setFetchMode(PDO::FETCH_INTO, new animals);

foreach($stmt as $animals)
{
    echo $animals->name;
}

If i skip the setFetchMode() method, then I need to call $animals["name"] which I do not want.
But I do not want to call the setFetchMode() for each query I do.
Is there a way to set the default FetchMode ? Or some other method to make the query() return objects with one global setting.

A: Perhaps you could try extending the PDO class to automatically call the function for you... in brief:

class myPDO extends PDO
{
   function animalQuery($sql)
   {
     $result = parent::query($sql);
     $result->setFetchMode(PDO::FETCH_INTO, new animals);
     return $result;
   }

//   // useful if you have different classes
//   function vegetableQuery($sql)
//   {
//     $result = parent::query($sql);
//     $result->setFetchMode(PDO::FETCH_INTO, new vegetables);
//     return $result;
//   }
}

$dbh = new myPDO("mysql:host=$hostname;dbname=animals", $username, $password);

$stmt = $dbh->animalQuery("SELECT * FROM animals");

foreach($stmt as $animals)
{
    echo $animals->name;
}

A: Since PDO would need to know what object you want to fetch into, you would need to specify it manually.
But of you just want to use the object to retrieve the data rather than an array and do not care if its not an animal object, you can use anonymous objects by default when you set the attribute after the connection string which could be done in a wrapped constructor
  $connection = new PDO($connection_string);
  //PDO::FETCH_OBJ: returns an anonymous object with property names that correspond to the column names returned in your result set
  $connection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);

Then all queries will return objects. Though it's not exactly what you want its close.

You could also inject the data into your animal class:
while($dataObj = ...) {
 $animal = new Animal($dataObj);
}

If you look at the query function it is possible to change some options by passing extra parameters:
http://www.php.net/manual/en/pdo.query.php
I haven't tested it but it looks like it gets you close to what you want

A: Speaking of fetching objects in general, PDO has half a dozen different modes for this task. I had to write a dedicated article regarding fetching objects with PDO to list them all.
Regarding your particular questions,

How can I simply return objects in PDO?

Simply use the PDO::FETCH_OBJ mode

Is there a way to set the default FetchMode?

It depends.
If your concern is just a syntax, and you simply want to use $animal->name instead of $animal['name'], then you can ask PDO to create instances of stdClass() by default. To do so, just add
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ

to the list of your PDO connection options (the link is to another example I wrote, which I highly recommend to check out, because connection to PDO is a complex business that is anything but a single line from your example).
Having this option set you can have your object syntax right away:
$stmt = $dbh->query("SELECT * FROM animals");
foreach($stmt as $animal)
{
    echo $animal->name;
}

While in case you need to fetch into a particular class, for a list of objects either use your current approach with setFetchMode() / foreach
or you can use fetchAll() with a dedicated PDO::FETCH_CLASS fetch mode:
$herd = $pdo->query('SELECT name FROM animals')->fetchAll(PDO::FETCH_CLASS, 'Animal');

This is all you can have, simply because you need to tell PDO, instances of which particular class you will need.
There are other options like providing constructor arguments and such. You can check them out in the article linked above.

A: You can try this way:
$dbh = new PDO("mysql:host=$hostname;dbname=animals", $username, $password);

$stmt = $dbh->query("SELECT * FROM animals");
$stmt->setFetchMode(PDO::FETCH_CLASS, animals::class);

foreach($stmt as $animals)
{
    echo $animals->name;
}


text:
Q: How to create a CLI in Python that can be installed with PIP? As the title suggests, I'm trying to make a python script accessible from the command line. I've found libraries like click and argv that make it easy to access arguments passed from the command line, but the user still has to run the script through Python.
Instead of
python /location/to/myscript.py

I want to be able to just do
myscript

from any directory
From what I understand, I can achieve this on my computer by editing my PATH variables. However, I would like to be able to simply do:
pip install myscript

and then access the script by typing myscript from anywhere. Is there some special code I would put in the setup.py?

A: Use console_scripts to hook to a specific Python method (not a whole executable), setup.py file:
from setuptools import setup
setup(
    ...
    entry_points = {
        'console_scripts': ['mybinary=mymodule.command_line:cli'],
    },
    name='mymodule',
    ...
)

the command_line.py script would be:
import mymodule

def cli():
    print("Hello world!")

and the project directory would look like this:
myproject/
    mymodule/
        __init__.py
        command_line.py
        ...
    setup.py

Setuptools will generate a standalone script 'shim' which imports your module and calls the registered function.

That shim allows you to call mybinary directly and ensures it's correctly invoked by python. It provides platform-specific shims (i.e., on Windows it generates a .exe).
See packaging documentation for more details.

A: You can do this with setuptools
an example of a nice setup.py (say your package requires pandas and numpy):
import setuptools
setuptools.setup(
    name='myscript',
    version='1.0',
    scripts=['./scripts/myscript'],
    author='Me',
    description='This runs my script which is great.',
    packages=['lib.myscript'],
    install_requires=[
        'setuptools',
        'pandas >= 0.22.0',
        'numpy >= 1.16.0'
    ],
    python_requires='>=3.5'
)

Your directory should be setup as follows:
[dkennetz package]$ ls
lib scripts setup.py

inside lib would be:
[dkennetz package]$ ls lib
myscript

inside of myscript would be:
[dkennetz package]$ ls lib/myscript
__main__.py
__init__.py
helper_module1.py
helper_module2.py

main would be used to call your function and do whatever you want to do.
inside scripts would be:
[dkennetz package]$ ls scripts
myscript

and the contents of myscript would be:
#!/usr/bin/env bash

if [[ ! $@ ]]; then
    python3 -m myscript -h
else
    python3 -m myscript $@
fi

then to run you do: python setup.py install
which will install your program and all of the dependencies you included in install_requires=[] in your setup.py and install myscript as a command-line module:
[dkennetz ~]$ myscript

A: Assuming you are in the bash shell and python 3 is installed and you want to be able to do what you are requesting, you will need to append the path of the script file to your PATH variable in your .bash_profile file in your home directory.  Also, in your python script file, you need to have something similar to the following as the first line of the script:
#!/usr/bin/env python3

Additionally, you can remove the extension (.py) from the script file, such that, as in my example above, the filename is a script in contrast to script.py.
You will also need to set the permission of your filename to
chmod 755 filename
If you want the script to be accessible system-wide, you will need to modify /etc/profile and add to the bottom of the file:
export PATH=$PATH:/path/to/script

Alternatively, if you move the python script file to /usr/local/bin, it may not be necessary to make any profile changes as this directory is often already in the PATH.
To see the value of PATH issue the following command at the shell
echo $PATH

A: I know this question is older and for a project using setuptools definitely use Tombart's answer
That said, I have been using poetry and that uses a .toml file and if that's what you use, and since this is likely what others will search for here's how you package a script with a toml file (at least with poetry)
[project.scripts]
myscript = "mybinary=mymodule.command_line:cli"

Not sure if this works for flit or any other package managers but it works for poetry


text:
Q: Can I refer to the default target on the "make" command line? If I type just
$ make

it will invoke the make command with the default target (typically the first target specified in the Makefile, but the rules are a bit more complicated than that).
Is there a way to specify the default target on the command line without knowing what it is, other than by simply omitting the target name?
What I'd like to be able to do is combine these two commands:
$ make clean
$ make

into a single invocation of make.  If I happen to know that the default target is all, I can type:
$ make clean all

but that doesn't work if I don't know what the default target is.
Ideally, I'd like some syntax that refers to the default target (the GNU make manual calls it the "default goal").  This:
 $ make clean .DEFAULT_GOAL

shows the general idea, but it doesn't work.
Second best would be a simple and reliable way to determine, from the command line, what the default target is:
$ make clean $(get-default-target)

A GNU-specific solution would be ok.
I suspect, from a quick look into the manual, that there's no good way to do this.

A: For a shot at the second-best solution, you can parse the default goal from the output of make -pq:
make -pq  | sed -ne 's/^.DEFAULT_GOAL := //p'


text:
Q: Cannot install virtualbox 5.1 on Ubuntu 17.04 I have downloaded virtualbox 5.1 from the virtualbox website but I can't install it. When I open the .deb file with ubuntu software and I click on Install, it doesn't do nothing. I also tried from the command line, but it says that there's an error on the dependencies. I also tried by adding the repository and then download the package, but it says that it's not available.
Help me, please!
Thanks.

A: *

*Verify you downloaded the correct package i386/amd64 from https://www.virtualbox.org/wiki/Linux_Downloads

*sudo dpkg -i virtualbox*.deb
It throws dependencies error

*sudo apt-get -f install

*run sudo dpkg -i virtualbox*.deb again.

You can easily install from ppa
sudo apt-get install virtualbox

A: Try running this
$ echo deb http://download.virtualbox.org/virtualbox/debian xenial contrib | sudo tee -a /etc/apt/sources.list.d/virtualbox.list
$ wget -q https://www.virtualbox.org/download/oracle_vbox_2016.asc -O- | sudo apt-key add -
$ sudo apt-get update
$ sudo apt-get install virtualbox-5.1

After it finishes installing run
sudo apt-get update && sudo apt-get upgrade

just to make sure you got the latest version


text:
Q: Is there any way to make this code simpler? I feel like there should be but I am very new to Python def life():
    print("You wake up")
    eat = input("are you hungry? Please Enter y or n.")
    if eat.upper() == "Y":
        print("I predict you will eat breakfast")
    elif eat.upper() == "N":
        print("I predict you will skip breakfast")
    while eat.upper() not in ("Y","N"):
        print("input not accepted")
        eat = input("are you hungry? Please Enter y or n.")
        if eat.upper() == "Y":
            print("I predict you will eat breakfast")
        elif eat.upper() == "N":
            print("I predict you will skip breakfast")
    print("You leave the house")
    day = input("is it cloudy? please enter y or n")
    if day.upper() == "Y":
        print("I predict you will bring an umbrella")
    elif day.upper() == "N":
        print("I predict you will wear sunglasses")
    while day.upper() not in ("Y","N"):
        print("input not accepted")
        day = input("is it cloudy? please enter y or n")
        if day.upper() == "Y":
            print("I predict you will bring an umbrella")
        elif day.upper() == "N":
            print("I predict you will wear sunglasses")
    print("You go out for dinner")
    food = input("Do you want meat? please enter y or n")
    if food.upper() == "Y":
        print("I predict you will order steak!")
    elif food.upper() == "N":
        pass
    while food.upper() not in ("Y", "N"):
        print("input not accepted")
        food = input("Do you want meat? please enter y or n")
        if food.upper() == "Y":
            print("I predict you will order steak!")
        elif food.upper() == "N":
            pass
    pasta = input("Do you want Pasta: please enter y or n")
    if pasta.upper() == "Y":
        print("I predict you will order spaghetti and meatballs!!")
    elif pasta.upper() == "N":
        print("I predict you will order salad.")
    while pasta.upper() not in ("Y", "N"):
        print("input not accepted")
        pasta = input("Do you want Pasta: please enter y or n")
        if pasta.upper() == "Y":
            print("I predict you will order spaghetti and meatballs!!")
        elif pasta.upper() == "N":
            print("I predict you will order salad.")
life()

I feel like it is unnecessary to repeat multiple lines of code in the while statement. Is there any way to make the while statement go to a previous line of code and run it from there instead of re-entering the same code back into the while statement. The code seems to run fine but I would like it to be less clunky if possible.
Thanks!

A: There are several modifications I would suggest.

*

*Use inline conditional statements <expression1> if <condition> else <expression2>

*Use string formatting "Today is {}".format(date)
So you can write
s = "eat" if eat.upper() == "Y" else "skip" if eat.upper() == "N" else ""
print("I predict you will {} breakfast".format(s))

Be sure to check that eat.upper() is "Y" or "N" first, or the code would fail.
Since your code for eat and day are similar, you could also use a function to simplify your code.


text:
Q: git same project, two separate repos - how to merge together Two repos of the same project with different histories (unrelated from the git point of view).  I need to merge them into one repo and remember histories of both.
The main problem is that the one of the repos one additional directory.
 repo1  ---DIR----[project dirs]

 repo2  ---[project dirs]

The project dirs are almost the same.
I have tried to move the directories, create dummy branches, then merge unrelated histories and then merge. But it never see the conflicts - it just replaces files using one of the repos.
Is it possible to merge two separate repos?


text:
Q: Ideals with infinitely many generators As the title may suggest, I am not sure if I understand the ideals with infinitely many generators correctly. Let us take the ring $R=\mathbb{Z}[x_1,x_2,x_3,\dots]$ and consider the ideal $(x_1,x_2,x_3\dots)$ generated by all the indeterminates in the polynomial ring $R$. As a set
\begin{equation}
(x_1,x_2,x_3,\dots)=\{f_1x_1+f_2x_2+f_3x_3+\dots|f_1,f_2,f_3,\dots\in R\}.
\end{equation}
My understanding is that the $+$ in the above notation does not stand for the ring operation (we can't add infinitely many elements) and that $f_1x_1+f_2x_2+f_3x_3+\dots$ is an element of $R$ and so automatically only finitely many $f_i\neq0_R$. Is my understanding correct?

A: Writing $$(x_1,x_2,x_3,\dots)=\{f_1x_1+f_2x_2+f_3x_3+\dots|f_1,f_2,f_3,\dots\in R\}$$ is rather imprecise, because (as you said), you cannot add infinitely many elements in a ring (unless you have a topology). It would be better to write instead
$$
(x_1,x_2,x_3,\dots) = \left\{\sum_{i\geq 1} f_i x_i\mid f_i\in R\textrm{ and }f_i = 0\textrm{ for all but finitely many }i\right\}.
$$
The sum in the set on the right hand side is now well-defined, and this is the ideal that you want.


text:
Q: Warning: session_start(): Cannot send session cache limiter here is the error i get on my website when trying to process a payment page am not sure what to do i found this code
Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /home/bargainhivee/public_html/wp-includes/wp-db.php:1482) in /home/bargainhivee/public_html/wp-content/plugins/Tevolution/tmplconnector/templatic-connector.php on line 5

this is the line 5
 if (!isset($_SESSION)) { session_start(); }

here is the php file templatic-connector.php
<?php
    /*
    * includes the main files of tevolution default ad-on such as claim ownership,custom taxonomy,csutom fields,etc. and common functions.
    */
    if (!isset($_SESSION)) { session_start(); }

    require_once(TEMPL_MONETIZE_FOLDER_PATH."/templatic-claim_ownership/install.php" );
    require_once(TEMPL_MONETIZE_FOLDER_PATH."/templatic-custom_taxonomy/install.php" );
    require_once(TEMPL_MONETIZE_FOLDER_PATH."/templatic-custom_fields/install.php" );
    require_once(TEMPL_MONETIZE_FOLDER_PATH."/templatic-monetization/install.php" );
    require_once(TEMPL_MONETIZE_FOLDER_PATH."/templatic-ratings/install.php" );
    require_once(TEMPL_MONETIZE_FOLDER_PATH."/templatic-registration/install.php" );
    require_once (TEMPL_MONETIZE_FOLDER_PATH . "/templatic-widgets/templatic_browse_by_categories_widget.php");
    require_once (TEMPL_MONETIZE_FOLDER_PATH . "/templatic-widgets/templatic_advanced_search_widget.php");
    require_once (TEMPL_MONETIZE_FOLDER_PATH . "/templatic-widgets/templatic_people_list_widget.php");
    require_once (TEMPL_MONETIZE_FOLDER_PATH . "/templatic-widgets/templatic_metakey_search_widget.php");

    require_once(TEMPL_MONETIZE_FOLDER_PATH."templatic-generalization/general_functions.php" );

    /* Add to favourites for tevolution*/
    if(file_exists(TEMPL_MONETIZE_FOLDER_PATH."templatic-generalization/add_to_favourites.php") && (!strstr($_SERVER['REQUEST_URI'],'/wp-admin/') || strstr

    ($_SERVER['REQUEST_URI'],'/admin-ajax.php') )){
        require_once(TEMPL_MONETIZE_FOLDER_PATH."templatic-generalization/add_to_favourites.php" );
    }

    /*
     do action for admin menu
    */
    add_action('admin_menu', 'templ_add_admin_menu_'); /* create templatic admin menu */
    function templ_add_admin_menu_()
    {
        do_action('templ_add_admin_menu_');
    }

    add_action('templ_add_admin_menu_', 'templ_add_mainadmin_menu_', 0);
    add_action('templ_add_admin_menu_', 'templ_remove_mainadmin_sub_menu_');
    if(!function_exists('templ_remove_mainadmin_sub_menu_')){
        function templ_remove_mainadmin_sub_menu_(){
            remove_submenu_page('templatic_system_menu', 'templatic_system_menu');
            add_submenu_page( 'templatic_system_menu', __('Overview','templatic-admin'), __('Overview','templatic-admin'), 'administrator',

    'templatic_system_menu', 'templatic_connector_class' );
        }
    }
    /*
     include the main.connector.class.php file
    */
    function templatic_connector_class()
    {
         require_once(TEVOLUTION_PAGE_TEMPLATES_DIR.'classes/main.connector.class.php' );
    }
    /*
        Return the main menu at admin sidebar
    */
    function templ_add_mainadmin_menu_()
    {
        $menu_title = __('Tevolution', 'templatic');
        if (function_exists('add_object_page'))
        {
            if(isset($_REQUEST['page']) && $_REQUEST['page'] == 'templatic_system_menu'){
                $icon = TEMPL_PLUGIN_URL.'favicon-active.png';
            }else{
                $icon = TEMPL_PLUGIN_URL.'favicon-active.png';
            }
            $hook = add_menu_page("Admin Menu", $menu_title, 'administrator', 'templatic_system_menu', 'dashboard_bundles', '',3); /* title of new

    sidebar*/
        }else{
            add_menu_page("Admin Menu", $menu_title, 'administrator',  'templatic_wp_admin_menu', 'design','');
        }
    }
    /*
     return the connection with dashboard wizards(bundle box)
    */
    function dashboard_bundles()
    {
        $Templatic_connector = New Templatic_connector;
        require_once(TEVOLUTION_PAGE_TEMPLATES_DIR.'classes/main.connector.class.php' );
        if(isset($_REQUEST['tab']) && $_REQUEST['tab'] =='extend') {
            $Templatic_connector->templ_extend();
        }else if(isset($_REQUEST['tab']) && $_REQUEST['tab'] =='payment-gateways') {
            $Templatic_connector->templ_payment_gateway();
        }else if((!isset($_REQUEST['tab'])&& @$_REQUEST['tab']=='') || isset($_REQUEST['tab']) && $_REQUEST['tab'] =='overview') {
            $Templatic_connector->templ_overview();
            $Templatic_connector->templ_dashboard_extends();
        }

    }

    /*
     return main CSS of Plugin
    */
    add_action('admin_head', 'templ_add_my_stylesheet'); /* include style sheet */
    add_action('wp_head', 'templ_add_my_stylesheet',0); /* include style sheet */

    function templ_add_my_stylesheet()
    {

      /* Respects SSL, Style.css is relative to the current file */
        wp_enqueue_script('jquery');

        $tmpl_is_allow_url_fopen = tmpl_is_allow_url_fopen();

        /* Tevolution Plug-in Style Sheet File In Desktop view only  */
        if (function_exists('tmpl_wp_is_mobile') && !tmpl_wp_is_mobile()) {

            /* if "allow_url_fopen" is enabled then apply minifiled css otherwise includse seperately */
            if(!$tmpl_is_allow_url_fopen){
                wp_enqueue_style('tevolution_style',TEMPL_PLUGIN_URL.'style.css','',false);
            }else{
                wp_enqueue_style('tevolution_style',TEMPL_PLUGIN_URL.'css.minifier.php','',false);
            }
        }
        if(function_exists('theme_get_settings')){
            if(theme_get_settings('supreme_archive_display_excerpt')){
                if(function_exists('tevolution_excerpt_length')){
                    add_filter('excerpt_length', 'tevolution_excerpt_length');
                }
                if(function_exists('new_excerpt_more')){
                    add_filter('excerpt_more', 'new_excerpt_more');
                }
            }
        }
    }

    /* check if "allow_url_fopen" is enabled or not */
    function tmpl_is_allow_url_fopen(){
        if( ini_get('allow_url_fopen') ) {
            return true;
        }else{
            return false;
        }
    }

    /*
    return each add-ons is activated or not
    */
    function is_active_addons($key)
    {
      $act_key = get_option($key);
      if ($act_key != '')
      {
        return true;
      }
    }
    /*
     Function will remove the admin dashboard widget
    */
    function templ_remove_dashboard_widgets()
    {
      /* Globalize the metaboxes array, this holds all the widgets for wp-admin*/
      global $wp_meta_boxes;
      /* Remove the Dashboard quickpress widget*/
      unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press']);
      /* Remove the Dashboard  incoming links widget*/
      unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_incoming_links']);
      /* Remove the Dashboard secondary widget*/
      unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']);
    }
    add_action('wp_dashboard_setup', 'templ_remove_dashboard_widgets');

    /* -- coding to add submenu under main menu-- */
    add_action('templ_add_admin_menu_', 'templ_add_page_menu');
    function templ_add_page_menu()
    {

        /*tevolution_menu_before_general_settings hook for add additional menu before general settings */
        do_action('tevolution_menu_before_general_settings');

        $menu_title2 = __('Settings', 'templatic-admin');
        add_submenu_page('templatic_system_menu', $menu_title2, $menu_title2,'administrator', 'templatic_settings', 'my_page_templates_function');

        /*tevolution_menu_after_general_settings hook for add additional menu after general settings */
        do_action('tevolution_menu_after_general_settings');
    }

    /*
        Email, security , and set up steps menu selected
     */
    add_action('admin_footer','tevolution_menu_script');
    function tevolution_menu_script()
    {
        ?>

         <?php
    }

    /* include general_settings.php file */
    function my_page_templates_function()
    {
        include(TEMPL_MONETIZE_FOLDER_PATH.'templatic-generalization/general_settings.php');

    }

    /*
        Redirect on plugin dashboard after activating plugin
    */
    add_action('admin_init', 'my_plugin_redirect');
    function my_plugin_redirect()
    {
        global $pagenow;
        if (get_option('myplugin_redirect_on_first_activation') == 'true' && $pagenow=='plugins.php' ){
            update_option('myplugin_redirect_on_first_activation', 'false');
            wp_redirect(MY_PLUGIN_SETTINGS_URL);
        }
        if (get_option('myplugin_redirect_on_first_activation') == 'true' && $pagenow=='themes.php' ){
            update_option('myplugin_redirect_on_first_activation', 'false');
            wp_redirect(site_url().'/wp-admin/themes.php');
        }
    }

    /*
     * View counter for detail page
     */
    function view_counter_single_post($pid){
        if($_SERVER['HTTP_REFERER'] == '' || !strstr($_SERVER['HTTP_REFERER'],$_SERVER['REQUEST_URI']))
        {
            $viewed_count = get_post_meta($pid,'viewed_count',true);
            $viewed_count_daily = get_post_meta($pid,'viewed_count_daily',true);
            $daily_date = get_post_meta($pid,'daily_date',true);

            update_post_meta($pid,'viewed_count',$viewed_count+1);
        if(get_post_meta($pid,'daily_date',true) == date('Y-m-d')){
                update_post_meta($pid,'viewed_count_daily',$viewed_count_daily+1);
            } else {
                update_post_meta($pid,'viewed_count_daily','1');
            }
            update_post_meta($pid,'daily_date',date('Y-m-d'));
        }
    }

    /*
     * return the count of post view
     */
    if(!function_exists('user_single_post_visit_count')){
    function user_single_post_visit_count($pid)
    {
        if(get_post_meta($pid,'viewed_count',true))
        {
            return get_post_meta($pid,'viewed_count',true);
        }else
        {
            return '0';
        }
    }
    }
    /*
     * Function Name:user_single_post_visit_count_daily
     * Argument: Post id
     */
    if(!function_exists('user_single_post_visit_count_daily')){
    function user_single_post_visit_count_daily($pid)
    {
        if(get_post_meta($pid,'viewed_count_daily',true))
        {
            return get_post_meta($pid,'viewed_count_daily',true);
        }else
        {
            return '0';
        }
    }
    }
    /*
     * add view count display after the content
     */
    if( !function_exists('view_count')){
    function view_count( $content ) {

        if ( is_single())
        {
            global $post;
            $sep =" , ";
            $custom_content='';
            $custom_content.="
".__('Visited','templatic')." ".user_single_post_visit_count($post->ID)." ".__('times','templatic');
            $custom_content.= $sep.user_single_post_visit_count_daily($post->ID).__(" Visits today",'templatic')."
";
            $custom_content .= $content;
            echo $custom_content;
        }
    }
    }
    /*
     * show counter and share button after custom fields.
     */
    function teamplatic_view_counter()
    {
       $settings = get_option( "templatic_settings" );
       if(isset($settings['templatic_view_counter']) && $settings['templatic_view_counter']=='Yes')
       {
            global $post;
            view_counter_single_post($post->ID);
            view_count('');
       }
       //view_sharing_buttons('');
       tevolution_socialmedia_sharelink();

    }

    /*Remove the  the_content filter to add view counter everywhere in single page and add action tmpl_detail_page_custom_fields_collection before the custom

    field display*/

    add_action('tmpl_detail_page_custom_fields_collection','teamplatic_view_counter',5);
    function view_sharing_buttons($content)
    {
        global $post;
        if (is_single() && ($post->post_type!='post' && $post->post_type!='page'  && $post->post_type!='product'   && $post->post_type!='product_variation'

    ))
        {
            $post_img = bdw_get_images_plugin($post->ID,'thumb');
            $post_images = $post_img[0];
            $title=urlencode($post->post_title);
            $url=urlencode(get_permalink($post->ID));
            $summary=urlencode(htmlspecialchars($post->post_content));
            $image=$post_images;
            $settings = get_option( "templatic_settings" );

            if($settings['facebook_share_detail_page'] =='yes' || $settings['google_share_detail_page'] == 'yes' || $settings

    ['twitter_share_detail_page'] == 'yes' || $settings['pintrest_detail_page']=='yes'){
            echo '
';
                if($settings['facebook_share_detail_page'] == 'yes')
                  {
                    ?>
                    <a onClick="window.open('//www.facebook.com/sharer.php?s=100&p[title]=<?php echo $title;?>&p[summary]=<?php echo

    $summary;?>&p[url]=<?php echo $url; ?>&&p[images][0]=<?php echo $image;?>','sharer','toolbar=0,status=0,width=548,height=325');"

    href="javascript: void(0)" id="facebook_share_button"><?php _e('Facebook Share.',T_DOMAIN); ?>
                    <?php
                  }
                if($settings['google_share_detail_page'] == 'yes'): ?>

                <?php endif;

                if($settings['twitter_share_detail_page'] == 'yes'): ?>
                        <a href="https://twitter.com/share" class="twitter-share-button" data-lang="en" data-text='<?php echo htmlentities

    ($post->post_content);?>' data-url="<?php echo get_permalink($post->ID); ?>" data-counturl="<?php echo get_permalink($post->ID); ?>"><?php _e

    ('Tweet',T_DOMAIN); ?>

                <?php endif;

                if(@$settings['pintrest_detail_page']=='yes'):?>

                        <a href="//pinterest.com/pin/create/button/?url=<?php echo urlencode(get_permalink($post->ID)); ?>&media=<?php echo $image; ?

    >&description=<?php the_title(); ?>" ><?php _e('Pin It','templatic');?>

                   <?php endif;
            echo '
';
            }
        }
        return $content;
    }

    /*
        return the currency code
    */
    function templatic_get_currency_type()
    {
        global $wpdb;
        $option_value = get_option('currency_code');
        if($option_value)
        {
            return stripslashes($option_value);
        }else
        {
            return 'USD';
        }

    }
    /*
        this function returns the currency with position selected in currency settings
    */
    function fetch_currency_with_position($amount,$currency = '')
    {
        $amt_display = '';
        if($amount==''){ $amount =0; }
        $decimals=get_option('tmpl_price_num_decimals');
        $decimals=($decimals!='')?$decimals:2;
        if($amount >=0 )
        {
            if(@$amount !='')
                $amount = number_format( (float)($amount),$decimals,'.','');
                $currency = get_option('currency_symbol');
                $position = get_option('currency_pos');
            if($position == '1')
            {
                $amt_display = $currency.$amount;
            }
            else if($position == '2')
            {
                $amt_display = $currency.' '.$amount;
            }
            else if($position == '3')
            {
                $amt_display = $amount.$currency;
            }
            else
            {
                $amt_display = $amount.' '.$currency;
            }
            return apply_filters('tmpl_price_format',$amt_display,$amount,$currency);
        }
    }

    /*
        this function returns the currency with position selected in currency settings
    */
    function fetch_currency_with_symbol($amount,$currency = '')
    {
        $amt_display = '';
        if($amount==''){ $amount =0; }
        $decimals=get_option('tmpl_price_num_decimals');
        $decimals=($decimals!='')?$decimals:2;
        if($amount >=0 )
        {
            if(@$amount !='')
                $amount = $amount;
                $currency = get_option('currency_symbol');
                $position = get_option('currency_pos');
            if($position == '1')
            {
                $amt_display = $currency.$amount;
            }
            else if($position == '2')
            {
                $amt_display = $currency.' '.$amount;
            }
            else if($position == '3')
            {
                $amt_display = $amount.$currency;
            }
            else
            {
                $amt_display = $amount.' '.$currency;
            }
            return apply_filters('tmpl_price_format',$amt_display,$amount,$currency);
        }
    }

    /* eof - display currency with position */

    /*  this function will display the legends descr


text:
Q: Calculate the number of entries in a Page Table We have a system that uses 3-level hierarchical page table. Logical address is 32 bit.
We know that the same amount of bits is allocated for each level in the logical address.
The system is byte-addressable.
Physical address is 27 bits, and we have 8192 frames is the physical memory.
I want to calculate the number of entries in each level of the page table.
We have 8192 frames, that is 2^13, so we need 13 bits to represent the frame number.
So 27-13=14 bits for the offset.
That gives us 32-14=18 bits for page number.
We know that we can split it equally, so 6 bits represents each level of the hierarchical page table.
But how many entries are in each level? 2^6? If so - why is that?
Thanks!


text:
Q: Correct approach to handle react-routes on a server? I have uploaded my application to the server and encountered a problem.
going to example.com displays homepage correctly, however after doing something like example.com/dashboard I get an error Cannot GET /dashboard. I assume this is because server is actually trying to get that path, but it still needs to go through index.html as this is a single page app using react-router. I believe I need to redirect all requests to got to index.html to make this work, but I'm not sure how I can implement this. I am using express to server my files, here is my server.js
var express = require('express');
var app = express();

app.use(express.static(__dirname + '/dist'));

app.listen(8080, function() {
  console.log('Listening on port: ' + 8080);
});

A: You need to set up Express so that if a request is not for a static file it falls through and is handled as a frontend route by your React app on index.html.
Adding to your above example, something like this,
var express = require('express');
var app = express();

app.use('/static', express.static(__dirname + '/dist'));

app.get('*', function (req, res, next) {
  if (req.path.startsWith('/static')) return next()
  res.sendFile('dist/index.html')
})

app.listen(8080, function() {
  console.log('Listening on port: ' + 8080);
});

Notice that I added the /static path for your static assets. That means every request for a static asset by your app has to look like /static/foo.jpg (or whatever). It might be worth renaming your dist folder static too, to keep names in sync.
This is a useful pattern because it lets you easily differentiate between a request for a static asset, and a request that should fall through to your frontend app.


text:
Q: magento not following .htaccess rule have a magento site i click on all links and they rewrite fine. Only one issue, I have some links that look like this assume my domain name is somesite.com
http://www.somesite.com/?htm/147 and i want it to redirect to http://www.somesite.com/someplace/ of course homesite is replaced with my real domain. assume i am using https://github.com/nexcess/magento/blob/master/.htaccess.sample renamed to .htaccess
i add this to .htaccess but it has no affect
Redirect 301 /?htm/147 http://www.somesite.com/someplace/ ideas?

A: In your .htaccess the following should work:
Redirect 301 /?htm/147 /someplace
You could also look at using a rewrite match
redirectMatch 301 ^/?htm/147/?$  /someplace/
If you're going from someplace.com to someplace.net you would need to setup the following:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^someplace.com [NC,OR]
RewriteCond %{HTTP_HOST} ^www.someplace.com [NC]
RewriteRule ^(.*)$ http://someplace.net/$1 [L,R=301,NC]
Hope this helps.