text:
Q: tf.unstack did not work with tf 1.8 CudnnGRU tensors Describe the problem
tf.unstack did not work as expected. It did not reduce R rank tensor to R-1 rank tensor
the corresponding issue in tensorflow github issue list: https://github.com/tensorflow/tensorflow/issues/22223
Source code / logs
code:
#! /usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import tensorflow as tf
rnn_model = tf.contrib.cudnn_rnn.CudnnGRU(
        num_layers=1,
        num_units=64,
        direction='unidirectional')
rnn_model.build([3, 1, 3])
inputs=[[[1,1,1],[1,1,1],[1,1,1]]]
inputs_tensor= tf.convert_to_tensor(inputs, dtype=tf.float32)
print(tf.shape(inputs_tensor))
rnn_out, rnn_state = rnn_model(inputs_tensor)
print("rnn_state: ", rnn_state)
rnn_layers = tf.unstack(rnn_state)
print("rnn_layers", rnn_layers)

paste the code to file demo.py, then run from linux command line:
$ python3.6 demo.py

output:
Tensor("Shape:0", shape=(3,), dtype=int32)
rnn_state:  (<tf.Tensor 'cudnn_gru/CudnnRNN:1' shape=(1, ?, 64) dtype=float32>,)
rnn_layers [<tf.Tensor 'unstack:0' shape=(1, ?, 64) dtype=float32>]

the rnn_layers should be rnn_layers [<tf.Tensor 'unstack:0' shape=(?, 64) dtype=float32>]
Env Details
Have I written custom code (as opposed to using a stock example script provided in TensorFlow):
Yes
OS Platform and Distribution (e.g., Linux Ubuntu 16.04):
$uname -r
3.10.0-327.el7.x86_64

Mobile device:
Not mobile
TensorFlow installed from (source or binary):
anaconda tf 1.8
TensorFlow version (use command below):
$conda list|grep tensor
tensorboard               1.8.0            py36hf484d3e_0
tensorflow                1.8.0                hb381393_0
tensorflow-base           1.8.0            py36h4df133c_0
tensorflow-gpu            1.8.0                h7b35bdc_0

Python version:
$python3.6 -V
Python 3.6.2 :: Continuum Analytics, Inc.

Bazel version (if compiling from source):
$bazel version
Build label: 0.4.5
Build target: bazel-out/local-fastbuild/bin/src/main/java/com/google/devtools/build/lib/bazel/BazelServer_deploy.jar
Build time: Thu Mar 16 12:19:38 2017 (1489666778)
Build timestamp: 1489666778
Build timestamp as int: 1489666778

CUDA/cuDNN version:
$conda list|grep -i cuda
cudatoolkit               8.0                           3    https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free
cudnn                     7.0.5                 cuda8.0_0

GPU model and memory:
== cat /etc/issue ===============================================
Linux rvab01298.sqa.ztt 3.10.0-327.el7.x86_64 #1 SMP Thu Nov 19 22:10:57 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
VERSION="7.2 (Paladin)"
VERSION_ID="7.2"
qihoo360_BUGZILLA_PRODUCT_VERSION=7.2
qihoo360_SUPPORT_PRODUCT_VERSION=7.2

== are we in docker =============================================
No

== compiler =====================================================
c++ (GCC) 4.9.2
Copyright (C) 2014 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

== uname -a =====================================================
Linux rvab01298.sqa.ztt 3.10.0-327.el7.x86_64 #1 SMP Thu Nov 19 22:10:57 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux

== check pips ===================================================
numpy (1.13.3)
protobuf (3.5.1)
tensorflow (1.8.0)

== check for virtualenv =========================================
False

== tensorflow import ============================================
tf.VERSION = 1.8.0
tf.GIT_VERSION = b'unknown'
tf.COMPILER_VERSION = b'unknown'
Sanity check: array([1], dtype=int32)

== env ==========================================================
LD_LIBRARY_PATH :/usr/local/mpc-0.8.1/lib:/usr/local/gmp-4.3.2/lib:/usr/local/mpfr-2.4.2/lib:/gruntdata/qihoo360/cuda/lib64
DYLD_LIBRARY_PATH is unset

== nvidia-smi ===================================================
Wed Sep 12 13:34:30 2018
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 375.26                 Driver Version: 375.26                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  Tesla K40m          On   | 0000:02:00.0     Off |                    0 |
| N/A   36C    P0    67W / 235W |   1161MiB / 11439MiB |     39%      Default |
+-------------------------------+----------------------+----------------------+
|   1  Tesla K40m          On   | 0000:03:00.0     Off |                    0 |
| N/A   35C    P0    60W / 235W |     73MiB / 11439MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID  Type  Process name                               Usage      |
|=============================================================================|
|    0     13950    C   bin/arks                                       868MiB |
|    0     27880    C   python3.6                                      288MiB |
|    1     27880    C   python3.6                                       71MiB |
+-----------------------------------------------------------------------------+

== cuda libs  ===================================================
/usr/local/cuda-8.0/doc/man/man7/libcudart.7
/usr/local/cuda-8.0/doc/man/man7/libcudart.so.7
/usr/local/cuda-8.0/lib64/libcudart_static.a
/usr/local/cuda-8.0/lib64/libcudart.so.8.0.61
/usr/local/cuda-7.5/doc/man/man7/libcudart.7
/usr/local/cuda-7.5/doc/man/man7/libcudart.so.7
/usr/local/cuda-7.5/lib64/libcudart.so.7.5.18
/usr/local/cuda-7.5/lib64/libcudart_static.a
/usr/local/cuda-7.5/lib/libcudart.so.7.5.18
/usr/local/cuda-7.5/lib/libcudart_static.a

A: Solved, the return value format is changed to tuple


text:
Q: EditText setError is not showing in FragmentActivities I have a form in an Activity, that have their fields validated on an second class (BLL class) and I use setError() method to display the validation message. It works well until then.
But now I need to put this form on an fragment activity. I did all the changes needed and the validation works fine, but the "baloon" is not been showed.
I had searched everywhere, but i couldnt find anything that helps.
Here's my code:
public class OrderCustomFieldsFragment extends Fragment {

  public void save() {

    try {
        CustomFieldsBll customFields = new CustomFieldsBll(this.getActivity());
        customFields.validateCustomFields(irrelevant...);
        ...irrelevant code...
        Toast.makeText(this.getActivity(), "Saved.", Toast.LENGTH_LONG).show();
    }
    catch (CustomException z) {
        if (setError(z.getThrowerField(), z.getMessage()))
            Toast.makeText(this.getActivity(), z.getMessage(), Toast.LENGTH_SHORT).show();
    }

  }

  private boolean setError(Integer throwerField, String msg) {
    //If thorwerField is null then is a general error, otherwise is a form field
    if (throwerField == null) {
      //here display an dialog
      showOKMessage(this.getActivity(), "Pedidos", msg, false);
      return false;
    }
    else {
      try {
          //linearLayout is my view, instanciated in onCreateView method
        TextView customField = (TextView)linearLayout.findViewById(throwerField);
        if (customField != null) {
           customField.setError(msg);
           customField.requestFocus();
           return true;
        }
        else {
          showOKMessage(this.getActivity(), "Pedidos", msg, false);
        }
      }
      catch (Exception e) {
        showOKMessage(this.getActivity(), "Pedidos", msg, false);
      }
   }

   return false;
  }

}

The exception is throwed, the field is found, the error is setted, but only the Toast appears, the error ballon doesnt.
Any ideias?
Thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can not create TStream in Lazarus It fails in this simple example to:
      procedure TForm1.Button1Click(Sender: TObject);
      var
        ts: TStream;
      begin
        ts.Create; //<---- fails here
        ts.Free;
      end;

With error:
Project project1 raised exception class 'External: SIGSEGV'.
At address 10000DB38

A: You are using the wrong code.  It should be
 procedure TForm1.Button1Click(Sender: TObject);
      var
        ts: TStream;
      begin
        ts := TStream.Create; //  If Lazarus supports  creation of Stream instances.
        ts.Free;
      end;

Until it is created, your variable ts simply contains junk from previous use of the stack.  You have to call the class's constructor to allocate the actual object on the heap and point your ts variable at it.
If Lazarus complains that it can't create an instance of TStream (it may treat it as an abstract class and I don't have Lazarus on this machine to check), try something like this instead:
 var
    ts: TMemoryStream;
  begin
    ts := TMemoryStream.Create;
    ts.Free;
  end;

Instead of TMemoryStream, you could use any other concrete TStream-descendant class.

A: Was originaly trying this code:
memStream.Create;

But it should be:
memStream := TMemoryStream.Create;

Blah...


text:
Q: Injected script and https Are Safari extension injected scripts allowed to access secure pages? When I try to hit GMail's secure page I get in the console.log "Script Cancelled" at "ServiceLogin".

A: I should hope not. Make sure you're actually going to GMail's secure page; make sure you haven't picked up any unknown extensions and do a virus and spyware scan.
Lastly, not sure this is the right place to ask about that - You might do better on a specifically security-oriented site.


text:
Q: Getting unexpected error cocoapod install pods I had the pods working fine until I tried to install another pod and started getting a strange error, I have done no updates and was working perfectly until recently.
Podfile
platform :ios, '8.0'

