text:
Q: override BackButton press in SearchView I'm getting mad with using SearchView in a fragment and the back button is always shown whatever i touched the search bar or not  and i do the search but i have a problem that back button do nothing but clear the text in search i would like to use it to switch also between fragments. I've tried many solutions in stack overflow questions but seems not solving my issue.
the code after adding toolbar in the fragment:
    @Override
   public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.search_menu_fragment, menu);
    MenuItem searchItem = menu.findItem(R.id.action_search_locations);
    SearchView searchView = new SearchView(((AppCompatActivity)getActivity()).getSupportActionBar().getThemedContext());
    MenuItemCompat.setShowAsAction(searchItem, searchItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW ); //searchItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW |
    MenuItemCompat.setActionView(searchItem, searchView);

    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            // filter recycler view when query submitted
            locationStatesPreviewAdapter.getFilter().filter(query);
            return false;
        }

        @Override
        public boolean onQueryTextChange(String query) {
            // filter recycler view when text is changed
            Log.e("QueryChange",query);
            locationStatesPreviewAdapter.getFilter().filter(query);
            return false;
        }
    });

}

the xml file has only the search item in the menu :
       <?xml version="1.0" encoding="utf-8"?>
       <menu xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">
       <item android:id="@+id/action_search_locations"
       xmlns:app="http://schemas.android.com/apk/res-auto"
       android:title="@string/app_name"
       android:icon="@android:drawable/ic_menu_search"
       app:showAsAction="always|collapseActionView"
       app:actionViewClass="android.support.v7.widget.SearchView" />
       </menu>

Thanks.

A: That was a problem of mis-understanding, as i thought it's the back button of the SearchView in Fragment and afterwards it was the toolbar Navigation button and after adding this lines to make it responsive and all things done ! thanks for help all.
    ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
    ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    ((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("TOOLBAR");

    toolbar.setNavigationOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view) {
            Toast.makeText(getActivity(), "Back clicked!", Toast.LENGTH_SHORT).show();
        }
    });


text:
Q: jdbi version 3, stringtemplate when to escape <, > characters? I am using jdbi3 with StringTemplate 4 templating engine, I have this test query:
    @SqlQuery("select * from test "
        + "where field1 = 5"
        + "<if(cond1)> or field2 \\<= :value1<endif>"
        + "<if(cond2)> or field2 >= :value2<endif>"
        + "<if(cond3)> or field2 in (<values>)<endif>")
@RegisterBeanMapper(Test.class)
@UseStringTemplateEngine
public List<Test> selectTest(
        @Define("cond1") boolean cond1, @Bind("value1") int value2,
        @Define("cond2") boolean cond2, @Bind("value2") int value3,
        @Define("cond3") boolean cond3,
        @BindList(value="values", onEmpty=BindList.EmptyHandling.NULL_STRING ) List<Integer> values);

Using StringTemplate engine when I have to escape with \ the characters < or >  in the query?
Testing I found that I have to escape <= in the query like I did.
In the IN clause using @BindList I have to use the <values> but in this case I was expecting to escape it like \\<values> otherwise it will be used as attribute by StringTemplate but if I do this the query doesn't work.
About >= escaping it or not seems the same in the query.

A: Introduction
Let's consider:

*

*The 3.27.1 Jdbi version as the current Jdbi version.

*The 4.3.1 StringTemplate version as the current StringTemplate version, since the current Jdbi version uses it. Please, see: jdbi/pom.xml at v3.27.1 · jdbi/jdbi.

Answer
Jdbi
Documentation: Which characters to escape
Please, note the warning on which characters to escape:

Since StringTemplate by default uses the < character to mark ST expressions, you might need to escape some SQL: String datePredSql = "<if(datePredicate)> <dateColumn> \\< :dateFilter <endif>"
— jdbi/index.adoc at v3.27.1 · jdbi/jdbi.

Unit-test: Do not escape @BindList variable name
Please, see the BindListTest.ifValueGivenWithNullValueOptionThenResultIsTruthy() test method: jdbi/BindListTest.java at v3.27.1 · jdbi/jdbi.
Please, note that the test covers a very similar annotated method:
@SqlQuery("select name from something <if(name)> where name in (<name>) <endif>")
@UseStringTemplateEngine
List<String> getForValue(@Nonnull @BindList(value = "name", onEmpty = NULL_VALUE) List<String> name);

Please, note that the @BindList variable name is not escaped:
in (<name>)

StringTemplate
Documentation: Which characters to escape
Please, note which characters to escape:

A template is a sequence of text and expression elements, optionally interspersed with comments. At the coarsest level, the basic elements are:
text
<expr>
<! comment !>

Escape delimiters with a backslash character: \< or \>.
— stringtemplate4/templates.md at 4.3.1 · antlr/stringtemplate4.

redpajama_set_name: RedPajamaStackExchange


text:
Q: не могу передать функции строку в СИ++ сделал все как в книге, но чет не хочет
#include <iostream>
#include <cstring>
using namespace std;
struct mystr {
    void buildstr(char* s);
    void printstr();
private:
    char str[100];
};

void mystr::buildstr(char* s) {
    if (!*s) *str = '\0';
    else strcat(str, s);
}

void mystr::printstr(){
    cout << str << endl;
}
int main() {
    mystr s;
    s.buildstr("sdfdf");
    s.buildstr("fdsf");
    s.printstr();

}

A: Функция должна принимать указатель на константную строку — литерал менять нельзя...
void buildstr(const char* s);

Только это не всё — у вас str неинициализированный массив... Если компилятор позволяет, напишите
char str[100] = "";

вместо просто
char str[100];


text:
Q: I need help understanding the applications of basic axioms and propostions in a probability question J is taking 2 books along on her holiday vacation. With Probability .5 she will like the first book. With probability .4 she will like the second book. With probability .3 she will like both books. What is the probability that she likes neither book?
The book gives:
$P(B_1 U B_2)= P(B_1)+P(B_2)-P(B_1 B_2)$ is the probability she likes at least one book.
How does it follow that $P(B_1 U B_2)$ equals what I listed above.

A: This is inclusion-exclusion. If you draw a venn diagram of two circles representing the events $B_1$ and $B_2$, you can see how the formula arises.

A: One of the probability axioms is that when $A\cap B=\emptyset$ one has $Pr(A\cup B)=Pr(A)+Pr(B)$
Note now that

*

*$B_1 = (B_1\setminus B_2)\cup (B_1\cap B_2)$

*$B_2 = (B_2\setminus B_1)\cup (B_1\cap B_2)$

*$B_1\cup B_2 = (B_1\setminus B_2)\cup (B_1\cap B_2)\cup (B_2\setminus B_1)$

*All of $(B_1\setminus B_2), (B_2\setminus B_1)$ and $(B_1\cap B_2)$ are mutually disjoint.

From the axiom mentioned in the first line, it follows that

*

*$Pr(B_1)=Pr(B_1\setminus B_2)+Pr(B_1\cap B_2)$

*$Pr(B_2) = Pr(B_2\setminus B_1)+ Pr(B_1\cap B_2)$

*$Pr(B_1\cup B_2) = Pr(B_1\setminus B_2)+ Pr(B_1\cap B_2)+Pr(B_2\setminus B_1)$

