text:
Q: Does Skype continue transferring video to clients that choose not to consume it? I attempt to find any information on whether Skype continues to download video streams in conference calls, when I close/minimize the video window, thus effectively downgrading the conference to an audio-call (for me).
However I don't find any clear answer on the internet. The motivation behind this question is to better plan whether I can reliably join calls in low-bandwidth environments (like on a train).
The same question was already asked here, however MS chose to close and lock the thread after replying with an answer that clearly shows that the support team didn't even care to read the question: https://answers.microsoft.com/en-us/skype/forum/all/turn-off-receiving-video-on-ios-to-save-bandwidth/b318c339-2361-457c-8c16-0c3266bf8870
So now I'm wondering, if anyone has already done some measurements and can provide a clear answer. After all, all involved computers (including central infrastructure) would benefit from lower resource usage.

A: Skype must be continuing to download video streams even when the video window is
minimized.
You can see that by hovering with the cursor over the taskbar icon of Skype.
You will see that the mini-window is still moving in sync with the audio.
In fact, I would guess that this mini-window is taking even more resources,
since the image has also to be scaled down from the received video dimensions.


text:
Q: Could not find stored procedure 'insertForum' Trying to insert into my database from the web page but am shown an error message that the values been inserted cannot be passed on to the database and after debugging the error message it became clear to me that "insertforum" stored procedure cannot be found. What can be done to resolve the issue?
public class PostForum
{
    public static int insertForum(int titleid, string question, string posterName,    DateTime datetime, string username)
    {
        int rowsAffected = 0;

        using (SqlConnection connection = ConnectionManager.GetDatabaseConnection())
        {
            SqlCommand cmmand = new SqlCommand("insertForum", connection);
            cmmand.CommandType = CommandType.StoredProcedure;

            cmmand.Parameters.Add("@titleid", SqlDbType.Int).Value = titleid;
            cmmand.Parameters.Add("@question", SqlDbType.VarChar).Value = question;
            cmmand.Parameters.Add("@posterName", SqlDbType.VarChar).Value = posterName;
            cmmand.Parameters.Add("@datetime", SqlDbType.DateTime).Value = datetime;
            cmmand.Parameters.Add("@username", SqlDbType.VarChar).Value = username;

            cmmand.ExecuteNonQuery();
        }

        return rowsAffected;
    }
}

Here is my connection string:
    <connectionStrings>
    <add name="nn008ConnectionString" connectionString="Data Source=SQL-SERVER;Initial     Catalog=nn008;Integrated Security=True"
  providerName="System.Data.SqlClient" />

A: I simply created a stored procedure for insertForum on management studio and that fixed the error. Below is how i solved the error:
CREATE PROCEDURE insertForum
(
@titleid int,
@question varchar(200),
..........
.........
)
AS
INSERT forum
(
titleid,
question,
.......
.......
)
Values
(
titleid,
question,
........
.......
)
RETURN

redpajama_set_name: RedPajamaStackExchange


text:
Q: Prove that a non-empty subset of an open set which is evenly covered is evenly covered Let $p: E\rightarrow B$ a continuous surjective map and $U \subseteq B$ be open and not empty and who is being evenly covered by $p$. Show that all non-empty subsets of $U$ are being evenly covered by $p$.
What I've got so far with the hints:
Let $W \subseteq U$ with $W$ open and non-empty.
$$
W = W \cap U = W \cap p( \cup V_\alpha)
$$
So that
$$
p^{-1}(W) = p^{-1}(W \cap p(\cup V_\alpha)) = p^{-1}(W) \cap \cup V_\alpha = \cup (p^{-1}(W) \cap V_\alpha)
$$
Since $p$ is continuous and $W$ is open in $B$ we know $p^{-1}(W)$ is open and $V_\alpha$ is open by definition. So $p^{-1}(W) \cap V_\alpha$ is open.
Next up we have to prove that:
$$
p: p^{-1}(W) \cap V_\alpha \rightarrow W
$$
is a homeomorphism. By definition $p$ is continuous and surjective and notice that only $p(0) = 0$ so this map is also injective.
If $Z \subseteq W \subseteq U$ with $Z$ open then we know
$$
p(p^{-1}(Z) \cap V_\alpha) = Z \cap V_\alpha
$$
is open. So $p$ is also an open mapping and thus is $p$ a homeomorphism and thus is $W \subseteq U$ being evenly covered by $p$.

A: Since $W\subseteq U$, you have $p^{-1}(W)=p^{-1}(W)\cap\coprod_\alpha V_\alpha$ which is the union $\coprod_\alpha p^{-1}(W)\cap V_\alpha$. Can you show that each $p^{-1}(W)\cap V_\alpha$ is open and that $p:p^{-1}(W)\cap V_\alpha\to W$ is a homeomorphism?


text:
Q: check commits on remote not yet pulled on local I have git master branch, which had some updates which i didn't updated on local machine and created a new commit and tried to push it to master branch, however it rejected my commits and throws error saying there are updates on the remote branch which need to be merged on local machine first before sending any commits to remote branchNow i don't know what are the updates currently on remote branch which i have not yet pulled it in my local copy, as it's the master branch (production copy) i am bit concerned about what updates it will bring into my local copy which is currently working.
Is there any way i can see what updates it will bring if i make a fetch call in GIT.Any help will be greatly appreciated

A: git fetch will not do anything to your working copy. You need to either merge or rebase to get the new changes into your working copy.
So, you must git fetch first to be able to check anything that is happening on the remote.
You should be able to check the state of origin/master, the remote branch, using any of several different commands. Among others:
git log origin/master
git diff master origin/master


text:
Q: Can Elastic APM measure the performance of applications other than web applications? I've seen some APM that only measures web applications which run on WAS.
Can Elastic APM meausure the performance of other applications like pure Java application and etc?
If not,  can I use https://www.elastic.co/guide/en/apm/agent/java/1.x/public-api.html (Public API) so that it can measure the performance of non web applications?
I will appreciate any advice. Cheers.

A: The key features of APM agents is normally in their framework integrations. The Java APM agent is mostly focussed on web frameworks — see the list of supported technologies.
But you already mentioned the public API — if you manually instrument your code with that, you will still be able to use it. It just doesn't automatically understand the framework and you need to help it with that.
Alternatively, if your tool supports OpenTracing then you could use the OpenTracing bridge for that.


text:
Q: Combining tables in sqlite Suppose I have two tables like this:
table 1:
a    b    data
---  ---  ----
a1   b1   1
a1   b2   2
a2   b1   3
a2   b2   4

table 2:
a    b    data
---  ---  ----
a1   b1   5
a1   b2   6
a2   b1   7
a2   b2   8

I need to combine them in the following way:
a    b    c    data
---  ---  ---  ----
a1   b1   1    1
a1   b2   1    2
a2   b1   1    3
a2   b2   1    4
a1   b1   2    5
a1   b2   2    6
a2   b1   2    7
a2   b2   2    8

The input tables are in two different files, and I need the output table to be written into a new file.
I've found this question, but it's not asking exactly the same, and I need a new table in a new file, rather than a view.
It's not important that column c come after a and b.
I know that a column can be added with
ALTER TABLE table_name ADD c TEXT;

but that fills the new column with NULL.

A: You want to make a new table with the contents of two others?
CREATE TABLE table3 AS
  SELECT a, b, 1 AS c, data FROM table1
  UNION ALL
  SELECT a, b, 2, data FROM table2;

is one easy way. Use ATTACH as needed to get the various database files all loaded into a single session and use the schemaname.tablename form of specifying table names.

You can also split it up into parts, if you want to add constraints or whatever to the new table:
CREATE TABLE table3(a TEXT, b TEXT, c INTEGER, data INTEGER);
INSERT INTO table3 SELECT a, b, 1, data FROM table1;
INSERT INTO table3 SELECT a, b, 2, data FROM table2;


text:
Q: JQuery $.getJSON with username and password basic authentication? I want something like this: How to use Basic Auth with jQuery and AJAX?
In the question there they explained how to use authentication
I need to use a jQuery $.getJSON instead of a $.ajax request to a server because it doesn't support cross-site.
And also I need to submit a user and a password.
Is there a way to submit a user and password as parameters in a $.getJSON WITHOUT sending it in the URL like https://user:password@myserver.com?

A: $.getJSON is a shorthand for $.ajax, so indeed you probably need ajax. You can see on http://api.jquery.com/jquery.ajax/ how to set headers
$.ajax(url, {crossDomain:true, headers:{'X-My':'Foo'}})

And this is possible duplicate of Pass request headers in a jQuery AJAX GET call

A: $.getJSON("url", { user: "name", password: "123456" })
    .done(function(json) {
        console.log("Store User autthentication successfully");
    })
    .fail(function(jqxhr, textStatus, error) {
    });


text:
Q: Change language of command in Excel How can you change the language of the commands in Excel to English? Now the language of the commands are in Dutch (equal to the language of my pc). But can you change it into English? I use Windows 10 and Office 2013.
For example: This command
=ALS(SOM(B1:B8)>5; VANDAAG(); REST(20;11))

is in dutch but the same command is this
=IF(SUM(B1:B8)>5; TODAY(); REST(20;11))

in English.

A: It depends on your Office version. With an Office 365 license that has received Office 2016 you can change the language.
Go File > Options > Language and click on "How do I get more Display and Help Languages".
You may need to download some files to do that. The "how to" link gets you to  this page.
With older versions of Office you may need to install the localised language version, and that may not be a free download.


text:
Q: Failed to connect to github.com:8080 I created a new Git repository but am unable to push it using terminal.
This is what I'm doing
git remote add origin https://github.com/dilipptt/first_app.git
git push origin master

and what I'm getting back:

error: Failed to connect to github.com:8080; Connection refused while accessing https://github.com/dilipptt/first_app.git/info/refs?service=git-receive-pack
  fatal: HTTP request failed

A: With the changes you have made, the GitHub URL you have configured is wrong. You should either use the HTTP url as in https://github.com/foo/bar.git or the SSH url as in git@github.com:foo/bar.git
When you added the origin for the second time, you specified git://git@github.com/dilipptt/first_app.git
Instead you should specify
git remote add origin git@github.com/dilipptt/first_app.git

Please copy and paste text from the error instead of posting screenshots. The latter is hard for people who want to help you.


