text:
Q: How can I find posts related to lost reputation due to a "user was removed" message? Today I noticed that my reputation got truncated by 64 points, and when I looked at my reputation history, I saw a bunch of lines notifying me of points removal along to a "user was removed" message. Each has a slightly different timestamp, ranging from 12:39:04 to 12:39:43.

I can't find the questions/answers concerned by this (and I don't remember having won as much as 65 points once, making this even stranger). I would like to find out how I could have lost 65 points while I never won as much in a single question/answer.
Is there a way I can check which of my posts were impacted?

A: Today I discovered by accident that this information is (sometimes) visible in your personal timeline/feed in the Stack Exchange app:

These two -10s corresponds to this -20 "user was removed" entry in my profile:

That means it's available via the Stack Exchange API, using the Reputation History call:

*

*Go to this page

*Change the site with the [edit] link (default is Stack Overflow)

*Click the 'Get Token' button so that the API knows it's you

*After authenticating, click the 'Run' button

Scroll down to the user_deleted events, you'll find clickable post IDs which will take you to the involved posts:

A: The system doesn't give you a way to figure out which posts lost votes.  A sufficiently-curious person could use SEDE, which is updated only weekly, to try to figure it out, I suppose (assuming the votes weren't also recent).
On the full site (which is what your screen shot appears to be from), you get one "user was removed" entry for each removed user.  So in your case several users were deleted around the same time -- whether that's a sock ring or diverse requests that all got handled together is impossible for mere mortals (i.e. people without direct database access) to say.  On the mobile web site, in contrast, you get one entry per removed vote and no indication of how many came from the same source.
(Your tagging says feature-request, but your actual question says support or discussion to me, so that's how I answered.)


text:
Q: Map the following transformation: $ w = \frac{z}{|z|} $ Sketch the region onto which the circle of radius $R$ centered at the origin $(|z| = R, R>0)$ is mapped by the following transformation:
$$ w = \frac{z}{|z|} $$
I know the answer to this. But my initial instinct was to do this in terms of $u, v$
I thought this should be $$w= \frac{x+iy}{\sqrt{x^2 + y^2}}$$
Thus $$u=\frac{x}{\sqrt{x^2+y^2}} \ ,\ v= \frac{y}{\sqrt{x^2+y^2}}$$
Then take the norm of this, and I have no idea what it would look like, but "plot" this on the $u,v$ plane... I got zero credit, though my text Complex Variables and Applications has this method in section 14

redpajama_set_name: RedPajamaStackExchange


text:
Q: Starting new session on every curl request My question is about SESSIONS in PHP.
I am using the following code to start a new session when user opens my website:
<?php session_start(); ?>

What I want to know is, suppose a script sends "two" CURL request to my website, then will they get a new session each time?
Or will PHP recognize the "second" CURL request from same server, and open the previous session which PHP allotted to this request maker?
Suppose I want a new session started on every CURL request, then is my current PHP code session_start() okay?
Suppose I want an older session to be resumed, on every CURL request, then how should I do that while starting a session?

A: PHP uses cookies to manage sessions. In order to use cookies with curl you need to enable a cookie jar
For example:
curl --cookie-jar cookies.txt  http://www.example.com

Note: cookies.txt must be placed somewhere your instance of curl can read and write to it.
Using this format on each invocation of curl should allow you to use the same PHP session each time.
Without the cookie-jar argument, curl won't persist cookies between sessions. PHP won't see a cookie it recognises, so it will start a new session each time.
More details on the cURL page: https://curl.se/docs/manpage.html


text:
Q: Why might extra-lib-dirs not work like LD_LIBRARY_PATH in stack? --extra-lib-dirs should ostensibly function like LD_LIBRARY_PATH, but when used with stack exec I see different results:
$ stack --extra-lib-dirs=$MATLAB_PATH/bin/glnxa64 --extra-include-dirs=$MATLAB_PATH/extern/include --nix exec matlab-engine-test
/home/bebarker/workspace/haskell-matlab/.stack-work/install/x86_64-linux-nix/24c5769e9013838d87aa76fb4cdd10a09798b6904a6faa380de6fe6949e2c952/8.6.5/bin/matlab-engine-test: error while loading shared libraries: libmx.so: cannot open shared object file: No such file or directory

$ LD_LIBRARY_PATH=$MATLAB_PATH/bin/glnxa64 /home/bebarker/workspace/haskell-matlab/.stack-work/install/x86_64-linux-nix/24c5769e9013838d87aa76fb4cdd10a09798b6904a6faa380de6fe6949e2c952/8.6.5/bin/matlab-engine-test
matlab-engine-test: user error (engOpen)

LD_LIBRARY_PATH behaves as expected in this case (though clearly I have another unrelated issue to deal with there). Should I be looking for another option or am I using --extra-lib-dirs incorrectly?

A: I don't tend to use Stack, but in build systems the library path provided by command line flags is usually only passed to the linker.  Observe (with main = print =<< lookupEnv "LD_LIBRARY_PATH"):
$ stack --extra-lib-dirs=/foopath/bin/glnxa64 --extra-include-dirs=/foopath/extern/include exec ./foo
Just ""
$

Compare with what you did second:
$ LD_LIBRARY_PATH=/foopath/bin/glnxa64 ./foo
Just "/foopath/bin/glnxa64"


text:
Q: Is there a way to find out if a class has an overloaded operator? I am writing a template class where I need a method to print out element class into stdout. But I am having a problem writing it - what if cout << or operator const char*() is not defined or overloaded in my element class?
Is there a way to find it out to maybe throw an exception and not get compilation error?

A: If the operator is not overloaded, your program can not compile. This is a compile time error and there is no way to delay that until runtime.
A way around would be to not use an operator, but a function pointer. If the operation is not supported, than the function pointer could be set to 0 which you can detect at runtime.
class A {
public:
    int q; // some data

    typedef std::function<void(std::ostream& os, const A&)> PrinterFunc;
    PrinterFunc func;

    friend std::ostream& operator<<(std::ostream& os, const A& a) {
        if(!a.func) {
            throw "Not supported";
        }
        func(os,a);
        return os;
    }
};

A a;
a.func = [](std::ostream& os, const A& a) { os << "hello " << a.q; }
std::cout << a << std::endl; // will print

A b;
std::cout << b << std::endl; // will throw

This example uses C++11 and <functional>. For C++03 you would have to use a "normal" function pointer.

A: You might use some SFINAE to test if an (formatted) output operator exists:
#include <iostream>

// HasFormattedOutput
// ============================================================================

namespace HasFormattedOutput {

    namespace Detail
    {
        struct Failure{};
    }

    template<typename OutputStream, typename T>
    Detail::Failure operator << (OutputStream&, const T&);

    template<typename OutputStream, typename T>
    struct Result : std::integral_constant<
        bool,
        ! std::is_same<
            decltype(std::declval<OutputStream&>() << std::declval<T>()),
            Detail::Failure
        >::value
    > {};
} // namespace HasFormattedOutput

template <typename T, typename OutputStream = std::ostream>
struct has_formatted_output : std::conditional<
    HasFormattedOutput::Result<OutputStream, T>::value,
    std::true_type,
    std::false_type>::type
{};

// Test
// ============================================================================

struct X {};
int main() {
    std::cout.setf(std::ios_base::boolalpha);
    std::cout << has_formatted_output<const char*>() << '\n';
    std::cout << has_formatted_output<X>() << '\n';
}

(C++11)


text:
Q: Netbeans Xdebug on Windows 7 "waiting for connection" WAMP I read a lots of solutions for this common Xdebug's error, but it did not seems to resolve my issue:
netbeans shows "Waiting For Connection (netbeans-xdebug)"
Netbeans not connecting with xdebug on Wamp : "showing waiting for connection"
in phpinfo() Xdebug seems properly configured:

And below is my php.ini:
zend_extension = "c:/wamp/bin/php/php5.5.12/zend_ext/php_xdebug-2.2.5

-5.5-vc11-x86_64.dll"
;
[xdebug]

xdebug.remote_enable=1
xdebug.remote_mode = req
xdebug.remote_handler=dbgp
xdebug.remote_host=127.0.0.1
xdebug.remote_port=9001

xdebug.profiler_enable = off
xdebug.profiler_enable_trigger = off
xdebug.profiler_output_name = cachegrind.out.%t.%p
xdebug.profiler_output_dir = "c:/wamp/tmp"
xdebug.show_local_vars=0
xdebug.idekey=netbeans-xdebug

Netbeans:

Tried disable firewall doesn't seems to help.
Running out of ideas to know what is going on with my Xdebug.

A: Once you start debugging , Check in your command prompt that netbeans is listening on port 9001 :
C:\Users\***> netstat -ano | findstr 9001

  TCP    0.0.0.0:9001           0.0.0.0:0              LISTENING       20928
  TCP    [::]:9001              [::]:0                 LISTENING       20928

the PID in the end (20928 in my case) should belong to netbeans, this can be verified from Windows task manager  (after adding pid : view > select columns > pid)
If the PID is not correct or the port is not up., restart netbeans or  restart system and it will work
If netbeans has the 9001 port, this means your browser is not listening or getting attached to netbeans. Sometimes browser cannot establish the connection or cannot start properly.
In order to manually attempt a connection , you need to press the debugging button in netbeans and within the next minute or so(before it times out) open the following url in your favorite browser (try different browser if one fails)
localhost/<yoursite>/page/?XDEBUG_SESSION_START=netbeans-xdebug

You may also try switching to embedded browser in netbeans project properties.
You can also try changing the port from 9001 to something else , eg 9002 on both sides , this helps if some other program is trying to connect to port 9001 or trying to listen on this port.

A: Set
zend_extension = "c:/wamp/bin/php/php5.5.12/zend_ext/php_xdebug-2.2.5
-5.5-vc11-x86_64.dll";
inside the [xdebug] section , not outside.
remove ; from the end.
wrong:
zend_extension = "c:/wamp/bin/php/php5.5.12/zend_ext/php_xdebug-2.2.5-5.5-vc11-x86_64.dll";
[xdebug]
xdebug.remote_enable=1
.....

right:
[xdebug]
zend_extension = "c:/wamp/bin/php/php5.5.12/zend_ext/php_xdebug-2.2.5-5.5-vc11-x86_64.dll"
xdebug.remote_enable=1
.....

also try
zend_extension_ts="c:/.../php_xdebug-2.2.5-5.5-vc11-x86_64.dll"
instaed of
zend_extension="c:/.../php_xdebug-2.2.5-5.5-vc11-x86_64.dll"

A: Finally, managed Xdebug to work follow this article, and one more thing i need to do is when netbeans showing "waiting for connection" message. I need to open the page manually in browser(netbeans not open pop-up itself), added index.php?"XDEBUG_SESSION_START=netbeans-xdebug" to the URL and refresh the page, and then netbeans Xdebug status changed to running right away :)
Thank you guys so much for valuable helps!!!!


text:
Q: Stochastic calculus with normal distribution For $l=1,2......$ prove that  $E[W^{2l+1} (t)]=0$
I am trying to find the ways of solving the task from Stochastic calculus, but it seems to be very difficult to start with.
I am really appreciate any hints and thoughts about solution.


text:
Q: How to apply a mask to a texture with transparency to achieve see-trough effect I'm trying to apply a mask to a texture with transparency. The effect I'm trying to achieve is an object with a crack, and you should be able to see trough the crack. I tried using blending and frame buffers with no success.
Here are the sprites I'm using:
The ball: http://i.stack.imgur.com/4gImO.png
(notice that the ball is transparent around)
The mask: http://i.stack.imgur.com/ij4Uw.png
(the mask is white with transparent cracks in the middle)
This is the current result I'm getting:

This is the result I'm looking for:

(this was done using pixmaps by checking each pixel in the mask, and drawing only those with alpha > 0, but it is too slow, it freezes for a second or two on android, and I can't preload it because I don't know the object I'm applying the mask to until I need to apply it)
This is my render function:
@Override
public void render() {
  Gdx.gl.glClearColor(1, 0, 0, 1);
  Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
  batch.begin();

  mBackground.draw(batch);

  batch.setBlendFunction(GL20.GL_ZERO, GL20.GL_SRC_COLOR);
  mMask.draw(batch);

  batch.setBlendFunction(GL20.GL_DST_ALPHA, GL20.GL_ONE_MINUS_DST_ALPHA);
  mObject.draw(batch);

  batch.end();
}

A: I managed to get this working by using shaders. Here is my solution:
The render function:
@Override
public void render() {
    Gdx.gl20.glClearColor(0, 0, 0, 1);
    Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT);

    batch.begin();
    mBackground.draw(batch);

    batch.setShader(mShaderProgram);

    Gdx.graphics.getGL20().glActiveTexture(GL20.GL_TEXTURE0);
    mObjectTexture.bind(0);
    mShaderProgram.setUniformi("u_texture", 0);

    Gdx.graphics.getGL20().glActiveTexture(GL20.GL_TEXTURE1);
    mMaskTexture.bind(1);
    mShaderProgram.setUniformi("u_mask", 1);

    Gdx.graphics.getGL20().glActiveTexture(GL20.GL_TEXTURE0);
    batch.draw(mObjectTexture, 0, 0, 500, 500);

    batch.end();
    batch.setShader(null);
}

The vertex shader:
attribute vec4 a_position;
attribute vec4 a_color;
attribute vec2 a_texCoord0;

uniform mat4 u_projTrans;

varying vec2 v_texCoords;

void main() {
    v_texCoords = a_texCoord0;
    gl_Position = u_projTrans * a_position;
}

The fragment shader:
varying vec2 v_texCoords;
uniform sampler2D u_texture;
uniform sampler2D u_mask;
uniform mat4 u_projTrans;

void main() {
    vec4 texColor = texture2D(u_texture, v_texCoords);
    vec4 maskColor = texture2D(u_mask, v_texCoords);

    gl_FragColor = texColor * maskColor.a;
}


text:
Q: Text formatting doesn't appear in emails that have been formatted using TinyMCE and sent using SwiftMailer I use SwiftMailer in my PHP scripts to send emails and I use TinyMCE as a text editor to write and format the message body. The problem is that when I send the message it appears without any formatting in all email clients (gmail, yahoo and hotmail), and even links doesn't appear as links, they appear as normal text but in blue. so what is the problem?
Here is the code I use to send emails:
<?php

require_once 'path/to/SwiftMailer/lib/swift_required.php';

$transport = Swift_MailTransport::newInstance();
# Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
# Create the message
$msg = Swift_Message::newInstance();
# Give the message a subject
$msg->setSubject($_POST['subject']);
# Set the From address with an associative array
$msg->setFrom(array($_POST['sender_email'] => $_POST['sender_name']));
# Give it a body
$msg->setBody($_POST['message'], 'text/html');

$failedRecipients = array();
$numSent = 0;
$to = array(
    'recipient_1@gmail.com',
    'recipient_2@yahoo.com' => 'Recipient 2',
    'recipient_3@hotmail.com',
    'recipient_4@gmail.com' => 'Recipient 4',
    'recipient_5@yahoo.com'
);

foreach ($to as $address => $name) {
    if (is_int($address)) {
        $msg->setTo($name);
    } else {
        $msg->setTo(array($address => $name));
    }

    $numSent += $mailer->send($msg, $failedRecipients);
}

echo $numSent > 0 ? 'SUCCESS' : 'FAILURE';

?>

note that $_POST['message'] holds body of the message that I have written and formatted using TinyMCE.

A: I have tried many things till I figure it out, the problem was that special characters in the formatted message body was being escaped (a back slash was being added in the front of each special character) I don't know why, and I don't know which of them (TinyMCE or SwiftMailer) that did this. So all I needed to do is to strip slashes out of the message body before sending the message throught SwiftMailer. I have just needed to change this line:
$msg->setBody($_POST['message'], 'text/html');

to be:
$msg->setBody(stripslashes($_POST['message']), 'text/html');

A: Not used Swiftmailer before but as a starting point it looks like it's stripping (not escaping) the HTML tags out of the content before sending. Are you able to post your code as it may be something you're doing there or something swift mailer itself is doing.
A quick look on swiftmailer and it looks like it supports html messages so it may also be the case that you're not using the correct MIME type.

A: I guess the problem is that your html email does not contain the stylesheet that is available in your tinymce editor. Make sure the same stylesheet gets apllied to your email content.


text:
Q: java.lang.LinkageError: attempted duplicate class definition Why does the error happen and how do I fix it?
[02:13:02] [pool-4-thread-2/WARN]: Exception in thread "pool-4-thread-2"
[02:13:02] [pool-4-thread-2/WARN]: java.lang.LinkageError: loader (instance of  org/bukkit/plugin/java/PluginClassLoader): attempted  duplicate class definition for name: "com/mongodb/client/model/Filters"
[02:13:02] [pool-4-thread-2/WARN]:  at java.lang.ClassLoader.defineClass1(Native Method)
[02:13:02] [pool-4-thread-2/WARN]:  at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
[02:13:02] [pool-4-thread-2/WARN]:  at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
[02:13:02] [pool-4-thread-2/WARN]:  at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
[02:13:02] [pool-4-thread-2/WARN]:  at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
[02:13:02] [pool-4-thread-2/WARN]:  at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
[02:13:02] [pool-4-thread-2/WARN]:  at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
[02:13:02] [pool-4-thread-2/WARN]:  at java.security.AccessController.doPrivileged(Native Method)
[02:13:02] [pool-4-thread-2/WARN]:  at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
[02:13:02] [pool-4-thread-2/WARN]:  at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:101)
[02:13:02] [pool-4-thread-2/WARN]:  at org.bukkit.plugin.java.JavaPluginLoader.getClassByName(JavaPluginLoader.java:195)
[02:13:02] [pool-4-thread-2/WARN]:  at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:97)
[02:13:02] [pool-4-thread-2/WARN]:  at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:86)
[02:13:02] [pool-4-thread-2/WARN]:  at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
[02:13:02] [pool-4-thread-2/WARN]:  at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
[02:13:02] [pool-4-thread-2/WARN]:  at me.franzsan.data.mongo.MongoCharacter.existsCharacter(MongoCharacter.java:109)
[02:13:02] [pool-4-thread-2/WARN]:  at me.franzsan.data.mongo.MongoCharacter.lambda$loadCharacter$0(MongoCharacter.java:44)
[02:13:02] [pool-4-thread-2/WARN]:  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
[02:13:02] [pool-4-thread-2/WARN]:  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
[02:13:02] [pool-4-thread-2/WARN]:  at java.lang.Thread.run(Thread.java:745)

This is the line that causes the error
FindIterable cursor = connection.getCharacters().find(Filters.eq("uuid", uuid));

And then there is also this. It's from another module and both should be executed asynchronously at the same time (or shortly after one another, because I think right now I have only one thread). This one works without error.
FindIterable cursor = connection.getPlayers().find(Filters.eq("uuid", id));

Filters.eq is a static method.
Both are using the same
ExecutorService pool = Executors.newCachedThreadPool();

I feel like i'm lacking crucial knowledge, but I have no idea where to look fo rit.

A: duplicate class definition for name says all. It seems that you copied the mongodb driver in you plugin under the classpath com.mongodb.client like in your other plugin and you are running both plugins on the same server. This causes a conflict, because you attempt to load 2 classes with the exact same classpath.


text:
Q: Detect Touch on Surfaceview android I'm creating a camera app and need to detect Touch on surfaceView which is camera preview. I want to set focus of camera where user touch. But Right i just only need to detect touch place.
Here is my preview class code.
public class Preview extends SurfaceView implements SurfaceHolder.Callback {
    public Preview(Context ctx, SurfaceView surfaceView) {
      super(ctx);
      init(surfaceView);
    }

  private void init(SurfaceView surfaceView){
        mSurfaceView = surfaceView;
        final SurfaceHolder surfaceHolder = mSurfaceView.getHolder();
        surfaceHolder.addCallback(this);
  }
  public void setCamera(){
     mCamera = Camera.open()
         mCamera.setPreviewDisplay(mSurfaceView.getHolder());
            mCamera.startPreview();
  }
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    Log.i(TAG, "onInterceptTouchEvent");
    return true;
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    Log.i(TAG, "onTouchEvent");
    return super.onTouchEvent(event);
}
 // Other code.... like override methods etc

MainActivity
  // inside onCreate() method
  preview = new Preview(this, surfaceView);
    RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.mainLayout);
    mainLayout.addView(preview);
  preview.setCamera();
  // Other codes .....

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/mainLayout">
<SurfaceView
    android:id="@+id/surfaceView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
</RelativeLayout>

I added onTouchEvent and onInterceptTouchEvent But both are not working. Whenever I touched on sufaceView nothing show in Log I think I'm missing some thing, can you please let me know ?

A:
preview = new Preview(this, surfaceView);
preview.setCamera();
There is just two line code in MainActivity initilizing the Preview and setCamera() nothing else.

Why you do not see onTouchEvent and onInterceptTouchEvent logs?
I assume, that you haven't added that layout to your view hierarchy.
 rootView.addView(preview);

After adding it you should see touch event logs.
But that's not what you actually expect to do, because you have just incorrectly "wrapped" your SurfaceView inside a Java class, which yet doesn't mean that touch events on your SurfaceView would be reflected in your logs.
What you really want is to extend SurfaceView and override those touch events there. Now you would receive correct touch events. Then make sure you are inflating your custom SurfaceView into view hierarchy.
Or, second approach, you can add SurfaceView as a child of your ViewGroup:
yourCustomViewGroup.addView(surfaceView);

A: There are a few issues with your extended class, in that it does not include all required override methods. However I will assume this is still being developed.
In theory this should work:
preview.setOnClickListener( new OnClickListener(){
    @Override
    public void onClick() {
        //do stuff
    }
});

I have not tested it, but as this is extending ViewGroup, this should work.
Note: You probably will need to add this
android:clickable="true"

To your 'Preview' layout, to allow the click to be processed.
Hope that helps.


text:
Q: Keras weight file load exception: loading 2 layers into a model with 0 layers Exception happened when I add dropout to the input layer.
The exception was mentioned in other threads as well related to another issues and most common suggested solution is to downgrade the Keras version. Is there a workaround for this exception?
def baseline_model() :
    model = Sequential()
    model.add(Dropout(0.35)) #THIS LINE CAUSES THE EXCEPTION
    model.add(Dense(200, input_dim=1200, kernel_initializer='normal', activation='relu'))
    model.add(Dropout(0.8))
    rms = RMSprop(lr = 0.00050)
    model.add(Dense(1, kernel_initializer='normal', activation='sigmoid'))
    model.compile(loss='binary_crossentropy', optimizer=rms, metrics=['accuracy'])
    return model

Model throws the following exception during weight file loading:
ValueError: You are trying to load a weight file containing 2 layers into a model with 0 layers.

A: The problem is that you have not assigned the input shape for the first layer:
model.add(Dropout(0.35, input_shape=(1200,)))

And then remove the input_dim argument of second layer as it is redundant.


text:
Q: Content Security Policy meta tag within sandboxed iframe not working in Safari (14.0.2) I'm trying to embed a page whose Content Security Policy does not seem to be respected in Safari, but does works in Chrome, Firefox, Edge, Brave. The embed looks like this:
<iframe src="https://cloudflare-ipfs.com/ipfs/QmUiDhFZeFnJvHgxGbwPucT8kyZvAzBsFFA12vPNxfsP6u/" sandbox="allow-scripts" />