Adding and subtracting $Pr(B_1\cap B_2)$ to the final line (which is a fancy way of adding zero which doesn't change anything) and using the previous two lines, we get then what is referred to as the principle of inclusion-exclusion for two sets, namely
$Pr(B_1\cup B_2)=Pr(B_1)+Pr(B_2)-Pr(B_1\cap B_2)$

One can extend this inductively to any number of sets/events.  The four set case for example would look like
$Pr(A\cup B\cup C\cup D)=Pr(A)+Pr(B)+Pr(C)+Pr(D)\\~~~~-Pr(A\cap B)-Pr(A\cap C)-Pr(A\cap D)-Pr(B\cap C)-Pr(B\cap D)-Pr(C\cap D)\\~~~~ + Pr(A\cap B\cap C)+Pr(A\cap B\cap D)+Pr(A\cap C\cap D)+Pr(B\cap C\cap D)-Pr(A\cap B\cap C\cap D)$


text:
Q: Unable to change Panel Visibility I'm having a panel inside another panel. Now I need to alter inner panel's visibility based on certain condition. But I'm unable to change. It always remains to False. Here is the code I'm trying to:
PnlTagFolders.Visible = True 'Always remains False.
PnlTagFolders.BringToFront()

Here is the screenshot for reference:

A: You can't make a Panel visible if the parent Panel isn't visible. So make sure the parent Panel is visible (.Visible = True).

true if the control and all its child controls are displayed; otherwise, false. The default is true.
source: Microsoft Docs

See the following:
ChildPanel.Visible = False
ParentPanel.Visible = False
ChildPanel.Visible = True
Debug.Print(ChildPanel.Visible) 'False

Another example:
ChildPanel.Visible = False
ParentPanel.Visible = True
ChildPanel.Visible = True
Debug.Print(ChildPanel.Visible) 'True


text:
Q: Find a string in a file and return the value before the string using ruby I am in the process of learning ruby. I am trying to read a file, find a string, and return the value before the string.
I've tried this:
line = "ALTER TABLE schemaname.tablename MODIFY col1 number(19,0)"
bol1 = line.include?("MODIFY")
puts "{#bol1}"

if bol1 = "true"
  if line =~ /ALTER TABLE/ then
    drop_found = "true"
    location = line.index("ALTER TABLE") + 11
    subline = line[location..-1]
    sublineParts = subline.split(" ")
    tableName = sublineParts[0]
    puts " found modify column on {#tableName}"
   end
   else
     puts " no modify found"
   end

I don't get any output here. bol1 = line.include?("MODIFY") returns nothing. Please help.

A: A few errors/style concerns:

*

*You're using an assignment equals in your conditional.  bol1 = "true" should be bol1 == "true" But:

*You're checking to see if the .include? function returned the string "true" You should check if the value is true. (bol1 == true or just if (bol1)) This is why you're not getting back the value you expect.

*then is rarely used but not never.

*If you're going to use then it closes the if statement, the if statement doesn't need an end unless it's completely by itself.  else will also close the if block.

*You're missing a closing end at the bottom

*You've tried to puts "{#bol1}" instead of "#{bol1}" which is how variable interpolation works.  (You can just puts bol1 though, it would be easier. No need to use #{})

The working version of your program I've got is this:
line = "ALTER TABLE schemaname.tablename MODIFY col1 number(19,0)"
bol1 = line.include?("MODIFY")
puts bol1

if (bol1)
  if (line =~ /ALTER TABLE/)
    drop_found = true
    location = line.index("ALTER TABLE") + 11
    subline = line[location..-1]
    sublineParts = subline.split(" ")
    tableName = sublineParts[0]
    puts " found modify column on {#tableName}"
  else
    puts " no modify found"
  end
end


text:
Q: How to restore Windows 2003 using a system backup? Didn't work for me I have had an easy time testing system restores with ASR NTBackups.
I wanted to try what I thought was an alternate approach provided by windows 2003 for full system restores. Using NTBackup, I made a system backup, and then a full backup of the C: drive (contains windows). Then I rebooted, put in the windows 2003 disk and told it to do a new install of windows into the existing windows partition. It did that and afterwards my plan was to restore the system backup, and the c drive backup. After running the system restore it wanted to reboot. But it fails to reboot successfully. The windows 2003 logo appears for ten seconds and then there is a short flash of BSOD and then it reboots.
I have probably not understood how one would use the system backup to fully restore an existing server. Should I have restored both system and c drive backups before allowing the reboot?
ASR Backups seem to work pretty well, but I'd like to know of other routes for getting a system back from full failure.


text:
Q: How to dynamically change the element definition of a region in content presenter template in Webcenter Portal? I have been following Yannick Ongena's tutorial http://yonaweb.be/webcenter_tutorial/using_content_presenter_templates
I am looking to alter some code in the content presenter template "training-list-item.jsff" so that the region definition will have a dynamic value.
That is, rather than writing
<af:outputText value="#{node.propertyMap['RD_TRAINING:description'].asTextHtml}"
         escape="false" id="ot5"/>

I am looking to write like
<af:outputText value="#{node.propertyMap['xRegionDefinition:description'].asTextHtml}"
         escape="false" id="ot5"/>

Unfortunately, this does not work. If I write only "xRegionDefinition" within the propertyMap,it displays the region definition name in the portal, that is "RD_TRAINING". But I am looking to display the value of element definition within the region that is, the "description".
My objective is to display different region definitions at the portal rather than a hard coded fixed region. I have wrote some Java code also to dynamically change the CMIS query to supply a new value for the region definition:
    if(news){
        query = "SELECT * FROM ora:t:IDC:GlobalProfile WHERE ora:p:xRegionDefinition LIKE \'RD_TRAINING\'";
    }
    else
        query = "SELECT * FROM ora:t:IDC:GlobalProfile WHERE ora:p:xRegionDefinition LIKE \'RD_SWEDISH\'";

Please help. Hope I am clear in explaining the requirement.

A: Why don't you use ADF Switcher component if you only have 2 options!
Check this video to know how to use it


text:
Q: Django - Limit the entries in models.ForeignKey() Is to possible to limit the entries in models.ForeignKey() field based on some condition?
customer = models.ForeignKey(Customer)

I just need to show the customer who are in active status.

A: Assuming you're using the django-admin site, I think you might want the limit_choices_to option:
i.e.
customer = models.ForeignKey(Customer, limit_choices_to={'active': True})


text:
Q: Probability question : How to find the actual numerical value without the lengthy calculation?
A class contains $10$ boys and $15$ girls. $8$ students are to be selected
  at random from the class without replacement. Let X be the number of
  boys selected and Y the number of girls selected. Find $E(X −Y )$.

I could chalk out the table:
$E(X-Y)= -8$ when $X=0$ and $Y=8$
$E(X-Y)= -7$ when $X=1$ and $Y=7$
etc etc
each with probability $\binom{25}{8}\frac{10}{25}^{x}\frac{15}{25}^{y}$
But how do i go about the lengthy calculation and find the actual expected value?

A: Well you could try $E(X)-E(Y)=E(X-Y)$

A: Following the comment in another answer, observe that $X$ and $Y$ are not independent variables. In fact, $Y=8-X$. So $E[X-Y]=E[X-(8-X)]=E[2X-8]=2E[X]-8$. Now, $X\sim\operatorname{Hypergeometric}(10,10+15,8)$, so $E[X]=8\cdot{10\over25}=\frac{16}5$, therefore $E[X-Y]=-\frac85$.
If you don't remember the mean of the hypergeometric distribution, another way to attack this is to observe that the distribution is exchangeable, that is, the probability depends only on the number of boys (and girls) selected, not on the order in which they were selected. Therefore, the probability of choosing a boy is order-independent: the probability that the $i$th selection is a boy is simply ${10\over25}$. If we let $B_i$ be indicator variables for these events and $G_i$ be indicator variables for the events "the $i$th choice is a girl," then $$E[X]=\sum_{i=1}^8E[B_i]=8\Pr(\text{boy is chosen}) \\ E[Y]=\sum_{i=1}^8E[G_i]=8\Pr(\text{girl is chosen}) \\ E[X-Y]=8\Pr(\text{boy is chosen})-8\Pr(\text{girl is chosen})=8\left({10\over25}-{15\over25}\right)=-\frac85.$$


text:
Q: Rails 5 logstash produces too many log items instead of one Is there any way I can customize the way standard errors are being logged? Starting with Rails 5, logstash receives one fatal error as a lot of error items. Rails 4 only created one item (The way I liked it)
The problem seems to be, that since Rails 5, the log_error method of the DebugExceptions middleware prints all lines of the backtrace calling logger.fatal separately, instead of Rails 4, which joins all lines to one string before calling logger.fatal only once.
Compared:
Rails 4: debug_exceptions.rb
message = "\n#{exception.class} (#{exception.message}):\n"
message << exception.annoted_source_code.to_s if exception.respond_to?(:annoted_source_code)
message << "  " << trace.join("\n  ")
logger.fatal("#{message}\n\n")

Rails 5: debug_exceptions.rb
logger.fatal "  "
logger.fatal "#{exception.class} (#{exception.message}):"
log_array logger, exception.annoted_source_code if exception.respond_to?(:annoted_source_code)
logger.fatal "  "
log_array logger, trace

I'm using logstash-logger with the :json_lines formatter over UDP.
The logstash configuration I use is working perfectly for rails 4 and other applications, but not for rails 5 (as it separates one error into several).
I know, I could use rescue_from to rescue errors in controllers, but this would not catch errors on routing or others, I guess?
Thank you in advance.

A: Actually for error handling it's more convenient to use a dedicated exception tracking solution like rollbar, airbrake, sentry, errbit or similar.
Point is in that for exceptions you need:

*

*a quick way to pinpoint location and conditions where it happens, including request parameters, user id, headers etc. by default not all these are written to logs. But most exception catchers also record additional info about the request.

*alerting, but not too noisy, because when something goes wrong in production - you'll quickly have hundreds of logged errors and you cannot simply forward all these to your email or im. So aggregation must be supported

*optional, but useful - tracking open/resolved errors

It's hard to navigate raw logs for exceptions, even if they're tagged and indexed, also there may be situation when you have a noisy non-mission-critical exception that floods the logs, and makes you miss some rare really important one.
As for catching the exception in rails - it's better to do in middleware, like all tools mentioned above (and rails itself) do:
class MyExceptionMidleware
  def initialize(app)
    @app = app
  end

  def call(env)
    @app.call(env)
  rescue => e
    # handle the error any way you like, for example:
    Rails.logger.fatal("oops, #{e.inspect}, backtrace: #{e.backtrace.join("\n")}")
  end
end

config.middleware.insert_after(ActionDispatch::DebugExceptions, MyExceptionMidleware)

(or insert_before, but that way the exception will not be logged, if you do not reraise it, or if it occurs in middleware itself, not recommended)


text:
Q: Deployment of Razor pages I find 2 issues deploying Razor page projects(perhaps in other .net core project also):

*

*When I deploy the main compilied release file myprojectname.dll, I need to stop the website in IIS or I will fail because the file is using.  How if I don't have control of IIS in the hosting environment?

*I have to re-deploy the file myprojectname.dll even changing a single word in the textual content.  Is there any simple method?

A:
When I deploy the main compilied release file myprojectname.dll, I need to stop the website in IIS or I will fail because the file is using. How if I don't have control of IIS in the hosting environment?

The solutions is you should firstly put a app_offline.htm file inside your IIS folder to stop the whole application, then after deploy remove the  app_offline.htm to start the application. More details, you could refer to this article.
Besides, without any permission to control the IIS, you also couldn't publish and running the application on that server.

I have to re-deploy the file myprojectname.dll even changing a single word in the textual content. Is there any simple method?

If you are using the web deploy inside the visual studio to publish the web application, it will firstly check what the file you have changed, it will only publish the file which you have changed. But if you compilied all the file into a single file, it have to build again and publish all the files to the remote folder.


text:
Q: Changing a MongoDB query into a Postgres query in Javascript I'm having a challenge converting this query. I have had success with others but this one combines multiple fields and I need some help. This is to get the dates to create a reservation.
//convert this:

var getByDate = (restId, date) => {
  return new Promise((resolve, reject) => {
    //  create search-between dates for the date sought
    var workDate = new Date(date);
    var fromDate = new Date(workDate.getFullYear(), workDate.getMonth(), workDate.getDate());
    var thruDate = new Date(fromDate);
    thruDate.setDate(thruDate.getDate() + 1);
    Reservation.find({
        restaurant_id: restId
      })
      .where('reservation_time').gte(fromDate).lt(thruDate)
      .exec((err, reservations) => {
        resolve(reservations);
      });
  });
};

//convert into PostgreSql query:

var getByDate = function (restId, date, callback) {
  return new Promise((resolve, reject) => {
    //  create search-between dates for the date sought
    var workDate = new Date(date);
    var fromDate = new Date(workDate.getFullYear(), workDate.getMonth(), workDate.getDate());
    var thruDate = new Date(fromDate);
    thruDate.setDate(thruDate.getDate() + 1);
    client.query('SELECT * FROM reservationSchema WHERE restaurant_id = restId ;', (error, results) => { //! NEED HELP ON THIS LINE
      if (error) {
        throw error;
      }
      callback(results.rows);
    })
      // .where('reservation_time').gte(fromDate).lt(thruDate) //! old section commented out
      // .exec((err, reservations) => {
      //   resolve(reservations);
      // });
  });
};

A: I came up with this:
var getByDate = function (restId, date, callback) {
  return new Promise((resolve, reject) => {
    //  create search-between dates for the date sought
    var workDate = new Date(date);
    var fromDate = new Date(workDate.getFullYear(), workDate.getMonth(), workDate.getDate());
    var thruDate = new Date(fromDate);
    thruDate.setDate(thruDate.getDate() + 1);
    client.query('SELECT * FROM reservationSchema WHERE restaurant_id = $1 and reservation_time >= $2, and reservation_time < $3;', [restId, fromDate, thruDate], (error, results) => {
      if (error) {
        throw error;
      }
      callback(results.rows);
    })
  });
};


text:
Q: Remove "Appendix" title from Cover Page I'm writing a report in latex and I included an appendix in my document. When I typeset, the title "Appendix" appears on a page by itself. I want this "Appendix" title to be on the same page as my appendix content. What should I do?
\documentclass[12pt, oneside]{report}
\usepackage[left=1in, top=1in, bottom=1in, right=1in]{geometry}
\geometry{letterpaper}
\usepackage{setspace}
\usepackage{graphicx}
\usepackage{indentfirst}
\usepackage{abstract}
\usepackage{biblatex}
\usepackage[toc,page]{appendix}

\begin{document}

\tableofcontents
\thispagestyle{empty}

\chapter{Introduction}

\newpage
\addcontentsline{toc}{chapter}{Bibliography}
\nocite{Lec2}
\printbibliography

\begin{appendices}
\chapter{stuff} \label{App: AppendixA}
\begin{figure}[h]
\centering
\includegraphics[scale=0.62]{stuff}
\end{figure}

\chapter{stuff} \label{App: AppendixB}
\begin{figure}[h]
\centering
\includegraphics[scale=0.75]{stuff}
\end{figure}
\end{appendices}

\end{document}

A: I would suggest to simply remove the page option when loading appendix so that the page with "Appendices" is not shown.
But if you really want to have the "Appendices" title to be on the same page as your appendix contents, here is a way (I don't recommend to do it, of course).
Add the following lines just after \begin{appendices}
\clearpage
\begingroup
\let\clearpage\relax
\begin{center}
  \Huge\bfseries\appendixpagename
\end{center}
\chapter{stuff} \label{App: AppendixA}
\endgroup

and remove the page option when loading appendix.
MWE:
\documentclass[12pt, oneside]{report}
\usepackage[left=1in, top=1in, bottom=1in, right=1in]{geometry}
\geometry{letterpaper}
\usepackage{setspace}
\usepackage[demo]{graphicx}
\usepackage{indentfirst}
\usepackage{abstract}
\usepackage[toc]{appendix}

\begin{document}

\tableofcontents
\thispagestyle{empty}

\chapter{Introduction}

\begin{appendices}
\clearpage
\begingroup
\let\clearpage\relax
\begin{center}
  \Huge\bfseries\appendixpagename
\end{center}
\chapter{stuff} \label{App: AppendixA}
\endgroup

\begin{figure}[h]
\centering
\includegraphics[scale=0.62]{stuff}
\end{figure}

\chapter{stuff} \label{App: AppendixB}
\begin{figure}[h]
\centering
\includegraphics[scale=0.75]{stuff}
\end{figure}
\end{appendices}

\end{document}

Output


text:
Q: ggplot - geom_raster scale_fill_identity I'm kinda stuck in a matter.
Following the advice of another fellow user in this platform, I was able to plot a raster image and have the pixel assume the values I had assigned I a column, named "colors" in my df.
That was great, but know I need the legends assum the categories I have created in another column. So far, my code and my out put look like this
ggplot(data = Xinjiang_df) + geom_raster(aes(x = x, y = y, fill = colors))+  scale_fill_identity(guide = "legend")

Output

I appreciate any suggestion. Thanks.


text:
Q: PL/SQL: procedure with table and column name as parameters I would like to write a procedure in PL\SQL, which would change the special characters (in the example below: a hash) to a apriori declared characters (in the example below: an underscore). The procedure should take a table name and a column name as parameters. I wrote such a code, however, it doesn't work:
create or replace procedure change_chars(table_name in varchar2, column_name in varchar2)
    begin
        execute immediate 'update ' || table_name ||
        ' set ' || column_name || ' = replace(' || column_name ||', '''#''', '''_''')';
    end;

Any help would be appreciated

A: You're missing the IS just before the BEGIN and you have too many quotes in your string:
create or replace procedure change_chars(table_name in varchar2, column_name in varchar2) is
begin
    execute immediate 'update ' || table_name ||
    ' set ' || column_name || ' = replace(' || column_name ||', ''#'', ''_'')';
end;

To handle strings with quotes, you could use the Q operator instead:
' set ' || column_name || ' = replace(' || column_name || q'[, '#', '_')]';


text:
Q: Use Shortcode in Shortcode (insert post meta field value) i have a shortcode from a plugin which i cant modify... This shortcode has some arguments ex. [some_shortcode value=""] - I tried to input the value from post meta as argument for this shortcode, but its not working - here is the code...
This is the code from shortcode i created ( it returns values from post meta )
function test_shortcode( $string ) {
    extract( shortcode_atts( array(
        'string' => 'string'
    ), $string));

    // check what type user entered
    switch ( $string ) {
        case 'first':
            return get_post_meta( get_the_ID(), 'post_meta_one', true );
            break;
        case 'second':
            return get_post_meta( get_the_ID(), 'post_meta_two', true );
            break;
    }
}
add_shortcode('test', 'test_shortcode');

Now i want to insert this shortcode in the existing shortcode from the plugin on my page.
For example: [some_shortcode value='[test string="first"]']

It isnt working like this. Thanks for help!

A: It will not work to insert the shortcode in the existing shortcode like you provided. Your shortcode should have opportunity to process the provided shortcode as attribute.
You should to use the do_shortcode() in your shortcode. You have
[some_shortcode value='[test string="first"]']

and want to use returned value of [test string="first"] which is first in your shortcode. Your code will be:
function some_shortcode($atts){
    $atts = shortcode_atts(array(
        'value' => ''
    ), $atts);

    $second_shortcode_value = do_shortcode($atts['value']);

    //some code

    return $something;
}
add_shortcode('some_shortcode', 'some_shortcode');

The variable $second_shortcode_value will containt the output of the [test string="first"] shortcode.
P.S. Avoid of using exctract() function just because it can make your code hard readable.
EDIT:
Here is solution dinamically add attributes to [some_shortcode] value attribute.
function my_shortcode($atts){
    $atts = shortcode_atts(array(
        'str' => ''
    ), $atts);

    switch ( $atts['str'] ) {
        case 'first':
            $modified = get_post_meta( get_the_ID(), 'leweb_gender', true );
            break;
        default:
            $modified = '';
    }

    if(!empty($modified)) {
        $second_shortcode_with_value = do_shortcode("[some_shortcode value='$modified']");
    }else{
        $second_shortcode_with_value = do_shortcode('[some_shortcode]');
    }

    return $second_shortcode_with_value;
}
add_shortcode('some_shrt', 'my_shortcode');

What we are doing: instead of calling [some_shortcode value='something'] we are generating something into our shortcode and getting content like
[some_shrt str="first"]


text:
Q: KeyError in the .append() function, when translating csv to json Okay, so here is what Im trying to do.
I am trying to take a csv file and translate this into a Json so i can compare data sets.
However, for some reason I am unable to find, when i try and append the headings there is an error:
KeyError: 0

Here is my code
#Open file
Open file
with open(filename, "r") as f:
        sampleReader = csv.DictReader(f)
        next(sampleReader)
        data = {"test":[]}
        for row in sampleReader:
            data["test"].append({"ACTIVITY DATE": row[0]})
        print(data)

Traceback:
KeyError                                  Traceback (most recent call last)
<ipython-input-4-582fa1fa84a1> in <module>
      5         data = {"test":[]}
      6         for row in sampleReader:
----> 7             data["test"].append({"ACTIVITY DATE": row[0]})
      8         print(data)
      9

KeyError: 0

A: If you are to specify a field by its column number (as you do with row[0]) rather than its column name, you should use csv.reader instead of csv.DictReader:
sampleReader = csv.reader(f)

If you would like to specify a field by its column name, you should not skip a row with next(sampleReader) since csv.DictReader already consumes the header row, and you should also use the desired column name as a key to retrieve the value of the field:
with open(filename, "r") as f:
        sampleReader = csv.DictReader(f)
        data = {"test":[]}
        for row in sampleReader:
            data["test"].append({"ACTIVITY DATE": row['activity date']})
        print(data)


text:
Q: Training with tensorflow and colab I'm working on a project that involves temperature reading and LEDs. I need to train the connection between a certain temperature and the LED, but only with tensorflow and coding, not the real LED. For example, if the temperature is 37 degrees, the LED is ON and if the temperature is 39 the LED is OFF. What can I do to train this kind of connection between this variables?

A: The first step is to generate a csv dataset with the true value labels for the temperatures.
For example:
21,1
37,1
39,0
50,0

Then split this dataset into training and testing. A good split is 80%(training) to 20%(testing). Then use the information to train your tensorflow model which will have a single output which will either be a 1 or a 0.
Once you have trained your model to fit this data you can use the predict function to determine if the LED should be going on or off.


text:
Q: Cannot find using self reference associations in Waterline - Sails.js - MongoDB I'm trying to create a tree structure using associations in Waterline which in the end connects to a MongoDB database. The definition of a treee no is:
TreeNode.js
module.exports = {
    attributes: {
        name: 'string',
        childrenCategory: 'string',
        parent: {
            model: 'TreeNode'
        },
        children: {
            collection: 'TreeNode',
            via: 'parent'
        }
    }
};

And that's it for my tree structure. This node reference itself having multiple childrens of the same node and a unique parent, again of the same node.
Populating these tree seems to be working. But trying to find node with a given 'parent' does not. The following query gives nothing:
TreeNode.find().where({parent: someId}).exec(function (err, r) {}

Any ideas? Also, what do you think about this tree structure?
Thanks!

A: Have a look at this post:
https://github.com/balderdashy/waterline/issues/410
Will it help you if you try using objectid as the type for the parent?


text:
Q: How to display uploaded image with php laravel How can I display uploaded image from stored location and I want to carry over the same image name to
<input id = "Picture" type="file" name="Picture" accept="image/*" />

This code is used in Controller.php when upload
$img = $input['Picture'];
$name = $img->getClientOriginalName();
$uploaded = $img->move('public/img', $name);

This is where uploaded image will show in my new.blade.php

And Image name doesn't save original name to mysql, it saved like C:xampp mpphpB7CF.tmp
How can I do to save original name that I Uploaded.

A: Check below code this is working code.
$file = $request->file('Picture');
$destinationPath = 'public/img/';
$originalFile = $file->getClientOriginalName();
$file->move($destinationPath, $originalFile);

This line $originalFile = $file->getClientOriginalName(); will assign original file name to  $originalFile and use this variable name where you insert image in database.
Add below line to display image you have uploaded.

A: $path = '';

if ($request->hasFile('Picture')) {
    $file = $request->file('Picture');
    $path = $file->storeAs(public_path('img'), $imageName);

    //or
    if (file_put_contents(public_path(img) . $imageName, $file)) {
        $path = public_path(img) . $imageName;
    }
}

return view('your-view', ['img_path' => $path]);;

and in your new.blade.php

A: In Controller
public function show($name)
{
    $extension = File::extension($name);
        $path = public_path('storage/' . $name);
        if (!File::exists($path)) {abort(404);}
        $file = File::get($path);
        $type = File::mimeType($path);
        $response = Response::make($file, 200);
        $response->header("Content-Type", $type);
        return $response;

}
Route
Route::get('/images/{name}', 'FileController@show');

Index.blade.php
file") }}'>click here to view image

A: Return your $uploaded from controller to view
return view('new',['uploaded'=>$uploaded]);

and then in your view

A: Return path from controller and display :

A: I think you can try this:
use Input;
use Image;

$file = Input::file('Picture');
$imageName = $file->getClientOriginalName();

$imgUpload = Image::make($file)->save(public_path('img/' . $imageName));

Note: If you have get error for Image then install package for Image from this link


text:
Q: Why can't a finitely generated module over a PID be generated by fewer elements than the number of invariant factors? Suppose $V$ is a finitely generated module over the a PID with $n$ invariant factors. Why can't $V$ be generated by fewer than $n$ elements?
Is there a quick linear algebra reason?


text:
Q: AudioToolbox framework capabilities I want to know if AudioToolbox.framework will suppport an array of pageviewcontrollers to change with audio synchronization programmtically. From the apple documentation I found that Audio Queue Services lets you record, play, pause, loop, and synchronize audio but when they say synchronize audio are they referring to page change synchronization or something else?
I already have AVFoundation.framework in my app to play an audio file.

A: It's a 'Core' AV library. You'll have to you your own program to interact with or manipulate your UI. The library does not rely on either AppKit or UIKit.
Sync: consider it along the lines of accurate timing of audio playback.


text:
Q: Arguments or parameters? I often find myself confused with how the terms 'arguments' and 'parameters' are used. They seem to be used interchangeably in the programming world.
What's the correct convention for their use?

A: There is nice section in parameter Wikipedia article about this subject.
In short -- parameter is the formal name defined by function and argument is actual value (like 5) or thing (like variable) passed into function.

A: Although Wikipedia is hardly an authoritative source, it does a decent job of explaining the terms.
I guess you could say that parameters are to arguments what classes are to instances of objects...

A: For user1515422, a very concrete example showing the difference between parameters and arguments:
Consider this function:
int divide(int numerator, int denominator) {
    return numerator/denominator;
}

It has two parameters: numerator and denominator, set when it's defined.  Once defined, the parameters of a function are fixed and won't change.
Now consider an invocation of that function:
int result = divide(8, 4);

In this case, 8 and 4 are the arguments passed to the function.  The numerator parameter is set to the value of the argument 8, and denominator is set to 4.  Then the function is evaluated with the parameters set to the value of the arguments.  You can think of the process as equivalent to:
int divide() {
    int numerator = 8;
    int denominator = 4;
    return numerator/denominator;
}

The difference between a parameter and an argument is akin to the difference between a variable and its value.  If I write int x = 5;, the variable is x and the value is 5.  Confusion can arise because it's natural to say things like "x is five," as shorthand for "The variable x has the value 5," but hopefully the distinction is clear.
Does that clarify things?

A: Parameters are the things defined by functions as input, arguments are the things passed as parameters.
void foo(int bar) { ... }

foo(baz);

In this example, bar is a parameter for foo. baz is an argument passed to foo.

A: A Parameter is a variable in the declaration of a function:
functionName(parameter) {
    // do something
}

An Argument is the actual value of this variable that gets passed to the function:
functionName(argument);

A: When you define a function like:
MyFunction(param1,param2) {
  print parameter1, parameter
}

You set the parameters when you define the function.
When you call the function like this:
MyFunction('argument1', 'argument2');

You set the values of the parameters to the arguments you passed. The arguments are what you put in the question when you call it. Hope that helped.

A: Arguments are what you have when you're invoking a subroutine. Parameters are what you are accessing inside the subroutine.
argle(foo, bar);

foo and bar are arguments.
public static void main(final String[] args) {
    args.length;
}

args is a parameter.

A: Simply there is no major differences. If we go deeply inside this we can identify the diff.Mainly we know that Argument/Parameter/signature all are same.
Basically Parameter  defines the type of Data we are passing.Where as the Argument  defines the actual data/variable we are passing.
Parameter Example :-
int add(int a,int b){ //Here a and be both can treated as Parameter
 return a+b;
}

Argument Example :-
int return_result=add(3,4); // Here 3 and 4 both can treated as Argument

or

int x=3,y=4;
int return_result=add(x,y);// Here x and y both can treated as Argument

A: In most cases, a procedure needs some information about the circumstances in which it has been called. A procedure that performs repeated or shared tasks uses different information for each call. This information consists of variables, constants, and expressions that you pass to the procedure when you call it.
To communicate this information to the procedure, the procedure defines a parameter, and the calling code passes an argument to that parameter. You can think of the parameter as a parking place and the argument as an automobile. Just as different automobiles can park in the parking place at different times, the calling code can pass a different argument to the same parameter each time it calls the procedure.
Parameters
A parameter represents a value that the procedure expects you to pass when you call it. The procedure's declaration defines its parameters.
When you define a Function or Sub procedure, you specify a parameter list in parentheses immediately following the procedure name. For each parameter, you specify a name, a data type, and a passing mechanism (ByVal or ByRef). You can also indicate that a parameter is optional, meaning the calling code does not have to pass a value for it.
The name of each parameter serves as a local variable within the procedure. You use the parameter name the same way you use any other variable.
Arguments
An argument represents the value you pass to a procedure parameter when you call the procedure. The calling code supplies the arguments when it calls the procedure.
When you call a Function or Sub procedure, you include an argument list in parentheses immediately following the procedure name. Each argument corresponds to the parameter in the same position in the list.
In contrast to parameter definition, arguments do not have names. Each argument is an expression, which can contain zero or more variables, constants, and literals. The data type of the evaluated expression should normally match the data type defined for the corresponding parameter, and in any case it must be convertible to the parameter type.

A: In fact both parameter and argument are different types of parameters. Those are

1)Formal Parameters - variables appear in function/subroutine definitions

for eg. (in Java)
public void foo(Integer integer, String... s2)

Here both integer and s2 are formal parameters or loosely speaking parameters.

2)Actual parameters or arguments - variables appear in subroutines while calling the
already defined subroutine

for eg. (in Java)
suppose If the function "foo" resides in object "testObject" ,
testObject.foo(new Integer(1), "test")

So variables in the function definition are called formal parameters or simply parameters and variables while calling methods are called as actual parameters or arguments. I hope it helps.

A: Think of it like basic algebra. X is the parameter that you have to fill in, and the number you place inside of it is the argument. So if you have an equation like X+2, X is your parameter, and any numbers you change for X become known as the arguments. So if using that equation you supplement 1 for x, you get 1+2. That means that 1 is an argument, supplied to the parameter of X.
Equally, if you have a function like dosomething("This"), it's definition would be dosomething(string parametername), but "This" would be the actual argument that is being supplied to the parameter, here named parametername.
In the simplest way to look at it, the parameter is the thing that the argument fills in, and the argument can be any number of things allowed by that parameter.
So it's a many-to-one relationship between Parameters and arguments, as you can have one parameter that can have many valid arguments, like our X+1 equation above. X can be any number known, and they are all valid.

A: A variable is a storage location and an associated symbolic name (an identifier) which contains data, a value.
A parameter is a variable passed to a function.
An argument is data (a value) passed to a function.
$variable = 'data/value';

function first($variable){ ... }

function second('data/value'){ ... }
function third(16){ ... }

In function first we are passing a parameter.
In function second and third we are passing arguments.


text:
Q: How to stop to add same address Multiple times in Magento 2? I have faced a problem regarding on adding same address multiple times like

I don't want to add it multiple times same address.
Any Help is appreciated.


text:
Q: MLE estimation of parameters, converting normalized observations to integers and back I am fitting a model's parameters to grouped data by maximizing the likelihood equation:
$L(\theta)=N!\prod_{i=1}^{G}\frac{p_i(\theta)^{n_i}}{n_i!}$
$\theta$ is the vector of parameters.  $n_i$ is the number of observations in group i.  That is, $n_i=x_i-x_{i-1}$ where $x_i$ is an individual observation.  $N$ is the total number of observations ($N=\sum_{i}n_i$).  $G$ is the number of groups.
And $p_i(\theta)=F(x_i;\theta)-F(x_{i-1};\theta)$, where $F(x_i;\theta)$ is the distribution function I am trying to fit to the data.
My problem is that the observations are normalized (they are percentiles).  So $0<n_i<1$, when I need integers for the factorials.  Multiplying $N$ and $n_i$ by 100 and rounding allows me to run the equation in matlab, but then I am not sure what to do with the output in order to convert it back to 1/100 scale.  Appreciate some advice.  Thanks.


text:
Q: How do I assign a character variable to a poistion in the string varible in python? I am working in Python right now.
My ch variable, which is the character variable has a character store in it, which has been entered by the user.
I also have a string variable (string1) in which I want to add the character without over-writing the string variable.
i.e I want to do string1[i]=ch, where i can be any position.
when i do this in python, it gives an error saying: 'str' object does not support item assignment.
here, string1[i]=ch, is in a while loop.
Is there a proper way of doing this? Please help.

A: str in python is immutable. That means, you can't assign some random value to a specific index.
For example, below is not possible:
a = 'hello'
a[2]= 'X'

There is an workaround.

*

*make a list from the str.

*mutate the specific index you wanted from that list.

*form a str again from the list.

Like below:
>>> a = 'hello'
>>> tmp_list = list(a)
>>> tmp_list
['h', 'e', 'l', 'l', 'o']
>>> tmp_list[2] = 'X'
>>> tmp_list
['h', 'e', 'X', 'l', 'o']
>>>
>>> a = ''.join(tmp_list)
>>> a
'heXlo'


text:
Q: How to get fileupload control in gridview using javascript Hi I have a file upload in my footer in my gridview, i want to get it in javascript. The following code gets me the fileupload but using vb,
Dim fileuploadftrCardImage As FileUpload = DirectCast(gvCardsProvider.FooterRow.FindControl("fileuploadftrCardImage"), FileUpload)

I want to take it using javascript
the following doesn't work since the fileupload is in my gridview
var file = document.querySelector('#<%=fileuploadftrCardImage.ClientID %>').files[0];

Anyways is there any way i can get it?


text:
Q: Is there a way to display the total count of rows in a separate row? I have a table that looks like this:

City_Id
City

41
Athena

39
Beijing

35
London

30
Rio de Janeiro

28
Salt Lake City

18
Sochi

7
Sydney

4
Torino

is there a way to display another row in the bottom that will display the total count of rows?

City_Id
City

41
Athena

39
Beijing

35
London

30
Rio de Janeiro

28
Salt Lake City

18
Sochi

7
Sydney

4
Torino

Total
8

A: I would agree with most of the other comments that acquiring a result set count would be more appropriate from the application code (which usually has a mechanism specifically for this purpose).
However...
If you must have a TSQL solution for your question, an option is to return the count in a separate column. This is different than returning it in a separate row, of course. There are pros & cons with each approach.
DROP TABLE IF EXISTS #Cities;

CREATE TABLE #Cities (
    City_Id INT,
    City VARCHAR(128)
);