text:
Q: Can't find RequireSignedAppinit_DLLs in Registery I am trying to do a small dll injection on my computer, and it doesn't seem to work.
I updated AppInit_DLLs with the path to my dll, and I read online that I need to set LoadAppinit_DLLs to 1 (which I have) and RequireSignedAppinit_DLLs to 0 for the injection to work.
but I can't find RequireSignedAppinit_DLLs in the registery..
My Registery
And here is my dll code: (It's very messy I am just trying to see if it will work before I actually make it clean)
#include "pch.h"
#define DLL_EXPORT
#include "mydll.h"
extern "C"
{
    DECLDIR void Share()
    {
        MessageBox(NULL, (LPCWSTR)L"DLL injection!", (LPCWSTR)L"Hacked", 0);
    }
    void Keep()
    {
        MessageBox(NULL, (LPCWSTR)L"DLL injection!", (LPCWSTR)L"Hacked", 0);
    }
    DECLDIR void openWindow()
    {
        MessageBox(NULL, (LPCWSTR)L"DLL injection!", (LPCWSTR)L"Hacked", 0);
    }
}

BOOL APIENTRY DllMain(HANDLE hModule, // Handle to DLL module

    DWORD ul_reason_for_call,
    LPVOID lpReserved) // Reserved

{
    openWindow();
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
        // A process is loading the DLL.
        Keep();
        Share();
        openWindow();
        break;
    case DLL_THREAD_ATTACH:
        // A process is creating a new thread.
        Keep();
        Share();
        openWindow();
        break;
    case DLL_THREAD_DETACH:
        // A thread exits normally.
        Keep();
        Share();
        openWindow();
        break;
    case DLL_PROCESS_DETACH:
        // A process unloads the DLL.
        Keep();
        Share();
        openWindow();
        break;
    }
    return TRUE;
}

Hope anyone can help...

A: Just create the RequireSignedAppinit_DLLs REG_WORD value yourself.
This is fine for experimentation but a real application should not modify these values because it decreases the security of the system.


text:
Q: Run execute resource in iterator I have to run execute resource in a loop. For eg:
ruby_block "iterate over states" do
    block do
        dir = "#{node['config']['location']}/config-script/properties/#{node['config']['payer']}"
        state_names = Dir.entries(dir).select do |file|
            File.directory?("#{dir}/#{file}") and ! file.start_with? "."
        end
        state_names = [""] if state_names.empty?
        state_names.each do |state|
            run_context = Chef::RunContext.new(node, {}, nil)
            r = Chef::Resource::Execute.new("config rest", run_context)
            r.cwd "#{node['config']['location']}/config-script"
            r.command "echo"
            r.run_action(:create)
        end
    end
end

Here I am trying to run a execute command by for each folder in a directory. However I am running into the following error:
ruby_block("iterate over states") do
  action [:create]
  retries 0
  retry_delay 2
  block_name "iterate over states"
  cookbook_name "config"
  recipe_name "rest"
  block #<Proc:0x96e0b3c@/var/chef/cache/cookbooks/config/recipes/rest.rb:11>
end

[2013-12-20T14:26:55+00:00] ERROR: Running exception handlers
[2013-12-20T14:26:55+00:00] ERROR: Exception handlers complete
[2013-12-20T14:26:55+00:00] FATAL: Stacktrace dumped to /var/chef/cache/chef-stacktrace.out
Chef Client failed. 1 resources updated
[2013-12-20T14:26:55+00:00] ERROR: ruby_block[iterate over states] (config::rest line 10) had an error: NoMethodError: undefined method `resource_action_start' for nil:NilClass
[2013-12-20T14:26:55+00:00] FATAL: Chef::Exceptions::ChildConvergeError: Chef run process exited unsuccessfully (exit code 1)

I am very new to chef and unable to debug this error.
EDIT
I have observed the following stack trace /var/chef/cache/chef-stacktrace.out
Generated at 2013-12-20 14:45:12 +0000
NoMethodError: ruby_block[iterate over states] (config::rest line 9) had an error: NoMethodError: undefined method `resource_action_start' for nil:NilClass
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/lib/chef/resource.rb:608:in `run_action'
/var/chef/cache/cookbooks/config/recipes/rest.rb:21:in `block (3 levels) in from_file'
/var/chef/cache/cookbooks/config/recipes/rest.rb:16:in `each'
/var/chef/cache/cookbooks/config/recipes/rest.rb:16:in `block (2 levels) in from_file'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/lib/chef/provider/ruby_block.rb:33:in `call'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/lib/chef/provider/ruby_block.rb:33:in `block in action_run'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/lib/chef/mixin/why_run.rb:52:in `call'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/lib/chef/mixin/why_run.rb:52:in `add_action'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/lib/chef/provider.rb:149:in `converge_by'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/lib/chef/provider/ruby_block.rb:32:in `action_run'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/lib/chef/provider.rb:114:in `run_action'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/lib/chef/resource.rb:625:in `run_action'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/lib/chef/runner.rb:49:in `run_action'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/lib/chef/runner.rb:81:in `block (2 levels) in converge'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/lib/chef/runner.rb:81:in `each'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/lib/chef/runner.rb:81:in `block in converge'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/lib/chef/resource_collection.rb:98:in `block in execute_each_resource'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/lib/chef/resource_collection/stepable_iterator.rb:116:in `call'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/lib/chef/resource_collection/stepable_iterator.rb:116:in `call_iterator_block'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/lib/chef/resource_collection/stepable_iterator.rb:85:in `step'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/lib/chef/resource_collection/stepable_iterator.rb:104:in `iterate'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/lib/chef/resource_collection/stepable_iterator.rb:55:in `each_with_index'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/lib/chef/resource_collection.rb:96:in `execute_each_resource'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/lib/chef/runner.rb:80:in `converge'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/lib/chef/client.rb:433:in `converge'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/lib/chef/client.rb:500:in `do_run'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/lib/chef/client.rb:199:in `block in run'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/lib/chef/client.rb:193:in `fork'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/lib/chef/client.rb:193:in `run'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/lib/chef/application.rb:208:in `run_chef_client'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/lib/chef/application/client.rb:312:in `block in run_application'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/lib/chef/application/client.rb:304:in `loop'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/lib/chef/application/client.rb:304:in `run_application'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/lib/chef/application.rb:66:in `run'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.8.2/bin/chef-client:26:in `<top (required)>'
/usr/bin/chef-client:23:in `load'
/usr/bin/chef-client:23:in `<main>'

A: You don't need to create a run_context , the run_context is already provided in the recipe
Instead of this code
        run_context = Chef::RunContext.new(node, {}, nil)
        r = Chef::Resource::Execute.new("config rest", run_context)
        r.cwd "#{node['config']['location']}/config-script"
        r.command "echo"
        r.run_action(:create)

You could probably have
        r = Chef::Resource::Execute.new("config rest", run_context)
        r.cwd "#{node['config']['location']}/config-script"
        r.command "echo"
        r.run_action(:create)

I think that would fix your problem


text:
Q: Apache Shiro UnknownSessionException occured after logout and before next page loading I'm trying my luck here. I had checked this and this to get some hint without success. I use Apache Shiro 1.4.0 on a Payara 4.1.1.171.1. The logout part in my shiro.ini is:
[main]
user.loginUrl = /login.xhtml
logout.redirectUrl = /index.xhtml

[urls]
/index.xhtml = ssl, user
/login.xhtml = ssl, user
/logout.xhtml = logout

On my user interface, I do have a logout button calling the submit() method defined as:
public void submit() throws IOException {
    // some actions involving EJBs
    Faces.redirect("/logout.xhtml");
}

Then I have this error:
Warning:   StandardWrapperValve[Faces Servlet]: Servlet.service() for servlet Faces Servlet threw exception
org.apache.shiro.session.UnknownSessionException: There is no session with id [db328e2a-8b78-40e6-afb7-72c01e10a20a]
    at org.apache.shiro.session.mgt.eis.AbstractSessionDAO.readSession(AbstractSessionDAO.java:170)
    at org.apache.shiro.session.mgt.DefaultSessionManager.retrieveSessionFromDataSource(DefaultSessionManager.java:236)
    at org.apache.shiro.session.mgt.DefaultSessionManager.retrieveSession(DefaultSessionManager.java:222)
    at org.apache.shiro.session.mgt.AbstractValidatingSessionManager.doGetSession(AbstractValidatingSessionManager.java:118)
    at org.apache.shiro.session.mgt.AbstractNativeSessionManager.lookupSession(AbstractNativeSessionManager.java:148)
    at org.apache.shiro.session.mgt.AbstractNativeSessionManager.lookupRequiredSession(AbstractNativeSessionManager.java:152)
    at org.apache.shiro.session.mgt.AbstractNativeSessionManager.getAttribute(AbstractNativeSessionManager.java:249)
    at org.apache.shiro.session.mgt.DelegatingSession.getAttribute(DelegatingSession.java:141)
    at org.apache.shiro.session.ProxiedSession.getAttribute(ProxiedSession.java:121)
    at org.apache.shiro.web.servlet.ShiroHttpSession.getAttribute(ShiroHttpSession.java:131)
    at com.sun.faces.context.SessionMap.get(SessionMap.java:118)
    at org.omnifaces.util.FacesLocal.getSessionAttribute(FacesLocal.java:1505)
    at org.omnifaces.util.Hacks.removeViewState(Hacks.java:437)
    at org.omnifaces.viewhandler.OmniViewHandler.unloadView(OmniViewHandler.java:136)
    at org.omnifaces.viewhandler.OmniViewHandler.restoreView(OmniViewHandler.java:103)
    at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:199)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.RestoreViewPhase.doPhase(RestoreViewPhase.java:123)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1696)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    at org.glassfish.tyrus.servlet.TyrusServletFilter.doFilter(TyrusServletFilter.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:61)
    at org.apache.shiro.web.servlet.AdviceFilter.executeChain(AdviceFilter.java:108)
    at org.apache.shiro.web.servlet.AdviceFilter.doFilterInternal(AdviceFilter.java:137)
    at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
    at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:66)
    at org.apache.shiro.web.servlet.AdviceFilter.executeChain(AdviceFilter.java:108)
    at org.apache.shiro.web.servlet.AdviceFilter.doFilterInternal(AdviceFilter.java:137)
    at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
    at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:66)
    at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449)
    at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365)
    at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90)
    at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83)
    at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:387)
    at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362)
    at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:466)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:169)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:526)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
    at java.lang.Thread.run(Thread.java:745)

I put some LOGGER.debug(...) in filter and my involved classes to know when this happens, assuming that filtering is sequential, and it appears that this error happens after logout filter afterCompletion() method and before the next page (namely the login page) loads.
So I struggle to find the guilty component. If anyone has an idea about this, please let me know.

A: I'm guessing 'logout' is getting called twice, or you are trying to use a session after a user has been 'logged out'
Does your /logout.xhtml have any logic that is requires a user session?
(The logout filter will run before the rendering of your page)


text:
Q: How do I get the first 140 characters of text while making sure protecting last word? How do I get the first 140 characters of a text, while making sure I am not breaking apart the last word?
So if the text is
Hello world my name is Amy Anderson.

And I want to get the first 13 characters:
It would be
hello world my ...

and not
hello world m

How do I do that using jquery?

A: One solution is to use regex:

var testString = "Hello world my name is Amy Anderson.";

// Replace 13 with whatever number you please
var regex_first13 = /^.{13}.*?(?=\s)/;

// If the regex returns nothing,
// then string < 13 characters or ends on a word,
// so use the whole string
var selection = regex_first13.exec(testString) || testString;

document.body.innerHTML = selection;

A: No need to use jQuery for this - try this solution:

var test = 'Hello world my name is Amy Anderson.';
var atest = test.split(' ');
var result = '';
var i = 0;
var maxlength = 13;
do {
  result = result + ' ' + atest[i];
  i += 1;
} while (atest.length >= i && result.length < maxlength);

document.body.innerHTML = result + ' ...';