The embedded page looks like this, and contains a CSP meta tag:
<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Security-Policy" content="default-src 'self' 'unsafe-inline';">
    <title>test</title>
    <meta charset="utf-8">
  </head>
  <body>
    <script src="test.js"></script>
  </body>
</html>

The CSP should dictate that the page can load resources from its own origin, as well as inline scripts. However, when I try to load the iframe in Safari, I get an error claiming the path to the script does not match the default-src directive:
Refused to load https://cloudflare-ipfs.com/ipfs/QmUiDhFZeFnJvHgxGbwPucT8kyZvAzBsFFA12vPNxfsP6u/test.js because it appears in neither the script-src directive nor the default-src directive of the Content Security Policy.

The response headers for the embedded page look like this:
headers
Here is a simple jsfiddle demostrating the issue: https://jsfiddle.net/4hLdygm9/1/
Thanks in advance!
UPDATE:
Have open an issue on the Webkit Bugzilla and has been confirmed to be a bug:
https://bugs.webkit.org/show_bug.cgi?id=223848


text:
Q: Probability of at least one triangle in Erdos-Renyi graph Cross-posting here as I didn't get a satisfactory solution on cv.
This is a well-known problem in random graph theory, where we show that if $X$ is the number of triangles in $G(V,E,p)$ with $p=\omega(\frac{1}{n})$, we can show that
$$
P(X \geq 1) \geq 1-o(\frac{1}{n}) \to_n 1
$$
using Chebyshev inequality and asymptotic expansion of binomial coefficients, $\binom{n}{k} \sim \frac{n^k}{k!}$.
What I don't understand is the part where the second moment is used for indicator variables:
$$
\mathbf{E}X^2 = \mathbf{E} (\sum_{k=1}^{\binom{n}{3}} X_k)^2 = \sum_{k=1}^{\binom{n}{3}} \mathbf{E}X^2_k +\sum_{k \neq j}\mathbf{E}X_k X_j
$$
Specifically, I don't understand the absence of 2 in front of the second sum. The explanation is that triangles are ordered. This means that selecting triangle $X_j$ and then $X_k$ is different to $X_k$ and then $X_j$. Essentially I don't understand why $\mathbf{E}X_k X_j \neq \mathbf{E}X_j X_k$. If I solve it with 2 in front of the sum, I don't get the convergence.

A: The square of the sum is expanded into a sum of products. Both $\mathbf EX_1X_2$ and $\mathbf EX_2X_1$ occur in the expansion. You can either leave them like that and write $\sum_{k\ne j}$, or you can combine them and write $2\sum_{k\lt j}$, that's just a matter of convenience. What you can't do is write $2\sum_{k\ne j}$, because then you're counting each pair four times, not just twice.


text:
Q: Bash script - How to know a program has terminated I have created a script that compiles and then executes 4 .c programs.
Now, my script is the following:
#!/bin/sh

echo "Compiling first program. . ."
gcc -o first first.c
echo "File compiled."
echo

echo "Compiling second program. . ."
gcc -o second second.c
echo "File compiled."
echo

echo "Compiling third program. . ."
gcc -o third third.c
echo "File compiled."
echo

echo "Compiling fourth program. . ."
gcc -o fourth fourth.c
echo "File compiled."
echo

./first
./second
./third
./fourth

Every executable file needs to run alone.
The question is: launching the execs in that way, will they be executed simultaneously? How do I know when a program has terminated before launching the following one?

A: Each command in a Bash script will complete before the next one starts, unless you specifically use a feature that does otherwise, such as &:
foo bar &                # starts `foo bar` to run "in the background"
                         # while the script proceeds

or |:
foo | bar                # runs `foo` and `bar` in parallel, with output
                         # from `foo` fed as input into `bar. (This is
                         # called a "pipeline", and is a very important
                         # concept for using Bash and similar shells.)

That said, this doesn't mean that the command completed successfully. In your case, some of your gcc commands might fail, and yet the other programs would still be run. That's probably not what you want. I'd suggest adding something like || { echo "Command failed." >&2 ; exit 1 ; } to each of your commands, so that if they fail (meaning: if they return an exit status other than 0), your script will print an error-message and exit. For example:
gcc -o first first.c || { echo "Compilation failed." >&2 ; exit 1 ; }

and:
./second || { echo "Second program failed." >&2 ; exit 1 ; }

(You can also put this sort of logic in a "function", but that's probably a lesson for another day!)
I recommend reading through a Bash tutorial, by the way, and/or the Bash Reference Manual, to get a better handle on shell scripting.


text:
Q: Geocode error: Error Domain=GEOErrorDomain Code=-8 "(null)" When I run that code I get the error!
 func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let userLocation:CLLocation = locations[0] as CLLocation

    let userLoc = CLLocation(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude )

    for i in 0 ..< streetArray.count{

        let geoCoder = CLGeocoder()
        geoCoder.geocodeAddressString(self.streetArray[i]) { (placemarks, error) in

            let location = placemarks?.first?.location

            let destLoc = CLLocation(latitude: (location?.coordinate.latitude)!, longitude: (location?.coordinate.longitude)! )

            let distanceInMeters = userLoc.distance(from: destLoc)

            self.distanceArray.append(distanceInMeters)

            print(self.distanceArray)

        }

    }

    locationManager.stopUpdatingLocation()

}

Any ideas why I get the error?
The error appears as Thread 1: EXC_Breakpoint ..
The line that the error appeared is
 let destLoc = CLLocation(latitude: (location?.coordinate.latitude)!, longitude: (location?.coordinate.longitude)! )


text:
Q: The range of the coefficients of 2 level Wavelet LeGall 5/3 2D transform As in the title, I am confused about the range of the coefficients of Wavelet LeGall 5/3 (has to be exact this filter) 2D transform (only for a 8*8 block) if the value of the input matrix are within the range from 0-255.
For the formulas, the link is here: Wavelet LeGall 5/3
Here is what I did for now:

*

*Minus 128 for all value (easier to calculate the low frequency values, see later);

*Do the transform in horizontal direction. This will generate all coefficients in all lines: the first 4 are low frequency and last 4 are high frequency. It is easy to find the range for high frequency is -255 to +255 (double the range of input). And the range for low frequency is actually -192 to +192 (1.5* the range of input).

*Do the transform in vertical direction. This will do the same in vertical directions. And there are four blocks generated: LL (lowlow), LH (low high), HL, HH. It is easy to calculate the range for the HH is largest: -511 to +511 and the range for LL is 1.5*1.5 = 2.25 times of the input range (-128 to +127).
Then, here comes the question. What if I do this wavelet again for the LL block? Theoretically the range of the HH (2nd level coefficients) of the LL block should be 4 times of the LL range which becomes 10 times of the input range (-128 to +127) which is -1280 to +1270.
However, I tried many times random calculation, the max value never exceed -511 to +511 (see code at the end). I guess it is because the theoretical values cannot be reached because all calculations are based on the previous one. But this seemly easy question is difficult for me to prove theoretically. So can someone help me get out please?
Code I used (put two files in one directory and run the test file for any times you want but just the max value will not exceed 512...):

*

*Function of waveletlegall53:
function X = waveletlegall53(X, Level)
%WAVELETLEGALL53  Le Gall 5/3 (Spline 2.2) wavelet transform.
%   Y = WAVELETLEGALL53(X, L) decomposes X with L stages of the
%   Le Gall 5/3 wavelet.  For the inverse transform,
%   WAVELETLEGALL53(X, -L) inverts L stages.  Filter boundary
%   handling is half-sample symmetric.
%
%   X may be of any size; it need not have size divisible by 2^L.
%   For example, if X has length 9, one stage of decomposition
%   produces a lowpass subband of length 5 and a highpass subband
%   of length 4.  Transforms of any length have perfect
%   reconstruction (exact inversion).
%
%   If X is a matrix, WAVELETLEGALL53 performs a (tensor) 2D
%   wavelet transform.  If X has three dimensions, the 2D
%   transform is applied along the first two dimensions.
%
%   Example:
%   Y = waveletlegall53(X, 5);    % Transform image X using 5 stages
%   R = waveletlegall53(Y, -5);   % Reconstruct from Y

X = double(X);
if nargin < 2, error('Not enough input arguments.'); end
if ndims(X) > 3, error('Input must be a 2D or 3D array.'); end
if any(size(Level) ~= 1), error('Invalid transform level.'); end

N1 = size(X,1);
N2 = size(X,2);

% Lifting scheme filter coefficients for Le Gall 5/3
LiftFilter = [-1/2,1/4];
ScaleFactor =1; sqrt(2);

LiftFilter = LiftFilter([1,1],:);

if Level >= 0   % Forward transform
    for k = 1:Level
    M1 = ceil(N1/2);
    M2 = ceil(N2/2);

%%% Transform along columns %%%
if N1 > 1
 RightShift = [2:M1,M1];
 X0 = X(1:2:N1,1:N2,:);

 % Apply lifting stages
 if rem(N1,2)
    X1 = [X(2:2:N1,1:N2,:);X0(M1,:,:)]...
       +floor(filter(LiftFilter(:,1),1,X0(RightShift,:,:),...
       X0(1,:,:)*LiftFilter(1,1),1));
 else
    X1 = X(2:2:N1,1:N2,:) ...
       +floor(filter(LiftFilter(:,1),1,X0(RightShift,:,:),...
       X0(1,:,:)*LiftFilter(1,1),1));
 end

 X0 = X0 + floor(filter(LiftFilter(:,2),1,...
    X1,X1(1,:,:)*LiftFilter(1,2),1)+0.5);

 if rem(N1,2)
    X1(M1,:,:) = [];
 end

 X(1:N1,1:N2,:) = [X0*ScaleFactor;X1/ScaleFactor];

end

%%% Transform along rows %%%
if N2 > 1
 RightShift = [2:M2,M2];
 X0 = permute(X(1:N1,1:2:N2,:),[2,1,3]);

 % Apply lifting stages
 if rem(N2,2)
    X1 = permute([X(1:N1,2:2:N2,:),X(1:N1,N2,:)],[2,1,3])...
       + floor(filter(LiftFilter(:,1),1,X0(RightShift,:,:),...
       X0(1,:,:)*LiftFilter(1,1),1));
 else
    X1 = permute(X(1:N1,2:2:N2,:),[2,1,3]) ...
       + floor(filter(LiftFilter(:,1),1,X0(RightShift,:,:),...
       X0(1,:,:)*LiftFilter(1,1),1));
 end

 X0 = X0 +floor( filter(LiftFilter(:,2),1,...
    X1,X1(1,:,:)*LiftFilter(1,2),1)+0.5);

 if rem(N2,2)
    X1(M2,:,:) = [];
 end

 X(1:N1,1:N2,:) = permute([X0*ScaleFactor;X1/ScaleFactor],[2,1,3]);
 end

 N1 = M1;
N2 = M2;
end
else           % Inverse transform
for k = 1+Level:0
M1 = ceil(N1*pow2(k));
M2 = ceil(N2*pow2(k));

%%% Inverse transform along rows %%%
if M2 > 1
 Q = ceil(M2/2);
 RightShift = [2:Q,Q];
 X1 = permute(X(1:M1,Q+1:M2,:)*ScaleFactor,[2,1,3]);

 if rem(M2,2)
    X1(Q,1,1) = 0;
 end

 % Undo lifting stages
 X0 = permute(X(1:M1,1:Q,:)/ScaleFactor,[2,1,3]) ...
    - floor(filter(LiftFilter(:,2),1,X1,X1(1,:,:)*LiftFilter(1,2),1)+0.5);
 X1 = X1 - floor(filter(LiftFilter(:,1),1,X0(RightShift,:,:),...
    X0(1,:,:)*LiftFilter(1,1),1));

 if rem(M2,2)
    X1(Q,:,:) = [];
 end

 X(1:M1,[1:2:M2,2:2:M2],:) = permute([X0;X1],[2,1,3]);