target 'Wireless' do
pod 'TapjoySDK', '~> 10.2'
pod 'MBProgressHUD', '~> 0.9.1'
pod 'IQDropDownTextField',
pod 'PayPal-iOS-SDK',
pod 'DLRadioButton'
end

Error message I am getting
SyntaxError - /Users/amir/Desktop/Wireless/Podfile:10: syntax error, unexpected tSTRING_BEG, expecting keyword_do or '{' or '('
pod 'PayPal-iOS-SDK',

     ^
/Users/amir/Desktop/Wireless/Podfile:10: syntax error, unexpected  ',', ex   pecting keyword_end
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-0.36.3/lib/cocoapods-core/podfile.rb:254:in `eval'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-0.36.3/lib/cocoapods-core/podfile.rb:254:in `block in from_ruby'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-0.36.3/lib/cocoapods-core/podfile.rb:51:in `instance_eval'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-0.36.3/lib/cocoapods-core/podfile.rb:51:in `initialize'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-0.36.3/lib/cocoapods-core/podfile.rb:251:in `new'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-0.36.3/lib/cocoapods-core/podfile.rb:251:in `from_ruby'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-0.36.3/lib/cocoapods-core/podfile.rb:227:in `from_file'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-0.36.3/lib/cocoapods/config.rb:176:in `podfile'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-0.36.3/lib/cocoapods/command.rb:109:in `verify_podfile_exists!'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-0.36.3/lib/cocoapods/command/project.rb:100:in `run'
/Library/Ruby/Gems/2.0.0/gems/claide-0.8.1/lib/claide/command.rb:312:in `run'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-0.36.3/lib/cocoapods/command.rb:46:in `run'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-0.36.3/bin/pod:44:in `<top (required)>'
/usr/bin/pod:23:in `load'
/usr/bin/pod:23:in `<main>'

A: The error description says that it gets an unexpected , symbol.
Change your Podfile to
platform :ios, '8.0'

target 'Wireless' do
pod 'TapjoySDK', '~> 10.2'
pod 'MBProgressHUD', '~> 0.9.1'
pod 'IQDropDownTextField'
pod 'PayPal-iOS-SDK'
pod 'DLRadioButton'
end

A: This is likely the culprit syntax error, unexpected  ','.
Remove the , from the end of the lines.
For instance:
platform :ios, '8.0'

target 'Wireless' do
pod 'TapjoySDK', '~> 10.2'
pod 'MBProgressHUD', '~> 0.9.1'
pod 'IQDropDownTextField'
pod 'PayPal-iOS-SDK'
pod 'DLRadioButton'
end


text:
Q: Is it possible to put A Column in a Row in Flutter? I tried putting a column in a row. But it does not work.
Then I tried putting the row and column in the same safe area using different child properties. It does not work.
The column is supposed to be in the middle of the row.
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.teal,
        body: SafeArea(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Container(
                height: 100.0,
                width: 100.0,
                color: Colors.yellow,
                child: Text('Container 1'),
              ),
              Container(
                height: 100.0,
                width: 100.0,
                color: Colors.green,
                child: Text('Container 1'),
              ),
              Container(
                width: double.infinity,
              ),
            ],
          ),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Container(
                height: 100.0,
                color: Colors.red,
                child: Text('Container 1'),
              ),
              Container(
                height: 100.0,
                color: Colors.blue,
                child: Text('Container 1'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

The error message is "BoxConstraints forces an infinite width."

A: Try expanded widget with flex attribute, you can put the column in a row:
Container(
    width: 300,
    height: 100,
    child: Row(
      children: <Widget>[
        Expanded(flex: 1,
        child: Container(
          color: Colors.red,
          width: double.infinity,
          height: double.infinity,
        ),
        ),
        Expanded(flex: 2,
          child: Column(
            children: <Widget>[
              Expanded(flex:1,
                child: Container(
                  color: Colors.yellow,
                  width: double.infinity,
                  height: double.infinity,
                ),
              ),
              Expanded(flex:1,
                child: Container(
                  color: Colors.blue,
                  width: double.infinity,
                  height: double.infinity,
                ),
              ),
            ],
          ),
        ),
        Expanded(flex: 1,
          child: Container(
            color: Colors.green,
            width: double.infinity,
            height: double.infinity,
          ),
        ),
      ],
    ),
  ),

A: also, you can place column using a container
body: SafeArea(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Container(
            width: 100.0,
            color: Colors.red,
          ),
          Container(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Container(
                  width: 100.0,
                  height: 100.0,
                  color: Colors.yellow,
                ),
                Container(
                  width: 100.0,
                  height: 100.0,
                  color: Colors.green,
                ),
              ],
            ),
          ),
          Container(
            width: 100.0,
            color: Colors.blue,
          ),
        ],
      ),
    ),


text:
Q: What are key differences between sbt-pack and sbt-assembly? I've just stumbled upon the sbt-pack plugin. The development stream seems steady. It's surprising to me as I believed that the only plugin for (quoting sbt-pack's headline) "creating distributable Scala packages." is sbt-assembly (among the other features).
What are the key differences between the plugins? When should I use one over the other?

A: (Disclaimer: I maintain sbt-assembly)
sbt-assembly
sbt-assembly creates a fat JAR - a single JAR file containing all class files from your code and libraries. By evolution, it also contains ways of resolving conflicts when multiple JARs provide the same file path (like config or README file). It involves unzipping of all library JARs, so it's a bit slow, but these are heavily cached.
sbt-pack
sbt-pack keeps all the library JARs intact, moves them into target/pack directory (as opposed to ivy cache where they would normally live), and makes a shell script for you to run them.
sbt-native-packager
sbt-native-packager is similar to sbt-pack but it was started by a sbt committer Josh Suereth, and now maintained by highly capable Nepomuk Seiler (also known as muuki88). The plugin supports a number of formats like Windows msi file and Debian deb file. The recent addition is a support for Docker images.
All are viable means of creating deployment images. In certain cases like deploying your application to a web framework etc., it might make things easier if you're dealing with one file as opposed to a dozen.
Honorable mention: sbt-progard and sbt-onejar.

A: Although Eugene Yokota's explanation is complete, I would like to explain the mentioned plugins with package command in the aspect of usages and how different results are generated.
Directory settings and build.sbt
lazy val commonSettings = Seq(
  organization := "stackOverFlow",
  scalaVersion := "2.11.12",
  version := "1.0",
)

lazy val app  = (project in file ("app")).
  enablePlugins(PackPlugin).
  settings(commonSettings)

Above build.sbt file declares project called app and includes all the source files in the app directory. To enable Pack plugins, enablePlugins(PackPlugin) should be included in the sbt file.
Also, I've put the below line in project/plugins.sbt file to use pack plugins in our project
addSbtPlugin("org.xerial.sbt" % "sbt-pack" % "0.9.3")
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.5")

The package is already integrated into the sbt by default, so you don't have to explicitly specify the plugins using addSbtPlugins. However, the sbt-pack and sbt-assembly plugins are not included in the sbt by default, so you have to specify that you want to use them. addSbtPlugin is a way to say that "I want to use xxx, yyy plugins in my project" to your sbt.
Also, I implemented two contrived scala files in the ./app/src/main/scala:
AppBar.scala
class AppBar {
  def printDescription() = println(AppBar.getDescription)
}

object AppBar {
  private val getDescription: String = "Hello World, I am AppBar"

  def main (args: Array[String]): Unit = {
    val appBar = new AppBar
    appBar.printDescription()
  }
}

AppFoo.scala
class AppFoo {
  def printDescription() = println(AppFoo.getDescription)
}

object AppFoo {
  private val getDescription: String = "Hello World, I am AppFoo"

  def main (args: Array[String]): Unit = {
    val appFoo = new AppFoo
    appFoo.printDescription()
  }
}

sbt package
This is very basic sbt command included in the sbt to help you distribute your project through the jar file. The jar file generated by the package command is located in the projectDirectoy/target/scala-2.11/app_2.11-1.0.jar (Here, the specified scalaVersion and version setting keys included in the build.sbt file are used to generate the jar file name).
When you look inside the jar, you can see the class files generated by the sbt tool, which is the result of compiling the sources in the app/src/main/scala. Also, it includes a MANIFEST file.
$vi  projectDirectoy/target/scala-2.11/app_2.11-1.0.jar

META-INF/MANIFEST.MF
AppBar$.class
AppBar.class
AppFoo.class
AppFoo$.class

Note that it only includes the class files generated from the scala files located in the app/src/main/scala directory. The jar file generated by the package command does not include any scala related libraries such as collection in the scala library (e.g., collection.mutable.Map.class). Therefore, to execute the program you may require scala library because the generate jar file only contains the minimal classes generated from the scala sources that I implemented. That is the reason why the jar file contains AppBar.class, AppBar$.class for companion object, etc.
sbt-assembly
As mentioned by the Eugene Yokota, sbt-assembly also help you distribute your project through generating the jar file; however the generated jar file includes not only the class files generated by your source code, but also all the libraries that you need to execute the program. For example, to execute the main function defined in the AppFoo object, you may need scala libraries. Also, when you add external libraries in your project, which can be included by adding the dependencies to the libraryDependencies key.
libraryDependencies ++= Seq("org.json4s" %% "json4s-jackson" % "3.5.3")

For example, you can include json4s libraries in your project, and jar files related to supporting json4s in your project also will be added to the final jar file generated by the sbt-assembly. In other words, when you invoke assembly in your sbt, it generates one jar file containing all the requirements to execute your program, so that you don't need another dependency to execute yout program.
When you prompt assembly command in your sbt shell, then it will generate one jar file in your target directory. In this case, you may find the app-assembly-1.0.jar in the app/target/scala-2.11 directory. When you look inside the jar file, you can find that it contains lots of classes.
$vi  projectDirectoy/target/scala-2.11/app_2.11-1.0.jar
ETA-INF/MANIFEST.MF
scala/
scala/annotation/
scala/annotation/meta/
scala/annotation/unchecked/
scala/beans/
scala/collection/
scala/collection/concurrent/
scala/collection/convert/
scala/collection/generic/
scala/collection/immutable/
scala/collection/mutable/
scala/collection/parallel/
scala/collection/parallel/immutable/
scala/collection/parallel/mutable/
scala/collection/script/
scala/compat/
scala/concurrent/
scala/concurrent/duration/
scala/concurrent/forkjoin/
scala/concurrent/impl/
scala/concurrent/util/
scala/io/
scala/math/
scala/ref/
scala/reflect/
scala/reflect/macros/
scala/reflect/macros/internal/
scala/runtime/
scala/sys/
scala/sys/process/
scala/text/
scala/util/
scala/util/control/
scala/util/hashing/
scala/util/matching/
AppBar$.class
AppBar.class
AppFoo$.class
AppFoo.class
......

As mentioned before, because the jar file generated by the assembly contains all the dependencies such as scala and external libraries to execute your program in the jar, you may think that you can invoke the main functions defined in the AppFoo object and AppBar object.
jaehyuk@ubuntu:~/work/sbt/app/target/scala-2.11$ java -cp './*' AppFoo
Hello World, I am AppFoo
jaehyuk@ubuntu:~/work/sbt/app/target/scala-2.11$ java -cp './*' AppBar
Hello World, I am AppBar

Yeah~ you can execute the main function using the generated jar file.
sbt-pack
sbt-pack is almost same as the sbt-assembly; it saves all the library on which your project depends as jar files required to execute your program. However, sbt-pack doesn't integrate all the dependencies into one jar files, instead, it generates multiple jar files which correspond to one library dependencies and your classes (e.g., AppFoo.class).
Also, interestingly it automatically generates scripts for invoking all the main functions defined in your scala source files and Makefiles to install the program. Let's take a look at the pack directory created after you prompt pack command on your sbt shell.
jaehyuk@ubuntu:~/work/sbt/app/target/pack$ ls
bin  lib  Makefile  VERSION
jaehyuk@ubuntu:~/work/sbt/app/target/pack$ ls bin/
app-bar  app-bar.bat  app-foo  app-foo.bat
jaehyuk@ubuntu:~/work/sbt/app/target/pack$ ls lib/
app_2.11-1.0.jar  sbt_2.12-0.1.0-SNAPSHOT.jar  scala-library-2.11.12.jar
jaehyuk@ubuntu:~/work/sbt/app/target/pack$

As shown in the above, two directories and two files are created; bin contains all the script files to execute the functions defined in your sources (each file is a script that helps you execute the main method defined in your scala files); lib contains all the required jar files to execute your program; and lastly Makefile can be used to install your program and dependent libraries in your system.
For the details, please refer the github pages for each plugins.


text:
Q: Plot Circles on Line Chart I want to plot marker of circle shape on a line chart to represent some values from x-axis. Screenshot is attached with details. Thanks!
check this image for what I am looking for

A: You can use dataLabels and marker properties:
series: [{
    data: [1, 2, 3, 4, 5, 6, 7],
    dataLabels: {
        enabled: true,
        y: 10
    },
    marker: {
        radius: 10,
        fillColor: '#FFF',
        lineColor: '#7cb5ec',
        lineWidth: 2
    }
}]

Live demo: http://jsfiddle.net/BlackLabel/n7uhwzk8/
API Reference:
https://api.highcharts.com/highcharts/series.line.dataLabels.enabled
https://api.highcharts.com/highcharts/series.line.marker


text:
Q: dateFromString prints out "(null)" I know that there are lots of questions about this, but none of the answers seem to be working for me. Here's my code (iOS SDK 6.0)
NSDateFormatter *df = [NSDateFormatter alloc];
[df setDateFormat:@"yyyy-MM-dd"];
[df setFormatterBehavior:NSDateFormatterBehavior10_4];
[df setTimeZone:[NSTimeZone defaultTimeZone]];
[df setLocale:[NSLocale currentLocale];
NSDate *TERMIN = [NSDate alloc];
TERMIN = [df dateFromString:T]; //'T' is date in string NSLog(...,T) is 2002-05-05

When I output TERMIN through NSLog the output is (null)

A: You forgot to initialize the NSDateFormatter object
NSDateFormatter *df = [[NSDateFormatter alloc] init];

A: OK this is kinda akward, i was NSLoging like object.variable instead of [object getVariable] from outside...that was the whole problem. Sorry to bother you guys, im such a dumb*ss :D
Another problem showed up that the code above turns 2002-05-05 into 2002-05-04. But that is for another story i guess...


text:
Q: Wsdl optional params become mandatory in generated java stub code I am newbie to webservices.
I have generated the stub from the provided wsdl.
What I have observed is the stub generated code asking me to provide the optional parameters mandatory.
For example this is one of the method in wsdl file.
        <complexType name="OPP_BOOK_FACT">
           <sequence>
              <element form="unqualified" name="Descriptions" type="tns:Descriptions" minOccurs="0"/>
              <element form="unqualified" name="CustomerID" type="tns:CustomerConfirmationID" minOccurs="0"/>
              <element form="unqualified" name="UID" type="tns:UPRID" minOccurs="0"/>
              <element form="unqualified" name="Ext" type="tns:ExtAuth" minOccurs="0"/>
              <element form="unqualified" name="Partner" type="tns:Partner"/>
              <element form="unqualified" name="Subscriber" type="tns:Subscriber"/>
              <element form="unqualified" name="FactBook" type="tns:FactBook"/>
              <element form="unqualified" name="FactAuth" type="tns:FactAuth"/>
              <element form="unqualified" name="Price" type="tns:Price"/>
              <element form="unqualified" name="SubseReqData" type="tns:SubseReqData" minOccurs="0"/>
              <element form="unqualified" name="FactBundleTemplate" type="tns:FactBundleTemplate" minOccurs="0"/>
              <element form="unqualified" name="ContentInfo" type="tns:ContentInfo" minOccurs="0"/>
              <element form="unqualified" name="Discount" type="tns:Discount" minOccurs="0"/>
                <element form="unqualified" name="FactShoppingBasket" type="tns:FactShoppingBasket" minOccurs="0"/>
           </sequence>
        </complexType>

Here if you notice for example "CustomerID", "UID" and "Ext" are optional param as the minOccurs="0".
But the generated stub api is as below.
com.xstg.www.soap.schemas.services.v80.Xaction80Stateful_wsdl.Xaction80StatefulPortType.OPP_BOOK_F
 ACT(Description[] arg0, Long arg1, String arg2, ExtAuthElement[] arg3, Partner arg4, Subscriber arg5,
 FactBook arg6, FactAuth arg7, Price arg8, SubseReqData arg9, FactBundleTemplate arg10, ContentInfo
 arg11, Discount arg12, FactShoppingBasket arg13) throws RemoteException
It is clear that to invoke this method from client, I have to definitely supply all optional param variables also.
I have used <axis-wsdl2java> ant call to generate the stub.
May I know the reason for this? According to me, client stub should not expect me to provide all optional params also.
Please let me know if you need any additional info.
Update:
We are using axis-1.4. The above stub was generated using axis-1.4.
I tried the same with axis2. The generated stub is different in axis2. But I need to use axis-1.4 as the old client code was already developed using this version

A: Would you mind to try adding nillable="true".
Like:
<element form="unqualified" name="Ext" type="tns:ExtAuth" nillable="true" minOccurs="0"/>


text:
Q: Can swift closures be set to a default value when used as a parameter in a function? A pretty handy feature of Swift functions is that function parameters can have default values:
func someFunction(parameterWithDefault: Int = 42) {
    //if no arguments are passed to the function call,
    //value of parameterWithDefault is 42
}

If a parameter is a closure, is there a way to make it have a default value? See the example below:
func sendBody(
    body: NSData? = nil,
    success: (data: NSData) -> Void,
    failure: (data: NSData?) -> Void) {
}

Is there a way to not force the developer to pass a value for success or failure when calling sendBody?

A: Yes, functions are just values, so you can supply them as defaults
// just to show you can do it with inline closures or regular functions
func doNothing<T>(t: T) -> Void { }

func sendBody(
    body: NSData? = nil,
    success: (data: NSData) -> Void = { _ in return },
    failure: (data: NSData?) -> Void = doNothing
)
{  }

Alternatively, you could make them optional, that way you can detect if the caller passed one:
func sendBody(
    body: NSData? = nil,
    success: ((NSData) -> Void)? = nil,
    failure: ((NSData?) -> Void)? = nil
    )
{ success?(NSData()) }

sendBody(success: { _ in print("ah, yeah!") })

Also worth noting if you're doing this: if the caller uses the trailing closure syntax, this will be the last closure in the argument list.  So you want the last one to be the one the user is most likely to want to supply, which is probably the success closure:
func sendBody(
    body: NSData? = nil,
    success: ((NSData) -> Void)? = nil,
    failure: ((NSData?) -> Void)? = nil
    )
{
    if success != nil { print("passed a success closure") }
    if failure != nil { print("passed a failure closure") }
}

// this prints "passed a failure closure"
sendBody { data in
    print("which closure is this?")
}

Other than this, the order in the function declaration doesn't matter to the caller – defaulted arguments can be supplied in any order.

A: You could do something like this,
let defaultSuccess: NSData -> Void = {
    (data: NSData) in

}

let defaultFailure: NSData? -> Void = {
    (data: NSData?) in
}

func sendBody( body: NSData? = nil, success: (data: NSData) -> Void = defaultSuccess, failure: (data: NSData?) -> Void = defaultFailure) {
}

Then, you may be able to call either one of these methods. Notice sendBody which is called with default parameters.
sendBody()
sendBody(body: , success: , failure: )

You can also call with all the variants like passing just one of the argument in the above method, for that you have to call it with named parameter.
sendBody()
sendBody(body:)

sendBody(failure: )
sendBody(success:)

sendBody(body: , success: , failure: )

A: How to set a default value for a function parameter. Swift 4 and (probably) 5.
func someFunction(age: Int, doSomething:@escaping () -> Void = {}){
  //do work here

  //
  doSomething()
}

Then you can do this
someFunction(age: 18) {
  print("hello")
}

someFunction(age: 19)

You may or may not need to use the @escaping keyword. See Swift @escaping and Completion Handler for that.

A: My preferred way to specify public facing closures - in particular completion closures which you might want to store somewhere for later - is to define a typealias for them, like this:
public typealias FooCompletion = (String) -> Void

Then in the public facing function you can easily make it optional like this:
var onCompletion: FooCompletion? = nil

public func foo(completion: FooCompletion? = nil) {
    // Store completion for later
    onCompletion = completion
}

The completion parameter is optional, so it's allowed to be nil, and the default value is nil, meaning the caller doesn't have to specify it. Also, because you use the type in more than one place, if you need to change its definition during development there's only one place to do so. It's easy to call too:
private func someBackgroundThing() {
    var completionString = "done"
    ...
    onCompletion?(completionString)
}


text:
Q: These values aren't comparing in this function (vanilla javascript) I know the answer to this is probably really simple, as it's only a simple number guessing game. For whatever reason the comparison between "num1" and "num2" in the function and the code that follows doesn't execute.
Notably, the 2nd condition in the function works and I believe this is because they don't involve the first two arguments.
I also know it is easier to monitor the amount of guesses with a counter but I want to use the array for now. Unless the array is causing the problem then I'll remove it

let randomNumber = Math.floor(Math.random() * 100);

console.log(randomNumber);

const numberArr = [];

const sub1 = document.getElementById("sub1");

const numberGuessingGame = (num1, num2, arr) => {
  if (num1 === num2) {
    arr.splice(0, 3);
    randomNumber = Math.floor(Math.random() * 100);
    return alert(`Congratulations ${num1} is correct!`);
  } else if (arr.length === 3) {
    arr.splice(0, 3);
    console.log(randomNumber = Math.floor(Math.random() * 100));
    return alert("You've guessed three times, start over")
  } else if (!num1 === num2) {
    return alert("Try again");
  };
};

sub1.addEventListener("click", e => {
  const values = document.getElementById("number").value;
  numberArr.push(values);
  console.log(values);
  numberGuessingGame(values, randomNumber, numberArr);
  e.preventDefault();
  form1.reset();
});
<form id="form1">

      <input type="number" name="number" id="number" min="0" max="100">

      <button type="submit" form="form1" id="sub1">Submit</button>

</form>

A: Try making sure num1 and num2 are integers, or try:
if (num1 == num2) {
Also you probably want
    } else if (num1 != num2) {
        return alert("Try again");

in the third logical condition.

A: *

*You need to convert your textual value from the input control to an integer.

*Your test for inequality was flawed. You had else if (!num1 === num2)  instead of else if (num1 !== num2)
See //**** for changes

let randomNumber = Math.floor(Math.random() * 100);

console.log(randomNumber);

const numberArr = [];

const sub1 = document.getElementById("sub1");

const numberGuessingGame = (num1, num2, arr) => {
  if (num1 === num2) {
    arr.splice(0, 3);
    randomNumber = Math.floor(Math.random() * 100);
    return alert(`Congratulations ${num1} is correct!`);
  } else if (arr.length === 3) {
    arr.splice(0, 3);
    console.log(randomNumber = Math.floor(Math.random() * 100));
    return alert("You've guessed three times, start over")
  } else if (num1 !== num2) { //****
    return alert("Try again");
  };
};

sub1.addEventListener("click", e => {
  const values = parseInt(document.getElementById("number").value); //****
  numberArr.push(values);
  console.log(values);
  numberGuessingGame(values, randomNumber, numberArr);
  e.preventDefault();
  form1.reset();
});
<form id="form1">

      <input type="number" name="number" id="number" min="0" max="100">

      <button type="submit" form="form1" id="sub1">Submit</button>

</form>

A: The problem is that you are comparing a string with a number.
With value you query a string:
document.getElementById("number").value

Therefore, you must first convert the string into a number:
parseInt(document.getElementById("number").value)

Alternatively, you could make the comparison less restrictive and use type coercion (double equals, not triple equals):
if (num1 == num2)

Working example:

let randomNumber = Math.floor(Math.random() * 100);

console.log(randomNumber);

const numberArr = [];

const sub1 = document.getElementById("sub1");

const numberGuessingGame = (num1, num2, arr) => {
  if (num1 === num2) {
    arr.splice(0, 3);
    randomNumber = Math.floor(Math.random() * 100);
    return alert(`Congratulations ${num1} is correct!`);
  } else if (arr.length === 3) {
    arr.splice(0, 3);
    console.log(randomNumber = Math.floor(Math.random() * 100));
    return alert("You've guessed three times, start over")
  } else if (!num1 === num2) {
    return alert("Try again");
  };
};

sub1.addEventListener("click", e => {
  const values = parseInt(document.getElementById("number").value);
  numberArr.push(values);
  console.log(values);
  numberGuessingGame(values, randomNumber, numberArr);
  e.preventDefault();
  form1.reset();
});
<form id="form1">

      <input type="number" name="number" id="number" min="0" max="100">

      <button type="submit" form="form1" id="sub1">Submit</button>

</form>

Please note that your code contains a lot more bugs. For example, if the number is wrong, no alert is displayed because the following comparison is incorrect:
else if (!num1 === num2)

I have completely corrected your solution so that the game now works correctly. Please compare the two solutions and check if the differences are clear to you. If you have any further questions, feel free to post a comment.

const submitButton = document.getElementById('sub1');
const form = document.getElementById('form1');
let numberArray = [];
let randomNumber = generateRandomNumber();

function generateRandomNumber() {
  const number = Math.floor(Math.random() * 100);
  console.log(number);
  return number;
}

function checkInput(value) {
  if (value == randomNumber) {
    numberArray = [];
    randomNumber = generateRandomNumber();
    alert(`Congratulations ${value} is correct!`);
  } else if (numberArray.length >= 3) {
    numberArray = [];
    randomNumber = generateRandomNumber();
    alert(`You've guessed three times, start over`);
  } else {
    alert(`Try again`);
  }
}