INSERT INTO #Cities
VALUES
    (41,    'Athena'),
    (39,    'Beijing'),
    (35,    'London'),
    (30,    'Rio de Janeiro'),
    (28,    'Salt Lake City'),
    (18,    'Sochi'),
    (7 ,    'Sydney'),
    (4 ,    'Torino');

SELECT *, COUNT(*) OVER(ORDER BY (SELECT NULL)) AS Total
FROM #Cities;

--Count is properly reflected based on WHERE clause.
SELECT *, COUNT(*) OVER(ORDER BY (SELECT NULL)) AS Total
FROM #Cities
WHERE City LIKE 'S%';

--Be careful with this one--the COUNT(*) may not be what you expected.
SELECT TOP(4) *, COUNT(*) OVER(ORDER BY (SELECT NULL)) AS Total
FROM #Cities;

NOTE: be aware that this approach may not scale (perform) well for large result sets. Be sure to do some testing!

A: You can actually use GROUPING SETS for this. This avoids having to scan the table twice.
However you still have the data-type mismatch problem. You could solve it by casting, but it's probably easier to just swap the columns around
SELECT
  CASE WHEN GROUPING(City) = 0 THEN City ELSE 'Total' END AS City,
  CASE WHEN GROUPING(City_Id) = 0 THEN City_Id ELSE COUNT(*) END AS City_Id