end

%%% Inverse transform along columns %%%
if M1 > 1
 Q = ceil(M1/2);
 RightShift = [2:Q,Q];
 X1 = X(Q+1:M1,1:M2,:)*ScaleFactor;

 if rem(M1,2)
    X1(Q,1,1) = 0;
 end

 % Undo lifting stages
 X0 = X(1:Q,1:M2,:)/ScaleFactor ...
    - floor(filter(LiftFilter(:,2),1,X1,X1(1,:,:)*LiftFilter(1,2),1)+0.5);
 X1 = X1 - floor(filter(LiftFilter(:,1),1,X0(RightShift,:,:),...
    X0(1,:,:)*LiftFilter(1,1),1));

 if rem(M1,2)
    X1(Q,:,:) = [];
 end

 X([1:2:M1,2:2:M1],1:M2,:) = [X0;X1];
end
end
end

*The test .m file:
clear all
close all
clc

n=100000;
maxt=zeros(1,n);
maxt2=zeros(1,n);
for it=1:n
    X=floor(rand(8,8)*256);
    X = X-128;
    a = waveletlegall53(X,2);
    maxt(it)=max(max(abs(a)));
    if max(max(abs(a))) > 470
        max(max(abs(a)))
     end

end
[fr ind]=hist(maxt,length(unique(maxt)));
pr = length(find(maxt>512))/n
fr=fr/n;

figure()
plot(ind, fr)
grid on

Maxvalue = max(maxt)


text:
Q: How to properly hydrate and extract Doctrine Entities from Zend Forms I'm just starting out with Doctrine and was rewriting some code to use Doctrine entities in some Forms.
I have an Entity Business which has some 1:n relations with addresses, employees, emails etc. the Setup is really basic and working fine.
To add new Businesses i created a BusinessForm and Fieldsets for each of my entities. Here the constructor of the form:
public function __construct($scenario='create', $entityManager = null) {
    parent::__construct('business_form');
    $this->scenario = $scenario;
    $this->entityManager = $entityManager;
    $this->setAttribute('method', 'post');

    $businessFieldset = new BusinessFieldset($this->entityManager);
    $businessFieldset->setUseAsBaseFieldset(true);
    $this->add($businessFieldset);

    $hydrator = new DoctrineHydrator($this->entityManager, new Business());
    $this->setHydrator($hydrator);
    $this->addElements();
    $this->addInputFilter();
}

addElements just adds a Submit and CSRF input.
And here the Controller action:
public function addAction(){
    $form = new BusinessForm('create', $this->entityManager);
    if ($this->getRequest()->isPost()) {
        $data = $this->params()->fromPost();
        $form->setData($data);
        if($form->isValid()) {
            // save Object
            return $this->redirect()->toRoute('subcontractor', ['action'=>'index']);
        }
    }
    return new ViewModel([
        'form' => $form
    ]);
}

The form validates and i can get the Data from the form with $form->getData(). But i cant figure out how to get a populated Object from the form using the form's hydrator. When I use setObject(new Business()) at the start of the controller i get an error while $form->isValid() is running :
Zend\Hydrator\ArraySerializable::extract expects the provided object to implement getArrayCopy()

Isnt that the wrong hydrator being called ?
If i dont setObject() but instead use $form->bind(new Business()) after the validation i get an empty Object from $form->getObject(). If i get the data and hydrate a new Object with the form's hydrator like so : $form->getHydrator()->hydrate($data['business], new Business()) i do get the populated Object i was expecting. (Business being the name of the base fieldset)
So my question is, how to i get the result of the last call from just using $form->getObject() after the validation?
[EDIT]
The Problem seems to be with the Collections of Fieldsets used as sub-fieldsets in the businessfieldset. If i validate the form without using the collections i do get the expected Business Object from $form->getData()
Here an example how i add the collection (in the business fieldset):
$this->add([
        'name' => 'emails',
        'type' => 'Zend\Form\Element\Collection',
        'attributes' => [
            'id' => 'business_emails',
        ],
        'options' => [
            'label' => 'Emails',
            'count' => 1,
            'should_create_template' => true,
            'template_placeholder' => '__index__',
            'allow_add' => true,
            'target_element' => [
                'type' => 'LwsSubcontractor\Form\EmailFieldset',
            ],
            'target_class' => 'LwsSubcontractor\Entity\Email'
        ],
    ]);

and here the EmailFieldset:
public function __construct() {
    parent::__construct('email');
    $this->setObject(new Email());
    $this->addElements();
}

protected function addElements() {
    $this->add([
        'name' => 'email',
        'type' => 'Zend\Form\Element\Email',
        'attributes' => [
            'placeholder' => 'E-Mail (z.B. email@muster-email.de)',
            'class' => 'form-control',
            'required' => true,
            'size' => 50,
        ],
        'options' => [
            'label' => 'Email',
        ],
    ]);

}
}
If using the Collections i get the Error message from above. So after adding a hydrator to each Fieldset i was fine.
Although i was under the impression that setting the hydrator for the form would result in the used fieldsets to inherit that hydrator.Or was this because of using the fieldsets as collections and not directly ?

A: You have to add the hydrator to all your fieldsets, personally I use DoctrineModule\Stdlib\Hydrator\DoctrineObject for doctrine entities.
I would also look at using the init() method to initialize your forms and add elements then register and retrieve your form and fieldsets through the FormElementManager, $serviceLocator->get('FormElementManager')->get(yourFieldsetorForm::class).  The form can than be injected into your controller.
I hope this helps.


text:
Q: (Linux) Are printk() messages supposed to go to /dev/console? If so, why aren't they appearing? I am trying to teach myself Linux kernel development by working through Linux Device Drivers, and I'm currently on the chapter about debugging. From everything I've read, printk() messages are supposed to go to "the console", which from what I understand, is usually represented by the device "/dev/console".
The problem is that I can not get any of my pritnk statements to appear when I monitor /dev/console using the xconsole utility. My messages DO appear in the system logs, and I can see my messages when I use dmesg. So I am not asking about this for practical purposes, but rather to fill in my own gaps in understanding the Linux system.
I set my printk messages to the highest log level (KERNEL_EMERG), just to be sure they weren't getting filtered. I used dmesg -E which supposedly "enables console logging", but nothing worked.
I am running Kubuntu 20, with custom kernel 5.4.55. with the kernel debugging config option enabled. Here is my /proc/cmdline file:
BOOT_IMAGE=/boot/vmlinuz-5.4.55 root=UUID=3978ed71-51b0-4505-83b9-58401946ed0f ro console=tty0 vt.handoff=7
Here is my /proc/sys/kernel/printk :
4       4       1       7
And here is my kernel configurations:
https://pastebin.com/ijAS6tVa
Thank you for your help
Edit
To addition to @user433151's answer, I found that printk() messages only appear on the currently active virtual terminal, even when the console is explicitly set during boot. For example, booting with console=tty2 only seems to effect the fact that /dev/console "points" to tty2, it does not make tty2 the "target" console for kernel messages. It appears the default "target" console for kernel messages is always tty0, so in order for printk messages to appear on tty2, tty2 must the be the currently active virtual terminal at the time the printk message is written. Part of my confusion came from running my modules on tty1, then switching to tty2 only to find my printk statements not appearing. My solution was to start the modules in tty2, or to redirect messages with ioctl(TIOCL_SETKMSGREDIRECT)

A: xconsole (1) can only get what user-land programs write to /dev/console, but not any kernel messages written to any of the terminals /dev/console is a kind of alias for (2).
The printk kernel messages can only go to

*

*a linux virtual terminal like /dev/tty0 (but not to any pseudo-terminal or terminal emulator) (3). "Virtual terminals" are those "black" non-gui terminals you can switch through with Ctrl-Alt-Fx on a PC running Linux.

*a serial console like /dev/ttyS0 (but not to any serial-over-USB console or similar).

*the dmesg buffer, from where they're picked by the system logger (whether rsyslog or some systemd thing) or by programs like dmesg.
(1) xconsole works by creating a pseudo terminal, and redirecting there with ioctl(TIOCCONS) any userland writes to /dev/console.
(2) Linux has no interface to get which terminal /dev/console refers to; the only way to get that info is by live-debugging the kernel ;-)
(3) /dev/tty0 is an alias for the currently "focused" virtual terminal. You can redirect kernel messages to another virtual terminal with ioctl(TIOCL_SETKMSGREDIRECT).

A: There is a way to see all the printk messages.  Boot up the linux OS  in the text mode.  I tried it with Raspbian OS.  Set the option to boot up in the text mode via (sudo raspi-config).
You are logging into a text mode because none of the messages can be displayed on a terminal of GUI.  This is the reason.
After the bootup,
Type tty at the command prompt to confirm that it is indeed /dev/console.
$tty
/dev/tty1
If you set console=tty1 in /boot/cmdline.txt file, you get /dev/tty1.
Now all the printk messages will appear immediately without dmesg.


text:
Q: Cardinality of a finite field is $p^{n}$
Theorem:
Let F be a finite field of characteristic p.
Then p is a prime and $\left | F \right |=p^{n},\left [ \exists n>0 \right ] \in \mathbb{N}$

Note that the characteristic of F denoted Char\left ( F \right )=p \neq 0
$\mathbf{For\space each \space \lambda \in \mathbb{Z}_{p} \space and \space a\in F}$
then $\lambda\cdot a=a+\cdot \cdot \cdot +a$
and $\lambda \cdot a \in F$ by definition of ring.
The ring axiom implies that F is a vector space over $\mathbb{Z}_{p}$. Since F is finite, F has finite dimension and so have a finite basis $b=\left \{ \vec{e}_{1},\cdot \cdot \cdot \vec{e}_{n} \right \}$
In a vector space, every vector element \alpha is a unique linear-combination of basis vector
so $\forall \alpha \in F$,
$\alpha =p_{1}\vec{e}_{1}+\cdot \cdot \cdot +p_{n}\vec{e}_{n} \forall \left \{ p_{i} \right \}^{n}_{i=1}$
so, $\mathbf{the \space size \space of \space F \space is\space p^{n}}$.
Two questions:
What is the motivation behind the first highlighted bold?
Secondly, is $\left | F \right |=p^{n}$ to be interpreted as $\left | F \right |=n\cdot p$
?

A: I guess $Z_p$ plays role of scalars in the definition of vector spaces, while the elements of $F$ are vectors. $\lambda \cdot a$ is just a notation for multiplication of a vector $a$ by a scalar $\lambda$.
Note also that the finite field of order $p^n$ can be constructed using an irreducible polynomial $p(x)$ of order $n$ with coefficients in $Z_p$. So we can treat the finite field of order $p^n$ as a set of polynomials in $Z_p[x]$ with order between $0$ and $n-1$, consider them as vectors. Then elements of $Z_p$ are scalars. Multiplication and addition are performed mod $p(x)$.


text:
Q: Intervention Image. Get md5 hash I using intervention library. And want to get md5($image), not hash of image path.
I am doing $interventionPicture = Image::make($pictureUrl)  and get object.
Just saw someting like that: md5(file_get_contents($file->path())).
But need to use Intervention way.
Thanks.


text:
Q: ListView Rowlayout in a own coded Chat What I'm trying to do
I'm trying to create a chat which has to diffrent row's. For every row I made a own layout file, but the problem is that the layoutfile of one row dosn't fit the screen.
Question
What do I need to change in the row layout that it fits like it should. You'll find the code and also a printscreen of what I'm trying.

Code