submitButton.addEventListener('click', e => {
  e.preventDefault();
  const value = document.getElementById('number').value;
  console.log(value);
  numberArray.push(value);
  checkInput(value);
  form.reset();
});
<form id="form1">

      <input type="number" name="number" id="number" min="0" max="100">

      <button type="submit" form="form1" id="sub1">Submit</button>

</form>


text:
Q: get the source domain from a post request Third-party need to send Data to Salesforce using Https post request - They cant handle token access so it must be a force.com site.
I referred an Apex class to the site (Without using VF page), by taking the URL of the site and add the /services/apexrest/< nameOfTheClass >.
I want to know -
I there a way to get from Apex (not JS) the URL of the third-party who tried to get the service?
I need this URL because they cant supply an IP, and they want us to handle the access by the source domain from the URL...
What are the disadvantages of using a URL instead of an IP address?
Many thanks.

A: You should never use a domain from which a request originates as a way of "authentication", as a it doesn't provide any means of security and can easily be bypassed.
IP whitelisting is indeed the more secure way to go, as even though an IP address from which a request is sent CAN be spoofed, it will never receive any data back, since it will be sent back to the "legitimate" client with that particular IP address.


text:
Q: Execute two query from mysql in same page by passing value in url I have created a page in php
I want to show when user type in weektable.php it should show all the value i.e it should execute this query
 $sql = "SELECT * FROM `battery`";