FROM Table1
GROUP BY GROUPING SETS (
    (City_Id, City),
    ()
)
ORDER BY GROUPING(City_Id);

SQL Fiddle
What this does is generate separate result-sets, unioned together. You can differentiate between a grouped row and a non-grouped row using the GROUPING function.

A: As you know already, it should be done in the presentation layer. But if you just want to know if there is any way, then I would suggest to use UNION ALL
select cast(City_Id as varchar(10)) City_Id, City from Table1
union all
select 'Total' as City_Id, cast(count(*) as varchar(14)) from Table1

Here is the sql fiddle


text:
Q: How do I troubleshoot a 404 error on a webapp accessed via apache vhost? In my development system ( macos ) I have a webapp running in a jetty container on port 8080
Part of this webapp is a REST service
I can hit the REST service as follows
curl http://fake.hostname.com:8080/find/http%3A%2F%2Fwww.nfl.com

and I get the expected JSON result from this call.
Because on the server I am deploying on, I have an apache front end using ajp to route to tomcat, on my dev system I have an apache vhost routing to port 8080. This helps with testing some oauth dependencies where facebook redirects to a specific host URL.
The webapp works fine in this configuration except when I try and hit the service using
curl http://fake.hostname.com/find/http%3A%2F%2Fwww.nfl.com