ListAdapter
    public class ChatListAdapter extends BaseAdapter {
            private ArrayList<String> ContentList;
            private ArrayList<Integer> ChatUserList;

            private static LayoutInflater inflater = null;

            public ChatListAdapter(Activity activity, ArrayList<String> _ContentList,
                                   ArrayList<Integer> _ChatUserList) {
                        ContentList = _ContentList;
                        ChatUserList = _ChatUserList;
                        inflater = (LayoutInflater) activity
                                               .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            }

            public int getCount() {
                        return ContentList.size();
            }

            public Object getItem(int position) {
                        return position;
            }

            public long getItemId(int position) {
                        return position;
            }

            public View getView(int position, View convertView, ViewGroup parent) {
                        View vi = convertView;
                        TextView tv_text;
                        TextView tv_date;

                        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

                        if (ChatUserList.get(position) == 1) {
                                   // I'm RECIVER -> Message is left align
                                   vi = inflater.inflate(R.layout.rowlayout_leftalign, null);
                                   tv_text = (TextView) vi.findViewById(R.id.tv_chat_leftalign);
                                   tv_date = (TextView) vi.findViewById(R.id.tv_chat_leftalign_date);
                        } else {
                                   // I'm SENDER -> Message is right align
                                   vi = inflater.inflate(R.layout.rowlayout_rightalign, null);
                                   tv_text = (TextView) vi.findViewById(R.id.tv_chat_rightalign);
                                   tv_date = (TextView) vi.findViewById(R.id.tv_chat_rightalign_date);
                        }

                        tv_date.setText(sdf.format(new Date()));
                        tv_text.setText(ContentList.get(position));
                        tv_text.setMaxWidth(((Chat.display.getWidth() / 4) * 3));

                        return vi;
            }

RowLayout XML Left (Blue bubbles)
 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="@android:color/transparent" >

    <RelativeLayout
        android:id="@+id/ly_rf_row_r"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="2.5dp"
        android:layout_marginTop="2.5dp"
        android:background="@drawable/shape_rightalign"
        android:paddingBottom="2.5dp"
        android:paddingTop="2.5dp" >

        <TextView
            android:id="@+id/tv_chat_rightalign"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:gravity="right"
            android:paddingBottom="2dp"
            android:paddingLeft="5dp"
            android:paddingRight="5dp"
            android:paddingTop="2dp"
            android:textColor="@android:color/black" />

        <TextView
            android:id="@+id/tv_chat_rightalign_date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_marginBottom="-3dp"
            android:layout_marginLeft="-3dp"
            android:layout_toLeftOf="@id/tv_chat_rightalign"
            android:paddingLeft="4dp"
            android:paddingRight="4dp"
            android:textColor="@android:color/black"
            android:textSize="8.5dp" />
    </RelativeLayout>

</RelativeLayout>

RowLayout XML right (red bubbles)
 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="@android:color/transparent" >

    <RelativeLayout
        android:id="@+id/ly_rf_row_l"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginBottom="2.5dp"
        android:layout_marginTop="2.5dp"
        android:background="@drawable/shape_leftalign"
        android:paddingBottom="2.5dp"
        android:paddingTop="2.5dp" >

        <TextView
            android:id="@+id/tv_chat_leftalign"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:gravity="left"
            android:paddingBottom="2dp"
            android:paddingLeft="5dp"
            android:paddingRight="5dp"
            android:paddingTop="2dp"
            android:textColor="@android:color/black" />

        <TextView
            android:id="@+id/tv_chat_leftalign_date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_marginBottom="-3dp"
            android:layout_marginLeft="-3dp"
            android:layout_toRightOf="@id/tv_chat_leftalign"
            android:paddingLeft="4dp"
            android:paddingRight="4dp"
            android:textColor="@android:color/black"
            android:textSize="8.5dp" />
    </RelativeLayout>

</RelativeLayout>

A: for both XML add  android:layout_width="fill_parent" and android:layout_height="wrap_content" like followings
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:background="@android:color/transparent"
            android:layout_height="wrap_content"
            android:layout_width="fill_parent" >

and so on...


text:
Q: A urn contains blue balls and red balls. I need to find probabiltiy of drawing more blue balls than red balls
A urn contains 5 identical blue balls and 4 identical red balls. Taking 5 balls at random from the urn what is the probability that the number of blue balls be greater than the number of red balls?

My first guess was setting the ways that I can draw the balls.
It was:

$\color{blue} {BBBBB}$ ; $\color{blue} {BBBB}\color{red}{R}$; $\color{blue} {BBB}\color{red}{RR}$; $\color{blue} {BB}\color{red}{RRR}$; $\color{blue} {B}\color{red}{RRRR}$

Only $3$ cases have the number of blue balls greater than the number of red balls. Then the odds must be $\displaystyle{\frac{3}{5}}$.
But this answer sounds strange for me. I think that it is wrong?
Could anyone help me how to figure out this question?

A: Three approaches:
(1) This can be viewed as a hypergeometric distribution. The urn contiains
four red balls and five blue balls. Let $X$ be the number of red balls
among five balls drawn at random without replacement. To draw more blue balls
then red you need to evaluate $P(X \le 2).$  In R statistical software
this can be evaluated as follows:
phyper(2, 4, 5, 5)
## 0.6428571

(2) The equivalent answer can be obtained using a combinatorial argument:
$$\frac{{4 \choose 0}{5 \choose 5}+{4\choose 1}{5 \choose 4}+{4 \choose 2}{5 \choose 3}}{{9 \choose 5}} = \frac{1 + 20 + 60}{126} = 81/126 = 9/14 = 0.6428571$$
(3) An approximate value (to about 3 places) from simulating a million draws of five balls from
such an urn and counting the red balls can be obtained as follows:
set.seed(616)
m = 10^6;  urn = c(1,1,1,1,1,2,2,2,2)    # 1 = blue, 2 = red
r = replicate(m, sum(sample(urn, 5)==2)) # sample 5 balls without replacement
mean(r <= 2)                             # mean of logical vector is nr of TRUEs
## 0.642822

The histogram below shows the simulated hypergeometric distribution of the number of red balls drawn. The open red dots show exact hypergeometric probabilities.
At the scale of the graph, it is not easy to see any difference between the
simulated and exact values.

Note: You should be sure you understand and can explain the details of either method (1) or method (2) for your class. The simulation is probably not something you are expected to know.

A: Hint
There are $31$ permutations for selecting $5$ balls:
$$\left(
\begin{array}{ccccc}
 \color{blue}{B} & \color{blue}{B} & \color{blue}{B} & \color{blue}{B} & \color{blue}{B} \\
 \color{blue}{B} & \color{blue}{B} & \color{blue}{B} & \color{blue}{B} & \color{red}{R} \\
 \color{blue}{B} & \color{blue}{B} & \color{blue}{B} & \color{red}{R} & \color{blue}{B} \\
 \color{blue}{B} & \color{blue}{B} & \color{blue}{B} & \color{red}{R} & \color{red}{R} \\
 \color{blue}{B} & \color{blue}{B} & \color{red}{R} & \color{blue}{B} & \color{blue}{B} \\
 \color{blue}{B} & \color{blue}{B} & \color{red}{R} & \color{blue}{B} & \color{red}{R} \\
 \color{blue}{B} & \color{blue}{B} & \color{red}{R} & \color{red}{R} & \color{blue}{B} \\
 \color{blue}{B} & \color{blue}{B} & \color{red}{R} & \color{red}{R} & \color{red}{R} \\
 \color{blue}{B} & \color{red}{R} & \color{blue}{B} & \color{blue}{B} & \color{blue}{B} \\
 \color{blue}{B} & \color{red}{R} & \color{blue}{B} & \color{blue}{B} & \color{red}{R} \\
 \color{blue}{B} & \color{red}{R} & \color{blue}{B} & \color{red}{R} & \color{blue}{B} \\
 \color{blue}{B} & \color{red}{R} & \color{blue}{B} & \color{red}{R} & \color{red}{R} \\
 \color{blue}{B} & \color{red}{R} & \color{red}{R} & \color{blue}{B} & \color{blue}{B} \\
 \color{blue}{B} & \color{red}{R} & \color{red}{R} & \color{blue}{B} & \color{red}{R} \\
 \color{blue}{B} & \color{red}{R} & \color{red}{R} & \color{red}{R} & \color{blue}{B} \\
 \color{blue}{B} & \color{red}{R} & \color{red}{R} & \color{red}{R} & \color{red}{R} \\
 \color{red}{R} & \color{blue}{B} & \color{blue}{B} & \color{blue}{B} & \color{blue}{B} \\
 \color{red}{R} & \color{blue}{B} & \color{blue}{B} & \color{blue}{B} & \color{red}{R} \\
 \color{red}{R} & \color{blue}{B} & \color{blue}{B} & \color{red}{R} & \color{blue}{B} \\
 \color{red}{R} & \color{blue}{B} & \color{blue}{B} & \color{red}{R} & \color{red}{R} \\
 \color{red}{R} & \color{blue}{B} & \color{red}{R} & \color{blue}{B} & \color{blue}{B} \\
 \color{red}{R} & \color{blue}{B} & \color{red}{R} & \color{blue}{B} & \color{red}{R} \\
 \color{red}{R} & \color{blue}{B} & \color{red}{R} & \color{red}{R} & \color{blue}{B} \\
 \color{red}{R} & \color{blue}{B} & \color{red}{R} & \color{red}{R} & \color{red}{R} \\
 \color{red}{R} & \color{red}{R} & \color{blue}{B} & \color{blue}{B} & \color{blue}{B} \\
 \color{red}{R} & \color{red}{R} & \color{blue}{B} & \color{blue}{B} & \color{red}{R} \\
 \color{red}{R} & \color{red}{R} & \color{blue}{B} & \color{red}{R} & \color{blue}{B} \\
 \color{red}{R} & \color{red}{R} & \color{blue}{B} & \color{red}{R} & \color{red}{R} \\
 \color{red}{R} & \color{red}{R} & \color{red}{R} & \color{blue}{B} & \color{blue}{B} \\
 \color{red}{R} & \color{red}{R} & \color{red}{R} & \color{blue}{B} & \color{red}{R} \\
 \color{red}{R} & \color{red}{R} & \color{red}{R} & \color{red}{R} & \color{blue}{B} \\
\end {array}
\right)$$
(Was too long to post as a comment, my apologies)


text:
Q: Whats the meaning of "she and Evan were about as fat as popsicle sticks " in this paragraph. Is it an idiom? He'll pick up anything. The diet book, for instance that was just ridiculous. She and Evan were about as fat as popsicle sticks.

A: This is a joke. Since popsicle sticks are in fact very thin, the joke is that, despite considering themselves fat, they are not fat at all.


text:
Q: How to DRY up my switch statement which does almost the same thing in each scenario? I have a function which conjugates a verb in latin given the word(object), voice(string), and tense(string). For reference active and passive are the voices and then present, imperfect etc... are the tenses.
Essentially my nested switch statements just run different functions with very similar names and purposes and I was wondering if there was some way to make it more efficient that I am not thinking of because it seems very redundant and clunky.
Any help would be appreciated and here is my code below:
function getChart(word, voice, tense) {

//Root word variables
var inf = word.inf;
var pp3 = word.pp3;
var pp4 = word.pp4;
var conj = word.conj;

//If voice is active go to the active charts for the tense
//If voice is passive go to the passive charts for the tense
switch(voice) {
    case "Active":
        switch(tense) {
            case "Present":
                activePresentConj(inf, conj);
                break;
            case "Imperfect":
                activeImperfectConj(inf, conj);
                break;
            case "Future":
                activeFutureConj(inf, conj);
                break;
            case "Perfect":
                activePerfectConj(pp3);
                break;
            case "Plu Perfect":
                activePluPerfectConj(pp3);
                break;
            case "Future Perfect":
                activeFuturePerfectConj(pp3);
                break;
            default:
                return null;
        }
        break;
    case "Passive":
        switch(tense) {
            case "Present":
                passivePresentConj(inf, conj);
                break;
            case "Imperfect":
                passiveImperfectConj(inf, conj);
                break;
            case "Future":
                passiveFutureConj(inf, conj);
                break;
            case "Perfect":
                passivePerfectConj(pp4);
                break;
            case "Plu Perfect":
                passivePluPerfectConj(pp4);
                break;
            case "Future Perfect":
                passiveFuturePerfectConj(pp4);
                break;
            default:
                return null;
        }
        break;
    default:
        return null;
}

}

A: You could just switch on tense and pass the voice into a more general conjugation method that handles both active and passive voices.
Ex:
switch(tense) {
    case "Present":
        presentConj(inf, conj, voice);
        break;
    case "Imperfect":
        imperfectConj(inf, conj, voice);
        break;
    case "Future":
        futureConj(inf, conj, voice);
        break;
    case "Perfect":
        perfectConj(pp3, voice);
        break;
    case "Plu Perfect":
        pluPerfectConj(pp3, voice);
        break;
    case "Future Perfect":
        futurePerfectConj(pp3, voice);
        break;
    default:
        return null;
}

A: You could use a dictionary to hold references to functions, like this
//Add this to your initialization routine
var dict = {};
dict["Present"] = presentConj;
dict["Imperfect"] = imperfectConj;
dict["Future"] = futureConj;

//use this code to process a particular tense
var func = dict[tense];
if (func == undefined) return null;
func(inf, conj, voice);

This is just a simple example.  To make it work in your case, you'd have to define all of the functions so that they take the same parameters (even if they don't necessarily use all of them).  And you might need two dictionaries (one for passive and one for active) or you could concatenate voice and tense into a single string for the dictionary lookup.