above query display all the value.
and when user type in url weektable.php?sort=w it should execute this query
 $sql = "SELECT * FROM battery WHERE date BETWEEN '".$week."' AND '" .$date."'";

above query display value between current date and one week before date.
But I have no Idea how to do it.
I want to do it without go to another page i.e I want show both the value in same page
Below is my PHP code:
<?php
$hostdb = 'localhost';
$namedb = 'my_db';
$userdb = 'root';
$passdb = 'root';

try {

  $conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
  $conn->exec("SET CHARACTER SET utf8");      // Sets encoding UTF-8

$currDate = date('Y-m-d H:i:s');
$date = $currDate ;
// parse about any English textual datetime description into a Unix timestamp
$ts = strtotime($date);
// calculate the number of days since Monday
$dow = date('w', $ts);
//$offset = $dow - 3;
$offset = $dow - date('d');
if ($offset < 0) {
    $offset = 6;
}
// calculate timestamp for the Monday
$ts = $ts - $offset*86400;
// loop from Monday till Sunday
for ($i = 0; $i < 1; $i++, $ts += 86400){
    //print date("Y-m-d l", $ts) ."
" . "\n";
$week = date("Y-m-d H:i:s", $ts) ."
";

}

        $sql = "SELECT * FROM `battery`";
        $sql = "SELECT * FROM battery WHERE date BETWEEN '".$week."' AND '" .$date."'";

  $result = $conn->query($sql);

echo "

User Id
Firstname
LastName
EmailId
Date

";

  while($row = $result->fetch(PDO::FETCH_ASSOC)) {
  echo "
";

  echo "" . $row['id'] . "	";
  echo "" . $row['firstname'] . "	";
  echo "" . $row['lastname'] . "	";
  echo "" . $row['emailid'] . "	";
  echo "" . $row['date'] . "	";

  echo "
";
  }

echo "
";

} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();

}