Nothing is showing up in the jetty console reporting a proplem and I am getting a 404 response from apache.
Can anyone suggest how to troubleshoot such an issue? Or things I should look at?
note 1. I know the issue of using apache as a proxy to tomcat or jetty is contentious but given there are other apps already living on apache port 80 I'm not willing to run tomcat in its place.
note 2. the webapp is in scala using the lift framework.

A: Not really an answer to the exact question, but did you consider to use nginx as a proxy+load balancer? It's a de-facto standard, as far as I know.
Also, what's in the logs? tomcat-s logs, apache logs..


text:
Q: nHibernate Distinct query Code
IList VendorList;
                VendorList = session
                    .CreateCriteria<VendorLookup>()
                    .Add(Expression.Eq("NetworkRunId", networkRunId))
                    .Add(Expression.Not(Expression.Eq("VendorName", " ")))
                    .SetResultTransformer(new NHibernate.Transform.DistinctRootEntityResultTransformer())
                    .AddOrder(new Order("VendorName", true))
                    .List<IVendorLookup>().Distinct<IVendorLookup>().ToList();

Generated Query Please help me out
SELECT   this_.Sp    as HCO1_25_0_,
         this_.NID  as Network2_25_0_,
         this_.Vname as HCO3_25_0_
FROM     HCO_V_Lookup this_
WHERE    this_.NID = 5 /* @p0 */
         and not (this_.VNAME = ' ' /* @p1 */)
ORDER BY this_.VNAME asc

A: I presume you're wondering why the DISTINCT doesn't appear in the SQL. It's because it's applied in your criteria query as a result transformer - the SQL query results are filtered to make them distinct after the query has been run.

A: ICriteria criteria = session.CreateCriteria(typeof(Person));
criteria.SetProjection(
    Projections.Distinct(Projections.ProjectionList()
        .Add(Projections.Alias(Projections.Property("FirstName"), "FirstName"))
        .Add(Projections.Alias(Projections.Property("LastName"), "LastName"))));

criteria.SetResultTransformer(
    new NHibernate.Transform.AliasToBeanResultTransformer(typeof(Person)));

IList people = criteria.List();


text:
Q: Save cursors in temporary table I'm an absolute noob and couldn't find the answer to this one.
How can I add the result into a temporary table?
Perhaps you guys have some tips for me to improve my code as well?
I created a function here with cursors through the results. But I need to:
drop function if exists non_married_presidents();
create or replace function non_married_presidents()
returns varchar as $$
declare
    c_emp cursor for
        select name, birth_year from president
        where id not in(select pres_id from pres_marriage);
begin

    for emp in c_emp loop
        raise notice 'name: %, birth_year: %', emp.name, emp.birth_year;
    end loop;
end;
$$language plpgsql;

Call:
select non_married_presidents();

A: You ask:

How can I add the result into a temporary table?

You may be overthinking this. Just use CREATE TEMP TABLE AS ...
CREATE TEMP TABLE tmp_tbl AS
-- INSERT INTO tmp_tbl (name, birth_year) -- or insert into existing table
SELECT name, birth_year FROM president p
WHERE  NOT EXISTS (SELECT 1 FROM pres_marriage WHERE pres_id = p.id);

You don't need a cursor. It's a rare occasion that an explicit cursor would be the best option in plpgsql.
While being at it, NOT IN is a construct best avoided:

*

*Select rows which are not present in other table


text:
Q: Magento PDF invoice totals I have Magento web shop with prices on totals displaying both with included and excluded tax. On my cart and sales emails, the order of the totals is normal, like:
Product price Incl tax
Product price Excl tax
Shipping price Incl tax
Shipping price Ecl tax
Tax for shipping
Tax for product
Only on my PDF invoices, I have things unsorted, like.
Product price Incl tax
Product price Excl tax
Tax for shipping
Tax for product
Shipping price Incl tax
Shipping price Ecl tax
Is there a way to change order of the totals in PDF invoices and where?

A: You can find totals sort order here app/code/core/mage/sales/etc/config.xml under the node pdf.You need to override the config.xml.The link descibes how to do it.


text:
Q: Searching/predicting next terminal/non-terminal by CFG/Tree? I'm looking for algorithm to help me predict next token given a string/prefix and Context free grammar.
First question is what is the exact structure representing CFG. It seems it is a tree, but what type of tree ? I'm asking because the leaves are always ordered , is there a ordered-tree ?
May be if i know the correct structure I can find algorithm for bottom-up search !
If it is not exactly a Search problem, then the next closest thing it looks like Parsing the prefix-string and then Generating the next-token ? How do I do that ?
any ideas

my current generated grammar is simple it has no OR rules (except when i decide to reuse the grammar for new sequences, i will be). It is generated by Sequitur algo and is so called SLG(single line grammar) .. but if I generate it using many seq's the TOP rule will be Ex:>
S : S1 z S3 | u S2 .. S5 S1 | S4 S2 .. |... | Sn
S1 : a b
S2 : h u y
...

..i.e. top-heavy SLG, except the top rule all others do not have OR |

As a side note I'm thinking of a ways to convert it to Prolog and/or DCG program, where may be there is easier way to do what I want easily ?! what do you think ?

A: TL;DR: In abstract, this is a hard problem. But it can be pretty simple for given grammars. Everything depends on the nature of the grammar.

The basic algorithm indeed starts by using some parsing algorithm on the prefix. A rough prediction can then be made by attempting to continue the parse with each possible token, retaining only those which do not produce immediate errors.
That will certainly give you a list which includes all of the possible continuations. But the list may also include tokens which cannot appear in a correct input. Indeed, it is possible that the correct list is empty (because the given prefix is not the prefix of any correct input); this will happen if the parsing algorithm is unable to correctly verify whether a token sequence is a possible prefix.
In part, this will depend on the grammar itself. If the grammar is LR(1), for example, then the LR(1) parsing algorithm can precisely identify the continuation set. If the grammar is LR(k) for some k>1, then it is theoretically possible to produce an LR(1) grammar for the same language, but the resulting grammar might be impractically large. Otherwise, you might have to settle for "false positives". That might be acceptable if your goal is to provide tab-completion, but in other circumstances it might not be so useful.
The precise datastructure used to perform the internal parse and exploration of alternatives will depend on the parsing algorithm used. Many parsing algorithms, including the standard LR parsing algorithm whose internal data structure is a simple stack, feature a mutable internal state which is not really suitable for the exploration step; you could adapt such an algorithm by making a copy of the entire internal data structure (that is, the stack) before proceeding with each trial token. Alternatively, you could implement a copy-on-write stack. But the parser stack is not usually very big, so copying it each time is generally feasible. (That's what Bison does to produce expanded error messages with an "expected token" list, and it doesn't seem to trigger unacceptable runtime overhead in practice.)
Alternatively, you could use some variant of CYK chart parsing (or a GLR algorithm like the Earley algorithm), whose internal data structures can be implemented in a way which doesn't involve destructive modification. Such algorithms are generally used for grammars which are not LR(1), since they can cope with any CFG although highly ambiguous grammars can take a long time to parse (proportional to the cube of the input length). As mentioned above, though, you will get false positives from such algorithms.
If false positives are unacceptable, then you could use some kind of heuristic search to attempt to find an input sequence which completes the trial prefix. This can in theory take quite a long time, but for many grammars a breadth-first search can find a completion within a reasonable time, so you could terminate the search after a given maximum time. This will not produce false positives, but the time limit might prevent it from  finding the complete set of possible continuations.


text:
Q: Annotation does not work correctly in Okular I hava a pdf file.
In okular 0.17.2 under Ubuntu 12.04, I have found two problems:

*

*added inline note (by F6, and then 2)  will be rotated 90 degree counterclockwise.

*added underline (by F6, and then 8)  doesn't show.

See the resulted pdf file here.
Is this some problem with the pdf file, or with okular?
Thanks.

A: I tried with various PDF readers in ubuntu .
some give annotation and it is not saved in file directly,uses some mechanism.
Thats why your notes,highlights done in okular cannot be viewed in another PDF viewer.
The best way is to install Foxit reader along with wine.
As of my knowledge there is no native application in ubuntu that can annotate PDF's