text:
Q: Using a variable as an index for a list Can't find a way around this anywhere else.
Using Python 3.7
rowNum = input
row = [1,2,3,4,5,6,7,8,9]
print(row[rowNum])

This is an overly simplified example of my program.
Basically all i want to do is make it so that i can use whatever value is entered into "rowNum" as the index. I'm getting "Keyerror : Number inputted"
Not sure how to fix.
(I am relativley new to this site so excuse me for bad formatting if any)

A: rowNum = int(input())
row = [1,2,3,4,5,6,7,8,9]
print(row[rowNum])

A: You have to actually grab the user input:
rowNum = int(input("Enter a row number: "))
row = [1,2,3,4,5,6,7,8,9]
print(row[rowNum])

Convert it to an integer, a list will not take a string. Here is your output:
Enter a row number: 4
5


text:
Q: vue-cli jest setting problems when npm run serve After I installed jest, setup babel, eslint, jest-setup and etc then I checked jest works fine.
 But when I npm run serve(vue-clie-service serve), It includes test folders(__test __/abc.spec.js).
I would like to exclude all files below __test
__ direcotry when npm run serve.
It occurs error now jest is not defined. describe is note defined...
#jest.config.js

module.exports = {
  moduleFileExtensions: [
    "js",
    "json",
    "vue",
  ],

  transform: {
    ".*\\.(vue)$": "vue-jest",
    "^.+\\.js$": "<rootDir>/node_modules/babel-jest",
    ".+\\.(css|styl|less|sass|scss)$": "jest-transform-css",
  },

  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/src/$1",
    "\\.(css|less|scss|sass)$": "identity-obj-proxy",
  },

  transformIgnorePatterns: ["<rootDir>/node_modules/"],
  collectCoverage: false,
  collectCoverageFrom: ["**/*.{js,vue}", "!**/node_modules/**"],
  coverageReporters: ["html", "text-summary"],

  testMatch: [
    "<rootDir>/src/**/__tests__/**/*.{js,jsx,mjs}",
    "<rootDir>/src/**/?(*.)(spec|test).{js,jsx,mjs}",
  ],

  setupFilesAfterEnv: ["<rootDir>/jest-setup.js"],
  preset: "@vue/cli-plugin-unit-jest",
};

# main.js

import Vue from "vue";
import "./plugins/axios";
import App from "./App";
import router from "./router";
import store from "./store";
import i18n from "./plugins/i18n";
import vuetify from "./plugins/vuetify";
import "@/assets/styles/_global.scss";
import "@babel/polyfill";

Vue.config.productionTip = false;

new Vue({
  i18n,
  router,
  store,
  vuetify,
  render: h => h(App),
}).$mount("#app");

# vue.config.js
const path = require("path");
const ansiRegex = require("ansi-regex");

module.exports = {
  devServer: {
    proxy: {
      "/api": {
        target: process.env.VUE_APP_TARGET,
        changeOrigin: true,
      },
    },
  },
  configureWebpack: {
    resolve: {
      alias: {
        "@": path.join(__dirname, "src/"),
      },
    },
  },
  css: {
    loaderOptions: {
      scss: {
        prependData: "@import \"@/assets/styles/_global.scss\";",
      },
    },
  },
  transpileDependencies: [
    "vuetify",
    ansiRegex,
  ],
};

A: i try to help you but could you share jest.config.js or another config file.
Could you try this code on config file.
Attention: You must edit your folder path and if you don't use Typescript, you delete ts and tsx.
#jest.config.js
module.exports = {
  preset: 'ts-jest',
  verbose: true,
  collectCoverage: true,
  collectCoverageFrom: [
    '**/*.{ts,vue}',
    '!**/node_modules/**',
    '!**/vendor/**'
  ],
  coverageReporters: [
    'json', 'lcov', 'text'
  ],
  moduleFileExtensions: [
    'js',
    'jsx',
    'json',
    'vue',
    'ts',
    'tsx'
  ],
  transform: {
    '^.+\\.vue$': 'vue-jest',
    '.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
    '^.+\\.tsx?$': 'ts-jest',
    '^.+\\.ts?$': 'ts-jest',
    '^.+\\.jsx?$': 'babel-jest',
    '^.+\\.js?$': 'babel-jest'
  },
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1',
    '^@/application/(.*)$': '<rootDir>/src/application/$1',
    '^@/common/(.*)$': '<rootDir>/src/common/$1',
    '^@/components/(.*)$': '<rootDir>/src/components/$1'
  },
  transformIgnorePatterns: [
    '/node_modules/(?!(tiny-slider)/(.*)$)'
  ],
  snapshotSerializers: [
    'jest-serializer-vue'
  ],
  testMatch: [
    '**/src/**/*.spec.(js|jsx|ts|tsx)',
    '**/src/application/**/*.spec.(js|jsx|ts|tsx)',
    '**/src/common/**/*.spec.(js|jsx|ts|tsx)',
    '**/src/components/**/*.spec.(js|jsx|ts|tsx)',
    '**/tests/unit/**/*.spec.(js|jsx|ts|tsx)'
  ],
  testURL: 'http://localhost:8080/'
}


text:
Q: android - Picasso with OkHTTP can not load images containing vertical bar character ( "|" ) in their URL I use Picasso and MapBox in my project. As long as MapBox has OkHTTP in it's dependecies, I'm forced to use OkHTTP.
But when I add OkHTTP to gradle dependencies, Picasso becomes unable to load images containing vertical bar character ( "|" ) in their URL.
Without OkHTTP:
Picasso.with(context).load("http://example.com/image.jpg").into(imageView); //OK
Picasso.with(context).load("http://example.com/image.jpg|100:100").into(imageView); //OK
With OkHTTP:
Picasso.with(context).load("http://example.com/image.jpg").into(imageView);
 //09-01 19:07:35.280  24916-24916/com.test D/Picasso﹕ Main        errored      [R6]+287ms
Picasso.with(context).load("http://example.com/image.jpg|100:100").into(imageView); //OK
So, my question is: How to avoid using OkHTTP with Picasso if another library needs OkHTTP or how to resolve this problem and continue using OkHTTP?

A: Try OkHttp 2.5.0. It supports URLs containing the | character.

A: I have resolved the problem by adding the next code in MyApplication.onCreate() method:
    Picasso picasso = new Picasso.Builder(getApplicationContext())
            .requestTransformer(new Picasso.RequestTransformer() {
                @Override
                public Request transformRequest(Request request) {
                    Uri oldImageUri = request.uri;
                    Uri newImageUri = oldImageUri.buildUpon().query(oldImageUri.getEncodedQuery()).build();
                    return request.buildUpon().setUri(newImageUri).build();
                }
            }).build();
    picasso.setLoggingEnabled(true);
    Picasso.setSingletonInstance(picasso);

A: I had the same problem when I started using OkHttp. The issue seems to be that the vertical bar character must be encoded. Just replace it with the encoded value (%7C) and it should work fine. In your case the url becomes:
http://example.com/image.jpg%7C100:100


text:
Q: Drawing vector addition Lets say I have the following arrays which contain the X and Y values for a bunch of vectors, respectively:
xdat = np.array([3,2,7,4])
ydat = np.array([2,4,4,9])

Lets say that I wanted to draw the sum total of these vectors (a+b+c+d), not only as a single line from the origin, but drawn sequentially from the sum of each individual vector.
How do I do this?
My idea is to use plt.plot for the values of two new arrays which contain the X and Y coordinates for each start/end point of all the vectors. The specific coordinates would be calculated from xdat and ydat. Assuming this was the most efficient method (without resorting to some easy-to-use function already built into python) how would I code this?

A: It sounds like you want numpy.cumsum
import numpy as np

xdat = np.array([3,2,7,4])
ydat = np.array([2,4,4,9])

dat = np.vstack((xdat, ydat))
# array([[3, 2, 7, 4],
#        [2, 4, 4, 9]])

dat = np.cumsum(dat, axis=1)
# array([[ 3,  5, 12, 16],
#        [ 2,  6, 10, 19]], dtype=int32)

# optionally start at 0, 0 (can do this before or after cumsum)
dat = np.hstack([np.zeros((2, 1)), dat])
# array([[  0.,   3.,   5.,  12.,  16.],
#        [  0.,   2.,   6.,  10.,  19.]])

I stacked them up for convenience, but you could also run cumsum on the 1-D arrays.  The axis argument selects either to run over the whole flattened array (None, the default), or along the n-th axis (row = 0, column = 1)
If you want to plot the X-Y coordinates, I'd do so with plt.plot(*dat), which will unpack the X and Y rows as arguments to plot.


text:
Q: How to send embed in direct messeger I want to send this embed in direct. How can i send this embed in ditect?
@bot.commnd()
@commands.has_role(1012777316864241694)
async def loader(ctx):
    emb = discord.Embed(title = '', colour=0x87CEEB)
    emb.set_author(name=bot.user.name)
    emb.set_thumbnail(url='')
    emb.add_field(name="", value = '', inline = False)
    emb.add_field(name="", value = '',  inline = False)
    emb.add_field(name="", value = '', inline = False)
    emb.add_field(name="", value = '', inline = False)
    emb.set_image(url ="")
    await bot.send_message(embed=emb)
    await ctx.message.delete()
    await asyncio.sleep(5)

A: You can send a direct message to a use by using Member.send
To send to the command user, you can use:
await ctx.author.send(embed=emb)

All attributes of messages including embeds work no differently when sending to users.


text:
Q: how can I configure an actionbar to show a progressbar in each long process? I want to have a methond or something in my action bar, for showing a progress bar indeterminate each time I need to do a long process.
I had been trying with a ViewStub, I thought also about using a frameLayout and a fragment, but I am not sure.

A: Use Activity#setProgressBarIndeterminateVisibility(boolean).
// This has to be called before setContentView
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

// This shows an indeterminate progress bar in the action bar
setProgressBarIndeterminateVisibility(true);

A: *

*Put a ProgressBar view in the action bar.

*Run the long task as an AsyncTask.

*Use the PublishProgress method during the long task to indicate how much work has been done so far.

*Use OnProgressUpdate callback to update the ProgressBar.


text:
Q: CPT Validation to not show "Post updated." Now this has been asked several times over on all WP forums, but how you change the success message?
First, I know there are 2 choices for managing the error message: setting in the options and using a session.  I chose the latter.  With concurrent users, the setting of error messages in the options just sounds like a bad idea.  Personally, I wish I did not have to do either, but WP is stateless, so I don't have a choice.
So, this is my basic code.
add_action('init', 'myStartSession', 1);
add_action('wp_logout', 'myEndSession');
add_action('wp_login', 'myEndSession');