?>

Please I need help.
Any Help will be greatly appreciated.

A: Define a different variable for second query. such as $sql_range = "SELECT * FROM battery WHERE date BETWEEN '".$week."' AND '" .$date."'"; and then fetch results for it in a separate variable $result2 = $conn->query($sql_range );
I hope that should solve your question.

A: if (isset($_GET["sort"])) {
  if ($_GET["sort"] == "w") {
    $sql = "SELECT * FROM battery WHERE date BETWEEN '".$week."' AND '" .$date."'";
  }
}else{
    $sql = "SELECT * FROM `battery`";
}

I'm assuming that you are requesting this page with something like:
./weektable.php?sort=w

I was also a bit lazy and should have added as isset($_GET["sort"]) - I have edited the code sample above..... EDIT sorry become very rushed IRL, I hope this helps. Thanks to those that pointed out earlier error.


text:
Q: Optimizing file write C how can I improve speed while working with a file?
Here's my code:
#include <stdio.h>
#include <string.h>
#include <sys/time.h>

void swap(char *x, char *y)
{
  char temp;
  temp = *x;
  *x = *y;
  *y = temp;
}

void permute(char *a, int l, int r)
{
  int i;
  if (l == r) {
    printf("%s\n", a);
    FILE *fp;
    fp = fopen("test.txt", "a");
    fprintf(fp,"%s\n", a );

    fclose(fp);
  }

  else
  {
    for (i = l; i <= r; i++)
    {
      swap((a+l), (a+i));
      permute(a, l+1, r);
      swap((a+l), (a+i)); //backtrack
    }
  }
}