A: A newer Okular version (20.12.3 in my case) annotates correctly and the annotations can be viewed by any other external programs.


text:
Q: Creating a bit mask with BigInts Is there a more efficient way of performing the following calculation? It works fine, but something tells me that x &= (1 << 8) - 1 ^ 1 << 3 can be written to avoid some calculations and increase speed.
def unset_mask(width, index):
    return (1 << width) - 1 ^ 1 << index

x = 0b11111111
x &= unset_mask(8, 3)
assert x == 0b11110111

A: Actually, you don't need to state the width. Bigints behave the right way when you do this:
>>> bin(255 & ~(1 << 3))
'0b11110111'
>>> bin(65535 & ~(1 << 3))
'0b1111111111110111'
>>> bin(75557863725914323419135 & ~(1 << 3))
'0b1111111111111111111111111111111111111111111111111111111111111111111111110111'

It's because negative numbers have an "infinite" string of ones preceding them. So when you complement a positive number (which starts with an "infinte" string of zeros), you get a negative number (-(x + 1) to be exact). Just don't trust the bin representation of negative numbers; it doesn't reflect the actual bits in memory.
So you would rewrite unset_mask like so:
def unset_mask(index):
    return ~(1 << index)

x = 0b11111111
x &= unset_mask(3)
print x == 0b11110111  # prints True

A: This will unset the bit:
x ^= 1 << 3 & x

In a function:
def unset_bit(x, n):
    return 1 << n & x ^ x

A: You can use this to clear a bit in x:
x &= ~(1 << index)


text:
Q: Which is correct: contribute or contributes? Which sentence is correct:
1. We ask that each person contribute one item to our potluck.
2. We ask that each person contributes one item to our potluck.

A: Think of it this way.  First, here is a declarative sentence:-

*

*We say that each person contributes.

It is a simple indirect (reported) statement in which the verb is, therefore in the indicative;  third person singular present indicative of the verb contribute.

*We ask that each person contribute.  (not "contributes)

This sentence says nothing about how the world is.  It says how we want it to be; are asking people to make it that way.  So we use the verb in its modal form:  contribute, not contributes.

A: Under the grammar rules, the subjunctive mood must be used in the object clause after the word ask. Ex: The Province of Nova Scotia asked that this issue be addressed in response to cases of inadequate design and construction, and catastrophic failures. I have sat waiting for my turn and watched the barber use a blade twice before getting to me at which point i kindly asked that he pull out a new blade for me.


text:
Q: remove text from the page which is under no tag I have html page which is appearing properly but it has some dynamic text which is coming, and it is under no tag. how can i remove that text using jquery.
The text is coming as:

Search Setup 1 FIA - need to remove this {the text appearing is dynamic}


text:
Q: swift update frame of uitableviewcell with uiswipegesturerecognizer I added an UISwipeGestureRecogniser into my tableviewcell. Now I'd like to add a real time slide effect to my tableviewcell. If I currently swipe over the cell nothing happens. The cell should just be swipeable.
My code:
var originalCenter = CGPoint()

var rightSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipes:"))
rightSwipe.direction = .Right
self.addGestureRecognizer(rightSwipe)

func handleSwipes(recogniser:UISwipeGestureRecognizer) {

    let location : CGPoint = recogniser.locationInView(self)

    if (recogniser.direction == .Right) {

        if recogniser.state == .Began {

            // when the gesture begins, record the current center location
            originalCenter = center
        }

        if recogniser.state == .Changed {

            let translation = recogniser.locationInView(self)
            center = CGPointMake(originalCenter.x + translation.x, originalCenter.y)
        }

        if recogniser.state == .Ended {

        }

        println("Swipe Right")
    }
}

A: You can easily do what you want to do by subclassing UIPanGestureRecognizer. But don't. Instead of adding a gesture recognizer, turn your cell into a UIScrollView. Now you can set its contentSize and bounds origin so that it can be scrolled left to right only. The advantage here is that you are using a built-in interface class that is made to be draggable automatically. You can use the delegate methods to keep track of what the user does if you need to.

A: I have custom cell swipes implemented in my previous projects... you need to animate the things to look exactly like the swipe which works in notification draw message swiping. I can give you snippet in Objective-C. you should be able to translate it into swift easily ;)
-(void)handleLeftCellSwipe:(UISwipeGestureRecognizer *)recognizer{
     CGPoint location = [recognizer locationInView:self.localTableView];
     NSIndexPath *swipedIndexPath = [self.localTableView indexPathForRowAtPoint:location];
     UITableViewCell *swipedCell  = [self.localTableView cellForRowAtIndexPath:swipedIndexPath];
     if(swipedCell){
          [UIView animateWithDuration:0.3 delay:0.0 usingSpringWithDamping:0.7 initialSpringVelocity:1.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
          [swipedCell.contentView setFrame:CGRectMake(swipedCell.contentView.frame.origin.x - 40, swipedCell.contentView.frame.origin.y, swipedCell.contentView.frame.size.width, swipedCell.contentView.frame.size.height)];
          } completion:^(BOOL finished){
              // Do whatever you need to do after animation completes
          }];
     }
}


text:
Q: How to solve the ODE: $xy'-y=f(x)$ How to solve the following ODE:
$xy'-y=\left(x^{2}+2x\right)\sin\left(3x\right)$.
That is: how we find a relation between $x$ and $y$ without any derivative or integral symbol in that relation.
If we use the standard formula, it might be difficult by calculating the antiderivative.

A: We have $$y'-\frac {1}{x} y =(x+2)\sin 3x $$ This is a linear differential equation. The integrating factor is $e^{\int -\frac {1}{x} dx} = e^{-\log x} =\frac {1}{x} $.
The solution is thus $$y (\frac {1}{x}) =\int \frac {1}{x}(x+2)\sin 3x dx$$ Can you take it from here?


text:
Q: What are the retransmission rules for TCP? The Wikipedia article on TCP indicates that the IP packets transporting TCP segments can sometimes go lost, and that TCP "requests retransmission of lost data".
What exactly are the rules for requesting retransmission of lost data? At what time frequency are the retransmission requests performed? Is there an upper bound on the number? Is there functionality for the client to indicate to the server to forget about the whole TCP segment for which part went missing when the IP packet went missing?

A: What exactly are the rules for requesting retransmission of lost data?
The receiver does not request the retransmission. The sender waits for an ACK for the byte-range sent to the client and when not received, resends the packets, after a particular interval.
This is ARQ (Automatic Repeat reQuest). There are several ways in which this is implemented.
Stop-and-wait ARQ
Go-Back-N ARQ
Selective Repeat ARQ

are detailed in the RFC 3366.
At what time frequency are the retransmission requests performed?
The retransmissions-times and the number of attempts isn't enforced by the standard. It is implemented differently by different operating systems, but the methodology is fixed. (One of the ways to fingerprint OSs perhaps?)
The timeouts are measured in terms of the RTT (Round Trip Time) times. But this isn't needed very often due to Fast-retransmit which kicks in when 3 Duplicate ACKs are received.
Is there an upper bound on the number?
Yes there is. After a certain number of retries, the host is considered to be "down" and the sender gives up and tears down the TCP connection.
Is there functionality for the client to indicate to the server to forget about the whole TCP segment for which part went missing when the IP packet went missing?
The whole point is reliable communication. If you wanted the client to forget about some part, you wouldn't be using TCP in the first place. (UDP perhaps?)

A: There's no fixed time for retransmission.  Simple implementations estimate the RTT (round-trip-time) and if no ACK to send data has been received in 2x that time then they re-send.
They then double the wait-time and re-send once more if again there is no reply.  Rinse.  Repeat.
More sophisticated systems make better estimates of how long it should take for the ACK as well as guesses about exactly which data has been lost.
The bottom-line is that there is no hard-and-fast rule about exactly when to retransmit.  It's up to the implementation.  All retransmissions are triggered solely by the sender based on lack of response from the receiver.
TCP never drops data so no, there is no way to indicate a server should forget about some segment.


text:
Q: Stop overlaying of features in openlayers I have a vector layer and I'm adding multiple features of polygon geometry to it. The code of adding features to the layer is mentioned down below:
        let recentPointStyle = new Style({
            stroke: new Stroke({
                color: '#1c568f',
            }),
            fill: new Fill({
                color: 'rgba(28, 86, 143, 0.5)'
            })
        });

        let pointStyle = new Style({
            fill: new Fill({
                color: 'rgba(124, 252, 0, 0.5)'
            })
        });

        let feature = new Feature({
            geometry: new Polygon([bounds]),
        });

        feature.setStyle(recentPointStyle);

        let allFeatures = [feature];

        let previousBounds = [...this.props.areaVisited];

        for (let i = 0; i < previousBounds.length; i++) {
            let currBound = previousBounds[i];

            let currFeature = new Feature({
                geometry: new Polygon([currBound]),
            });

            currFeature.setStyle(pointStyle);

            allFeatures.push(currFeature);
        }

        previousBounds.push(bounds);

        this.props.dispatch(updateVisitedArea(previousBounds));

        vectorLayer.setSource(new VectorSource({
            features: allFeatures,
            wrapX: false
        }));

Now this code is working absolutely fine but when the user goes back to the same area, then the feature is drawn again and it becomes darker and darker and the content of the other layer is not visible. So how can I stop this and maintain the opacity of the layer?
I tried with adding multiple polygons instead of multiple features to the layer. But the same result is coming. This the updated code.
               let recentPointStyle = new Style({
                    stroke: new Stroke({
                        color: '#1c568f',
                    }),
                    fill: new Fill({
                        color: 'rgba(28, 86, 143, 0.5)'
                    })
                });

                let pointStyle = new Style({
                    fill: new Fill({
                        color: 'rgba(124, 252, 0, 0.5)'
                    })
                });

                let allPolygons = [];
                let previousBounds =[...this.props.areaVisited];

                for(let i = 0; i < previousBounds.length; i++) {
                    let currBound = previousBounds[i];

                    allPolygons.push(new Polygon([currBound]));
                }

                let feature = new Feature({
                    geometry: new Polygon([bounds]),
                });

                feature.setStyle(recentPointStyle);

                let allFeatures = [feature];

                let currFeature = new Feature({
                    geometry: new MultiPolygon(allPolygons),
                });

                currFeature.setStyle(pointStyle);

                allFeatures.push(currFeature);

                if(!previousBounds.includes(bounds)) {
                    previousBounds.push(bounds);
                }

                this.props.dispatch(updateVisitedArea(previousBounds));

                vectorLayer.setSource(new VectorSource({
                    features: allFeatures,
                    wrapX: false
                }));