function my_admin_notices(){
  if(!empty($_SESSION['my_admin_notices'])) print $_SESSION['my_admin_notices'];
  unset ($_SESSION['my_admin_notices']);
}
add_action( 'admin_notices', 'my_admin_notices' );

Plugin::initialize(); // do all the wonderful plugin stuff

// at the very end, remove the notices from the session
if(isset($_SESSION['my_admin_notices']))
  $value = '';

Also, I added this to my Plugin class when doing the add_action('save_post', $callback_function).
$_SESSION['my_admin_notices'] .= '

Something bad happened!

';

Everything works when I click "Update" on my post.  I get a nice error message of "Something bad happened!", but I have a problem.
I also see "Post updated."
Not good.
I skipped all the logic on updating and even did a "return false;", but the callback_function evidently does not process a boolean return and probably any return value for that matter.
How do I fix this so there is NO "Post updated." message?
If there is not an easy way with my approach, then what's a better way of doing this?


text:
Q: Using Expression language under javascript? I have below CheckBox in JSP file
<input type="checkbox" name="vehicle" value="Bike"
    onclick="javascript:selectCustomers(${sessionScope.custId});">

Getting the following error:

org.apache.jasper.JasperException: customer.jsp(1419,33) According to TLD or attribute directive in tag file,
          attribute onclick does not accept any expressions

Can we not use expression language in JavaScript (in my case under onClick() Event)?

A: When a JSP page is called, the following happens, in this order:

*

*Server checks to see if the .jsp has already been compiled and whether or not it has changed since it was last compiled.

*Server runs the jsp through the Jasper compiler, which interprets the jsp into Java code, anything that is not Java (CSS, HTML, JavaScript, etc) is placed in a String.

*The Java code is compiled and executed.

*The results are placed in the response and sent to the user.

So, your statement: ${sessionScope.custId} is executed before the the HTML is sent to the user, and the input of selectCustomers() function is already set to before calling it.

For more info have a look at my another post JSP inside ListItems onclick
How to verify it?
Right click in the browser and look at the view source.

Try below sample code that might help you.
Enclose ${...} inside the single quotes.
<c:set var="custId" value="1234" scope="session" />

Before :
<c:out value="${sessionScope.custId}"></c:out>

<input type="checkbox" name="vehicle" value="Bike"
    onclick="javascript:selectCustomers('${sessionScope.custId}');">

<c:set var="custId" value="4321" scope="session" />

After:
<c:out value="${sessionScope.custId}"></c:out>

View Source code: (Right click in browser to view it)
Before : 1234

<input type="checkbox" name="vehicle" value="Bike"
    onclick="javascript:selectCustomers('1234');">

After: 4321

A: Try this:
<input type="hidden" id="custId" name="custId" value="${sessionScope.custId}">

<input type="checkbox" name="vehicle" value="Bike" onclick="javascript:selectCustomers();">

function selectCustomers(){
   var custId = document.getElementById('custId').value;
}


text:
Q: Static Hardware Identifiers on Amazon EC2 We're trying to set up a Windows Continuous Integration server in the cloud that has software with a particularly difficult licensing scheme (a certain embedded software compiler). This compiler either lets the user run with a dongle, or node locks the software to run on a specific set of hardware. Seeing as how we can't exactly ship off a dongle to Amazon to plug in to our machine for us, we want to use the node locked licensing scheme with this software.
However, in order for this license to remain valid, my EC2 instance needs to have a set of "static" hardware IDs. We don't actually know which hardware IDs this software will look for (and they won't tell us), but I'd like to know which hardware IDs I should expect to change with instance restarts, and which hardware IDs, if any, I can lock down through proper configuration of my EC2 instance.
For example, I already know that I can lock down the MAC address of the Network Interface using Amazon's Elastic Network Interface (ENI). Is there any other configuration I can do, or need to do, in order to get a set of static hardware IDs?


text:
Q: Can not remove generated DataBinding code I used DataBinding in one of my classes CardRecicleViewAdapterTech.class , but I imported a library which does not support DataBinding and I switched to butter knifefor that class.
The problem is that when I run the project, Android Studio always generates a class binding related with CardRecicleViewAdapterTech.class  and this causes a crash. The generated class is:

CardViewTechBinding.java

I have deleted that java file in Android Studio databinding folder, but its generated again and again even when I do not use databinding anymore in my xml or my class.
This is my layout where I do not using dataBinding

card_view_tech.xml

so that generate CardViewTechBinding.java  even when I am not using dataBinding
<?xml version="1.0" encoding="utf-8"?>

<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:ProgressWheel="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_tech"
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:layout_gravity="center"
        android:layout_marginTop="@dimen/standard_margin"
        android:layout_marginLeft="@dimen/standard_margin"
        android:layout_marginRight="@dimen/standard_margin"
        card_view:cardCornerRadius="4dp"
        card_view:cardBackgroundColor="@color/primary_light">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:text="TextView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/text_view_technologie_name" />

            <com.pro.soft.apppresentation.ProgressWheel
                android:id="@+id/pw_spinner"
                android:layout_width="200dp"
                android:layout_height="200dp"
                android:layout_centerInParent="true"
                ProgressWheel:pwText="Authenticating..."
                ProgressWheel:pwTextColor="#222"
                ProgressWheel:pwTextSize="14sp"
                ProgressWheel:pwRimColor="#330097D6"
                ProgressWheel:pwBarLength="60dp"
                ProgressWheel:pwBarColor="#0097D6"
                ProgressWheel:pwBarWidth="5dp"
                ProgressWheel:pwRimWidth="2dp" />
        </LinearLayout>

    </android.support.v7.widget.CardView>

I tried to restart my Pc and Invalidate cache and restart Android Studio but without success. Please help.

A: I had the same issue, and it was caused by having <layout> root tags in the XML. I did not realise that these tags were databinding related and the compiler also does not help you in this regard.

A: In this order:
1.- Remove your file generated (build folder)
2.- Clean your project
3.- Invalidate cache and restart Android Studio
4.- Restart computer

A: In app build.gradle disable it first by using:
dataBinding {
        enabled = false;
    }
and sync the project and then enable and sync the project

A: Solved my problem by adding this to the build.gradle
buildFeatures {
  viewBinding false
}

and sync the project


text:
Q: Loop through a list of unknown length in SASS I want to style a list of posts – I have seen a lot of great examples of that being done when the list is predefined
(list values are 1,2,3 – loop through and do something)
My question is: if it's possible to pick up a list length through SASS?

A: SASS doesn't add any functionality to CSS, it just makes some kinds of CSS simpler to write.  If you can write it in CSS, it's possible with SASS.  If not, it isn't.


text:
Q: Approximating step function with Tanh to compute integral It is easy to compute by hand the following integral.
$$ Q(k) = \lim \limits_{\varepsilon \to 0} \int_2^{\infty} \frac{e^{-\varepsilon r}}{k}\sin(kr) \mathrm{d}r = \frac{\cos(2k)}{k^2}$$
I wanted to use smoothened version of step function to compute this integral using Mathematica. My idea was to rewrite this integral in the following way.
$$ Q(k) = \lim \limits_{\varepsilon \to 0} \int_0^{\infty} \Theta(r-2) \frac{e^{-\varepsilon r}}{k}\sin(kr) \mathrm{d}r$$
Here, I use step function $\Theta(r-2)$ in the following smooth form.
$$ \Theta(r-2) = \frac{1}{2} + \frac{1}{2} \tanh(1000(r-2)) $$
I would like to compute this integral in this way and then compare it to the result $\cos(2k)/k^2$. To do the computations, I use the following code.
Regularized[k_, epsilon_] := Assuming[epsilon >= 0 && k >= 0, Integrate[Sin[x*k]/k*Exp[-epsilon*x]*(0.5 + 0.5*Tanh[1000*(x - 2)]), {x, 0, Infinity}]];

ft[k_] := Limit[Regularized[k, P], P -> 0, Direction -> "FromAbove"];

To compare, I now do two plots using the following commands.
Plot[ft[k], {k, 0, 10}]

Plot[Cos[2 k]/(k*k), {k, 0, 10}]

My problem is that this computation takes more than 2 hours on my PC (which is not that old), and I have not yet seen the final result, so I wonder if I do something wrong. Maybe this approximation for step function is bad and instead of $\tanh$ I should use something else? Or is there a problem with my Mathematica code? Any help is very much appreaciated