int main()
{
  remove("test.txt");
  struct timeval  tv1, tv2;
  gettimeofday(&tv1, NULL);
  char str[] = "ABCD";
  int n = strlen(str);
  permute(str, 0, n-1);

  gettimeofday(&tv2, NULL);
  printf ("Total time = %f seconds\n",
  (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 +
  (double) (tv2.tv_sec - tv1.tv_sec));

  return 0;
}

If I run it saving the permutations to a file I get Total time = 0.161452 seconds
Without saving permutations to a file I get Total time = 0.00000 seconds
Thanks!

A: Basic optimizations:

*

*Leave the file open for as long as you write to it.

*There is no need to remove the file at start up, you can as well "w" write to it and it will have the same effect.

*Replace recursion with a loop.

These will make a vast difference. Opening a file takes lots of time, as does writing to it or removing it. Everything file-related are the main bottlenecks in this program.
As for the recursion, you have written a version that isn't likely tail-call optimized, so it will bloat up the stack needlessly.
Advanced optimizations:

*

*Separate algorithm from printing to screen and/or file. Store all results in a RAM buffer. When done, print to screen or file.

*Outsource printing to file to a dedicated thread, which can chew away on the file write in the background while the main thread does other things. That way, the file write isn't a slow, blocking call.

*Investigate the algorithm itself. Could you do things in different order? Minimize the number of branches?

Micro-optimizations (will only have a small effect):

*

*Replace strlen with sizeof.

*Replace printf/fprintf with puts/fputs.

*restrict qualify the pointers in swap (probably not needed since it should get inlined).

A: Try open/close file only once, in the main() function, like below:
void permute(char *a, int l, int r, FILE *fp)
{
    int i;
    if (l == r)
    {
        printf("%s\n", a);
        fprintf(fp, "%s\n", a);
    }
    else
    {
        for (i = l; i <= r; i++)
        {
            swap((a+l), (a+i));
            permute(a, l+1, r, fp);
            swap((a+l), (a+i)); //backtrack
        }
    }
}

int main()
{
    remove("test.txt");
    struct timeval  tv1, tv2;
    gettimeofday(&tv1, NULL);
    char str[] = "ABCD";
    int n = strlen(str);

    // open file
    FILE *fp;
    fp = fopen("test.txt", "a");

    permute(str, 0, n-1, fp);

    // close file
    fclose(fp);

    gettimeofday(&tv2, NULL);
    printf ("Total time = %f seconds\n",
        (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 +
        (double) (tv2.tv_sec - tv1.tv_sec));

    return 0;
}


text:
Q: Pyspark script to copy table data from postgres to s3 in parquet format I am working on a pyspark script to copy data from postgres table to s3 in parquet format.
My table has more than 150 million records. The script works fine if a limit the row count but cannot load the complete data.
Please give your suggestions to improve the performance.
'''
import psycopg2
import datetime
class DataMigrator:

  def __init__(self, database, schema, host, table, partition_key, s3bucket):
    self.database = database
    self.host = host
    self.schema = schema
    self.table = table
    self.bucket = s3bucket
    self.partition_key = partition_key

  def connection_props(self):

    jdbcHostname = self.host
    jdbcDatabase = self.database
    jdbcPort = 5432
    username=
    password=
    jdbcUrl = {4}&ssl=false'".format(jdbcHostname, jdbcPort, jdbcDatabase, username, password)
    connectionProperties = {
                            "user" : username,
                            "password" : password,

                          }
    return connectionProperties, jdbcUrl

  def read_data(self):
    conpropererties = self.connection_props()[0]
    url = self.connection_props()[1]
    pushdown_query = "(select * from {DB}.{SCHEMA}.{TABLE} ) a".format(DB=self.database, SCHEMA=self.schema, TABLE=self.table)
    df = spark.read.jdbc(url=url, table=pushdown_query, properties=conpropererties).coalesce(200)
    return df

  def write_parquet(self):
    print(datetime.datetime.now())
    dataframe = self.read_data()

    #print(ind, datetime.datetime.now())
    dataframe.write.partitionBy("{PARTITON_KEY}".format(PARTITON_KEY=self.partition_key))\
      .mode("overwrite")\
      .parquet("s3a://{BUCKET}/migration/{table}".format(BUCKET=self.bucket, TABLE=self.table))

if __name__ == "__main__":
  migrator = DataMigrator(database='coficoreply', schema='coficoreply', host=' ', table='item',  partition_key='created', s3bucket='db2-databricks-prod/dwh')
  migrator.write_parquet()

'''


text:
Q: Customize notifications on Android wear (watch) I'm developing an app on Android which send notifications connected to an Android watch (emulator).
I can display the notifications on the watch all is ok but I would like to customize these notifications on the watch. I already used the WearableExtender object but you only can change the background and hide the logo and that's not enough. I would like to create my own layouts.
Is it possible ?
Thanks.

A: I don't know of any way to further customize the "peek" that initially appears, but you can build a completely custom screen for the full notification. See Google's Custom Layouts documentation.


text:
Q: pip: command not found (OS X) - editing bash_profile doesn't work I have installed Python 2.7 on Mac and installed pip (with the eventual goal of installing python-swiftclient: https://www.swiftstack.com/docs/integration/python-swiftclient.html )
Unfortunately I get the error "command not found" on using pip.
I have followed the instructions in this thread: pip: command not found I added export PATH=${PATH}:/Library/Python/2.7/site-packages (I verified that this is the correct path) to .bash_profile and ran the source command.
Pip is still not being found.
Anyone know a solution? (Keep in mind this is my first foray into installing python and doing command line stuff. I'm not a born unix user so installing packages and such is pretty new to me...)
Thanks!

A: When I use python on Mac, I simply install Anaconda, which is shipped with pip. So maybe you could use that.
Anaconda

A: Try using python -m pip until you get this resolved (or forever if you want :P)


text:
Q: Using normal distribution to create confidence interval Let $Y~N(\mu, 1)$. Use the fact that $P(\left | Y-\mu \right | < 1.96\sigma) \approx.95$ to construct an interval $(a(Y), b(Y))$, such that the probability $\mu$ is in the interval is approximately 0.95.
I am not sure where to start on this one. Any and all help is appreciated.

A: We will transform $|Y−μ|<1.96\sigma$ into the form $a(Y)<\mu<b(Y)$:
$$|Y−μ|<1.96\sigma\Leftrightarrow1.96\sigma<Y−μ<1.96\sigma\Leftrightarrow1.96\sigma-Y<−μ<1.96\sigma-Y$$$$\Leftrightarrow Y-1.96\sigma<μ<Y+1.96\sigma.$$
From $P(\left | Y-\mu \right | < 1.96\sigma) \approx0.95$ and transforming done above we obtain $P(Y-1.96\sigma<μ<Y+1.96\sigma)\approx0.95.$


text:
Q: How is Hölder's inequality with $p=q=2$ equivalent to Cauchy-Schwarz inequality? The Cauchy-Schwarz inequality says that
$$\left|\sum_i x_i y_i \right| \leq \sqrt{\sum_i x_i^2} \sqrt{\sum_i y_i^2}$$
Hölder's inequality for the special case $p=q=2$ says that
$$\sum_i |x_i y_i| \leq \sqrt{\sum_i x_i^2} \sqrt{\sum_i y_i^2}$$
Clearly the former implies the latter via the triangle inequality. However, there appears to be general consensus online that the latter also implies the former. For example, mathworld

[Hölder's inequality with] $p=q=2$ becomes Cauchy's inequality

or Wikipedia

The special case [of Hölder's inequality with] p = q = 2 gives a form of the Cauchy–Schwarz inequality.

Why is this true? It seems to me that Cauchy's inequality is a stronger statement than this special case of Hölder's inequality, and so Hölder's inequality does not become Cauchy's inequality at all.
This has been asked before here Why is the Cauchy Schwarz inequality a special case of Holder's inequality? but not answered. In particular, Hrit Roy's final comment on the answer is not dealt with.

A: "Clearly the former implies the latter via the triangle inequality." No, it is actually the other way around. The triangle inequality states
$$|\sum_i x_iy_i| \leq \sum_i |x_i y_i|,$$
so clearly Hölders inequality implies Cauchy-Schwarz and it would seem that Hölders is the stronger statement, although they are equivalent. To see that Cauchy-Schwarz inequality implies this special case of Hölders inequality, apply Cauchy-Schwarz inequality to the vectors $(|x_1|,...,|x_n|)$ and $(|y_1|,...,|y_n|)$.

A: Actually Holder's inequality for $p=q=2$ is stronger than CS inequality.
Triangle inequality:
$\left|\sum{x_{i}y_{i}}\right|\leq\sum{\left|{x_{i}y{i}}\right|}$
Therefore:
$\left|\sum{x_{i}y_{i}}\right|\leq\sum{\left|{x_{i}y{i}}\right|}\leq\sqrt{\sum{x_{i}^{2}}}\sqrt{\sum{y_{i}^{2}}}$


text:
Q: Next Auth -TypeError: Cannot read properties of undefined (reading 'nodeName') So, I am making a authentication for a project using next-auth, everythings is fine. I can Sign in and Sign out using My github acc. But when I sign in there is an error
'TypeError: Cannot read properties of undefined (reading 'nodeName')'
const { data: session, loading } = useSession()
 const handleSignIn=() => {

    signIn('github');

the errror automatically disappear after 3 or 4 sec.
When i remove the 'github' from the bracket it doesn't show any error but take me to a default next-auth sign in page which is I didn't wanted. How can I fix this error?


text:
Q: How can I use a different SSH port on TextWrangler? I want to use a different port number for connecting to a remote server via SSH on TextWrangler on Mac OS X.
How can I do that?

A: With most programs you can use various ports for, you simply append :portnum to the end of the ip or domain name.
For example, I used:
Server: http://192.168.1.1:2222

Works fine for me.


text:
Q: Optimizing batched matrix multiplication opencl code Below is an opencl kernel which performs blocked matrix multiplication for multiple independent matrices. selectMatrixA and selectMatrixB store multiple matrices (same size and square matrices) in row major order.
// Matrix multiplication: C = A * B.

#define BLOCK_SIZE 20
#define MATRIX_SIZE 100 * 100

#define BLOCK_DIMX 5 // Number of blocks in the x dimension

__kernel void
batchedMatrixMul(__global float *selectMatrixC, __global float *selectMatrixA, __global
float *selectMatrixB, int wA, int wB)
{
    // Block index
    int bx = get_group_id(0);
    int by = get_group_id(1);

    __global float *C = selectMatrixC + (bx/BLOCK_DIMX) * MATRIX_SIZE;
    __global float *A = selectMatrixA + (bx/BLOCK_DIMX) * MATRIX_SIZE;
    __global float *B = selectMatrixB + (bx/BLOCK_DIMX) * MATRIX_SIZE;

    int tx = get_local_id(0);
    int ty = get_local_id(1);

    float Csub = 0;

    // Identify the row and column of the C matrix to work on

    int Row = (by * BLOCK_SIZE)  + ty;
    int Col = ((bx %(BLOCK_DIMX)) * BLOCK_SIZE) + tx;

    // Declaration of the local memory array As used to store the sub-matrix of A
    __local float As[BLOCK_SIZE][BLOCK_SIZE];

    // Declaration of the local memory array Bs used to store the sub-matrix of B
    __local float Bs[BLOCK_SIZE][BLOCK_SIZE];

    // Loop over all the sub-matrices of A and B required to compute the block sub-matrix
    for (int m = 0; m < wA / BLOCK_SIZE; ++m)
    {

        // Load the matrices from global memory to local memory. Each thread loads one
        //element of each matrix
        As[ty][tx] = A[Row * wA + m * BLOCK_SIZE + tx];
        Bs[ty][tx] = B[(m * BLOCK_SIZE + ty)*wA + Col];

        // Synchronize to make sure the matrices are loaded
        barrier(CLK_LOCAL_MEM_FENCE);

        // Multiply the two matrices together each thread computes one element of the block
        //sub-matrix
        for (int k = 0; k < BLOCK_SIZE; ++k)
            Csub += As[ty][k] * Bs[k][tx];

        // Synchronize to make sure that the preceding computation is done before loading
        //two new sub-matrices of A and B in the next iteration
        barrier(CLK_LOCAL_MEM_FENCE);

    }

    // Write the block sub-matrix to device memory each thread writes one element
    C[Row * wA + Col] = Csub;

}

Here is how I launch the kernel:
localWorkSize[0] = BLOCK_SIZE;
localWorkSize[1] = BLOCK_SIZE;

// for a 100 X 100 matrix, MATRIX_DIMX = MATRIX_DIMY = 100
globalWorkSize[0] = MATRIX_DIMX * NUM_MATRICES;
globalWorkSize[1] = MATRIX_DIMY ;

cl_event             event;
errcode = clEnqueueNDRangeKernel(clCommandQueue,
          clKernel, 2, NULL, globalWorkSize,
          localWorkSize, 0, NULL, &event);

Below are some performance numbers when running this on an NVIDIA Grid K520:
1. matrix size:100 X 100 . Number of matrices = 20000. Time taken for multiplication =
0.262 seconds. As shown in the code, the block size was set to 20. Block size of 10 was
slower. This calculates to around 152 GFLOPS

2. matrix size: 10000 X 10000. Number of matrices = 1. Time taken for multiplication = 10.6
seconds. Here also the block size was 20. Using a block size of 50 is not possible due to
the size of the local memory.

Can someone please help me to understand why the code is running slow, and why 2. is so much slower than 1. I am new to OpenCL, and I am wanting to learn how to optimize code based on the underlying architectural details.

A: The reason why your first test is so much faster is because there is a difference in the amount of work each test is doing. Actually, a factor of 50x.
Big-O for square matrix multiplication is O(n^3). See: why is the time complexity of square matrix multiplication defined as O(n^3)? As a result, the 10k squared matrix actually takes 1 million times more work to multiply than a single 100x100 multiplication. Your 20000 executions of the 100x100 multiplication does not make up for the massive amount of work needed to multiply the large matrices once.
Matrix multiplication is just many dot-products.Your algorithm only breaks the dot products into groups to easy handling, and does not use any special tricks to reduce the numbers in my calculations below.
For your small matrix test:
Total dot products: 10^4
MADs per dot product: 10^2
Total matrix-multiply operations: 20000 = 2*10^4
Total multiply-adds: 2* 10^(4+2+4) = 2*10^10 = 20,000,000,000

20 Billion.
Large matrix test:
Total dot products: 10^8
MADs per dot product: 10^4
Total multiply operations: 1 (or 10^0)
Grand total multiply-adds: 10 ^ (8 + 4 + 0) = 10^12 = 1,000,000,000,000

1000 Billion.
Your 10000x10000 test was technically running faster -- crunching 50x more operations in only 40x more run time.
Read more about 'special tricks' here: http://en.wikipedia.org/wiki/Strassen_algorithm. Even though this algorithm is not considered practical for GPU computing. Mor complicated algorithms also exist, but the brute-force approach on graphics hardware seems to be used most often.
Why is your kernel running slowly in general? There are a number of different optimizations you can use to speed things up. Below are just a few you can google and experiment with yourself. You will probably come across some I haven't mentioned here.

*

*Optimize work group and block sizes. see opencl PREFERRED_WORK_GROUP_SIZE

*Use float4 datatype. opencl includes a dot product function which computes dot product for floatn datatypes.

*Transpose matrix B before running the kernel. you can use another kernel to do the transposition.

A: In my opinion the reason why 2. is so much slower is that access pattern of matrix multiplication is not so cache friendly. If you need to get first value of first row and first value of second row, they are stored to memory very far away from each other. If matrix size increases, they are stored even further away from each other. This will lead to lot of cache misses.
I don't have any personal experience on matrix multiplication, but I just thought that it might be possible to store your data in Z-order curve to achieve more cache friendly pattern. From the references of Wikipedia it seems something like that has been done by Valsalam & al 2002.
Another quick fix, I would try before using lot of time to Z-ordering, is to use private variables and get rid of barriers. Even it requires more loads from global memory, it might be possible that compiler can do much better optimization to that code.


text:
Q: Environment aligned doesn't output first part in bracket \begin{equation}
    \begin{aligned}
        [c\mathbf{v}+c'\mathbf{v}',\mathbf{w}]=&c[\mathbf{v},\mathbf{w}]+c'[\mathbf{v}',\mathbf{w}],\\
        [\mathbf{v},c\mathbf{w}+c'\mathbf{w}']=&c[\mathbf{v},\mathbf{w}]+c'[\mathbf{v},\mathbf{w}'],
    \end{aligned}
\end{equation}

In this code, [c\mathbf{v}+c'\mathbf{v}',\mathbf{w}] is not shown in the equation. Is it because of the aligned environment? How to fix it?

A: Update Jan. 2021. The current version of the amsmath package, 2020/09/23 v2.17i, no longer generates the problem described in the OP's query. Hence, taking "precautions" such as inserting a \relax or {} element before a [ element at the start of a line is no longer necessary.
What you're experiencing is the fact that the aligned environment -- as set up by the amsmath package -- is set to scan ahead for a positioning argument such as [t] or [b]. Material that's found in square brackets but which doesn't meet this format is simply discarded.
I can think of two solutions:

*

*Insert \relax before the left square bracket (it will stop the bracket from being interpreted as an argument);

*Insert {} (an empty math atom) before the left square bracket;

*Load the mathtools package instead of the amsmath package, as the former takes care to disable this generally-unexpected-and-unwelcome setting.
A separate matter: To get the correct (and symmetric) amount of spacing around the = symbols, you should write &= rather than =&.


text:
Q: PHP Fatal error: Allowed memory size of 1610612736 bytes exhausted Can someone explain to me a little bit more detailed how can I fix this?
I am trying to get lighthouse pack for graphql-playground.
I have tried this but does not work said can't find this composer.phar
 php composer.phar COMPOSER_MEMORY_LIMIT=-1 require nuwave/lighthouse


text:
Q: Как реализованы обучающая платформа Codecademy и ей подобные? Кто может объяснить, как реализован ввод и обработка кода у обучающих сервисов вроде Codecademy.com и ей подобных?
С FreeCodeCamp более-менее ясно - там обрабатывается только html+css+js код. А вот у Codecademy обрабатывается и Java, и Ruby... Сомневаюсь, что они позволяют обрабатывать чужой код на своих серверах...
Есть ли готовые решения для этих целей, кто знает?


text:
Q: python - Caesar cipher - decryption of string using ord() and chr() Ceasar cipher encryption method.
Using ord() and chr () to decrypt a string.
If a value with the offset is < 32 or > 126 on the ASCII table it will loop back around to the appropriate value.
However, it is not working 100%, skips over symbols from the ASCII table for some reason, and isn't getting every value correct?
input - yohvldvk#wioH#$
offset - 5
expected output - tjcqg_qf}rdjC}~
user_decrypt_message = input("Please enter string to decrypt: ")
decrypted_message = ""
user_decrypt_offset = 0

while not user_decrypt_offset in range (1, 95):
    user_decrypt_offset = int(input("Please enter offset value (1 to 94): "))

for letter in user_decrypt_message:
    if ord(letter) + user_decrypt_offset < 32:
        decrypted_message += chr(ord(letter) - user_decrypt_offset + 95)
    elif ord(letter) + user_decrypt_offset > 126:
        decrypted_message += chr(ord(letter) + user_decrypt_offset - 95)
    else:
        decrypted_message += chr(ord(letter) - user_decrypt_offset)

print()
print("Decrypted string: ")
print(decrypted_message)

A: def inputOffset():
    user_decrypt_offset = 0
    while user_decrypt_offset < 1 or user_decrypt_offset >= 95:
        user_decrypt_offset = int(input("Please enter offset value (1 to 94): "))
    return user_decrypt_offset

def decrypt(iuser_decrypt_message, user_decrypt_offset):
    decrypted_message = ""
    for letter in iuser_decrypt_message:
        if ord(letter) + user_decrypt_offset < 32:
            print("1. if", ord(letter))
            decrypted_message += chr(ord(letter) - user_decrypt_offset + 95)
        elif ord(letter) + user_decrypt_offset > 126:
            print("2. if", ord(letter))
            decrypted_message += chr(ord(letter) + user_decrypt_offset - 95)
        else:
            print("3. if", ord(letter))
            decrypted_message += chr(ord(letter) - user_decrypt_offset)
        print(decrypted_message, ord(decrypted_message[-1]))
    return decrypted_message

iuser_decrypt_message = input("Please enter string to decrypt: ")
user_decrypt_offset = inputOffset()
decrypted_message = decrypt(iuser_decrypt_message, user_decrypt_offset)

print()
print("Decrypted string: ")
print(decrypted_message)

I just rewrote your code and added a few print statements. If you run this code you will see that when the loop inside decrypt() function come to '#'(whose ASCII value is 35) it will jump to 3. if statement and it will append a character with ASCII value 30(35 - 5) which is ␞(record separator delimiter). I guess there is a problem with it because it won't display.

A: The problem is that your code is not consistent in subtracting the offset. Sometimes it adds it, sometimes it subtracts it. It should always do the same thing.
To avoid this mistake, first calculate the new offset, put it in a variable, and only work with that name from then onwards.
So:
for letter in user_decrypt_message:
    # Subtract the offset (never add it)
    new_offset = ord(letter) - user_decrypt_offset
    if new_offset < 32:
        decrypted_message += chr(new_offset + 95)
    elif new_offset > 126:
        decrypted_message += chr(new_offset - 95)
    else:
        decrypted_message += chr(new_offset)

It may be useful to work with the modulo operator:
for letter in user_decrypt_message:
    new_offset = (ord(letter) - user_decrypt_offset - 32) % 95 + 32
    decrypted_message += chr(new_offset)

And you can also build the string via a list comprehension:
decrypted_message = "".join(
    chr((ord(letter) - user_decrypt_offset - 32) % 95 + 32)
    for letter in user_decrypt_message
)


text:
Q: TcpListener Timeout/about/something? Without ASync? I create a thread which uses TcpListener and when my app closes i'd like the thead to terminate. I can call abort but the thread is still alive since TcpListener is blocking with AcceptTcpClient.
Is it possible to about or set a timeout or to do SOMETHING with AcceptTcpClient? i cant imagine how it would be useful if theres no way to stop it from blocking forever. My code is serial and i would like it to stay that way so is there a solution without using BeginAcceptTcpClient? and writing ASync code?

A: You could replace the call to AcceptTcpClient with one for Socket.Select(), which can timeout.
var sockl = new ArrayList { listener.Server };
Socket.Select(sockl, null, null, _timeout_);
if (sockl.Contains(listener.Server)) listener.AcceptTcpClient();

A: I use AcceptTcpClient() in a while(!Disposing) loop to accept my clients.
When I dispose the Class I call the Stop() function of the TcpListener and set Disposing to true; like this:
public class Server : IDisposable
{
    private TcpListener _tcpListener;
    private bool _isDisposing;

    public void Start()
    {
        (new Thread(new ThreadStart(ListenForClients))).Start();
    }

    private void ListenForClients()
    {
        this._tcpListener = new TcpListener(System.Net.IPAddress.Any, this.ListenPort);
        this._tcpListener.Start();

        while (!_isDisposing)
        {
            //blocks until a client has connected to the server
            TcpClient client = this._tcpListener.AcceptTcpClient();

            if (client == null) continue;

            //create a thread to handle communication with connected client
        }
    }

    public void Dispose()
    {
        this._isDisposing = true;
        this._tcpListener.Stop();
    }
}

Note that this is just a small excerpt from a server class...
This way, the program can stay locked on the AcceptTcpClient() function and still be ended.
However, the listening itself must also happen on a separate Thread (Start() function).

A: Simple solution. CHECK with pending.
while(!server.Pending())
{
    Thread.Sleep(10);
}
TcpClient client = server.AcceptTcpClient();


text:
Q: How to disable @Assert validation on removed widgets I don't know why assert validation still applies to a widget that I removed!
I create a form
$form = $this->createForm(UserType::class, $doctor);

then i removed some fields from it
$form ->remove("picture");
$form ->remove("phone");

Indeed the fields are removed from the view ! but when I click on submit i still get "@Assert\NotBlank() error message ! on phone!
On the controller I did
$doctor = new User();
$form = $this->createForm(UserType::class, $doctor);

$form ->remove("picture");
$form ->remove("phone");

Here is the code of User entity (i removed getters and setters)
<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 * @UniqueEntity(
 *     fields={"username"},
 *     message="The username is already used."
 * )
 * @UniqueEntity(
 *     fields={"email"},
 *     message="The Email is already used."
 * )
 */
class User implements UserInterface
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255 ,  unique=true)
     * @Assert\NotBlank()
     */
    private $username;

    /**
     * @ORM\Column(type="string", length=255 , unique=true)
     * @Assert\NotBlank()
     * @Assert\Email(message="This Email is not valid ")
     */
    private $email;

    /**
     * @ORM\Column(type="string", length=255 )
     * @Assert\NotBlank()
     * @Assert\Length(
     *      min = 8, max = 30,
     *      minMessage = "Your password must be between 8 and 30 characters.")
     *  @Assert\EqualTo(propertyPath = "password2", message="Passwords does not match!" )
     */
    private $password;

   /**
     * @Assert\NotBlank()
    *  @Assert\EqualTo(propertyPath = "password", message="Passwords does not match!" )
     */

    private $password2;

    /**
     * @ORM\Column(type="string", length=50, nullable=true),
     * @Assert\NotBlank(),
     * @Assert\Regex(
     * pattern="/[0-9]{8}/",
     * message="Invalid Phone number"
     * )
     */
    private $phone;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $picture;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $braclet_id;

    /**
     * @ORM\Column(type="boolean")
     */
    private $is_doctor;

    /**
     * @Assert\Length(min=5, max=100)
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank()
     */
    private $Full_Name;

    /**
     * @ORM\Column(type="boolean")
     */
    private $isActive;

 }