text:
Q: GeometryReader unwanted full height/width behaviour I'm using the GeometryReader for making sure that an image is never wider than half of the screen's width. However, it messes up the rest of my view as the GeometryReader requests the full height/width of the View (as shown in the image with the green BG). As if it inserts unwanted Spacer().
struct ContentView: View {
    var body: some View {
        VStack{
            VStack {
                GeometryReader{ g in
                    HStack{
                        Text("Text Left").background(Color.yellow)
                        Image(systemName: "checkmark")
                            .resizable()
                            .aspectRatio(contentMode:.fit)
                            .frame(maxWidth: g.size.width/2)
                    }.background(Color.yellow)
                }.background(Color.green)
            }
            Text("Bottom Text")

            // This Spacer should push the "Bottom Text" right below the other Text and Image
            Spacer()
        }
    }
}

If I remove the GeometryReader and set the width to a fixed size, it works as expected and the green BG does not show up.
struct ContentView: View {
    var body: some View {
        VStack{
            VStack {
                HStack{
                    Text("Text Left").background(Color.yellow)
                    Image(systemName: "checkmark")
                        .resizable()
                        .aspectRatio(contentMode:.fit)
                        .frame(maxWidth: 200)
                }.background(Color.yellow)
            }.background(Color.green)
            Text("Bottom Text")
            Spacer()
        }
    }
}

Is this a bug or how can the dynamic width be achieved with the GeometryReader?

A: why do you set the geometryreader inside vstack? maybe you have a reason...but this way, i think, works as you want it?!
But yeah, you are right, the thing with the geometryreader is weird...
 GeometryReader{ g in

            VStack{
                VStack {
                    HStack{
                        Text("Text Left").background(Color.yellow)
                        Image(systemName: "checkmark")
                            .resizable()
                            .aspectRatio(contentMode:.fit)
                            .frame(maxWidth: g.size.width/2)
                            .background(Color.red)
                    }.background(Color.yellow)

                }
                Text("Bottom Text")

                // This Spacer should push the "Bottom Text" right below the other Text and Image
                Spacer()
            }
        }.background(Color.green)

A: You can use GeometryReader with a clear background element and save the size as a @State object since background() won't mess with the layout but still compute the full layout size:
struct ContentView: View {
    @State private var contentSize: CGSize = .zero // "proxy" size

    var body: some View {
        VStack{
            Text("Hello World")
                .frame(minWidth: contentSize.width) // use here
                .background(
                    GeometryReader { geometry in
                        Color.clear
                            .onAppear {
                                contentSize = geometry.size
                            }
                    }
                )
        }
    }
}

This effectively work in any subview.
I found this solution with this article:
https://swiftwithmajid.com/2020/01/15/the-magic-of-view-preferences-in-swiftui/


text:
Q: How can I evaluate a lazy val using reflection? Using the experimental Scala 2.10 reflection, when I try to call FieldMirror.get() on a field that is a lazy val, it returns null.  Is there a way to evaluate the lazy val using reflection?  The get() function should no longer return null afterwards.
Consider this example:
case class Person(val firstName: String,
                  val lastName: String) {
  lazy val name = firstName + " " + lastName
}

import scala.reflect.runtime.{universe => ru}

val runtimeMirror = ru.runtimeMirror(getClass.getClassLoader)

val fred = Person("Fred", "Smith")

val instanceMirror = runtimeMirror.reflect(fred)

val nameTerm = ru.typeOf[Person].declaration(ru.newTermName("name")).asTerm

val nameLazy = instanceMirror.reflectField(nameTerm)

nameLazy.get
    >>> res8: Any = null

fred.name
    >>> res9: String = Fred Smith

nameLazy.get
    >>> res10: Any = Fred Smith

A: I discovered the solution.  There is a hidden method that gets generated:
case class Person(val firstName: String,
              val lastName: String) {
 lazy val name = firstName + " " + lastName
}

import scala.reflect.runtime.{universe => ru}

val runtimeMirror = ru.runtimeMirror(getClass.getClassLoader)

val fred = Person("Fred", "Smith")

val instanceMirror = runtimeMirror.reflect(fred)

val nameMethod = ru.typeOf[Person].member(ru.newTermName("name")).asMethod
val nameValue = ru.typeOf[Person].member(ru.newTermName("name")).asTerm

val nameLazy = instanceMirror.reflectField(nameValue)
val nameLazyMethod = instanceMirror.reflectMethod(nameMethod)

nameLazy.get
    >>> null

nameLazyMethod()
    >>> res9: String = Fred Smith

nameLazy.get
    >>> res10: String = Fred Smith


text:
Q: why does this indentation error is arising? I am using the following code but I am facing indentation error while trying to run it.
import plotly.graph_objects as go
def plot_cases_for _country (country):
labels = ['confirmed' , 'death']
colors = ['blue' , 'red']
mode_size  = [ 6,8]
line_size = [4,5]

df_list = [confirmed_df , death_df]

fig = go.Figure()
    for i , df  in enumerate(df_list):
           if  country =='World' or country == 'world' :
                x_data = np.array(list(df.iloc[: , 5:].columns))
                y_data = np.sum(np.asarray(df.iloc[: , 5:]) ,axis = 0)

                else:
                x_data = np.array(list(df.iloc[: , 5:].columns))
                y_data = np.sum(np.asarray(df[df['country']==country].iloc[: , 5:]) ,axis = 0)

            fig.add_trace(go.scatter(x = x _data, y = y_data , mode ='lines +markers',
                                        name = labels[i]
                                        line  = dict(color=colors[i] , width = line_size[i] ) ,
                                        connectgaps = True ,
                                        text = "Total" + str(labels[i]) + " :" + str(y_data[-1])

                                        ))

            fig.show( )

            plot_cases_for_country('us')