A: Side-stepping the main question some, Rubi is capable of integrating this much more directly. In my own experience, adding a smoothed function to simplify a symbolic problem requires ensuring that the function in question has convenient cancellation behavior. I can't say that the choice of $\tanh$ is good or bad in this case, but it certainly does take longer than I'd expect on Mathematica.
On the other hand, using Rubi:
<< Rubi`
expr = Int[Exp[-ε r]/k Sin[k r], {r, 2, Infinity}]

ConditionalExpression[(E^(-2 ε) Cos[2 k])/(k^2 + ε^2) + (E^(-2 ε) ε Sin[2 k])/(k (k^2 + ε^2)), k > 0 && ε > 0]

If you plug this expression into an appropriate Limit:
Limit[expr, ε -> 0, Direction -> -1, Assumptions -> {k > 0}]

ConditionalExpression[Cos[2 k]/k^2, k > 0]

It also turns out that the original integrand also works if k is explicitly assumed to be positive:
 expr2 = Integrate[Exp[-ε r]/k Sin[k r], {r, 2, Infinity}, Assumptions -> {ε > 0, k > 0}]

Using HeavisideTheta also works as a step function under the same assumptions:
 Integrate[HeavisideTheta[r - 2] Exp[-ε r]/k Sin[k r], {r, 0, Infinity}, Assumptions -> {ε > 0, k > 0}]

Both of these expressions can be subjected to the same limit as above to give the same result. Again, I would expect that introducing inexact numbers or additional complicated functions would tend to make the result take longer, unless the form is peculiarly chosen to simplify the problem tremendously. I also generally trust that if a closed form solution to an integral exists and is at least somewhat well known, Rubi can provide a good head start on figuring out what it is.

A: There is another approximation for the step function which is commonly used in AI, namely the logistic function which takes the generic form $1/(1+e^{-x})$. In particular, it has the property
$$\vphantom{``}%The editor complained at me unless I put this invisible code here...
\Theta(x)=\lim_{z\rightarrow\infty}\frac{1}{1+e^{-zx}}.
$$
For the particular case of $\Theta(x-2)$ that you're interested in, we can compare the approximation you had using the $\tanh$ to the logistic function with $z=50$ (chosen such that the approximation isn't so good that we can't tell the functions apart):
Plot[{(0.5+0.5*Tanh[1000*(x-2)]),1/(1+Exp[-50*(x-2)])},{x,1,3}]

Now, the advantage of the logistic map in AI is typically that it's very fast to evaluate, so there are numerical advantages. It seem like here you're looking for a symbolic result (as you're using Integrate rather than NIntegrate, which admittedly fails to converge for the $\tanh$ approximation), so numerical efficiency isn't so helpful, but because this approximation seems to give a nicer result. In fact, the integral
$$
f(k;\epsilon,z)=\int_0^\infty\frac{\sin(kx)}{k}e^{-\epsilon x}\frac{1}{1+e^{-z(x-2)}}
$$
turns out to be doable in closed form for all $\epsilon,k,z>0$. Adding the $z>0$ condition to the assumptions in your original integration, Mathematica evaluates this integral to
$$
f(k;\epsilon,z)=\frac{1}{2k(\epsilon^2+k^2)}\left[(k+i\epsilon)_2F_1\left(1,\frac{\epsilon+ik}{z};\frac{\epsilon+ik+z}{z};-e^{2z}\right)+(k-i\epsilon)_2F_1\left(1,\frac{\epsilon-ik}{z};\frac{\epsilon-ik+z}{z};-e^{2z}\right)\right],
$$
where $_2F_1$ is one of the hypergeometric functions. Plotting this function for $\epsilon=0.05$ and $z=100$, we can see
Plot[{f[k,epsilon,z] /. {epsilon -> 0.05, z -> 100}, Cos[2*k]/k^2}, {k, 0, 10},PlotRange -> {{0, 10}, {-0.2, 0.2}}, PlotLegends -> Automatic]

where the yellow curve is the exact result and the blue curve is our approximation.


text:
Q: A more logical approach to a word problem I was taught in high school algebra to translate word problems into algebraic expressions. So when I encountered this problem I tried to reason out an algebra formula for it

For every dollar Ben spent on bagels, David spent 25 cents less. Ben
paid $12.50 more than David. How much did they spend in the bagel store
together?

To solve this I imagined a series of comparisons when Ben spends $x$, David spends $.75x$. Loop this relationship until $x - .75x \approx 12.50$. Good. Done. $x = 50$, then add David's for the answer. Coming from computers, I would have set this up in code where a loop (recursion) would increase $x$ until the condition $x - .75x = 12.50$ was met, then the "loop counter/accumulator" would be how much Ben spent, i.e., $50$, etc.
I'm a beginner with math, but it seems like there should be a better approach, something with series and sequences or even calculus derivatives, something better than my brute-force computer algorithm. Can someone enlighten? The "answer" given at the site (see link) is its own brute-force and hardly satisfying. I'm thinking there should be something more formal -- at least for the first part that derives $50$.
Update
I think everyone so far has missed my point. Many of you simply re-did the problem again. I'm wondering if there is a more formal way to do this other than just "figuring it out" (FIO). The whole FIO routine is murky. It looks like a limit problem; it looks like a system of equations, but I'm not experienced enough to know exactly. If there isn't, then let's call it a day....

A: From the step $x-.75x=12.50$ simplify to $.25x=12.5$,  divide by .25  to immediately get $x=50$.  No looping/brute force needed.

A: Another way, with no $x$'s needed:
The first condition says the difference between their spending is $1/4$ of what Ben spends.  That difference is $\$12.50$, so Ben's amount is $4 \times \$ 12.50 = \$50$.

A: If the difference is $\$12.50$ then it must be the product of dollars times $\$0.25$ so we divide:
$\quad\dfrac{12.50}{0.25}=50\quad$ for Ben and another $\quad 37.50 \quad$ for David for a total of $\quad\$87.50$

A: You can use linear algebra, by defining something as x, say the amount paid by Ben. Then Dave's will be 0.75x. Then we can get an easily solvable equation.

A: I have to admit I'm having a hard time seeing how you "imagine a series of comparisons " and how you "loop" them.
As a mathematician, I simply view this as Ben did a single transaction where in one go he spent $x$ dollars on bagels.
Therefore David spend $0.75x$ on bagels (in one go).
Set one equation (no series of loops) to get $x - 0.75x = 12.50$ and solve:

$x-0.75x = 12.50$
$0.25x = 12.50$
$\frac {0.25}{0.25} x = \frac {12.50}{0.25}$
$x = 50$

So Ben spent $50$ dollars on bagels.
Now add Davids answer.  David spent $0.75x$ and $x = 50$ so David spent $0.75 \times 50 = 37.50$.  Adding that they added $50+37.50 = 87.50$.
Or.... Ben spent $x$ and David spent $0.75x$ so together they spent $x + 0.75x = 1.75x$ and as $x = 50$ together they spent $1.75\times 50 = 87.50$.


text:
Q: Does the Photos access API in iPhone allow removal of photos from an application? Our development team is planning a product, and we need to figure out if it's possible to remove photos from Photos library on iOS via our application code. We are basically doing a backup and clean application. Please let me know if this is possible via API's provided by Apple.

A: You can do it via Photos.Framework , but it's only available later versions iOS 8.
Sample code is available at developer's library.
    // Delete asset from library
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        [PHAssetChangeRequest deleteAssets:@[self.asset]];
    } completionHandler:completionHandler];

A: It's possible using the Photos framework.
Look into PHAssetChangeRequest and the deleteAssets: method.

A: Nope it is not allowed to delete the photos =from app


text:
Q: Releasing ViewModel classes in a WPF Caliburn.micro app I wrote a program that has a window with a user control.
The window has a property 'ActiveView' that the user control is bound to.
I have a switch/case statement that sets ActiveView to a view model based on a selected list item.
Case "option1":
ActiveView = new OptionOneViewModel();
Break;

Case "option2":
ActiveView = new OptionTwoViewModel();
Break;

My question is, Everytime I click an option I am creating a new ViewModel. Say I click option 1, the ViewModel is shown, then I click on option 2 and another ViewModel is created. Is the first ViewModel still a resource or is it automatically disposed and replaced by the new ViewModel.
To save resources should I do something like:
If(ActiveView != Null)
{
    ActiveView.Dispose();
        //Or
    ActiveView = null;
}

Before setting the new ViewModel with the switch case?

A: So I figured out how to make this work for me.  In the "SelectedSubject" property I am calling "Selectedchanged();", then in the function "SelectedChanged() I am using a switch case to set the "ActiveSubject" property to the ViewModel associated with the selection.
public string SelectedSubject
    {
        get { return _selectedSubject; }
        set {
            _selectedSubject = value;
            Selectedchanged();
            NotifyOfPropertyChange(() => SelectedSubject);
        }
    }

public void Selectedchanged()
    {
        switch(SelectedSubject)
        {
            case "User Information":
                ActiveSubject = new UserInformationViewModel();
                break;

            case "Dealer Locations":
                ActiveSubject = new HelpLocationViewModel();
                break;

            case "Schedule Information":
                ActiveSubject = new HelpScheduleViewModel();
                break;

            case "Write Off Information":
                ActiveSubject = new HelpWriteOffViewModel();
                break;

            case "Loading Schedules":
                ActiveSubject = new HelpLoadingScheduleViewModel();
                break;

            case "Working with Repair Orders":
                ActiveSubject = new HelpRepairOrdersViewModel();
                break;

            case "Working with Write Offs":
                ActiveSubject = new HelpWorkingWithWriteOffViewModel();
                break;

            case "Generating Reports":
                ActiveSubject = new HelpGeneratingReportsViewModel();
                break;

            case "Working with Application Data":
                ActiveSubject = new HelpSavingDataViewModel();
                break;

            default:
                ActiveSubject = new PrimaryViewModel();
                break;

        }
    }


text:
Q: Correct way to remove -noframemerging option I noticed that when I start up IE in SeleniumWebdriver with
var ieoptions = new InternetExplorerOptions()
{
    EnablePersistentHover = false,
    EnsureCleanSession = true,
    RequireWindowFocus = true,
};

I have this -noframemerging flag in my IE command line. I don't want this flag
After some digging I managed to find that I can seemingly take it out by adding
 ForceCreateProcessApi = true,
 BrowserCommandLineArguments = "-framemerging"

but that would only work with an accompanying regedit for
HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main = 0

I'd prefer to keep my IE working in the same way in manual and automated tests - i.e. not messing about with the number of processes in play. So is there an easier solution available here? I find it hard to understand why the -noframemerging flag is turned on by IEServerDriver

A: No, there is no easier solution here. IEDriverServer.exe does nothing to modify the command line used to launch IE. If a switch is being added to the command line, it's being done by the Windows IELaunchURL API, which is what the driver uses by default to launch the browser to be able to accommodate Protected Mode. The way to have "control" over what command line is used is with the CreateProcessAPI, and you've already discovered how to make the driver do that. "Control" is deliberately put in scare quotes here because unfortunately, CreateProcess isn't reliable with IE unless you use the registry entry. Moreover, IE doesn't have the concept of user profiles, and your desire to maintain the browser's behavior for your non-WebDriver use is exactly why the driver doesn't set registry entries for you.


text:
Q: Remove external include depedency from codebase My task is to remove inclusion of C library headers from our C++ codebase. As first to remove the lib header files first I declare its included functions as exter type
extern "C"
{
        typedef unsigned int uint;
        uint function1(...);
        All library methods goes in here
}

The code compiles and links fine - but how can I remove the typedef - the uint type is defined in the C library header file?

A: A typedef is just another name for a type. If you don't wish to use uint, then declare that function with the type uint is aliasing, like this:
unsigned int function1(...);


text:
Q: Why are my random numbers not so random? int totalRecs = getTotalRecs(); // returns '13'
int MAX_RECS_PER_LOOKUP = 10;
Random rand = new Random();
int start = (totalRecs > Utl.MAX_RECS_PER_LOOKUP) ? rand.nextInt(totalRecs-Utl.MAX_RECS_PER_LOOKUP) : 0;
results = this.getNewRecs(filter, start, start+1);

I'm using this random number logic to retrieve records from the database based on their table row offset (start up to start+1).
But for some reason it keeps repeating the same numbers: start value of 0 and start value of 3.
I tried seeding the Random object but it made no difference:
long seed = System.currentTimeMillis();
rand.setSeed(seed);

A: The rand.nextInt(n) method returns a value between 0 (inclusive) and n (exclusive).
In your code, if totalRecs is 13, and Utl.MAX_RECS_PER_LOOKUP is 10 (I am assuming this one based on the MAX_RECS_PER_LOOKUP value in your code snippet, but I may be wrong), then this code:
rand.nextInt(totalRecs-Utl.MAX_RECS_PER_LOOKUP);

should return a random number between 0 and 2.
I am not sure if this is what you actually want?

A: Make sure your inputs are valid.
Via debug compare values of
totalRecs  Utl.MAX_RECS_PER_LOOKUP  & start on the same iteration.
You are calling
rand.nextInt(totalRecs-Utl.MAX_RECS_PER_LOOKUP)

The only way you should "always" be getting 0 is if totalRecs = Utl.MAX_RECS_PER_LOOKUP
However if the difference is only 1 then you will get back 0 or 1 randomly.

A: You could try java.security.SecureRandom
It seems to be a good alternative, and it inherits from java.util.Random


text:
Q: Переопределение метода get_queryset в Django Admin Подскажите, пожалуйста, почему может не работать такая конструкция:

class FastCountQuerySet(QuerySet):
    def count(self):
        pass

@admin.register(ItemOOSLog)
class ItemOOSLogAdmin(ImportExportModelAdmin):

    def get_queryset(self, request):
        qs = super(ItemOOSLogAdmin, self).get_queryset(request)
        return qs._chain(__class__=FastCountQuerySet)

Мне необходимо, чтобы при использовании метода get_queryset, использовался мой класс FastCountQuerySet вместо QuerySet.
Нашёл, что это можно реализовать через qs._chain(__class__=FastCountQuerySet), но это не работает, используется обычный QuerySet.

A: Решение оказалось следующим:
class FastCountQuerySet(QuerySet):
    def count(self):
        pass

@admin.register(ItemOOSLog)
class ItemOOSLogAdmin(ImportExportModelAdmin):

    def get_queryset(self, request):
        qs = super(ItemOOSLogAdmin, self).get_queryset(request)
        qs.__class__ = FastCountQuerySet
        return qs._chain()


text:
Q: Arbitrary transformation anchor (point) in QGraphicsView The task is that I have some GraphicsView and I need to scale and rotate it not around the center of the View or Scene or the mouse pointer, but around an arbitrary point.
For example, I have a huge scene. With LeftButton click I place an anchor for transformation (a pin) to mouseEvent.scenePos(). And then, holding right mouse button and moving mouse I scale and rotate scene around that anchor, meaning pin staying still on the screen.
 That means I can't use setTransformationAnchor because it can accept only transformationAnchor enumeration.
 So how can I set transformation point?