Here is the code of the view:
{{ form_start(form, {attr: {novalidate: 'novalidate'}}) }}

        {{ form_widget(form.Full_Name, {'attr': {'class': 'form-control', 'placeholder': 'Full Name','type': 'text'} }) }}
        {{ form_errors(form.Full_Name) }}

        {{ form_widget(form.username,  {'attr': {'class': 'form-control', 'placeholder': 'Username'} }) }}
        {{ form_errors(form.username) }}

        {{ form_widget(form.email,  {'attr': {'class': 'form-control', 'placeholder': 'Email Adress'} }) }}
        {{ form_errors(form.email) }}

        {{ form_widget(form.password, {'attr': {'class': 'form-control', 'placeholder': 'Password','type': 'Password'} }) }}
        {{ form_errors(form.password) }}

        {{ form_widget(form.password2, {'attr': {'class': 'form-control', 'placeholder': 'Confirm Password','type': 'Password'} }) }}

        {{ form_errors(form.password2) }}

        <button class="btn btn-raised g-bg-cyan waves-effect">SIGN UP</button>

{{ form_rest(form) }}
{{ form_end(form) }}

A: That's because you are validating your entity regardless of the fields you add or remove. In these cases you can use validation groups:
https://symfony.com/doc/current/validation/groups.html
So for your case you could create a new group next to the "Default", for example "doctor".
For all the fields that need validation in both add:
* @Assert\NotBlank(groups={"Default", "doctor"})
For the phone field:
* @Assert\NotBlank(groups={"Default"})
Don't forget to set the correct validation group in the form:
https://symfony.com/doc/current/form/validation_groups.html