text:
Q: can we use a function while accepting parameters in oracle procedure I need to ensure that the parameter "lastname" that is being passed to my Oracle procedure is in "initcap" format. Can I use the INITCAP function while accepting the value itself?
create or replace PROCEDURE SP_SPRIDEN_7_INSERT
 (
 PIDM in varchar2,
 STUD_ID IN OUT VARCHAR2,
 INITCAP(LASTNAME) IN VARCHAR2,
 ERROR OUT VARCHAR2
)

A: You can't define a procedure like this. The easiest way to get this behavior is to explicitly call initcap on that argument before using it in the procedure's body.


text:
Q: writing unit test for many to many model in django program in my django projects, I have a two class like following:
class DataTag(models.Model):
title = models.CharField(max_length=120, unique=True)
relations = models.ManyToManyField('DataTag',
related_name='related_data_tags', blank=True)

and the another class is:
class Data(models.Model):
    tags = models.ManyToManyField('DataTag',related_name = 'data')
    def tag_name(self):
        if self.tags.all():
            return self.tags.all()[0].title
        return ''

both my models work, but now I want to write a test for main_tag_name, and checking if this function returns a true value or not.until now I write the following:
from unittest import TestCase
class DataTest(TestCase):
    def test_tag_name(self):
        self.data = Data.objects.create()
        self.tag1 = DataTag.objects.create()

I am new on writing test. please help me for writing this test.
Thanks in advance

A: What you can do:
Create a Data object:
data_object = Data.objects.create()
Now, create a tag for this:
data_object.tags.create(name='Foo')
You can assert that the relationship exists: self.assertTrue(data_objects.tags.exists())
And now you can assert that tag_name returns what you expect: self.assertEqual(data_object.tag_name, 'Foo')


text:
Q: How to create a counter/stopwatch in Psychopy I am learning how to create Psychology experiments using Psychopy or OpenSesame. Currently, I am trying to create a Psychomotor Vigilance Task where a counter/stopwatch will appear and the participants have to press a button to stop it. How do I create this counter/stopwatch?
Please point me in the general direction and try not to provide me with the answers since I want to try to figure it out myself. Thanks!

A: You could provide an image to represent the clock face and another to represent the hand and then change the orientation of the hand (using set every frame) according to time (ori set to $t*6 would rotate 360deg every 60s).
Tips:

*

*make your image for the hand transparent on areas where you want the clock face to be visible and position it in your image so that the base of the hand is in the centre of the image

*you could give your hand a 'ticking' appearance by rounding the orientation


text:
Q: What about performance of 1 to 1 or 0 when join to single view I have 2 tables, first table is a raw data for calculate result and store to second table (tbl_cdn) and some time in in calculation process may use some record of tbl_fbk like self join. My question is should I use 2 tables in 1 to 1 or 0 relation or merge into single table ?
tbl_fbk

*

*fbkrec_id

*name

*value_a

*value_b

*reference_result_value ( foriegn key to fbkrec_id on tbl_cdn)

tbl_cdn

*

*fbkrec_id

*result value


text:
Q: My facebook tab app cannot post photo to page's wall when used by user NOT admin Alright, here's what I'm facing:
I have made an app for my facebook fan page, my app is a Facebook Page Tab app.
I have added the application to my facebook page by following:
http://developers.facebook.com/docs/appsonfacebook/pagetabs/
respectively, entering:
http://www.facebook.com/dialog/pagetab?app_id=YOUR_APP_ID&next=YOUR_URL
and choosing which page to be added to.
When I have done this I did it with my Facebook Page Admin user.
I have allowed manage_pages and publish_stream and publish_actions permissions.
Here is my code:
$objFacebook = App_Utils_Facebook::getFacebook();

    $user_id = $objFacebook->getUser();
    $objFacebook->setFileUploadSupport(true);

    if(isset($_REQUEST['pageId'])){
        $arrPriv = $objFacebook->api("/".$_REQUEST['pageId']."/", array('fields'=>'access_token'));
        $link = 'http://link/here/'.$this->objAnunt->id;
    }

    $privacy = json_encode(array('value'=>'SELF'));

    if(isset($arrPriv['access_token'])){
        $access_token = $arrPriv['access_token'];
    }else{
        $access_token = $objFacebook->api("/".$_REQUEST['pageId']."/", array('fields'=>'access_token'));
    }

    if($user_id){
        try{
            $ret=$objFacebook->api("/".$arrPriv['id']."/photos",'POST',array(
                    'source'=>'@link/to/pic.jpg',
                    'message'=>$strTitle.'

                               For more details click here  '.$link,
                    'access_token'=>$access_token,
                    'privacy'=>$privacy
                                                )
            );
            unlink('link/to/pic.jpg');
        }catch(FacebookApiException $e) {
            echo $e;
        }
    }else{
            $permissions = $objFacebook->api("/me/permissions");
            if( !array_key_exists('publish_stream', $permissions['data'][0]) ||
            !array_key_exists('manage_pages', $permissions['data'][0])) {
                // We don't have one of the permissions
                // Alert the admin or ask for the permission!
                header( "Location: " . $objFacebook->getLoginUrl(array("scope" => "publish_stream, manage_pages")) );
            }
    }

So I repeat myself, I want to allow the average user to access my application and THE PAGE ITSELF to post on it's own wall.
Can I do it? If not are there any alternatives.
Thank you for your time and patience to help me figure this out!

A: As far as I know, you do not need the manage_pages permission to post to a page.
Please see this documentation.
Making an API call to /{page_id}/feed using a valid user access_token should be enough to post to a page's feed.

As mentioned in the comments, Facebook probably doesn't allow a common user to upload photos to a page's albums. You'll need an access_token from an admin of that page (ensuring that the manage_pages permission is granted), retrive the page access token, and upload photos that way.
That page access token should be good for the life of the user access token.


text:
Q: Redshift - Weird behaviour from TO_TIMESTAMP function I'm trying to create a timestamp from separated date and time fields. The date field is of 'date' type while the time field is 'varchar'. The table has just over 60k records. Date is in YYYY-MM-DD format, ie 2017-07-25. Time is in HH:MIpm format, ie 4:25pm.
I run the following query to try and create the timestamp:
select *,
       to_timestamp(TO_CHAR("date", 'YYYY-MM-DD')||' '||(case when "time"='' then '11:59pm' else "time" end), 'YYYY-MM-DD HH:MIpm') as REQUIRED_TIMESTAMP
from TABLE;

However, it only returns 1023 records. Here's what makes things even weirder:
i. The records that are returned aren't always the same on subsequent runs. However, there is always 1023 records returned. On one run the first few IDs would be 43, 55, 63, 69, etc. and on the next run it'd be different. Sometimes I'd get the following error:
Query 1 ERROR: ERROR:  invalid value for "HH" in source string
ii. I used CAST(as timestamp) instead, it'd show the timestamp in a different format but again it'd only show 1023 records.
iii. It's not a specific time value that is omitted. A record with time 7:30pm may be omitted, but another record with 7:30pm shows up just fine.
Is there something wrong with my query? Could it be a problem with the data or is this an issue with Redshift?


text:
Q: How to use the variable of one method in another method in Java(android) I am retrieving the value of a TextView like this
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.calculation);
    TextView heading = (TextView) findViewById(R.id.paper_name);
    ......
}

I have another method in same class
@Override
public void onClick(View v) {
    int BLACK_AND_WHITE_MULTIUPLIER = 4200;
    int COLOR_MULTIUPLIER = 6400;
    switch (v.getId()) {
        case R.id.btCalculate:
        int multiplier = rbColor.isChecked() ? COLOR_MULTIUPLIER : BLACK_AND_WHITE_MULTIUPLIER;
        int column = Integer.parseInt((String) spColumn.getSelectedItem());
        int inch = Integer.parseInt((String) spInch.getSelectedItem());
        tvAmount.setText((multiplier * column * inch) + "");
        break;
    }
}

I want to set the value of COLOR_MULTIUPLIER and BLACK_AND_WHITE_MULTIUPLIER based on value of heading which I have got from the onCreate method. Is it possible?

A: Move the TextView heading; so that it is a class variable not a local variable and then it will be accessible throughout your whole class.
It can then be intialized in onCreate and read and or updated in onClick

A: Declare your TextView at class level...
TextView heading;

protected void onCreate(Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.calculation);

        heading = (TextView) findViewById(R.id.paper_name);
        heading.setText("something");

            ......

then access it in onClick() method as below...
@Override
public void onClick(View v)
{
     int BLACK_AND_WHITE_MULTIUPLIER = 4200;
     int COLOR_MULTIUPLIER = 6400;
    switch (v.getId())
    {
        case R.id.btCalculate:

            int multiplier = 0;

            if (heading.getText().toString.equals("something")) {

                multiplier = COLOR_MULTIUPLIER;

            } else {

                multiplier = BLACK_AND_WHITE_MULTIUPLIER;

            }

            //int multiplier = rbColor.isChecked() ? COLOR_MULTIUPLIER
            //        : BLACK_AND_WHITE_MULTIUPLIER;
            int column = Integer.parseInt((String) spColumn
                    .getSelectedItem());
            int inch = Integer.parseInt((String) spInch.getSelectedItem());
            tvAmount.setText((multiplier * column * inch) + "");
            break;
    }
}

A: Like I said in my comment, you just need to make heading a variable that belongs to the whole object, not just the onCreate method. You do this in the following way.
public class MyActivity extends Activity {

    TextView heading;  //Declared outside of onCreate

    protected void onCreate(Bundle savedInstanceState) {
        heading = (TextView) findViewById(R.id.paper_name); //Assigned inside of onCreate
    }
}

Then that variable becomes accessible inside your onClick
public void onClick(View v) {
    heading.getText(); //Or whatever you need to use it for
}

A: Declare your TextView heading outside of the onCreate method i.e. at class level. Inside  onCreate assign it a value and Now in onClick method can access the varaible heading and get it's value.


text:
Q: ofstream does not create file when running with CLion using CMake I have this code to create a file, when I run it with CLion it prints out to the console but does not create file, how can I fix this? thanks
#include <iostream>
#include <fstream>

using namespace std;

int main() {

    ofstream log_file;
    log_file.open("sample23.txt");

    if (log_file.is_open())
        std::cout << "Open";

    log_file << "stuff" << endl;

    log_file.close();

    return 0;
}

A: The file may be created into another directory (the working directory).
You can find that location (and change it if needed) as indicated here:
How do I change the working directory for my program

A: make sure to flush before closing because file is empty
try this out
ofstream f;
f.open( "sample.txt", ios::out );
f << flush;
f.close();

A: 3 things here:
1.) In order to output to another file, you must make another variable like this:
ifstream someoutputfile;
someoutputfile.open("filename");

2.) you actually must make another variable to be "placeholder" of sorts that will automatically assign the first thing your file finds and assigns that to. This may depend on what datatype (int, double, string etc) your input file consists of. Instead of:
log_file << "stuff" << endl;