how to solve the following error ?
File "<tokenize>", line 21
    fig.add_trace(go.scatter(x = x _data, y = y_data , mode ='lines +markers',
    ^
IndentationError: unindent does not match any outer indentation level

kindly help to find out


text:
Q: Claims-based auth and circles of users Let's think of a simple REST-based web service to store and retrieve JSON objects. Without any authentication, every user can access any data.
Now let's add usage of JWTs to authenticate users. Of course, since we are not doing authorization, still every user can access anything, but at least now we know who accesses what.
Next step: When storing an object, save the user's sub claim with the object, and verify that the user's sub claim matches the one of the requested object, and if so, deliver it. Now we have authorization on a per-user basis. So far, so easy.
Now let's add the possibility to let users share objects with other users. For the sake of simplicity, say, we want to have predefined groups (i.e., roles) and we want to let the user choose which group (role) has access to the objects they create. This is still easy, as you have a predefined list of groups, so you can let the user choose one or more, and attach them to the object. Additionally, the identity provider needs to be configured in a way that it put a groups claim into every user's token, so we can match them. As we can already see from the length of this paragraph, things become more complex.
Question 1: Am I right so far, that handling "static" groups this way it the way to go?
Now, let's give the users the opportunity to create groups on their own. This is still not complicated, but how do we make the identity provider use the dynamically created groups? For sure we do not want to make an administrator update the identity provider's configuration every day ;-).
Question 2: How do we handle dynamically created groups?
Now, finally, let's forget about groups, and let's say, that we want to allow the users to be able to simply share their objects with other users. This should be configurable for every object individually. How do we do this? Do we save a list of users on the object? If so, what exactly do we save? The sub claim? If so, how does the owner user know the appropriate values? Or ...?
And: Supposed the users want to put their friends dynamically into dynamically generated circles, how would we do that?
Question 3: How do tokens and dynamically created groups with dynamically assigned users work with each other?

A: In my opinion the tokens should only include identity-information(-claims) you'll need to identify the user on your ressource server or that wont change when refreshing, since you wouldn't want your user (or your app in place) to have to refresh his access tokens each and every time his permissions change (since access tokens grant access for a specific amount of time you wouldn't want your user to have access to certain ressources that he's lost the access rights to since his last token refresh by not refreshing the token and simply using the old one either). The more security related information you append to your token, the more vulnerability you may add to your system (depending on your token lifetime).
Stating so, I would (and always do) identify the users roles or groups by his user-id (which is included in the jwt-token) on the ressource server. To achieve this, I always attach the users identity-information to the current request on my ressource server and attach "dynamic"-claims like the users role or group to the identity.
By adding only the identity information I need to identify the user and the user's rights on my ressource server, I tend to use my identity providers across multiple applications without handling application scope on the identity provider, so I can use the exact same access token for multiple independent ressource servers.


text:
Q: Find the general term of the sequence defined by $x_0 = 3, x_1 = 4$ and $x_{n+1} = x_{n-1}^2- nx_n$ for all $n \in \mathbb N$ Find the general term of the sequence defined by $$x_0 = 3, x_1 = 4\quad  \&\quad  x_{n+1} = x_{n-1}^2- nx_n \quad \forall n \in \mathbb N$$
I realized this is not a homogeneous recursion relationship.
I don't know if it's the right expression, but it has variable coefficients, and it's not linear.
Is there another method to solve this without induction?

A: We prove by induction that $x_n=n+3$ for all $n\in\mathbb{N}$. Since $x_0=3=0+3$ and $x_1=4=3+1$, let $n\in\mathbb{N}$ such that $x_n=n+3$ and $x_{n+1}=n+4$, we have
$$ x_{n+2}=x_n^2-(n+1)x_n=(n+3)^2-(n+1)(n+4)=n+5=(n+2)+3 $$
This ends the induction.


text:
Q: Raycasting through a sampler2D in a fragment shader In glsl, one can look up the texel from a texture with the function:
vec4 texture2D(sampler2D sampler, vec2 coord)

I'm wondering if there's a similar function or method that would return the first non-0 texel between two vec2s? In pseudo-code, it'd be something like.
vec4 textureBetween(sampler2D sampler, vec2 starting, vec2 ending)

So it'd be kind of like raycasting - you'd cast a ray from starting to ending and return the texel of the first point you hit or (0.0, 0.0, 0.0, 0.0) if nothing is hit.
This is part of an experiment I'm doing trying to use points instead of instanced meshes for certain animations.


text:
Q: ASP.NET Web API, Complex Parameters, Calling from .NET I am trying to port some existing WCF code to Web API. The code acts as an interface for ADO.NET Sync Services and consists of the following method signatures...
[OperationContract]
SyncContext ApplyChanges(SyncGroupMetadata groupMetadata, DataSet dataSet, SyncSession syncSession);

[OperationContract]
SyncContext GetChanges(SyncGroupMetadata groupMetadata, SyncSession syncSession);

[OperationContract]
SyncSchema GetSchema(string[] tableNames, SyncSession syncSession);

[OperationContract]
SyncServerInfo GetServerInfo(SyncSession syncSession);

I then want to be able to call these methods from other .NET client applications, some of which will be on Compact Framework!
I have seen lots of suggestions and examples around the web as to the use of JObject, custom model bindings (with an encapsulating object) and even FormDataCollection - but all of these examples have JavaScript clients and I cannot then see how I might code a .NET client in such a way as to be able to pass all of the parameters correctly and also get back the results I am looking for (for example, are these PUT/POST as I am passing parameters as input, or GET as I am expecting content in the result)?
Can anybody offer any assistance here?
I have yet to determine how I name the methods in such a way as they can be called (I have found the ActionName attribute and the Http* attributes along with a custom routing example that allows the action name to be passed as a part of the URL but again I cannot really see how these map correctly to the HttpClient Get/Put/Post/Delete methods and of course the HttpClient is not - as far as I know - available on Compact Framework).


text:
Q: Capture high frame rate (240fps) with HTML5 MediaStream on iOS mobile Safari? I'm trying MediaStream + MediaRecorder HTML5 APIs to capture short videos in a Web app. And I need this to work on Apple mobile devices (iPad, iPhone).
All seems to be working but I can only capture at up to 60 fps at 1280x720 (and I think only 30 fps at 1920x1080). The iPad I'm trying can capture at 120 or 240 fps (for slow-motion effects), though. I set the video.frameRate property in the constraints passed to mediaDevices.getUserMedia() but I only get 30 or 60 fps.
Is there a way to access this high speed capture with these Web APIs?


text:
Q: How to split a string based off elements in a list statuses = ['421-A','421-G','ARTICLE 11','ARTICLES 14 & 15',
            'COOP/CONDO PLAN FILE','EVICT COOP/CONDO', 'GARDEN COMPLEX'
            'J-51','NON-EVICT COOP/CONDO','ROOMING HOUSE','SEC 608']

snip = [('11201', '131', 'MULTIPLE DWELLING A', '421-A ARTICLE 11', '291', '45')]

Each line of my file looks like snip. I have a list of statuses, some of which contain whitespace.
I want to check statuses and if I see them in snip[0][3], split the string accordingly. It's possible for snip[0][3] to be an empty string ('') but it will have no more than three statuses listed here.
So where it currently says: '421-A ARTICLE 11'. I want this to appear as '421-A', 'ARTICLE 11'. This will expand the length of snip and that's OK.
I have tried map, zip, lambda, and list comprehensions using any(). I feel like I'm close and that there is an elegant solution for this problem but cannot find it. I was trying to avoid regex, but if that is needed it's fine.
UPDATE:
Current code that seems to be very close to working now that I changed 'snip' to lists instead of tuples.
snip = ['11201', '131', 'MULTIPLE DWELLING A', '421-A ARTICLE 11', '291', '45']
status_break = [s for s in statuses if s in snip[3]]
newline = snip[:3] + status_break + snip[4:]
print(newline)

A: [s for s in statuses if s in snip[0][3]]

with regex:
import re
statuses = ['421-A','421-G','ARTICLE 11','ARTICLES 14 & 15',
            'COOP/CONDO PLAN FILE','EVICT COOP/CONDO', 'GARDEN COMPLEX'
            'J-51','NON-EVICT COOP/CONDO','ROOMING HOUSE','SEC 608']

snip = ' '.join(statuses)
statuses_re =  map(lambda s : (s,re.compile('(^| )%s($| )' % s)),statuses)
print([s[0] for s in statuses_re if s[1].search(snip)])

but if you have statuses like 'GARDEN COMPLEX', 'GARDEN COMPLEX 1', 'GARDEN COMPLEX 2' it isn't work


text:
Q: An expression of non-boolean type specified in a context where a condition is expected, near '@orderwhere' Why is the following syntax generates the error "An expression of non-boolean type specified in a context where a condition is expected, near '@orderwhere'"
use orders
declare @orderwhere varchar(5000)
set @orderwhere = 'order_status.step = 1'
select order_status.order_id
from order_status
where @orderwhere

A: You can't have parts of your query being dynamic. It has to be all or nothing. Then use EXEC() to run your dynamic query
exec('select order_status.order_id
      from order_status
      where ' + @orderwhere)

A: Your where clause is a string. You should use dynamic SQL or something like this:
use orders
declare @orderwhere varchar(5000)
set @orderwhere = '1'
select order_status.order_id
from order_status
where order_status.step = @orderwhere


text:
Q: Get document and referenced documents in mongodb I'm developing a Flask app using Mongodb and Pymongo.
I have a collection in mongo called document_load, that has a reference to another collection called document, and document has a reference to another collection called client.
The thing is, I want to query a document_load, but I also want to get it's document, and it's client in an efficient way.
I tried this to get the document of a particular document_load:
db.document_load.aggregate([
    {'$lookup': {
        'from': "document",
        'localField': "document",
        'foreignField': "_id",
        'as': "document"
    }},
    {'$match': {
        '_id': ObjectId('587f6e3ef28bd63078419194')
    }}
])

And it works! It shows this:
{'document': [{'client': ObjectId('5754b202b480776b79184780'), ...some other fields}],
...some other fields}

It shows the document of the document_load as an array of one element for some reason, but now I'm trying to also get the client the same way, not only the id, but I have no idea how to do it, or if it's even possible.
I've been searching but I haven't found anything that can help.
Thanks in advance.

A: When you define your mongo document, with minimal structure like
from mongoengine import Document,
from mongoengine import StringField, LazyReferenceField

class Client(Document):
    client_name = StringField(required = True, unique = True)
    ...

class DocumenT(Document):
    doc = YourDefinedField(required=True, unique= True)
    ref_client = LazyReference(Client, passthrough=False, reverse_delete_rule=3)
    ...

class Document_Load(Document):
    name = StringField(required = True, unique = True)
    ref_doc = LazyReference(DocumenT, passthrough=False, reverse_delete_rule=3)
        ...

you can do this:
Document_Load.objects(name="your_object_identifier").ref_field.fetch()
# This will return the DocumenT asosiated by ref_doc
# This ref_doc needs to have as value the ObjectId of the reference in DocumenT

Since you want to reach the collection document, you only must to concatenate some  ref_doc, ref_client and .fetch()'s
document_ = Document_Load(name = "Payments_Definitive").ref_doc.fetch().ref_client.fetch().client_name


text:
Q: How to write a constructor that takes a reference to a class, which points to an object in Java? What does it mean to write another constructor that takes a reference to GeometricObject, which points to an object rather than null?
And how can I Initialize this object to be an independent copy of the parameter object?
The following code is the GeometricObject class.
public class GeometricObject {
public String color = "white";
public double area = 0;
public double perimeter = 0;

  public boolean filled;

  /** Construct a default geometric object */
  public GeometricObject() {
  }

  public GeometricObject(String color, boolean filled){
      this.color = color;
      this.filled = filled;
  }

  /** Return color */
  public String getColor() {
    return color;
  }

  /** Return area */
  public double getArea(){
      return area;
  }

  /** Return object */
  public GeometricObject copy() {
      return null;
  }

  /** Return perimeter */
  public double getPerimeter(){
      return perimeter;
  }

  /** Set a new color */
  public void setColor(String color) {
    this.color = color;
  }

  /** Return filled. Since filled is boolean,
   *  the get method is named isFilled */
  public boolean isFilled() {
    return filled;
  }

  /** Set a new filled */
  public void setFilled(boolean filled) {
    this.filled = filled;
  }

  @Override
  public String toString() {
    return "\ncolor: " + color + " and filled: " + filled;
  }

A: It basically means that your constructor takes in another object of the same class, and instantiates a new object using its values.
public GeometricObject(final GeometricObject other){
    this.color = other.color;
    this.filled = other.filled;
    //copy other member variables
}

Then, if you have an object, you can create a copy of it like this:
final GeometricObject geometricObject = new GeometricObject();
//do stuff to geometricObject, give values to variables, etc
final GeometricObject copy = new GeometricObject(geometricObject);

A: so your should create your constructor like that
public GeometricObject(GeometricObject original){
    if (original != null) {
        this.color = original.color;
        ... other variables ...
    }
}


text:
Q: processo 24x5 no jar como converter para .war Criei um jar para calcular sinais de forex, porém gostaria de hospedá-lo em algum servidor na nuvem. Como andei pesquisando, será muito mais fácil converte-lo para um war.
Como meu app deve rodar 24x5, precisaria que rodasse nesse mesmo período, sem que eu precise efetuar nenhum comando para isso.
Já criei um projeto web, inicialmente em servlet, mas o problema principal:
no .jar eu coloquei um loop no Main e pronto...
no .war, onde eu poderia fazer algo parecido?
Obrigado!

A: Pelo o que entendi, você executa uma determinada ação de tempos em tempos, correto?
Acho que o Quartz resolve seu problema. Ele é basicamente um agendados de tarefas, semelhante ao CRON do Linux.

*

*Quartz

*Tutorial - Caelum


text:
Q: Expectation of Maximum of Translated Gaussian Given $X\propto N(\mu,\psi^2)$ and $K$ constant, find $E(\max\{K-X,0\})$.
My attempt:
$$
\begin{align}
E(\max\{K-X,0\})\\
&=\int_{-\infty}^{\infty}\max\{K-x,0\}f_X(x)dx\\
&=\int_{K}^{\infty}(K-x)f_X(x)dx\\
&=\int_{K}^{\infty}[(K-\mu)-(X-\mu)]f_X(x)dx\\
&=\int_{K}^{\infty}(K-\mu)f_X(x)dx-\int_{K}^{\infty}(x-\mu)f_X(x)dx\\
&=(K-\mu)(1-\Phi(K))-\int_{K}^{\infty}(x-\mu)f_X(x)dx\\
&=(K-\mu)(1-\Phi(K))-\int_{K}^{\infty}(x-\mu)\frac{1}{(2\pi \psi^2)^{1/2}}e^{-\frac{(x-\mu)^2}{2\psi^2}}dx\\
&=(K-\mu)(1-\Phi(K))-\int_{\frac{(K-\mu)^2}{2\psi^2}}^{\infty}\psi^2\frac{1}{(2\pi \psi^2)^{1/2}}e^{-z}dz\\
&=(K-\mu)(1-\Phi(K))+\frac{\psi}{\sqrt{2\pi}}e^{-z}|_{\frac{(K-\mu)^2}{2\psi^2}}^{\infty}\\
&=(K-\mu)(1-\Phi(K))-\frac{\psi}{\sqrt{2\pi}}e^{-\frac{(K-\mu)^2}{2\psi^2}}
\end{align}
$$
where I have used the change of variables $z=\frac{(x-\mu)^2}{2\psi^2}$.
However, when I check my answer numerically, I see that the integral is not correct. Here is working Python code to check:
import numpy as np
from scipy.stats import norm

# simulation parameters for checking answers numerically
trials = 100000
K = 0.25
mu = np.pi/2
psi = 3.0

simulated = np.mean([np.max([K-x, 0])
                     for x in np.random.normal(mu, psi, trials)])
numerical = (K-mu)*(1-norm.cdf(K, mu, psi)) - np.exp(-((K-mu)**2)/(2*psi**2))*psi/np.sqrt(2*np.pi)
print(simulated)
print(numerical)

This gives:
simulated = 0.6448298784565597
numerical = -1.9713797586737627
What is the issue with my integration?

A: The bounds on the original integral are not correct. The requirement $x\le K$ means the bounds must run from $-\infty$ to $K$.
Here are the correct steps:
$$
\begin{align}
E(\max\{K-X,0\})\\
&=\int_{-\infty}^{\infty}\max\{K-x,0\}f_X(x)dx\\
&=\int_{-\infty}^{K}(K-x)f_X(x)dx\\
&=\int_{-\infty}^{K}[(K-\mu)-(X-\mu)]f_X(x)dx\\
&=\int_{-\infty}^{K}(K-\mu)f_X(x)dx-\int_{-\infty}^{K}(x-\mu)f_X(x)dx\\
&=(K-\mu)\Phi(K)-\int_{-\infty}^{K}(x-\mu)f_X(x)dx\\
&=(K-\mu)\Phi(K)-\int_{-\infty}^{K}(x-\mu)\frac{1}{(2\pi \psi^2)^{1/2}}e^{-\frac{(x-\mu)^2}{2\psi^2}}dx\\
&=(K-\mu)\Phi(K)-\int_{\infty}^{\frac{(K-\mu)^2}{2\psi^2}}\psi^2\frac{1}{(2\pi \psi^2)^{1/2}}e^{-z}dz\\
&=(K-\mu)\Phi(K)+\frac{\psi}{\sqrt{2\pi}}e^{-\frac{(K-\mu)^2}{2\psi^2}}
\end{align}
$$
Here is working Python code to check:
import numpy as np
from scipy.stats import norm

# simulation parameters for checking answers numerically
trials = 100000
K = 0.25
mu = np.pi/2
psi = 3.0

simulated = np.mean([np.max([K-x, 0])
                     for x in np.random.normal(mu, psi, trials)])
numerical = (K-mu)*(norm.cdf(K, mu, psi)) + np.exp(-((K-mu)**2)/(2*psi**2))*psi/np.sqrt(2*np.pi)
print(simulated)
print(numerical)

This gives:
simulated = 0.6526939144762599
numerical = 0.650583431878866
where the difference in value arises because of the finite number of trials used for the simulation.


text:
Q: Vertical alignment in cell of longtable I am using a longtable where I'd like to align the content of a specific cell vertically to the top.

So far, I only found examples for tabularx which seem to made use of \cmidrule. But this does not seem to work with longtable.
I am sure there's a way to achieve this, therefore I am thankful for your inputs!
Latex Code
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%           Präambel                %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\documentclass{scrreprt}

%%%%%%%%%%%%%%%%%%%%%%%%%
%       Packages        %
%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage[bmargin=1.5cm,tmargin=1.5cm, headheight=1cm, includehead, includefoot]{geometry} %Seitenränder definieren
\usepackage[T1]{fontenc}
\usepackage[table,xcdraw]{xcolor}
\usepackage{tabularx}
\usepackage{longtable}
\usepackage{colortbl}
\usepackage{tablestyles}
\usepackage{enumitem}
\usepackage{pdfpages}
\usepackage[font=small]{caption}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%           Dokument                %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}

\tablestyle[sansbold]
\begin{longtable}{*{2}{p{0.25\textwidth}p{0.75\textwidth}}}
\theadstart
    \thead Bezeichner &
    \thead UC02: MultiSelectionField (Desktop) \\
\tbody
Beschreibung & Das bestehende SelectionField soll so erweitert werden, dass im Dropdown, abhängig von der Eingabe, entsprechende Vorschläge zur Auswahl angezeigt werden und mehrere Auswahlen möglich sind und wieder entfernt werden können. \\
 Akteure & Anwendungsbenutzer \\
 Vorbedingungen & Das \texttt{MultiSelectionField} ist noch leer. \\
 Nachbedingung & Eine Auswahl von 1-n Elementen wurde durch den Anwendungsbenutzer getätigt. Die Auswahl ist im \texttt{MultiSelectionField} sichtbar. Das \texttt{MultiSelectionField} wird als valid angezeigt. \\
 Hauptszenario &
        \begin{enumerate}[leftmargin=*]
            \item Der Anwendungsbenutzer fokussiert das \texttt{MultiSelectionField}.
            \item Das Dropdown erscheint, mit allen Auswahlsmöglichkeiten.
            \item Der {Anwendungsbenutzer} tippt eine Eingabe ins Textfeld des SelectionFields.
            \item Das Dropdown filtert die Auswahlsmöglichkeiten anhand der Eingabe im Textfeld des \texttt{MultiSelectionField}.
            \item Der Anwendungsbenutzer wählt ein Element per Mausklick im Dropdown an.
            \item Das \texttt{MultiSelectionField} leert alle Texteingaben und das selektierte Element wird anschliessend darin angezeigt.
            \item Der Anwendungsbenutzer wiederholt Schritt 2-5 solange bis die gewünschte Auswahl getroffen wurde.
            \item Das \texttt{MultiSelectionField} zeigt alle ausgewählten Elemente an.
        \end{enumerate}
     \\
\end{longtable}

\end{document}

A: You can remove the space around the enumerate with the options: topsep=0pt, partopsep=0pt, before=\vspace*{-\baselineskip}, after=\vspace*{-\baselineskip}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%           Präambel                %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\documentclass{scrreprt}

%%%%%%%%%%%%%%%%%%%%%%%%%
%       Packages        %
%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage[bmargin=1.5cm,tmargin=1.5cm, headheight=1cm, includehead, includefoot]{geometry} %Seitenränder definieren
\usepackage[T1]{fontenc}
\usepackage[table,xcdraw]{xcolor}
\usepackage{tabularx}
\usepackage{longtable}
\usepackage{colortbl}
\usepackage{tablestyles}
\usepackage{enumitem}
\usepackage{pdfpages}
\usepackage[font=small]{caption}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%           Dokument                %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}

\tablestyle[sansbold]
\begin{longtable}{*{2}{p{0.25\textwidth}p{0.75\textwidth}}}
    \theadstart
    \thead Bezeichner &
    \thead UC02: MultiSelectionField (Desktop)                                                                                \\
    \tbody
    Beschreibung      & Das bestehende SelectionField soll so erweitert werden, dass im Dropdown, abhängig von der Eingabe, entsprechende Vorschläge zur Auswahl angezeigt werden und mehrere Auswahlen möglich sind und wieder entfernt werden können. \\
    Akteure           & Anwendungsbenutzer                                                                                \\
    Vorbedingungen    & Das \texttt{MultiSelectionField} ist noch leer.                                                                                \\
    Nachbedingung     & Eine Auswahl von 1-n Elementen wurde durch den Anwendungsbenutzer getätigt. Die Auswahl ist im \texttt{MultiSelectionField} sichtbar. Das \texttt{MultiSelectionField} wird als valid angezeigt.                                \\
    Hauptszenario     & \begin{enumerate}[topsep=0pt, partopsep=0pt, before=\vspace*{-\baselineskip}, after=\vspace*{-\baselineskip}, leftmargin=*]
                            \item Der Anwendungsbenutzer fokussiert das \texttt{MultiSelectionField}.
                            \item Das Dropdown erscheint, mit allen Auswahlsmöglichkeiten.
                            \item Der {Anwendungsbenutzer} tippt eine Eingabe ins Textfeld des SelectionFields.
                            \item Das Dropdown filtert die Auswahlsmöglichkeiten anhand der Eingabe im Textfeld des \texttt{MultiSelectionField}.
                            \item Der Anwendungsbenutzer wählt ein Element per Mausklick im Dropdown an.
                            \item Das \texttt{MultiSelectionField} leert alle Texteingaben und das selektierte Element wird anschliessend darin angezeigt.
                            \item Der Anwendungsbenutzer wiederholt Schritt 2-5 solange bis die gewünschte Auswahl getroffen wurde.
                            \item Das \texttt{MultiSelectionField} zeigt alle ausgewählten Elemente an.
                        \end{enumerate} \\
\end{longtable}

\end{document}


text:
Q: does anyone know how docker log flush interval is set Does anyone know how to set docker log flush interval?
In other words, when you use command docker logs -f, where the log flush interval is set? I'm using docker SDK:
readerCloser, err := cli.ContainerLogs(context.Background(), container.ID[:10], clo)

to retrieve log, but now it seems time interval is set to 1 minute, how to change the interval?


text:
Q: Replace relative url from the href attribute to an absolute path I want to replace link url like this http://www.aaa.com/html/html/a01.html
a01
a02

A: This is the simplest thing that could possible work (You might want to use a RegExp match if this is too limited)
$(".screenId a").each(function(i,anchor){
    anchor.href = anchor.href.replace(window.location.hostname,"www.aaa.com")})

A: try this
$('.screenID a').each(function(){
    var link = $(this).attr('href');
    $(this).attr('href',link.replace('../','http://www.aaa.com/'));
});

A: $(".screenID").find("a").each(function(){
    var hrefReplace = $(this).attr("href");
    $(this).attr("href",hrefReplace.replace("../","http://www.aaa.com/"));
});


text:
Q: How I can create instance of an object in another object in js? I have an object like,
let axis = {
    x: -1,
    y: -1
}

and I want to create another object like,
let node = {
    //axis object's variable(1)
    //axis object's variable(2)
    //axis object's variable(3)
}

How I can create object like above in javascript?

A: Is this what you are after?
let axis = {
  x: -1,
  y: -1
}

let node = {
  x: axis.x,
  y: axis.y
}

console.log(node.x); // prints -1 to the console
console.log(node.y); // prints -1 to the console

A: You can use spread to do such task.

let axis = {
    x: -1,
    y: -1
}

let node = {
    ...axis
}

console.log(node)


text:
Q: Highlighting a non-rectangular portion inside div on hover I have a div ( rectangle ), and inside it I want to have a triangular shape. I want to highlight that  on hover. How do I do that?
I'm thinking of having 2 images with that same shape and different opacity and swapping them on hover. Would there be another way of doing this? can you have a non-rectangular shaped divs?

A: It depends how far back in internet explorer you need to go and the context of your triangle as to what you are using it for, but assuming you don't care about internet explorer.
Chris Coyer over @ CSS Tricks has a nice tutorial already setup.
http://css-tricks.com/triangle-with-shadow/
If you are planning to use it as an icon or button you might want to check out,
http://fortawesome.github.io/Font-Awesome/.  Its totally free and pretty easy to implement.  I have used it in a few projects and it was made for use with bootstrap.
Hope this helps.

A: You Can try that:
http://jsfiddle.net/H42U7/
The css code is:
.triangle-up {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid #959595;}

.triangle-up:hover {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid #123456;}

The html:

To rotate the triangle check this site:
http://css-tricks.com/examples/ShapesOfCSS/


text:
Q: Finding the different in a value when a condition from another column is met I am having trouble finding the difference in Unix time between readings at the same location. Below is an example of a table. The "Time in between readings" is the column I am attempting to create. I highlighted the table in terms of location to emphasize that the difference only needs to be taken if at the same location.
enter image description here
This is the command I have, but it does not work properly. Any suggestions on how to do this?
Time in between readings = IF(ISBLANK(Data[temperature]) = FALSE() && Data[Location = Data[Location], VAR Diff = Data[unix time] - CALCULATE(SUM(Data[unix time]), Filter(Data, Data[Index] = EARLIER(Data[Index]) ) )
return
IF(Diff = VALUE(Data[unix time]), 0, diff))


text:
Q: Is there a better way to read Excel sheets in R than with read_excel? I have a directory with big Excel files. I am interested in reading only some sheets within those Excel files. To this end, I am using:
readxl::read_excel(filepath, sheet = my_sheet)

However, this is taking long to read, even not too big sheets. Is there any other more efficient function / way to read only some sheets of Excel files in R?


text:
Q: Managed app installation on Salesforce Production Org Salesforce has two versions of Managed app

*

*Managed App ( Beta )

*Managed App ( Released )

Currently inorder to do a prototype testing I released a Managed App (Beta) and simulated how a real installation would look like in Sandbox Org.
But while Upgrading the Managed App (Beta) in same Org I encountered an error saying "can't upgrade a Beta App".
Currently I released my Managed app and sent for Salesforce Security review process. I have some unknowns here. Please help me understanding the same.

*

*Will I be able to install Managed Package ( Beta ) in a Production Org with installation URL ( even though upgrades are not possible )

*Will I be able to install the Managed Package ( Released ) through unique package installation URL  ( without using AppExchange 'get it now' link ) without getting approval from Security review.

*Will I be able push Patches to Customer who installed the packages through this URL.
or
only option to install Managed Package would be using Salesforce AppExchange  for Production org ?

A: Installing beta package releases into production orgs is not possible except in very special cases (the "production" orgs created via the partner portal), so the answer to your first question is almost always no.
For your second question, you can bypass the appexchange if you want, and distribute your app directly via it's install link, certainly. If you don't go through security review some benefits of being a managed app are witheld however. For example, if you go through security review tabs in your app don't count against the customer's tab limit for their org, but if you skip the review they do count.
You can still use the license management app with a non-reviewed application by creating a private appexchange listing and using that to manage the license settings, however going through security review is recommended of course.
Push upgrades are only available to apps that have undergone security review, and once that's done have to be enabled by salesforce support for your dev org.

A: *

*Yes, you can install manage package(Beta) to production org. But to install manage pacakge(Released) you first have to uninstall the Beta package from that org. It wont allow to install Managed package over Beta however, you can install another Beta package on it.

2.Yes, you can install Manage Package through unique package installation URL. Only thing is you have to logged in into customers org to install it and you cant track which org has installed it if you are creating it for business purpose i.e. you wont have control over license for your package used by customer(Customer can use app with no expiration date).
3.You can install patches by uploading it(Beta or Managed). This will create link(similar to new release) from that you can install it in customers org. Only thing is you wont be able to add new class to the patch..you can only modify components from the package.


text:
Q: Variavel aparecendo como html - IONIC FRAMEWORK Estou iniciando no Ionic, segui este tutorial, tudo certo ate entao, porem, quando vou no index.html e coloco a variavel {{firstname}}, no browser ele mostra como se estivesse passando por html, ao contrario ele tras escrito {{firstname}} e nao o data do array.
  <ion-content ng-controller="StudyingController">
  <button class="button" ng-click="getData()">Test</button>
  <br>
  name: {{firstname}} {{lastname}}
  </ion-content>

A: Pode estar havendo algum erro na conexão com seu arquivo de dados, o "store", da sua aplicação, nesse caso seria importante nos exibir como você está fazendo a inclusão do seu arquivo de dados como está na aplicação que você está seguindo como exemplo:
$http.get("http://localhost/example.json", { params: { "key1": "value1", "key2": "value2" } })
        .success(function(data) {
            $scope.firstname = data.firstname;
            $scope.lastname = data.lastname;
        })

A: Seguinte forma:
exampleApp.controller("StudyingController", function($scope, $http){

  $scope.getData = function(){
    $http.get("http://echo.jsontest.com/firstname/Nic/lastname/Raboy/state/California", { params: {"key1": "value", "key2": "value2"}})
      .success(function(data) {
        $scope.firstname = data.firstname;
        $scope.lastname = data.lastname;
      })
      .error(function(data) {
        alert("PAAAAMM!!!!!!");

      })
    }
  });

A: Resolvido galera,
o problema é que nao usei da seguinte forma:
exampleApp = angular.module('starter', ['ionic', 'starter.controllers'])
Vlw =D


text:
Q: Pypi: Is it possible to set up git to auto update my package on PyPi? For example if I have a package foo that's already on Pypi. I want to be able to git push origin master with a new version number in my setup.py, and then Pypi somehow auto updates their version/source code. Is this possible? If not is there some similar workflow that someone could share? This is my first time contributing to Pypi and I want to make the experience as easy going as possible.

A: I think the behaviour you're after would be best developed using git hooks. I'm not entirely sure that's the best rabbit hole to go down though, but here's some information if you're interested. (Publishing to Pypi automatically without additional checks could lead to your package being unreliable for other users!)
If you are pushing to PyPI, I assume you are developing an Open Source package? If you are, why not make use of the free CI tool Travis to run your tests and other CI tasks. One of your tasks could be to automatically upload your package to PyPI on successful new builds.


text:
Q: Upper bound of convergence of ellipsoid mathod Actually, I am looking for a tighter upper bound for $(1+\frac{1}{n^2 - 1})^{n-1} (\frac{n}{n+1})^{2}$. It is easy to prove $(1+\frac{1}{n^2 - 1})^{n-1} (\frac{n}{n+1})^2 < e^{-\frac{1}{n+1}}$.
But I found that in some papers, $(1+\frac{1}{n^2 - 1})^{n-1} (\frac{n}{n+1})^2$ can be bounded by $e^{-\frac{1}{n}}$.
So I just want to know that how to get this bound?


text:
Q: Task Cancellation and TaskContinuationOptions I was just introduced to Tasks (TPL) yesterday, and so I tried to do a little sample project in order to develop an understanding of how to use them.
My sample project is setup with a start button that begins incrementing a progressbar.  A second button to cancel the task.  A text box to report when the continuation using the TaskContinuationOptions.OnlyOnRanToCompletion is called, and a text box to report when the continuation using the TaskContinuationOptions.OnlyOnCanceled is called.
I can create and execute a Task, but canceling it in a way that lets a continuation with the TaskContinuationOptions.OnlyOnCanceled flag to fire, has been a problem.
I create the tasks as follows:
private void StartTask()
{
    CancellationTokenSource tokenSource = new CancellationTokenSource();
    CancellationToken token = tokenSource.Token;

    Task task = null;
    task = Task.Factory.StartNew(() => DoWork(tokenSource), tokenSource.Token);

    //A list<CancellationTokenSource> so that I can cancel the task when clicking a button on the UI Thread.
    MyTasks.Add(tokenSource);

    Task completed = task.ContinueWith(result => TaskCompleted(), TaskContinuationOptions.OnlyOnRanToCompletion);
    Task canceled = task.ContinueWith(result => TaskCanceled(), TaskContinuationOptions.OnlyOnCanceled);
}

I cancel the task as follows:
private void CancelTasks()
{
    foreach (CancellationTokenSource tokenSource in MyTasks)
    {
        tokenSource.Cancel();
    }
}

My worker function is as follows:
private void DoWork(CancellationTokenSource tokenSource)
{
    if (progressBar1.InvokeRequired)
    {
        progressBar1.Invoke(new Action(() => DoWork(tokenSource)));
        return;
    }

    try
    {
        bool dowork = true;
        while (dowork)
        {
            tokenSource.Token.ThrowIfCancellationRequested();

            if (progressBar1.Value == progressBar1.Maximum)
            {
                dowork = false;
            }
            Thread.Sleep(1000);
            progressBar1.PerformStep();
            Application.DoEvents();
        }
        countCompleted++;
    }
    catch (OperationCanceledException)
    {
    }
}

In other posts that I have read, it has been suggested that  tokenSource.Token.ThrowIfCancellationRequested() is what sets the condition evaluated by the TaskContinuationOptions.OnlyOnCanceled.
None of the examples that I have seen include the use of the:
catch (OperationCanceledException)
{
}

However, without it the programs stops when i call the tokenSource.Cancel();
As it stands, when I do call the tokenSource.Cancel(), the Continuation with the TaskContinuationOptions.OnlyOnRanToCompletion runs, instead of the TaskContinuationOptions.OnlyOnCanceled.
Clearly I'm not doing this correctly.
Edit:
Doing some further reading, I found a comment that states that:
"catch (OperationCanceledException) {} will set the task's status as RanToCompletion, not as Canceled"
So removing the catch (OperationCanceledException) {} allows the task's status to to be set to canceled, but the program breaks on the tokenSource.Token.ThrowIfCancellationRequested(); but if I then continue through the break, the continuation task with the TaskContinuationOptions.OnlyOnCanceled runs, which is good.
But how do I call tokenSource.Token.ThrowIfCancellationRequested() without allowing the program to break and while allowing the task status to be set to Canceled?

A: The comments above are correct in terms of the debugger and the options required to prevent the debugger breaking. However, the following should give you a better example of how to use continuations and indeed how to handle exceptions thrown from tasks within those continuations...
A continuation can find out if an exception was thrown by the antecedent Task by the antecedent task's exception property. The following prints the results of a NullReferenceException to the console
Task task1 = Task.Factory.StartNew (() => { throw null; });
Task task2 = task1.ContinueWith (ant => Console.Write(ant.Exception());

If task1 throws an exception and this exception is not captured/queried by the continuation it is considered unhandled and the application dies. With continuations it is enough to establish the result of the task via the Status keyword
asyncTask.ContinueWith(task =>
{
    // Check task status.
    switch (task.Status)
    {
        // Handle any exceptions to prevent UnobservedTaskException.
        case TaskStatus.RanToCompletion:
            if (asyncTask.Result)
            {
                // Do stuff...
            }
            break;
        case TaskStatus.Faulted:
            if (task.Exception != null)
                mainForm.progressRightLabelText = task.Exception.InnerException.Message;
            else
                mainForm.progressRightLabelText = "Operation failed!";
        default:
            break;
    }
}

If you don't use continuations you either have to wait on the task in a try/catch block or query a task's Result in a try/catch block
int x = 0;
Task<int> task = Task.Factory.StartNew (() => 7 / x);
try
{
    task.Wait();
    // OR.
    int result = task.Result;
}
catch (AggregateException aggEx)
{
    Console.WriteLine(aggEx.InnerException.Message);
}

Hope this helps.


text:
Q: Can't change html 5 canvas background Im using this script to create canvas on which i can paint and then save the picture all together.  :

But my background stays all white and doesn't change. When i open this website, it says :
"loadImage is not defined". Any help will be very apreciated.

A: First make sure you define a canvas in your HTML file and define the size of your canvas:
<canvas id="myCanvas" width="500" height="500"></canvas>

So instead of defining canvas in your Javascript, it's much easier to define it in the HTML and grab it in your Javascript.
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

The context is where you do all the drawing. Now, you can define your loadImage (or not use a method at all if you're only loading one image):
function loadImage(imageSrc, x, y) {
    var image = new Image();
    image.src = imageSrc;
    image.onload = function() {
        context.drawImage(image, x, y);
    }
}

Then, you can call that function when the page loads.
Live Demo Here
If you copy and paste the following code, you should get a working demo (however, there appears to be other issues with saving and clearing that you should look to fix):
<!DOCTYPE html>

    <title>HTML5 Picture</title>

    <canvas id="can" width="500" height="300" style="position:absolute;top:10%;left:10%;border:2px solid;"></canvas>

Choose Color

Eraser

    <input type="button" value="save" id="btn" size="30" onclick="save()" style="position:absolute;top:55%;left:10%;">
    <input type="button" value="clear" id="clr" size="23" onclick="erase()" style="position:absolute;top:55%;left:15%;">


text:
Q: SocketIo behind traefik and reverse proxy. Unable to connect I am unable to connect to socketio in production.
This is my traefik file. my backend gets all calls which go to /api....
  backend:
build:
  context: ./backend
  dockerfile: Dockerfile
command: ["npm", "run", "start"]
labels:
  - "traefik.enable=true"
  - "traefik.http.routers.backend.rule=Host(`mydomain.com`) && PathPrefix(`/api`)"

networks:
  - web

My express server:
export const io = new Server(server, {
  cors: {
    origin: [
      "http://localhost:5173",
      "https://mysecretdomain.com",
    ],
  },
});

My react frontend:
let socket: any;
if (import.meta.env.MODE === 'development') {
  socket = io(API_CONFIGS.SOCKET_IO_URL);
} else {
  // the app runs with traefik and is available under the prefix /api

  socket = io(API_CONFIGS.SOCKET_IO_URL, { path: '/api/socket.io' });
}

In Development, everything works fine but in prod im getting a 404 error
example call from my domain
https://mysecretdomain/api/socket.io/?EIO=4&transport=polling&t=OKSmUX8
Status:404

I am completly out of ideas. Can someone help me out?


text:
Q: Find files for which multiple variations on that filename exist together in the same directory I want to list the files for which there exists, in a given directory, ALL of these files:

*

*<filename>.wed

*<filename>.tis

*<filename>.are

*<filename>LM.bmp
I am currently doing it with find and sed. It works but it is inelegant and slow!
find . -iname "*.wed" -exec echo {} \; | sed s/.wed$// $1 | sed s/..// $1 | while read in; do find . -name "$in.are"; done | sed s/.are$// $1 | sed s/..// $1 | while read in; do find . -name "$in.tis"; done | sed s/.tis$// $1 | sed s/..// $1 | while read in; do find . -name "$in*.bmp"; done

Basically I chain a find, two sed and a while read for each extension I want to filter on.
It takes >35s for barely 30K files! How can I improve it?
Example
If in the directory there are files called AR0505.are, AR0505.tis, AR0505.wed and AR0505LM.bmp, then the script would print "AR0505".
If one or more of these files was missing, then the script wouldn't print it.

A: If I understand you correctly, you are looking for all file names that exist with each of the target extensions. If so, you could do:
( shopt -s nullglob;
  for i in *.wed; do
    set --  "${i//.wed}"{.tis,.are,LM.bmp}*;
    [[ $# -eq 3 ]] && printf '%s\n'  "${i//.wed}";
done )

Explanation

*

*shopt -s nullglob : this is a bash-specific option that makes globs expand to a null string instead of themselves if no matching files are found. The ( ) are there just to ensure that the option is only set for this command and won't affect the parent shell.

*for i in *.wed; do ...; done : iterate over all files or directories in the current directory whose name ends with .wed, saving each as $i.

*"${i//.wed}" : the file name without the .wed extension.

*set --  "${i//.wed}"{.tis,.are,LM.bmp}* : the braces will expand to foo.tis, foo.are etc, and the * is a trick to make bash attempt to match them as globs. This means it will only work if the actual file name exists.

*[[ $# -eq 3 ]] && printf '%s\n' "${i//.wed}" : if there are exactly 3 files in $@, so 3 in addition to the original .wed one, print the filename without the extension.

If you want to print all 4 file names, including the extension, just change the printf '%s\n' "${i//.wed}" to printf '%s\n' "$i".

A: I think the major bottleneck is the number of processes you spawn. Here is a simple script which lists and filters your directory in one pass:
#!/usr/bin/perl

use strict;
use warnings;

my %files;
my $dir;
my @extensions = ("\.tis","\.are","LM\.bmp","\.wed");

opendir($dir, ".") || die "Error opening dir\n";
while (my $file = readdir($dir)) {
    foreach my $ext (@extensions) {
        if ($file =~ /^(.*)$ext$/sm) {
            $files{$1} += 1;
        }
    }
}
closedir($dir);

foreach my $file (keys %files) {
    if ($files{$file} == scalar(@extensions)) {
        print "$file\n";
    }
}

A: find . -type d  -exec sh -c '
   h=$1; cd "$h" || exit
   set -- /dev/nul[l] [f]oobar.{wed,tis,are} [f]oobarLM.bmp; shift
   case $# in 4 ) for arg; do printf "%s/%s\n" "$h" "$arg"; done ;; esac
' {} {} \;

N.B.: Here we don't look at anything else but these 4 files & in the specific case and only when ALL 4 are found, then it displays them, even if other foobar.XXX files existed in the same directory. Coz the OP was not very clear about that.

A: Bash
We set up a for loop with a glob expression *LM.bm[p], so that we can disambiguate the scenario of file with name ending in p actually existing versus not. This is a bare-bones variety of shopt nullglob. If we see a name end in p => the shell was able to expand that glob, meaning, such a file existed. OTOH, if we see a name end in [p] => the shell was NOT able to expand the glob *LM.bm[p] meaning, there was no file with that name.
Next step is we clip the trailing 6 chars (L M . b m p) from the filename which we now know exists. Using the remaining part of the filename, we set up 3 positional parameters corresponding to the 3 extensions .wed .are .tis.
The key is that even if one of the extensions is left unexpanded, then it's name would show up with it's last character included in a [ ]. => All 3 files are not all present. => skip this . And the else clause => all 3 files are present + 1 (*LM.bmp) is already present due to our prior check. Hence we see all 4 files and => fit for printing.
for i in *LM.bm[p]; do
   case $i in
      *[p] )
         f=${i%??????}
         set -- "$f".we[d] "$f".ar[e] "$f".ti[s]
         savIFS=$IFS
            IFS=/
            case "$*/" in
               *"]/"* ) : ;;
               *      ) printf '%s\n' "$f" ;;
            esac
         IFS=$savIFS
   esac
done

A: perl -le '
   while ( <*LM.bmp> ) {
      (my $f = $_) =~ s|LM\.bmp$||;
      print $f if 3 == grep { -e $f . $_ } qw/.tis .are .wed/;
   }
'


text:
Q: Verification exercise in Lang's Algebra In the section on the simplicity of $PSL_n(F)$. The first line in page 544 (Lang Algebra, Third edition) there is remark that "This is easily seen..." I am afraid, I fail to see how. Can someone tell me how to go about that verification? In detail, the problem is as follows.
Theorem- Let G be a $SL_n(F)$-invariant subgroup of $GL_n(F)$ such that G is not contained in the center of $GL_n(F)$, then $SL_n(F)$ is contained in $ G$.
Proof: Let $A\in G$ s.t there exists $u\neq0$ such that $Au$ is not a scalar multiple of u, say $Au= v$. (Such an A is available because G is not in the center)
Let $u,v$ be contained in a hyperplane $H= kerf$ , where f is a linear functional on $F^n$.  Define T by $T=T_u$, where $T_u (x)= x+f(x)u$ for all $x\in F^n$.
Let $B=ATA^{-1}T^{-1}$.
To show that $B\neq I$, where I is the identity in $GL_n(F)$.
It says that it is easy to verify that $ATA^{-1} \neq T$ by checking RHS and LHS on arbitrary $x\in F^n$. I have tried this but am getting nowhere.

A: This is missing some context: e.g., I don't understand what an "$\operatorname{SL}_n\left(F\right)$-invariant subgroup of $\operatorname{GL}_n\left(F\right)$" is, and why a hyperplane $H$ containing $u$ and $v$ exists (is $n \geq 3$ a requirement?).
Anyway, I guess I can still answer the concrete question: We shall check that $AT \neq TA$. Indeed, pick $x \in F^n$ such that $f\left(x\right) \neq 0$. (Such $x$ exists, since $\ker F$ is a hyperplane.) Thus, $f\left(x\right) v$ is a nonzero multiple of $v$, and hence not a multiple of $u$ (since $v$ is not a multiple of $u$). In particular, $f\left(x\right) v \neq f\left(Ax\right) u$.
Now,
$\left(AT-TA\right)x = A\underbrace{Tx}_{=x + f\left(x\right) u} - \underbrace{TAx}_{=Ax + f\left(Ax\right) u} = A\left(x + f\left(x\right) u\right) - \left(Ax + f\left(Ax\right) u\right)$
$= Ax + f\left(x\right)Au - Ax - f\left(Ax\right) u = f\left(x\right)\underbrace{Au}_{=v} - f\left(Ax\right) u = f\left(x\right) v - f\left(Ax\right) u \neq 0$
(because $f\left(x\right) v \neq f\left(Ax\right) u$), so that $AT-TA \neq 0$ and thus $AT \neq TA$.


text:
Q: ElementUI doing validation with Sub Component How to validate a sub component inside a form?
In the form component I have the sub component:
<template>
  <el-form :model="value">
    <el-form-item
      prop="name"
      :rules="{ required: true, message: 'Necessary', trigger: 'blur' }"
    >
      <el-input v-model="value.name">
    </el-form-item>
    <ZipCode v-model="value.zipcode" />
  </el-form>
</template>

<script>
export default {
  props: {
    value: {
      type: Object,
      default: () => {
        return {
          name: null,
          zipcode: { code: null, local: null }
        }
      }
    }
  }
}
</script>

And in the ZipCode component:
<template>
  <el-form-item
    prop="code"
    :rules="{ required: true, message: 'Necessary', trigger: 'blur' }"
  >
    <el-input v-model="value.code">
  </el-form-item>

  <el-form-item
    prop="local"
    :rules="{ required: true, message: 'Necessary', trigger: 'blur' }"
  >
    <el-input v-model="value.local">
  </el-form-item>
</template>

<script>
export default {
  props: {
    value: {
      type: Object,
      default: () => { return { code: null, local: null } }
    }
  }
}
</script>

The validation on the form component is working as expected but not the validation on the sub component. If the field has data, still gives the error that data is required. This false validation is also working from the form component.
So problem might be on the "prop" field. If change the prop to "value.code" or "zipcode.code" it gives the error "Error: please transfer a valid prop path to form item".
What might be the issue? Thank you for any help.

A: The rule should have the type as an 'object' with a fields property for each sub rule.
  <el-form :model="value" :rules="
    {
      name: [
        { required: true, message: 'Please input name', trigger: 'blur' }
      ],
      zipcode: {
        type: 'object',
        required: true,
        fields: {
          code: { type: 'string', required: true, len: 8, message: 'invalid zip' },
          local: { type: 'string', required: true, message: 'required' }
        }
      }
    }
  ">


text:
Q: Will method invocation reflection in Scala cause performance degradation? I have a method intended to do some simple statistics for data IO, as shown below.
def ioStatSink[T <: { def length: Int }](): Sink[T, Future[(Long, Long)]] = Sink.fold((0L, 0L))((acc, bytes) => (acc._1 + 1L, acc._2 + bytes.length))

As I want it to be able to handle different data types that have a { def length: Int } method, I make it generic.
The problem is, this method invocation uses reflection.
As this method is called millions fo times, I don't want it to have performance issue.
I know class instantiation with reflection has performance penalty, but how about this method invocation?
(another issue about the method is, it cannot adapt to types with a method of { def length: Long }, any suggestion to deal with this?)

A: Since you said you were interested in the typeclass alternative.
Here is a simple demo.
import scala.language.higherKinds

trait Sizeable[T] {
  def size(t: T): Long
}

object Sizeable {
  private final val _IterableOnceSizable: Sizeable[IterableOnce[_]] =
    new Sizeable[IterableOnce[_]] {
      override final def size(iter: IterableOnce[_]): Long = {
        val knownSize = iter.knownSize
        if (knownSize == -1) iter.iterator.size.toLong
        else knownSize.toLong
      }
    }

  implicit final def CollectionSizeable[C[_], T](implicit ev: C[T] <:< IterableOnce[T]): Sizeable[C[T]] =
    _IterableOnceSizable.asInstanceOf[Sizeable[C[T]]]
}

object syntax {
  object sizeable {
    implicit class SizeableOps[T](private val sizable: T) extends AnyVal {
      @inline def size(implicit ev: Sizeable[T]): Long =
        ev.size(sizable)

      @inline def length(implicit ev: Sizeable[T]): Long =
        ev.size(sizable)
    }
  }
}

import syntax.sizeable._

def ioStatSink[T : Sizeable](): Sink[T, Future[(Long, Long)]] =
  Sink.fold((0L, 0L))((acc, bytes) => (acc._1 + 1L, acc._2 + bytes.length))


text:
Q: How do you save a snippet of code in SAS Studio as an abbreviation? In SAS Studio, is it possible to save a snippet of code, such as a header, as an abbreviation so you can pull-up the code in future programs without having to type the whole thing in again? This can be achieved is SAS EG by selecting "Program > Add Abbreviation Macro", does SAS Studio have a similar option?

A: The Snippet functionality is available in SAS Studio from version 3.1 on-wards.
Full details are on SAS support site here.
To create your own snippet:

*

*Open your .sas file in SAS Studio and select the code that you want to save as a snippet.

*On the Code tab, click Add to My Snippets button. The Add to My Snippets dialog box appears.

*Enter a name for the snippet and click Save.

This snippet is now available from the My Snippets folder.


text:
Q: Problem with \titleprefixword I'm trying to make a songbook with Songs Package. The songs are in Spanish and I want to use the \titleprefixword macro to avoid sorting my song titles starting with the articles (El, La, Los, Las).
This is the code and I think eveything is correct but it's obviously not because it's not working:
\documentclass[letterpaper]{article}
\usepackage[bookmarks]{hyperref}
\usepackage[chorded]{songs}
\usepackage[utf8x]{inputenc}
\usepackage[spanish]{babel}
\usepackage{xpatch}
% \includeonlysongs{2}

\setlength{\oddsidemargin}{0in}
\setlength{\evensidemargin}{0in}
\setlength{\textwidth}{6.5in}
\setlength{\topmargin}{0in}
\setlength{\topskip}{0in}
\setlength{\headheight}{0in}
\setlength{\headsep}{0in}
\setlength{\textheight}{9.1in}
\settowidth{\versenumwidth}{1.\ }
\pagestyle{empty}

\titleprefixword{El}
\titleprefixword{La}
\titleprefixword{Los}
\titleprefixword{Las}
\titleprefixword{Un}
\titleprefixword{Una}

\authsepword{y}
\authbyword{por}
\authignoreword{Desconocido}

\ifchorded
  \newcommand{\stopchords}{\chordsoff}
  \newcommand{\resumechords}{\chordson}
\else
  \newcommand{\stopchords}{}
  \newcommand{\resumechords}{}
\fi

%\makeatletter
%\xpatchcmd{\SB@@@beginsong}
%  {\SB@addtoindexes\songtitle}
%  {\SB@addtoindexes{\songtitle\ifx\songauthors\empty\else\ (\songauthors)\fi}}
%  {}{}
%\makeatother

\newindex{titleidx}{cbtitle}
%\indexsongsas{titleidx}{\thepage}
\newauthorindex{authidx}{cbauth}
\newscripindex{scripidx}{cbscrip}

\begin{document}

\showindex{Índice Completo de Canciones y Temas}{titleidx}

\songsection{Himnario de la Iglesia Reformada en Venezuela}
\begin{songs}{titleidx,authidx,scripidx}

 \beginsong{La Cruz Excelsa}[
  by={Isaac Watts},
  sr={Números 21:4-9; Marcos 15:1-47; Romanos 5:6-11; Filipenses 2:1-13; Salmos 34:2; 1 Corintios 1:17-31; 1 Pedro 2:19-25},
  ititle={(salvación)},
  ititle={(cruz)},
  ititle={(entrega)},
  ititle={(sacrificio)},
  ititle={(muerte de Cristo)}]

\beginverse
\[D]La cruz ex\[^\gtab{Dmaj9}{200220}]celsa al \[Em]con\[A]tem\[D]plar
\[D]Do Cristo a\[G]llí \[D/F#]por \[E7]mí mu\[A]rió,
\[D]De todo \[Dmaj9]cuanto es\[Em]ti\[A]mo a\[D]quí,
\[D]Lo más pre\[G]cio\[D/F#]so \[Em]es \[A]su a\[D]mor.
\endverse
\beginverse
^No busco \[Dmaj9]gloria ^ni ^ho^nor
^Sino en la ^cruz ^de \[Bm7]mi ^Se^ñor,
^Las cosas ^que me en^can^tan ^más
^Las sacri^fi^co ^por ^su a^mor.
\endverse
\stopchords
\beginverse
De su cabeza, manos, pies,
Preciosa sangre allí corrió;
Corona vil de espinas fue
La que Jesús por mí llevó.
\endverse
\beginverse
El mundo entero no será
Dádiva digna de ofrecer.
Amor tan grande, sin igual,
En cambio, exige todo el ser.
\endverse
\resumechords
\endsong

\beginscripture{Salmos 34:2}
\Acolon Mi alma se gloría en el Señor;
\Bcolon lo oirán los humildes y se alegrarán.
\endscripture
\end{songs}

\showindex{Índice de Autores y Compositores}{authidx}
\showindex{Índice de Referencias Bíblicas}{scripidx}

\end{document}

Any ideas on how to make it work!?

A: I had a very similar problem with authsepword and authignoreword. Moving them just before \begin{document} fixed the problem.

A: There seems to be a bug that \titleprefixword is completely ignored by the songs package (even after upgrading to version 3.0). However, the fix is actually pretty simple. You have to modify the script that creates the indices: songidx.lua. Change the line
prelist = { A=true, THE=true}

to add all your desired prefixes, all  in capitals, e.g.,
prelist = { A=true, THE=true, EL=true, LA=true}


text:
Q: How to get the width of each characters in a string in android I am having a framelayout with two textviews where the second textview has to follow after the first textview. There is too much of space between the two text views as the width depends on the character width of the string. How do i calculate the width of the string or the width of each characters in the string so that i could place the second text view after the first.
SpannableString strUserName = new SpannableString(String.format(
            "%" + Name().length() + "s", "")
            .replace("", " ")


text:
Q: Laravel - How to create a settings page for registered user I need to create a settings page when user register my site. Can I make it with register controller and user model or do I need a seperate model/table for this. What I tried is,
protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'title' => 'Your website title',
            'analytics' => 'Your google analytics code here',
            'adsense' => 'Your google adsense code here'
        ]);
    }

and in setting controller I use only edit and update route. But when user register I get error message that field title dont have any value.
I also tried in route Route::post('/register', 'SettingsController@store'); and in settings controller
public function store(Request $request)
    {
        $user_id = auth()->user()->id;
        $user = User::find(id, $user_id)->get();
        $user->title = 'Your website title';
        $user->analytics = 'Your google analytics code here';
        $user->adsense = 'Your google adsense code here';
        $user->save();
    }

Now when register user go to login page. What is the right approach to create a settings page when user register?


text:
Q: Can't merge master to feature branch after reverting a pushed merge We have been working on a feature branch with git for a while. Every now and then, I merged the master into this feature branch to keep the feature branch in sync with the master and to facilitate merging the feature branch into the master at the end.
Then, I accidentally merged the feature branch into the master (too early, I intended to merge the other way round as before). As the merge had already been pushed, I used git revert -m 1 <merge-commit> to revert the pushed merge according to these instructions.
The revert seems to have worked fine, but now I have the problem that when I try to merge the master into the feature branch, most of the changes in the feature branch get overwritten with the "older" files in the master. It looks like after the revert, the master is considered to have the newer versions of the files. I also suspect that I won't be able to merge the feature branch into the master when we're done.
How can I get back to the initial state where I was able to merge changes in the master into the feature branch without overwriting all other changes made in the feature branch?

A: I performed the following steps and it seems to have fixed the problem:

*

*make backup of the feature branch

*merge master into the feature branch (at this point, the "outdated" files  from the master are being merged into the feature branch)

*delete all files of the feature branch from git and commit

*copy backup of the feature branch into the local feature branch

*add all files to git, commit, and push

I just tried to make a minor update in the master and merge it into the feature branch. Only the minor update was merged into the feature branch, but not the "outdated" files from the master.

A: You can try performing a checkout of the commit directly before the feature-into-master commit. Branch from that (named master2 or whatever you want). Delete the current master. Then branch from master2 into a new branch named master.
git checkout <hash of commit before feature merge in master>
git checkout -b master2
git branch -D master
git checkout -b master
git branch -D master2

Delete the master branch on github and push your new master up. This might be a bit of a round-about way but it should essentially revert master to where it was before and allow you to continue merging into feature.


text:
Q: Active links not working on bootstrap I am really new with bootstrap, and I'm trying to apply the active class to a menu, but for some reason is not working, I don't know if it is the jquery function (I got it from a tutorial) or if bootstrap won't allow the use of active links.
JS Fiddle Demo
HTML

Home

Cars

Models

Colors

CSS
nav-justified a.activee {
    background:red !important;
    }

JS
jQuery(function() {
  jQuery('.nav-justified a').each(function() {
    if (jQuery(this).attr('href')  ===  window.location.pathname) {
      jQuery(this).addClass('activee');
    }
  });
});

A: In your JavaScript code you're checking to make sure that the href attribute of your link is equal to window.location.pathname but, in your JSFiddle, none of the links have a matching attribute. Try this instead:

Home

Cars

Models

Colors

http://jsfiddle.net/021qbcvd/7/
Note that window.location.pathname is equal to everything after the main URL. I had to do an alert(window.location.pathname) to get the correct one for the JSFiddle.

A: if you use twitter-bootstrap 3,can use this code :

Home

CARS

MODEL

COLORS

and use class="active" in li tag to show active page