text:
Q: Legal requirement for measurement equipment calibration in manufacturing We have a build approaching but one of our PSU's used in the function tester will be out of calibration in 3 weeks.  Most likely we will complete the build whilst the PSU is still within it's calibration date but if the build overruns there is a danger that the PSU will go out of calibration.
I can send the PSU for calibration now but this will delay the build or hope that we encounter no major issues and the build completes before the calibration expires.
Realistically, calibration is based on probability.  Calibrated now, so probably good for a year.
Extending a day or two past the calibration due date should not really adversely affect the test outcome but I am concerned about the legality.
Does anyone know what the legal impact obligation is during manufacturing with relation to the calibration date of test equipment?

A: IANAL, but it seems to me that the only legal impact of using an out-of-calibration power supply would be the extent to which it violates the terms of the specific contracts you have in place with your customers.
Outside of that, you simply need to evaluate the risk that the power supply will actually be outside of its performance specifications, and the extent to which this will affect the specifications of the gear you're producing and/or testing with it.
It isn't as though the power supply will suddenly change its characteristics on the day that its certificate expires — the date on the certificate is just a conservative estimate on how fast the unit's parameters drift or age with time. You could conceivably go ahead and do the production run past the date on the certificate, and then have the calibration lab tell you whether it was in fact out of calibration afterward. If not, then you have no exposure at all.


text:
Q: React: Always Keep the first four characters onchange So basically I have an input component for phone numbers. I am using the react native phone input library, so the international code is added by default. I want to set the input change in such a way that the international code +234 never gets deleted with the back button. I believe regex is the way to go using let regex = /[^+234]/g to match the start but I don't know how to proceed next.
So basically if a user types any number in, +234 is added by default to the beginning of phoneNumber. With the current design of the library, the +234 prefix gets deleted when the user deletes the number . What I want is for the +234 to be kept no matter how much the user deletes
CODE
 const onChangePhoneNumberHandler = (phoneNumber: string) => {
        setPhoneNumber(phoneNumber)
        showMessage({ text: ``});

    }

    <PhoneInput
         value={phoneNumber}
        onChangePhoneNumber={onChangePhoneNumberHandler}
    />

A: const onChangePhoneNumberHandler = (phoneNumber?: string) => {
    const newNumber = phoneNumber?.includes("+234") ? phoneNumber : "+234"
    setPhoneNumber(newNumber)
    showMessage({ text: ``});

}

Might wanna fine tune the logic part but that is a quick solutin


text:
Q: url_for migration to Flask Restful I had my Flask routes defined like this:
@api_app.route('/api/1.0/infrastructure/', methods=['POST'])
def create_infrastructure():

     return (jsonify({'job': job_instance.reference}), 202,
                    {'Location': url_for('get_job', ref=job_instance.reference, _external=True)})

get_job function:
@api_app.route('/api/1.0/job/<string:ref>', methods=['GET'])
def get_job(ref):

        job = Model.Job.query.filter_by(reference=ref).first()
        if not job:
            abort(400)
        return jsonify({'job': job.reference})

I migrated to a flask.ext.restful environment and now looks like this:
from flask.ext.restful import Resource
    class Job(Resource):
        def get(self, ref):
            job = Model.Job.query.filter(Model.Job.reference == ref).first()
            if job:
               return jsonify(job.serialize())

            resp = Response(status=404, mimetype='application/json')
            return resp

In this class based API using flask.ext.restful
How to define the url_for parameters in this class based environment?
In my main app file:
api.add_resource(Job, '/api/1.0/job/<string:ref>')
imbue_api.add_resource(Infrastructures, '/api/1.0/infrastructure')

A: The easiest way is to just use flask-restful's Api.url_for.
So instead of writing
url_for('get_job', ...)

You would have to
from flask_restful import Api

Api.url_for(Job, ...)

Note:
It is important to make sure you don't create circular imports by importing classes into each other. My personal preferred way to organize this is to import all involved resouces in the __init__.py and then if you want to link to them you import .Job, that way you enforce a clean import order.

A: Thanks I used the following:
from flask import current_app
api = restful.Api

In my Infrastructure class:
response.headers['Location'] = api.url_for(api(current_app),
                                                           Job,
                                                           ref=job_instance.reference,
                                                           _external=True)

And works fine now


text:
Q: PCA vs t-SNE for data-visualisation: is there a way of doing loading plots with t-SNE? In the past i've used to using PCA and loading plots to visualise data using  stats::prcomp and ggbiplot. Like this:

I've recently been introduced to t-SNE analysis (late to the game here) that has been revolutionary in reduction analysis and exploring patterns in data.
While t-SNE is picking up clusters in my data that PCA can't clearly distinguish, the downside is that there's no loading plot to understand which characteristic influences each cluster in space.
Is there any way with t-SNE I can form some sort of loading plot? Or are there any complementary methods associated with t-SNE that can be used? I'd really like to keep the t-SNE plot over the PCA plot for visualizing a particular dataset, but without the loading plot it's not as informative.
Any ideas? Dummy data below:
library(FD)
library(ggbiplot)

# generate random data
a <- sample(x = 1:5, size = 100, replace = TRUE)
b <- sample(x = 1:5, size = 100, replace = TRUE)
c <- sample(x = 1:5, size = 100, replace = TRUE)
d <- sample(x = 1:5, size = 100, replace = TRUE)
e <- sample(x = 1:5, size = 100, replace = TRUE)
f <- sample(x = 1:5, size = 100, replace = TRUE)
g <- sample(x = 1:5, size = 100, replace = TRUE)

# make ordinal
a <- ordered(a, levels = 1:5)
b <- ordered(b, levels = 1:5)
c <- ordered(c, levels = 1:5)
d <- ordered(d, levels = 1:5)
e <- ordered(e, levels = 1:5)
f <- ordered(f, levels = 1:5)
g <- ordered(g, levels = 1:5)

#as dataframe
table <- as.data.frame(cbind(a,b,c,d,e,f,g))

#PCA
pca <- prcomp(table,center = TRUE,scale. = TRUE)
ggbiplot(pca)

#t-SNE
gower_dist <- daisy(table, metric = "gower")

tsne_obj <- Rtsne(gower_dist, is_distance = TRUE)

tsne_data <- tsne_obj$Y %>%
  data.frame() %>%
  setNames(c("X", "Y"))

ggplot(aes(x = X, y = Y), data = tsne_data) +
  geom_point()