you can do something like this...
// if my input file is integers for instance..
int data = 0;
log_file >> data;

This can also work for if your file contains multiple data types.
ex:
// if I have two different data types...
string somebody;
int data = 0;
log_file >> data >> somebody;

3.) to output your file data to the screen, just follow a similar way as the example in #1.
someoutputfile << data << somebody << endl;

in addition, dont forget to close the data of BOTH your input and output files:
someoutputfile.close()
Hope that helps in some way :)


text:
Q: Items in File provider extension for ios 11 I have an app with file provider extension in it. I tried giving support to the new file app with the ios 11 using this link
I did what is instructed in this but no item is getting displayed. I have added this NSExtensionFileProviderSupportsEnumeration = YES in my plist as well.
ProviderEnumerator is my NSFileProviderEnumerator class where ProviderItem is a NSFileProviderItem. inside my enumerator class I have this,
func enumerateItems(for observer: NSFileProviderEnumerationObserver, startingAt page: NSFileProviderPage) {
    observer.didEnumerate([ProviderItem(name: "raghav", type: "public.folder", identifier: "12334444", parentId: "-1"), ProviderItem(name: "panth", type: "public.folder", identifier: "12334444", parentId: "-1")])
    var myInt = 100
    let myIntData = Data(bytes: &myInt, count: MemoryLayout.size(ofValue: myInt))
    observer.finishEnumerating(upTo: NSFileProviderPage(rawValue: myIntData))
}

observer.didEnumerate() gets called but the view is not getting populated
Am I missing something !!

A: Finally I figured out the problem here, that if we want to show the files in the root page the NSFileProviderItem requires it's parent_id as NSFileProviderItemIdentifier.rootContainer. Setting this solved my problem


text:
Q: Sequelize Relationships Been attempting to work through sequelize relationships today but am getting stuck at the first hurdle.
var models = require('../models');

var users = models.users;

users.hasMany(models.images, {as: 'Images'});
console.log(users.getImages());

I see no reason why this doesn't work and I'm copying it almost line by line from the examples.
I get the error 'getImages() is not a function'. The method doesn't exist.
I'm probably been stupid, but would love to know what I'm doing wrong.
Thanks!

A: You are trying to access your class ( table ) instead of your instance ( row ) images.
The right direction would be :
users.hasMany( models.images, { as : "Images" } );
users.findOne({}).then( function( user ) {
    // User is our instance ( the row, that actually has other rows related )
    user.getImages()
} );


text:
Q: Rx IObservable buffering to smooth out bursts of events I have an Observable sequence that produces events in rapid bursts (ie: five events one right after another, then a long delay, then another quick burst of events, etc.).  I want to smooth out these bursts by inserting a short delay between events.  Imagine the following diagram as an example:

Raw:      --oooo--------------ooooo-----oo----------------ooo|
Buffered: --o--o--o--o--------o--o--o--o--o--o--o---------o--o--o|

My current approach is to generate a metronome-like timer via Observable.Interval() that signals when it's ok to pull another event from the raw stream. The problem is that I can't figure out how to then combine that timer with my raw unbuffered observable sequence.
IObservable.Zip() is close to doing what I want, but it only works so long as the raw stream is producing events faster than the timer. As soon as there is a significant lull in the raw stream, the timer builds up a series of unwanted events that then immediately pair up with the next burst of events from the raw stream.
Ideally, I want an IObservable extension method with the following function signature that produces the bevaior I've outlined above.  Now, come to my rescue StackOverflow :)
public static IObservable<T> Buffered(this IObservable<T> src, TimeSpan minDelay)

PS. I'm brand new to Rx, so my apologies if this is a trivially simple question...

1. Simple yet flawed approach
Here's my initial naive and simplistic solution that has quite a few problems:
public static IObservable<T> Buffered<T>(this IObservable<T> source, TimeSpan minDelay)
{
    Queue<T> q = new Queue<T>();
    source.Subscribe(x => q.Enqueue(x));
    return Observable.Interval(minDelay).Where(_ => q.Count > 0).Select(_ => q.Dequeue());
}

The first obvious problem with this is that the IDisposable returned by the inner subscription to the raw source is lost and therefore the subscription can't be terminated.  Calling Dispose on the IDisposable returned by this method kills the timer, but not the underlying raw event feed that is now needlessly filling the queue with nobody left to pull events from the queue.
The second problem is that there's no way for exceptions or end-of-stream notifications to be propogated through from the raw event stream to the buffered stream - they are simply ignored when subscribing to the raw source.
And last but not least, now I've got code that wakes up periodically regardless of whether there is actually any work to do, which I'd prefer to avoid in this wonderful new reactive world.

2. Way overly complex appoach
To solve the problems encountered in my initial simplistic approach, I wrote a much more complicated function that behaves much like IObservable.Delay() (I used .NET Reflector to read that code and used it as the basis of my function).  Unfortunately, a lot of the boilerplate logic such as AnonymousObservable is not publicly accessible outside the system.reactive code, so I had to copy and paste a lot of code. This solution appears to work, but given its complexity, I'm less confident that its bug free.
I just can't believe that there isn't a way to accomplish this using some combination of the standard Reactive extensions.  I hate feeling like I'm needlessly reinventing the wheel, and the pattern I'm trying to build seems like a fairly standard one.

A: This is actually a duplicate of A way to push buffered events in even intervals, but I'll include a summary here (the original looks quite confusing because it looks at a few alternatives).
public static IObservable<T> Buffered<T>(this IObservable<T> source, TimeSpan minDelay)
{
    return source.Drain(x =>
        Observable.Empty<int>()
            .Delay(minDelay)
            .StartWith(x)
    );
}

My implementation of Drain works like SelectMany, except it waits for the previous output to finish first (you could think of it as ConactMany, whereas SelectMany is more like MergeMany). The built-in Drain does not work this way, so you'll need to include the implementation below:
public static class ObservableDrainExtensions
{
    public static IObservable<TOut> Drain<TSource, TOut>(
        this IObservable<TSource> source,
        Func<TSource, IObservable<TOut>> selector)
    {
        return Observable.Defer(() =>
        {
            BehaviorSubject<Unit> queue = new BehaviorSubject<Unit>(new Unit());

            return source
                .Zip(queue, (v, q) => v)
                .SelectMany(v => selector(v)
                    .Do(_ => { }, () => queue.OnNext(new Unit()))
                );
        });
    }
}


text:
Q: Validation of view state MAC failed Please don't mark this post as duplicated.. Please help me to fix my issue since I am very new to asp.net I have some difficulties with understanding.
I am working on VS 2010 and try to familiarize with asp.net web site. I have two web pages called Default.aspx and Result.aspx.
Default.aspx
<form id="Form1" runat="server" action="Result.aspx">
    //Some Controllers (Dynamically added textboxes and submit button)
</form>

Once I fill the form and when it is submit following error comes.
Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that  configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.
I tried to add EnableViewStateMac="false" but have no luck.
Please advice me to fix this and appreciate if you could explain me why this comes.

A: ASP.NET has a very different model to other languages in web development, designed to emulate the Windows Forms development paradigm. Whereas in other languages it is common to post to another URL, operations in ASP.NET are usually accomplished by posting back to events on the same page. The issue you are experiencing is related to the fact you are posting ViewState to another page, see http://blogs.msdn.com/b/tess/archive/2009/04/14/validation-of-viewstate-mac-failed-after-installing-net-3-5-sp1.aspx.
As an aside, you shouldn't set EnableViewStateMac=false" on a production server, it is a mechanism to prevent tampering of the data held in viewstate by the user, switching it off removes this protection - and only deals with a symptom of the problem, not the cause.
I don't think this is the issue in this case, but with this error it's always worth checking that you're not setting the ViewStateUserKey to the Session ID before you have stored data in the session (ASP.NET will not track Session IDs where the session does not contain data).


text:
Q: Android EditText won't take up remaining space In my Android app, I have a tabbed Activity. In one of the tabs I have two TextViews and two EditTexts.
The first EditText is only one line, and that's fine. However, I want the other EditText, android:id="@+id/paste_code", to take up the remaining space, but no matter what I do to it, it will only show one line. I don't want to manually set the number of lines, since the number that would fit on the screen differs based on your device.
Here's the relevant code. It's nested inside all the necessary components for a tabbed Activity.
<ScrollView
    android:id="@+id/basicTab"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1" >
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Paste title"
            android:layout_weight="0" />
        <EditText
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:hint="@string/paste_title_hint"
            android:id="@+id/paste_title"
            android:lines="1"
            android:gravity="top|left"
            android:layout_weight="0" />
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Paste text"
            android:layout_weight="0" />
        <EditText
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:hint="@string/paste_hint"
            android:id="@+id/paste_code"
            android:gravity="top|left"
            android:layout_weight="1" />
    </LinearLayout>
</ScrollView>

A: Since the accepted answer doesn't address the situation fully, here's a proper fix for people coming to this while searching:
Firstly, Romain Guy from the Android dev team addresses this well in this blog post:
http://www.curious-creature.org/2010/08/15/scrollviews-handy-trick/
Essentially, your ScrollView needs to contain the android:fillViewport="true" attribute.
If things aren't working once you've done that, here are a couple of things to check:

*

*The layout inside the ScrollView (such as a LinearLayout) needs to have layout_height="wrap_content"

*The view(s) you want to expand should have layout_height="wrap_content"

*The view(s) you want to expand should have layout_weight="1.0" or similar

Don't forget to set minLines="3" or similar in the view(s) you want to expand if you don't want it/them to shrink too much.

A: The problem seems to come from your use of ScrollView. I've tested your code using a ScrollView as the parent container, and got the same problem. However if I replaced the ScrollView with a LinearLayout, then the second EditText properly expanded to fill the whole screen. The problem must be that ScrollViews are designed to wrap to their smallest possible size, regardless of what settings you put in android:layout_height. I experimented with another few layouts, e.g. a RelativeLayout using layout_above and layout_below, but those only affected its maximum size, not its size when empty. Unfortunately, that means I'm not sure how to solve your problem... Is there a way you can redesign your layout to use something other than the ScrollView as the parent container?


text:
Q: Evaluation with variable pointing to operator Is it possible to include the operator in a variable when evaluating a condition. Like this:
>>> one = 1
>>> two = 2
>>> lessthan = '<'

>>> if one lessthan two: print 'yes'

is there a way to return the variable during the expression? I have also tried to return it via a function.
def operator(op):
    return op

if one operator(lessthan) two: print 'yes'

Many thanks,

A: You could use operator:
import operator

lessthan = operator.lt

one = 1
two = 2

if lessthan(one, two):
    print 'yes'

You could also make a mapping between strings and operations:
operators = {
    '<': operator.lt,
    '>': operator.gt,
    '>=': operator.ge,
    '<=': operator.le,
}

And then call the function:
>>> operators['<'](123, 456)
True