Q: Embedding Mathematica Console into a Java/.NET Application I enjoy using Mathematica's notebook interfaces, but more specifically the autocompletion in each notebook.
I'm in need of a way to put tons of Mathematica windows on the same page.
It would be an application to organize/structure Mathematica code.  The standard windowing system in Windows 7 doesn't work because the Windows both don't save state between shutdowns and the equations don't really overlap in the way I'm looking.
A similar piece of software would be something like Inkscape or PowerPoint, but instead of having all the settings in would just contain Mathematica input or output.
The simplest solution would involve taking text input from an application, and outputting a PNG version of the data to the screen of the application.  I would then be able to drag around the different examples.
My Question: Does there exist a way to embedded Mathematica's notebook interface into Java or .NET applications (or entirely other system)?
I could live without autocompletion but the character insertion techniques e.g. \[Infinity] -> ∞ are both incredibly helpful and keeps eyes and head sane.  :)

A: This is not necessarily an answer, but the Mathematica system is very flexible and I think you might be able to accomplish what you're after with Mathematica itself. Look at this code here:
nbWindow = Null;
nb = Notebook[{}];

OPEN[] := Module[{},
   nbWindow = NotebookCreate[Visible -> False];
   nbWindow = NotebookPut[nb];
   SetOptions[nbWindow, Visible -> True,
    DockedCells -> None, Saveable -> False,
    WindowTitle -> "",
    Background -> White, WindowFrame -> "Palette",
    WindowMargins -> {{Automatic, 0}, {Automatic, 0}},
    WindowSize -> {400, 200}, WindowTitle -> title,
    NotebookEventActions :> {
      "WindowClose" :> CLOSE[]
      }]
   ];

CLOSE[] := Module[{},
   If[Head[nbWindow] === NotebookObject,
    nb = NotebookGet[nbWindow];
    NotebookClose[nbWindow];
    nbWindow = Null]
   ];

Row[{Button[open, OPEN[]], Button[close, CLOSE[]]}]

This shows you some of the ways you can manipulate Notebooks. Notice that you can set up UI hooks (such as "WindowClose") and that you can specify the WindowFrame. You can have a notebook show up as a palette window, frameless, etc. You can also specify the location/dimensions of the window.

That code is a slightly cleaned-up simplification of a Mathematica project I was playing around with: an "idea-tracker."
workspace[title_: None] := DynamicModule[{
    CLOSE, nb, lnb, originalSymbol, symbol,
    frameColor = Lighter[Gray, .85],
    polarity = ImageApply[#^0.6 &, #] &,
    backgroundColor = Lighter[Gray, .9]},

   symbol = originalSymbol = Module[
      {g, effect = 0.198`, inflection = 1, spirality = 0,
       thickness = 0, x = 5.2`, y = 0.`, \[Zeta] = 2},

      g[angle_, scale_: 1, color_: GrayLevel[0]] :=
       Module[{rotate = ((Complex @@ #) E^(I angle) // ({Re[#],
                Im[#]} &)) &,
         \[Psi]$ =
          Round[Abs[FractionalPart[\[Zeta]]] 1.`, 0.25`] /. {0.` -> y,
             0.5` -> y/2, 0.25` | 0.75` -> y/4}},

        ParametricPlot[
         scale*rotate[
           (1.` +
              spirality (Log[\[Theta] + 1.`] -
                 1.`)) {\[Psi]$ Cos[\[Theta]] +
              x Cos[64.` \[Theta]] + ((1 -
                   effect RandomReal[]) \[Zeta]) (Cos[
                  512.` \[Theta]] +
                 Cos[(64.` \[Zeta]) \[Theta]]), \[Psi]$ Sin[\[Theta]] \
- x Sin[64.` \[Theta]] + (((1 -
                    effect RandomReal[]) inflection) \[Zeta]) (Sin[
                  512.` \[Theta]] + Sin[(64.` \[Zeta]) \[Theta]])}
           ]

         , {\[Theta], 0, 2 \[Pi]}, ImageSize -> {50, 50},
         PerformanceGoal -> "Quality",
         PlotStyle -> {{color, Opacity[0.05`],
            AbsoluteThickness[thickness]}},
         PlotRange -> 10*{{-1, 1}, {-1, 1}}, PlotPoints -> 270,
         Axes -> None]];

      Rasterize[Show[
        g[-(1/4) (2 Pi)/3, 1, Lighter@Blue],
        g[(1/4) (2 Pi)/3, 1, Darker@Blue]]
       , "Image"]
      ];

   lnb = Null;
   nb = Notebook[{}];

   CLOSE[] := {
     polarity = Identity;
     backgroundColor = Lighter[Gray, .9];

     If[Head[lnb] === NotebookObject,
      nb = NotebookGet[lnb];
      If[First[nb] =!= {},

       symbol = Rasterize[
         If[NotebookRead[lnb] =!= {}, NotebookRead[lnb], lnb]
         , "Image", ImageSize -> {50, 50}],
       symbol = originalSymbol
       ];
      NotebookClose[lnb];
      lnb = Null;
      ]
     };

   EventHandler[
    Deploy@
     Grid[{{Dynamic[polarity[symbol]]}}, Frame -> True,
      FrameStyle -> Dynamic[frameColor],
      Background -> Dynamic[backgroundColor]],
    {
     {"MouseClicked", 1} :> Module[{a, screenWidth, minH, maxH},
       If[Head[NotebookGet[lnb]] === NotebookGet,
         {{{a, screenWidth}, {minH, maxH}}} =
          "ScreenArea" /. ("ScreenInformation" /. $sysinfo);

         polarity = ColorNegate;
         backgroundColor = Lighter[Red, .9];

         lnb = NotebookCreate[Visible -> False];
         lnb = NotebookPut[nb];
         SetOptions[lnb, Visible -> True,
          DockedCells -> None,
          Saveable -> False, Background -> White,
          WindowFrame -> "Normal",
          WindowMargins -> {{Automatic, 0}, {Automatic, 0}},
          WindowSize -> screenWidth/2,
          WindowTitle -> title,
          NotebookEventActions :> {
            "WindowClose" :> CLOSE[]
            }];
         ];
       ],
     {"MouseClicked", 2} :> CLOSE[],
     "MouseEntered" :> {
       polarity = If[polarity =!= ColorNegate, Identity, polarity];
       backgroundColor = Lighter[Gray, .7];
       $sysinfo =
        If[ValueQ[$sysinfo], $sysinfo, SystemInformation["Devices"]];
       },
     "MouseExited" :> {
       polarity =
        If[polarity =!= ColorNegate, ImageApply[#^0.6 &, #] &,
         polarity];
       frameColor = Lighter[Gray, .85];
       backgroundColor = Lighter[Gray, .9];
       }
     }]
   ];

tetragrammaton[] :=
  DynamicModule[{txt, appearance = "Framed", content},
   content = {
     Style[
      InputField[Dynamic[txt], String,
       Appearance -> Dynamic[appearance],
       Alignment -> "Center", FrameMargins -> 2, ImageSize -> 400],
      FontFamily -> Default, FontWeight -> Bold],
     workspace[Dynamic[txt]]};

   Deploy@
      EventHandler[#, {"MouseEntered" :> {appearance = "Framed"},
        "MouseExited" :> {appearance = "Frameless"}}] &@
    Framed[Row[content, " "], FrameStyle -> Lighter[Gray, .8]]
   ];

tetragrammaton[]

You type your idea/note in the box and then you click on the little symbol (which is a DynamicModule) to open a "workspace," which is just a blank notebook. Right-clicking on the symbol or closing the notebook will save the notebook within the DynamicModule. If the workspace isn't blank, the swirly symbol is replaced by a thumbnail of the workspace, or if you select something in the workspace before closing it, that selection will be used as the thumbnail. Hypothetical notes.nb:

(The idea is that you can work on ideas in their own individual workspaces without clogging up the main notebook with a bunch of visually-noisy content and section/subsection stuff).
This code is exploratory, incomplete, non-clean, and buggy, and I'm now pursuing a different approach for an "idea tracker." But it shows some of the stuff you can do with the notebook system.
I also recommend you take a look at this thread: Use Mathematica as a terminal


Q: Java Scheduling task I am developing a spring mvc project where a notification will send to user mobile.User will select a datetime at format 'yyyy-MM-dd HH:mm' from frontend and save it to the database.when system time reach that time a notification will be send to the user mobile .
I created scheduler like this
  @Component
  public class NotificationScheduler extends BaseService {

  @Scheduled(fixedRate = 300000)
  public void sendNotification() {

    Date currentDate = new Date();

    System.err.println("HHHHHHHHHKKKKKK");

    List<ImageInfo> listImageInfo = imageInfoDao.getImageOfParticularDate(currentDate);

 }
}

this is my dao function which run a wuery to database
  public List getImageOfParticularDate(Date date) {
    session = getSession();
    session.beginTransaction();
    List<ImageInfo> imageInfoList = session.createQuery("select img from ImageInfo img where img.publishedTime =:publishedTime  ").setParameter("publishedTime", date).list();
    session.getTransaction().commit();
    return imageInfoList;
}

this code is checking repeatedly at 5 min interval whether system time equal to publish time.if it is equal then a notification will be sent.I used Date type in model and Date type column in database. I want to know my approach is right or wrong because i can not get desire output.

A: Why don't you use a debug mode? Change, your the time rate you use in order to not wait too much, but I think you could determine that yourself, could you?


Q: Vue 3 render dynamic comment How can I properly render a dynamic comment in Vue 3? I tried v-html which is not working in my case, for example, https://i.imgur.com/EtrVmGu.png
<template>

  <template v-html="COMMENT" />

  {{ COMMENT }}

   content here

</template>

A: The v-html should be mounted in real html tag not the virtual template :

You could see the comment inside the inspected DOM

A: You may also use dynamic component with the <component is>
Vue JS Dynamic Components
And put all your comment component code in a different file: comment.vue
<template>

Dynamic Component

  <component :is='currentComponent'>
</template>

A: Create a component Comment.vue that uses render function to create a comment

Usage:

<template>
  <Comment content="Hi, I'm just a comment!"/>
</template>

Rendered comment:

The vue internal api is not designed for these kinda hacks. So, please use carefully.


Q: May I place


Q: Invalid date django form validation I am learning Django and building a CRUD but I'm getting an error in my form validation.
This is the form that ** I created**
class addSignForm(forms.ModelForm):
active = forms.CharField(max_length=10)

class Meta:
    model = signs
    fields = ("id", "active", "action", "date", "expiration_date", "add_by", "user_sign")
    widgets = {
        'date': forms.DateTimeInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'),
    }

This is the date that I am receiving from the request **(also tried format: '%y-%m-%dT%H:%M'
'2000-04-16T18:57'

And when I try to:
if (form.is_valid()):

says that it is an invalid form and that I typed an invalid date

Enter a valid date/time.

can someone help me

A: "2000-04-16T18:57" is not %d/%m/%Y %H:%M format but %Y-%m-%dT%H:%M format. Check list date formatters here https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes

A: Your widget format just show for client, not for Form.So you can try add a method named clean_date(self) to replace 'T' with whitespace then return it.
or add your format into DATETIME_INPUT_FORMATS list of settings.py.

A: i ended up managing to solve the problem, however I did not like the solution because it does not seem the most right ... however I will share it here in case people experience the same problem :)
What i did was:
create a copy of my GET so it becomes mutable
getCopy = request.GET.copy()

after that i converted the DATE that was comming from GET
ts = time.strptime(request.GET['date'], "%Y-%m-%dT%H:%M")
getCopy['date'] = time.strftime("%m/%d/%Y", ts)

and when i call my form.is_valid instead of passing request.GET, i pass my mutable copy of GET with my formatted date :)


Q: Kendo UI how to get the id of elements during drop event? I have the following HTML and would like to get the DOM elements for the elements involved in the drag and drop event. Also, if you could tell me how i might be able to figure this out using debugger, that would be even better!
Here is the code:

proud

strong

merry

friendly

Drop here

Drop here

Drop here

Drop here

A:  function onDrop(e) {
     // Get the id of the elements involved in the drag and drop event
         var source = $(e.draggable.element).attr('id');
         var target = e.dropTarget.attr('id');
 }


Q: Latex Beamer and Multiple Languages via beamer mode I'm using LaTeX Beamer for preparing teaching slides; since I'm teaching courses in several languages, I was wondering whether there is an easy way of displaying only specific slides of a specific language by help of a simple command.
What I do NOT want to use are packages like comment since important features of editing are lost (jumping back and forth between source and pdf does not work in TeXWorks, TeXMaker, TeXShop, etc.).
Basically, I would like to work with beamer modes. The idea would be to select a specific language mode while loading a document class and then prepare for all languages slides as, e.g.:
\documentclass[modelangenglish]{beamer}
\begin{document}

\begin{frame}[modelangenglish]
English Slide
\pause
tba
\end{frame}
%
\begin{frame}[modelanggerman]
German Slide
\pause
tba
\end{frame}
%
\begin{frame}[modelangspanish]
Spanish Slide
\pause
tba
\end{frame}
\end{document}

It should be also compatible with handout mode (nice would be something like \documentclass[handout,modelangenglish]{beamer}).
I would also like to avoid using different source files for different languages, because making changes synchronously within one file is much easier.
Are there any solutions? Can such beamer modes be defined? I know, there is a ready made translation mode, but I would need a solution for several languages (and one screen).
Thanks a lot and all the best,
Christian

A: This problem seems like a good use-case for the beameraudience package:
\documentclass{beamer}

\usepackage[
%    audience=english
%    audience=spanish
    audience=german
]{beameraudience}

\begin{document}

\begin{frame}{Title}
 all version
\end{frame}

\justfor{english}{
    \begin{frame}
    English Slide
    \pause
    tba
    \end{frame}
}

\justfor{spanish}{
    \begin{frame}
    Spanish Slide
    \pause
    tba
    \end{frame}
}

\justfor{german}{
    \begin{frame}
    Deutcher Text
    \pause
    wird noch angekündigt
    \end{frame}
}

\end{document}


Q: Avoid Terraform module to create duplicate resources? I have the following project structure to build Lambda functions on AWS using Terraform :
.
├── aws.tf
├── dev.tfvars
├── global_variables.tf -> ../shared/global_variables.tf
├── main.tf
├── module
│   ├── data_source.tf
│   ├── main.tf
│   ├── output.tf
│   ├── role.tf
│   ├── security_groups.tf
│   ├── sources
│   │   ├── function1.zip
│   │   └── function2.zip
│   └── variables.tf
└── vars.tf

In the .main.tf file i have this code that will create 2 different lambda functions :
module "function1" {
  source = "./module"

  function_name    = "function1"
  source_code      = "function1.zip"

  runtime          = "${var.runtime}"
  memory_size      = "${var.memory_size}"
  timeout          = "${var.timeout}"
  aws_region       = "${var.aws_region}"
  vpc_id           = "${var.vpc_id}"
}

module "function2" {
  source = "./module"

  function_name    = "function2"
  source_code      = "function2.zip"
  runtime          = "${var.runtime}"
  memory_size      = "${var.memory_size}"
  timeout          = "${var.timeout}"
  aws_region       = "${var.aws_region}"
  vpc_id           = "${var.vpc_id}"
}

The problem is that in deployment terraform create all resources twice. For Lambda it's Ok, that's the purpose, but for security groups and Roles that's not what i want.
For example this security group is create 2 times :
resource "aws_security_group" "lambda-sg" {
  vpc_id = "${data.aws_vpc.main_vpc.id}"
  name   = "sacem-${var.project}-sg-lambda-${var.function_name}-${var.environment}"

  egress {
    protocol    = "-1"
    from_port   = 0
    to_port     = 0
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    protocol        = "-1"
    from_port       = 0
    to_port         = 0
    cidr_blocks     = "${var.authorized_ip}"
  }
  # To solve dependcies error when updating the security groups
  lifecycle {
    create_before_destroy = true
    ignore_changes        = ["tags.DateTimeTag"]
  }

  tags = "${merge(var.resource_tagging, map("Name", "${var.project}-sg-lambda-${var.function_name}-${var.environment}"))}"

}

So that's clear that the problem is the structure of the project. Could you help to solve that ?
Thanks.

A: If you create the SecurityGroup within the module, it'll be created once per module inclusion.
I believe that some of the variable values for the sg name change when you include the module, right? Therefore, the sg name will be unique for both modules and can be created twice without errors.
If you'd choose a static name, Terraform would throw an error when trying to create the sg from module 2 as the resource already exists (as created by module 1).
You could thus define the sg resource outside of the module itself to create it only once.
You can then pass the id of the created sg as variable to the module inclusion and use it there for other resources.


Q: Square root inside a square root python I was wondering how to write a code showing the square root inside a square root. This is what I have so far:
number=float(input("Please enter a number: "))
square = 2*number**(1/2)**(1/3)
print(square)

But that's not right as I'm getting a different number from the calculator.

A: Import math and use math.sqrt(math.sqrt(number))
import math
number=float(input("Please enter a number: "))
square = math.sqrt(math.sqrt(number))
print(square)

A: It looks like it is doing the square root (i.e., 1/2) of 1/3 and then applying that to number. You'll want to force the order of operations since it's evaluating the exponent operator from right to left.
square = 2*(number**(1/2))**(1/3)

By adding parenthesis, you are forcing it to take the square root first, and then the cube root.

You are using Python3, but for future readers, Python2 would evaluate 1/2 and 1/3 to 0. To change that you'd use floats instead:
square = 2*(number**(1.0/2.0))**(1.0/3.0)

A: If you want to find the square root of the square root of a number you can see using some algebra we can see that ((x)^0.5)^0.5) simplifies down to x^(0.25)
So you can either do x**(0.25)
or you can do the following:
import math
math.sqrt(math.sqrt(x))

One other thing, in your code you say:
square = 2*number**(1/2)**(1/3)

and in the title you say "Square root inside a square root python". This indicates to me that you might have made either a typo in your code or mistake in naming the title of your question. If you do want to find a square root of a square root then my suggestions above should be sufficient to do that.


Q: Running rospy dependent file in Github Actions I'm trying to implement CI with Github Actions to a repository. In the workflow, I would like to run a test script using pytest. However, the test script and the script it is testing had a rospy dependency, although the dependency is not vital to the test, where it is publishing the result of certain calculation (node.Publisher is mocked using pytest).
I'm still new to ROS and I am a bit confused about what I need to install. Do I need to install the whole ROS library for the test or do I only need to install rospy? What is the best way to install the package and add it to the path in Github Actions?
I tried sudo apt-get install -y python-rospy, but the package is not detected by python with ImportError: No module named rospy.
I am running the test in Ubuntu 18.04.
Thank you in advance


Q: What is the correct way to resolve warnings at Redis startup when using Docker? When I run my Redis Docker image, I face these warnings:
# Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
( ... )
# WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
( ... )
# WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.

Among the solutions I found in the internet, this one looks cover everything, but when I try it in Docker scope (Eg.: changing my Dockerfile to apply them), I get the error "Read-only file system". Manually example give me the same issues:
[root@769368ed0fc5 /]# sysctl -w net.core.somaxconn=65535
sysctl: setting key "net.core.somaxconn": Read-only file system
[root@769368ed0fc5 /]# echo 'vm.overcommit_memory = 1' >> /etc/sysctl.conf
[root@769368ed0fc5 /]# sysctl vm.overcommit_memory=1
sysctl: setting key "vm.overcommit_memory": Read-only file system
[root@769368ed0fc5 /]# echo never > /sys/kernel/mm/transparent_hugepage/enabled
bash: /sys/kernel/mm/transparent_hugepage/enabled: Read-only file system
[root@769368ed0fc5 /]# echo never > /sys/kernel/mm/transparent_hugepage/enabled
bash: /sys/kernel/mm/transparent_hugepage/enabled: Read-only file system

Does anyone know how to fix it in a proper way? I have found a lot of tricks to workaround it, like:

*

*Run container in privileged mode

*Mount host /proc inside a container

*Use host network stack (--net=host)

*

*Looks like this one is inevitable, because Redis doesn't support NATed environments, but anyway it doesn't solve everything.

I want to know what is the correct way to deal with it in Docker. Answers that provide technical explanation about the proposed solution will be appreciated.


Q: Get vs Post Auto Mapping dates C# I am having some confusion figuring out why I am experiencing the following:
If I using jquery AJAX to "post" some Json data containing a date to an MVC controller the automapper maps the date in the format dd/mm/yyyy however if I use "get" instead the automapper seems to convert the date in to the format mm/dd/yyyy.
Does anybody know why this would be the case? When I check the json payload and querystrings for the post and get respectively they are both in the same format. The date I am using goes across as "1/7/2013" in both cases.
Regards,
Gary

A: Are you using a JSON serializer for the POST but a DateTime.Parse for the GET? This could yield two different results.
User DateTime.ParseExact to ensure consistent results. I.E.
DateTime.ParseExact(input, "dd/MM/yyyy HH:mm", null);


Q: Set Meta Tag With jQuery I'm having trouble with a mobile page that uses a site of ours in an iframe.
It works fine on desktop but on mobile the page doesn't resize correctly. Based on internal testing it seems that the page is missing this meta tag:
 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
Is there any way to set that via jQuery and have it actually take effect?
In theory I believe that using this SO article I could inject the meta tag like this:
$('head').append('<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">');

But it seems the problem really comes down to forcing it to re-parse the html. Is there a way I could do that?

A: Yes you can append a meta tag, but no you can't force reparsing of the html. The browser is going to ignore any changes you make.


Q: Calling multiple httpclient that contain two different base address I have read up on named clients and typed clients in order to achieve my ultimate goal. However, I still do not understand how I need to implement either or. I have a blazor server side project that in the startup.cs file I have it set up as
services.AddSingleton(sp => new HttpClient { BaseAddress = new Uri("http://localhost:36626") });
services.AddSingleton(sp => new HttpClient { BaseAddress = new Uri("https://localhost:5443") });
I know that if I do this, the baseaddress of the first one will completely be overwritten and no longer be the set base address due to the second baseaddress. How would I go about making this work so that way I have two separate httpclients that will have two separate baseaddress without having to lose one because of the most recent line of code?

A: As said in the doc, the main differences are in how you are going to get an instance through Dependency Injection.
With Named Client you need to inject the factory and then get the client by a string.
var client = _clientFactory.CreateClient("github");

With Typed Client you can inject the client needed as a type.
//GitHubService encapsulate an HTTP client
public TypedClientModel(GitHubService gitHubService)
    {
        _gitHubService = gitHubService;
    }

Both of them give the solution to your problem. The selection is more in how comfortable you are with the dependency injection method of each one. I personally prefer the Typed client.


Q: Unable to create directory in External Storage public directory I am attempting to create a directory and file so that I can store files that I have downloaded from the Internet. However, I am unable to create the directory and file in the external public storage. If I write to the external private storage (specific storage location for the app) I am perfectly able to do so.
Here is the code:
    String storageDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath();
    System.out.println(storageDirectory);
    File mediaDir = new File(storageDirectory);
    if (!mediaDir.exists()) {
        System.out.println(mediaDir.mkdirs());
        System.out.println(mediaDir.isDirectory());
    }
    File mediaFile = new File(storageDirectory, "boga.jpg");
    try {
        mediaFile.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }

The above code results in:

09-13 05:33:45.258    5867-5867/? I/System.out﹕ /storage/0CED-0F09/Pictures

09-13 05:33:45.260    5867-5867/? I/System.out﹕ false
09-13 05:33:45.260    5867-5867/? I/System.out﹕ false
With an IOException (No such file or directory):

09-13 05:33:45.260    5867-5867/? W/System.err﹕ java.io.IOException: open failed: ENOENT (No such file or directory)
09-13 05:33:45.260    5867-5867/? W/System.err﹕ at java.io.File.createNewFile(File.java:939)
09-13 05:33:45.260    5867-5867/? W/System.err﹕ at com.example.terabyte.tut1app.MainActivity.onCreate(MainActivity.java:78)

And this is my manifest:
<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

What could be the issue?

A: Turns out I am fully capable of writing to the external storage directory on a real smartphone device (Huawei P8 api level 21, Version 5.0). But not to the emulator's external storage, even though the storage is fully available and can be browsed from within the emulator.
This also helped me in figuring out issues with the external storage on a real device: https://stackoverflow.com/a/6311955/5330055
I have no longer urgently require a solution on this, but it would be nice to know what is wrong with the emulator.

A: Actually nothing wrong with emulator.
Probably device you have used on emulator were on android equal or higher than version 6.0
In 6.0 and higher versions you need to request write permission at runtime. WRITE_EXTERNAL_STORAGE
in your smartphone it worked because it was on android 5.0
if this help someone I will glad.


Q: Accumulate promise values "functionally" Say I have this:
function getAllPromises(key: string, val: any): Promise {

 const subDeps = someHash[key];
 const acc = {}; // accumulated value

 return subDeps.reduce(function (p, k) {

  return p.then(v => getAllPromises(k, v)).then(function (v) {
        acc[k] = v;
        return acc;
   });

 }, Promise.resolve(val));

}

is there a way to avoid having to declare a separate variable:
const acc = {}; // accumulated value

and somehow return that from the promise chain instead?
Ultimately the acc variable is what gets resolved from the promise chain, but wondering if I can somehow avoid having to declare it "outside" the chain.
Edit: the seed data for something like this looks like:
  {
    'one': [function (v) {
      return Promise.resolve('one');
    }],

    'two': ['one', function (v) {
      return Promise.resolve('two');
    }],

    'three': ['one', 'two', function (v) {
      return Promise.resolve('three');
    }],

  }

It's just a declarative dependency tree. Dependencies can be resolved in parallel; but may effectively block, as they run. For example, if I have a function like so:
function foo(one,two,three){

}

I want to inject these 3 dependencies. They can be sourced "in parallel", but three will be blocked until one and two are procured.
What is the subDeps variable? In the case of key="three", subDeps is ['one','two'].

A: You can pass an array at second parameter to .reduce(), within .reduce() callback use destructing assignment to get Promise and object passed
return subDeps.reduce(([p, acc], k) =>
         [p.then(v => getAllPromises(k, v)).then(v => Object.assign(acc, {[k]:v}))
         , acc];
       }, [Promise.resolve(val), {}]).shift()//.then(result => /* result : acc */)

A: I'm going out on a bit of a limb, here, in thinking that the whole list of subDeps for any child node can be loaded in parallel. In looking at the problem, deeper, I see no reason for that not to be the case. In fact, the only potential problem I could see is that some value above but not below this point could be a promise, and thus, you might even be able to strike the promises from this particular recursive function...
but...
Here's what I saw as a plausible refactor. Let me know if that's missing some obvious need.
const appendKeyValue = (dict, [key, value]) => {
  dict[key] = value;
  return dict;
};

const getKeyValuePair = hash => key =>
  getRefactoredPromises(hash, hash[key])
    .then(value => [key, value]);

const getRefactoredPromises = (someHash, subDeps) => {
  return Promise.all(subDeps.map(getKeyValuePair(someHash)))
    .then(pairs => pairs.reduce(appendKeyValue, {}));
};

In fact, if I'm right about this refactor, then you don't even need the promises in there. It just becomes:
const appendKeyValue = (dict, [key, value]) => {
  dict[key] = value;
  return dict;
};

const getKeyValuePair = hash => key =>
  [key, getRefactoredHash(hash, hash[key])];

const getRefactoredHash = (someHash, subDeps) =>
  subDeps.map(getKeyValuePair(someHash))
         .reduce(appendKeyValue, {});

If the root level of this call happens to be a promise, that should be inconsequential at this point, unless there's something I'm missing (it IS 6:20am, and I've yet to close my eyes).


Q: Protect sidekiq admin with devise (documented way not working) I have an app that uses devise/omniauth for authentication, and runs a bunch of sidekiq workers.
I would like to protect /sidekiq and /sidekiq_monitor routes with devise as well, but so far I am running into a lot of trouble doing that.
The documented solution is to do this in routes.rb:
authenticate :user do
  mount Sidekiq::Web => '/sidekiq'
end

But that isn't working for me - what happens when I add that is that if a user goes to /sidekiq they are prompted to login regardless of their auth status, and if they login and go back to /sidekiq they are once again prompted to login.
Possible wrinkles - I am logging in via omniauth-saml, which means some redirects are happening in the mix here - but that's working fine with all other auth on my site. I am also only using a very minimal bit of devise, just:
devise :rememberable, :trackable, :omniauthable, :omniauth_providers => [:saml]

A: Try changing in your routes.rb file to this:
authenticate :user do
  mount Sidekiq::Web, at: "/sidekiq"
end

Also notice that :user refers to your app user model. If your user model has another name, let's say :admin, you should replace :user to :admin in the snipped code above.

A: try this inside of your routes:
Sidekiq::Web.use Rack::Auth::Basic do |username, password|
   username == USERNAME && password == PASSWORD
end if Rails.env.production?

mount Sidekiq::Web, at: "/sidekiq"


Q: Need help! kernel compilation error! https://www.youtube.com/watch?v=ekHpIfiUt8M i followed this guide, unfortunately TWICE got this error :

make[2]: Entering directory /home/dante/kernel/linux-4.2'
  scripts/kconfig/conf  --silentoldconfig Kconfig make[2]: Leaving
  directory/home/dante/kernel/linux-4.2' make[2]: Entering directory
  /home/dante/kernel/linux-4.2' sh ./arch/x86/boot/install.sh
  4.2.0-dante-core arch/x86/boot/bzImage \      System.map "/home/dante/kernel/linux/debian/linux-image-4.2.0-dante-core//boot"
  run-parts: executing /etc/kernel/postinst.d/apt-auto-removal
  4.2.0-dante-core /home/dante/kernel/linux/debian/linux-image-4.2.0-dante-core//boot/vmlinuz-4.2.0-dante-core
  /etc/kernel/postinst.d/apt-auto-removal: 84:
  /etc/kernel/postinst.d/apt-auto-removal: cannot create
  /etc/apt/apt.conf.d//01autoremove-kernels.dpkg-new: Permission denied
  run-parts: /etc/kernel/postinst.d/apt-auto-removal exited with return
  code 2 make[3]: *** [install] Error 1 make[2]: *** [install] Error 2
  make[2]: Leaving directory/home/dante/kernel/linux-4.2' make[1]: *
  [debian/stamp/install/linux-image-4.2.0-dante-core] Error 2 make[1]:
  Leaving directory `/home/dante/kernel/linux-4.2' make: *
  [kernel_image] Error 2

Kernel compilation takes A LOT of time on my pc, this is such a disappointment when after 3 hours of compilation  i get this freakin error and .deb package doesn't even appear. I am new to linux, please tell me what am i doing wrong? ubuntu version 14.04, my pc is asus k53sc. I beg you for help guys i really want to understand what am i doing wrong.

A: i found out what was the problem. I installed kernel-package_13.003_all.deb and it worked. My kernel config sucks tho, don't see real increase in speed


Q: Gestionar respuesta de una API de TPV Virtual os pongo en contexto. Estoy integrando una API de TPV Virtual, en concreto esta https://api-developer.easypaymentgateway.com/hosted.html#section/Quick-Start, y básicamente lo que hago es construir el enlace del link de pago a través de una serie de campos (algunos obligatorios y otros no, definidos en https://api-developer.easypaymentgateway.com/encryption-fields.html). Hasta aquí todo correcto, consigo crear el enlace a la pantalla de pago, y realizar el pago, pero mi problema llega cuando intento gestionar la respuesta del TPV Virtual, ya que hay un parámetro llamado "statusURL", en el que yo tengo que indicar una supuesta dirección donde la API me mandará el resultado de la transacción en un formato XML como el siguiente:
      <Payfrex-response operation-size="1">
        <message>WorkFlow has finished successfully, for transaction Id: 101134</message>
        <operations>
          <operation sorted-order="1">
            <amount>10.00</amount>
            <currency>EUR</currency>
            <details>
              <?xml version="1.0" encoding="UTF-8"?>
                <netdirect version="4.1">
                  <approval>yes</approval>
                  <amount>10.00</amount>
                  <trans_id>21545</trans_id>
                  <error>none</error>
                  <fee>0.71</fee>
                  <time>{ts'2013-12-10 15:51:16'}</time>
                  <firstname>EURFirstname</firstname>
                  <lastname>EURLastname</lastname>
                  <email>netellertest_eur@neteller.com</email>
                  <custom_1>121</custom_1>
                  <custom_2>DEBIT</custom_2>
                  <total_fee>0.71</total_fee>
                  <client_currency>EUR</client_currency>
                  <client_amount>10.00</client_amount>
                  <merchant_currency>EUR</merchant_currency>
                  <merchant_amount>10.00</merchant_amount>
                  <fxrate>1.00000000</fxrate>
                </netdirect>
            </details>
            <merchantTransactionId>1223434</merchantTransactionId>
            <message>none</message>
            <operationType>DEBIT</operationType>
            <paymentDetails>
              <cardHolderName>Jtester</cardHolderName>
              <cardNumber>401200****1003</cardNumber>
              <cardNumberToken>7888967934961003</cardNumberToken>
              <cardType>VISA/CREDIT</cardType>
              <extraDetails />
              <issuerBank>EXTRAS TEST - VISA</issuerBank>
              <issuerCountry>US</issuerCountry>
            </paymentDetails>
            <optionalTransactionParams/>
            <EPGTransactionId>101134</EPGTransactionId>
            <paySolTransactionId>12544</paySolTransactionId>
            <paymentSolution>wirecard</paymentSolution>
            <status>SUCCESS</status>
          </operation>
        </operations>
        <optionalTransactionParams>
          <entry><key>merchantParam2</key><value></value></entry>
          <entry><key>merchantParam1</key><value></value></entry>
        </optionalTransactionParams>
        <status>SUCCESS</status>
        <workFlowResponse>
          <id>10</id>
          <name>Neteller</name>
          <version>8</version>
        </workFlowResponse>
      </Payfrex-response>

Lo que no sé es de qué forma recibir estos datos del XML ni qué tipo de dirección he de introducir en el statusURL para posteriormente recibir estos datos.
Os dejo aquí cómo construyo mi link de pago, también le paso como parámetro dos direcciones de dos archivos PHP, errorURL.php y successURL.php, donde debería yo de gestionar la respuesta, pero mi duda es como puedo desde estos dos archivos obtener los datos del XML anterior que os he mostrado. Toda ayuda es bienvenida, llevo unas semanas estancado en esta parte del proyecto y me vendría bien un poco de ayuda.
$data = "amount=" . $amount . "&apiVersion=" . $apiVersion . "&country=" . $country . "&currency=" . $currency .
    "&description=" . $description . "&merchantId=" . $merchantId . "&merchantTransactionId=" . $merchantTransactionId
    ."&operationType=" . $operationType . "&paymentSolution=" . $paymentSolution .
    "&addressLine1=" . $addressLine1 . "&addressLine2=" . $addressLine2 . "&city=" . $city . "&customerId=" . $customerId .
    "&firstname=" . $firstName . "&postCode=" . $postCode . "&customerCountry=" . $customerCountry .
    "&errorURL=" . $errorURL . "&successURL=" . $successURL . "&statusURL=" . $statusURL;

$method = 'aes-256-ecb';
$encrypted = openssl_encrypt($data, $method, $merchantKey);
$integrityCheck = hash("sha256", $data);
$URI = "https://checkout-stg.easypaymentgateway.com/EPGCheckout/rest/online/tokenize";

$myParameters = "encrypted=" . urlencode(utf8_encode($encrypted)) . "&integrityCheck=" . $integrityCheck . "&merchantId=" . $merchantId;
$HtmlResult = "response";

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,$URI);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$myParameters);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$HtmlResult = curl_exec ($ch);


Q: Tomcat + Grails cluster doesnt work I have a Tomcat cluster over Debian Jessie, Tomcat 8.0.29 2 instances , PostgreSQL 9.5 ,Apache 2.4 , Mod_jk. When I try to run my project in this environment I get eerror. I tested with examples project and it works fine. My log iis this
01-Feb-2016 19:07:39.474 SEVERE [main] org.apache.catalina.ha.deploy.FarmWarDeployer.start FarmWarDeployer can only work as host cluster subelement!
01-Feb-2016 19:07:39.537 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Despliegue del archivo /opt/tomcat8_nodo1/webapps/clusterjsp.war de la aplicación web
01-Feb-2016 19:07:40.886 INFO [MessageDispatch15Interceptor.MessageDispatchThread1] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[
        Tx Msg:1 messages
        Sent:0.00 MB (total)
        Sent:0.00 MB (application)
        Time:0.01 seconds
        Tx Speed:0.06 MB/sec (total)
        TxSpeed:0.06 MB/sec (application)
        Error Msg:0
        Rx Msg:2 messages
        Rx Speed:0.00 MB/sec (since 1st msg)
        Received:0.00 MB]

01-Feb-2016 19:07:42.068 INFO [localhost-startStop-1] org.apache.catalina.util.SessionIdGeneratorBase.createSecureRandom Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [1.489] milliseconds.

01-Feb-2016 19:07:42.088 INFO [localhost-startStop-1] org.apache.catalina.tribes.tipis.AbstractReplicatedMap.init Initializing AbstractReplicatedMap with context name:localhost#/clusterjsp-map

01-Feb-2016 19:07:42.310 INFO [localhost-startStop-1] org.apache.catalina.tribes.tipis.AbstractReplicatedMap.init AbstractReplicatedMap[localhost#/clusterjsp-map] initialization was completed in 222 ms.

01-Feb-2016 19:07:42.585 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive /opt/tomcat8_nodo1/webapps/clusterjsp.war has finished in 3.048 ms

01-Feb-2016 19:07:45.652 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Despliegue del archivo /opt/tomcat8_nodo1/webapps/abacus.war de la aplicación web
01-Feb-2016
19:14:05.387 INFO [localhost-startStop-1] org.apache.jasper.servlet.TldScanner.scanJars Al menos un JAR, que se ha explorado buscando TLDs, aún no contenía TLDs. Activar historial de depuración para este historiador para una completa lista de los JARs que fueron explorados y de los que nos se halló TLDs. Saltarse JARs no necesarios durante la exploración puede dar lugar a una mejora de tiempo significativa en el arranque y compilación de JSP .
feb 01, 2016 7:14:05 PM org.apache.catalina.core.ApplicationContext log
INFORMACIÓN: Initializing AtmosphereFramework

feb 01, 2016 7:14:05 PM org.apache.catalina.core.ApplicationContext log
INFORMACIÓN: No Spring WebApplicationInitializer types detected on classpath
feb 01, 2016 7:14:06 PM org.apache.catalina.core.ApplicationContext log

INFORMACIÓN: Initializing Spring root WebApplicationContext
feb 01, 2016 7:14:54 PM org.apache.tomcat.jdbc.pool.ConnectionPool init
ADVERTENCIA: maxActive is smaller than 1, setting maxActive to: 100

<strong>
2016-02-01 19:14:59,345 [localhost-startStop-1] ERROR context.GrailsContextLoaderListener  - Error initializing the application: Error creating bean with name 'org.springframework.context.annotation.internalAsyncAnnotationProcessor' defined in class path resource [org/springframework/scheduling/annotation/ProxyAsyncConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.context.annotation.internalAsyncAnnotationProcessor' defined in class path resource [org/springframework/scheduling/annotation/ProxyAsyncConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected
        ... 5 more
Caused by: java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected
        ... 5 more
2016-02-01 19:14:59,346 [localhost-startStop-1] ERROR context.GrailsContextLoaderListener  - Error initializing Grails: Error creating bean with name 'org.springframework.context.annotation.internalAsyncAnnotationProcessor' defined in class path resource [org/springframework/scheduling/annotation/ProxyAsyncConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.context.annotation.internalAsyncAnnotationProcessor' defined in class path resource [org/springframework/scheduling/annotation/ProxyAsyncConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected
        ... 5 more
Caused by: java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected
        ... 5 more
feb 01, 2016 7:14:59 PM org.apache.catalina.core.StandardContext listenerStart

GRAVE: Excepción enviando evento inicializado de contexto a instancia de escuchador de clase org.codehaus.groovy.grails.web.context.GrailsContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.context.annotation.internalAsyncAnnotationProcessor' defined in class path resource [org/springframework/scheduling/annotation/ProxyAsyncConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected
        ... 5 more
Caused by: java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected
        ... 5 more

01-Feb-2016 19:14:59.347 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.startInternal One or more listeners failed to start. Full details will be found in the appropriate container log file
01-Feb-2016 19:14:59.349 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.startInternal Falló en arranque del Contexto [/abacus] debido a errores previos
feb 01, 2016 7:14:59 PM org.apache.catalina.core.ApplicationContext log
INFORMACIÓN: Closing Spring root WebApplicationContext
01-Feb-2016 19:14:59.363 WARNING [localhost-startStop-1] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesJdbc La aplicación web [abacus] registró el conductor JDBC [org.postgresql.Driver] pero falló al anular el registro mientras la aplicación web estaba parada. Para prevenir un fallo de memoria, se ha anulado el registro del conductor JDBC por la fuerza.
</strong>

01-Feb-2016 19:14:59.371 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive /opt/tomcat8_nodo1/webapps/abacus.war has finished in 433.719 ms
01-Feb-2016 19:14:59.373 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Despliegue del directorio /opt/tomcat8_nodo1/webapps/ROOT de la aplicación web
01-Feb-2016 19:14:59.434 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /opt/tomcat8_nodo1/webapps/ROOT has finished in 61 ms

01-Feb-2016 19:14:59.435 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Despliegue del directorio /opt/tomcat8_nodo1/webapps/manager de la aplicación web
01-Feb-2016 19:14:59.479 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /opt/tomcat8_nodo1/webapps/manager has finished in 45 ms
01-Feb-2016 19:14:59.479 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Despliegue del directorio /opt/tomcat8_nodo1/webapps/examples de la aplicación web
01-Feb-2016 19:14:59.726 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /opt/tomcat8_nodo1/webapps/examples has finished in 247 ms
01-Feb-2016 19:14:59.726 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Despliegue del directorio /opt/tomcat8_nodo1/webapps/host-manager de la aplicación web
01-Feb-2016 19:14:59.743 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /opt/tomcat8_nodo1/webapps/host-manager has finished in 17 ms
01-Feb-2016 19:14:59.750 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["ajp-nio-8009"]

01-Feb-2016 19:14:59.760 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in 442905 ms
01-Feb-2016 22:35:59.831 INFO [Tribes-Task-Receiver-5] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[
        Tx Msg:10,000 messages
        Sent:6.81 MB (total)
        Sent:6.81 MB (application)
        Time:2.39 seconds
        Tx Speed:2.85 MB/sec (total)
        TxSpeed:2.85 MB/sec (application)
        Error Msg:0
        Rx Msg:10,000 messages
        Rx Speed:0.00 MB/sec (since 1st msg)
        Received:6.81 MB]

01-Feb-2016 22:35:59.832 INFO [Tribes-Task-Receiver-5] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[
        Tx Msg:10,000 messages
        Sent:6.81 MB (total)
        Sent:6.81 MB (application)
        Time:2.39 seconds
        Tx Speed:2.85 MB/sec (total)
        TxSpeed:2.85 MB/sec (application)
        Error Msg:0
        Rx Msg:10,001 messages
        Rx Speed:0.00 MB/sec (since 1st msg)
        Received:6.81 MB]

02-Feb-2016 02:04:23.818 INFO [Tribes-Task-Receiver-1] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[
        Tx Msg:20,000 messages
        Sent:13.62 MB (total)
        Sent:13.62 MB (application)
        Time:4.07 seconds
        Tx Speed:3.35 MB/sec (total)
        TxSpeed:3.35 MB/sec (application)
        Error Msg:0
        Rx Msg:20,000 messages
        Rx Speed:0.00 MB/sec (since 1st msg)
        Received:13.62 MB]

02-Feb-2016 02:04:23.820 INFO [GroupChannel-Heartbeat-1] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[
        Tx Msg:20,000 messages
        Sent:13.62 MB (total)
        Sent:13.62 MB (application)
        Time:4.07 seconds
        Tx Speed:3.35 MB/sec (total)
        TxSpeed:3.35 MB/sec (application)
        Error Msg:0
        Rx Msg:20,000 messages
        Rx Speed:0.00 MB/sec (since 1st msg)
        Received:13.62 MB]

02-Feb-2016 05:32:47.761 INFO [Tribes-Task-Receiver-6] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[
        Tx Msg:30,000 messages
        Sent:20.43 MB (total)
        Sent:20.43 MB (application)
        Time:5.72 seconds
        Tx Speed:3.57 MB/sec (total)
        TxSpeed:3.57 MB/sec (application)
        Error Msg:0
        Rx Msg:30,000 messages
        Rx Speed:0.00 MB/sec (since 1st msg)
        Received:20.42 MB]

02-Feb-2016 05:32:47.763 INFO [Tribes-Task-Receiver-6] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[
        Tx Msg:30,000 messages
        Sent:20.43 MB (total)
        Sent:20.43 MB (application)
        Time:5.72 seconds
        Tx Speed:3.57 MB/sec (total)
        TxSpeed:3.57 MB/sec (application)
        Error Msg:0
        Rx Msg:30,001 messages
        Rx Speed:0.00 MB/sec (since 1st msg)
        Received:20.42 MB]

02-Feb-2016 09:01:11.617 INFO [Tribes-Task-Receiver-5] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[
        Tx Msg:40,000 messages
        Sent:27.23 MB (total)
        Sent:27.24 MB (application)
        Time:7.38 seconds
        Tx Speed:3.69 MB/sec (total)
        TxSpeed:3.69 MB/sec (application)
        Error Msg:0
        Rx Msg:40,000 messages
        Rx Speed:0.00 MB/sec (since 1st msg)
        Received:27.23 MB]

02-Feb-2016 09:01:11.618 INFO [GroupChannel-Heartbeat-1] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[
        Tx Msg:40,001 messages
        Sent:27.24 MB (total)
        Sent:27.24 MB (application)
        Time:7.38 seconds
        Tx Speed:3.69 MB/sec (total)
        TxSpeed:3.69 MB/sec (application)
        Error Msg:0
        Rx Msg:40,002 messages
        Rx Speed:0.00 MB/sec (since 1st msg)
        Received:27.23 MB]

02-Feb-2016 12:29:35.561 INFO [Tribes-Task-Receiver-2] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[
        Tx Msg:49,999 messages
        Sent:34.04 MB (total)
        Sent:34.04 MB (application)
        Time:8.99 seconds
        Tx Speed:3.79 MB/sec (total)
        TxSpeed:3.79 MB/sec (application)
        Error Msg:0
        Rx Msg:50,000 messages
        Rx Speed:0.00 MB/sec (since 1st msg)
        Received:34.04 MB]

02-Feb-2016 12:29:36.108 INFO [GroupChannel-Heartbeat-1] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[
        Tx Msg:50,000 messages
        Sent:34.04 MB (total)
        Sent:34.05 MB (application)
        Time:8.99 seconds
        Tx Speed:3.79 MB/sec (total)
        TxSpeed:3.79 MB/sec (application)
        Error Msg:0
        Rx Msg:50,001 messages
        Rx Speed:0.00 MB/sec (since 1st msg)
        Received:34.04 MB]

02-Feb-2016 15:57:59.873 INFO [Tribes-Task-Receiver-1] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[
        Tx Msg:59,999 messages
        Sent:40.85 MB (total)
        Sent:40.85 MB (application)
        Time:10.64 seconds
        Tx Speed:3.84 MB/sec (total)
        TxSpeed:3.84 MB/sec (application)
        Error Msg:0
        Rx Msg:60,000 messages
        Rx Speed:0.00 MB/sec (since 1st msg)
        Received:40.85 MB]

02-Feb-2016 15:58:00.431 INFO [GroupChannel-Heartbeat-1] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[
        Tx Msg:60,000 messages
        Sent:40.85 MB (total)
        Sent:40.85 MB (application)
        Time:10.64 seconds
        Tx Speed:3.84 MB/sec (total)
        TxSpeed:3.84 MB/sec (application)
        Error Msg:0
        Rx Msg:60,001 messages
        Rx Speed:0.00 MB/sec (since 1st msg)
        Received:40.85 MB]

A: There are many different possible causes to this problem. Two top suspects are:

*

*You are using a plug-in that is triggering a component scan of Spring classes.

*Your code has added a component scan that is hitting Spring classes.

A search for "component-scan" throughout your project can help you check for those two causes.


Q: Can't Add Nameservers 16.04 LTS virtual install Just did a fresh install of 16.04 LTS in virtual mode on Hyper-V... having trouble getting DNS resolution...
Finally got network working by using ifconfig add eth0 10.0.0.1/24, added default gateway with route add... but can't seem to figure out how to add nameservers... Then I completely screwed up networking by deleting all routes (experimenting). Couldn't get networking to work at all. Finally got network up again by adding all config to /etc/network/interfaces for auto eth0:
auto eth0
iface eth0 inet static
    address 10.0.0.1
    netmask 255.255.255.0
    gateway 10.0.0.200
dns-nameservers 10.0.0.50 10.0.0.51

Restarted the system after adding in config and now I can ping other hosts on network, but still no DNS resolution... What am I missing?

A: Interesting.. you could also try defining nameserver in /etc/resolv.conf
which should look something like this:
nameserver 10.0.0.50 10.0.0.51

A: $ nmcli connection modify eth0 ipv4.dns 10.0.0.50
# systemctl restart NetworkManager.service

*

*Editing /etc/resolv.conf is not an option because resolv.conf will be overridden with networkmanager.


Q: Bootstrap 4: I'd like my columns to take the full width of my container I would like my columns to take the full width of my container, I have tried many things but haven't find a solution how to fix it.
Here's an example of what I want:

While it looks like this for now:

See the little red arrows? This is the space that I don't want to see.
HTML:

Privacy & Security

Some quick example text to build on the card title and make up the bulk of the card's content.

Privacy & Security

Some quick example text to build on the card title and make up the bulk of the card's content.

CSS:
.framework {
    background: rgb(27,28,30);
    background: linear-gradient(180deg, #1b1c1e 0%, #27262d 200%);
    display:grid;
    max-width:100%;
    padding:30px 10px 30px 10px;
    margin-top:0.5em;
    height:100%;
    margin-left: auto;
    margin-right: auto;

    .card {
        background: #27262d;
        border-radius:5px;
    }

    img {
        width:50px;
        height:auto;
        display:block;
        margin-left:auto;
        margin-right:auto;
        margin-top:15px;
    }
}

CSS (for Mobile version) :
@import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@800&display=swap');

.framework {
    .card-title {
        font-family:'Open Sans',sans-serif;
        font-weight:800;
        font-size:14pt;
        text-align:left;
        text-transform:uppercase;
    }

    .card-text {
        font-family:geomanist,sans-serif;
        color:rgba(255, 255, 255, 0.377);
        font-weight:400;
        font-size:10pt;
        letter-spacing:-0.1px;
        line-height:15px;
        text-align:left;
    }

    @media only screen and (max-width: 600px) {
        .card-title {
            font-size:11pt;
            }
        .card-text {
            font-size:9pt;
        }
    }

}

edit (10/19/2020 | 12:09 [brussels])kind of fixed it by adding class ".mx-md-n5" next to class ".row" in the same div, this aint perfect but it satisfies me

A: Please add pl-0 and pr-0 class for the remove the padding

Privacy & Security

Some quick example text to build on the card title and make up the bulk of the card's content.

Privacy & Security

Some quick example text to build on the card title and make up the bulk of the card's content.

A:

Privacy & Security

Some quick example text to build on the card title and make up the bulk of the card's content.

Privacy & Security

Some quick example text to build on the card title and make up the bulk of the card's content.

Privacy & Security

Some quick example text to build on the card title and make up the bulk of the card's content.

A: Please use the predefined Bootstrap classes at first and if you have any custom CSS add it in a new classes.
Is this what you search for:
HTML

Privacy & Security

Some quick example text to build on the card title and make up the bulk of the card's
          content.

Privacy & Security

Some quick example text to build on the card title and make up the bulk of the card's
          content.

A: this is a demo for what exactly you want I have just remove padding for the full-width box and for the next two box I remove padding-left for left side box and padding-right for the right side box.
this is the code snippet which helps you to understand what I do.

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

          Box 1

          Box 2

          Box 3

I hope this answer will help you to solve your problem this time and also help you in future for this type of structure.
Thank you...


Q: Are variables de-allocated when they go out of scope Given this code snippet
def doSomething() = {

    val associations : HashMap[Int, Int] = function_that_create_a_hashmap
    println("something")
}

When doSomething terminates is the variable associations de-allocated? Should I call some destructor on it (maybe .clear, in this case) or is that operation not useful?

A: That is not necessary - if your application has no more references to the HashMap, then it will be garbage collected automatically at some point in the future.
If you really have a huge hash map that you want to get rid off to avoid its memory consumption trigger GC cycles after doSomething completes, you can call System.gc(), but this is in general neither needed nor a recommended practice.

A: Calling .clear on a HashMap doesn't remove it from memory; it simply clears it of preexisting mappings and so the object will still exist in memory.
Since Scala runs on the JVM, I would imagine that it will get collected by the garbage collector at some point in the future (assuming that there are no existing-references to associations). The JVM manages its own memory, thus freeing the programmer of the burden of manually-managing memory.

A: The binding associations ceases to exist when the scope in which it was created ceases to exist (when a given call to doSomething returns). That removes one reference to the HashMap and once there are none left, the value is garbage and subject to reclamation at an unspecified time in the future (possibly never / not before the JVM exits).


Q: Facebook SDK Graphrequest returns null Using Facebook SDK 4.4 in Xamarin.Android project. I have the following method :
protected override void OnCreate(Bundle savedInstanceState)
{
 LoginButton button = FindViewById<LoginButton>(Resource.Id.FbLoginBtn);
 button.SetReadPermissions(new List<string>{ "public_profile", "email" });
 mCallBackManager = CallbackManagerFactory.Create();
 button.RegisterCallback(mCallBackManager, this);
 button.Click += (o, e)=>
  {
    GraphRequest request = GraphRequest.NewMeRequest(AccessToken.CurrentAccessToken, this);
    Bundle paramenters = new Bundle();
    paramenters.PutString("fields", "id,name,email,first_name,last_name");
    request.Parameters = paramenters;
    request.ExecuteAsync();
  };
}

public void OnCompleted(JSONObject @object, GraphResponse response)
{
  if (@object != null)
  {
   userEmail.Text = @object.ToString();
  }
 }

The problem with the above code is that, in the OnCompleted method, the JSONObject always return null when i log in to my facebook account from the app. But when i click the button again to Log Out, i get the proper json with all fields that i specified.
My question is, why is the GraphRequest returning null upon log-in but successfully returns the JSON upon log out?


Q: If every infinte subset of E has a limit point in E then E is compact in X Let X be a metric space. Show that a subset E of X is compact if and
only if every infinite subset of E has a limit point in E.
How to prove the converse statement ?
i.e. if every infinite subset of E has a limit point in E then E is compact in X.
I want to prove from the definition of compact sets.

A: First note that by this answer we know that if $X$ limit point compact (i.e. every infinite set has a limit point), then $X$ is Lindelöf (i.e. every open cover has a countable subcover), otherwise $X$ would have a closed and discrete uncountable subspace, contradicting the limit point compactness.
Then as metric spaces are $T_1$, this answer shows that a limit point compact metric $X$ is also countably compact (every countable cover has a finite subcover).
And clearly then $X$ is compact (we reduce an open cover to a countable one via Lindelöfness, and then to a finite one using countable compactness). Also see this answer for an overview of similar ideas.


Q: Why there is no Server Name under integration services in SSMS? I cant connect to Integration Services in SSMS there is no Server Name under it when I browse , if I type manually the server name based on how other services have it says class not registered

A: If someone else has the same problem the reason was because I had installed SSIS 2017 but was using SSMS 18.x , if you have SSIS 2017 use SSMS 17.x and such with other versions


Q: Mystery gaps in CSS Grid In the snippet below, there are gaps above and beneath 'main' area which suppose to be an empty cells with the same height as the grid cells. Also there is an empty space at the very bottom.
I've tried setting grid-auto-flow to different values, but there is no effect except for the very bottom gap when it set to column.
What causes that? and how to fix it?

.header {
    grid-area: hd;
}
.footer {
    grid-area: ft;
}
.content {
    grid-area: main;
}
.sidebar {
    grid-area: sd;
}
* {box-sizing: border-box;}

.wrapper {
    border: 2px solid #f76707;
    border-radius: 5px;
    background-color: #fff4e6;
    max-width: 940px;
    margin: 0 auto;
}

.wrapper > div {
    border: 2px solid #ffa94d;
    border-radius: 5px;
    background-color: #ffd8a8;
    padding: 1em;
    color: #d9480f;
}
.wrapper {
    display: grid;

    grid-auto-rows: minmax(auto, auto);
    grid-template-areas:
      "hd hd ft"
      "sd . ft"
      "sd main ft"
      "sd . ft";
}

Header

Sidebar

Content

Footer

A: **I tested the code on Chrome and Firefox and the result was **

Always add the <!DOCTYPE> declaration to your HTML documents, so that the browser knows what type of document to expect.

.header {
    grid-area: hd;
}
.footer {
    grid-area: ft;
}
.content {
    grid-area: main;
}
.sidebar {
    grid-area: sd;
}
* {box-sizing: border-box;}

.wrapper {
    border: 2px solid #f76707;
    border-radius: 5px;
    background-color: #fff4e6;
    max-width: 940px;
    margin: 0 auto;
}

.wrapper > div {
    border: 2px solid #ffa94d;
    border-radius: 5px;
    background-color: #ffd8a8;
    padding: 1em;
    color: #d9480f;
}
.wrapper {
    display: grid;

    grid-auto-rows: minmax(auto, auto);
    grid-template-areas:
      "hd hd ft"
      "sd . ft"
      "sd main ft"
      "sd . ft";
}
<!DOCTYPE html>

Header

Sidebar

Content

Footer

A: Here's what's happening:
First, let's see the gaps (they don't appear in many cases):

.wrapper {
  display: grid;
  grid-auto-rows: minmax(auto, auto);
  grid-template-areas: "hd hd ft" "sd . ft" "sd main ft" "sd . ft";
}

.header {
  grid-area: hd;
}

.footer {
  grid-area: ft;
}

.content {
  grid-area: main;
}

.sidebar {
  grid-area: sd;
}

* {
  box-sizing: border-box;
}

.wrapper {
  border: 2px solid #f76707;
  border-radius: 5px;
  background-color: #fff4e6;
  max-width: 940px;
  margin: 0 auto;
}

.wrapper > div {
  border: 2px solid #ffa94d;
  border-radius: 5px;
  background-color: #ffd8a8;
  padding: 1em;
  color: #d9480f;
}

Header

Sidebar

Content

Footer

What you're seeing is the rendering of   (non-breaking space) characters in the HTML code.

As white space characters, they're invisible, which makes them hard to detect. But once you remove them, the layout works as expected.

.wrapper {
  display: grid;
  grid-auto-rows: minmax(auto, auto);
  grid-template-areas: "hd hd ft" "sd . ft" "sd main ft" "sd . ft";
}

.header {
  grid-area: hd;
}

.footer {
  grid-area: ft;
}

.content {
  grid-area: main;
}

.sidebar {
  grid-area: sd;
}

* {
  box-sizing: border-box;
}

.wrapper {
  border: 2px solid #f76707;
  border-radius: 5px;
  background-color: #fff4e6;
  max-width: 940px;
  margin: 0 auto;
}

.wrapper > div {
  border: 2px solid #ffa94d;
  border-radius: 5px;
  background-color: #ffd8a8;
  padding: 1em;
  color: #d9480f;
}

Header

Sidebar

Content

Footer

Lastly, why doesn't the faulty layout display in many cases?
When you copy HTML code as rendered on a web page (e.g., copy the code directly from the question), the   characters, being HTML code, have already been rendered. So only plain (collapsible) white space gets copied and the layout will appear to be working fine.
Also, if you copy the HTML code from some code editors in some browsers (e.g., the Stack Snippet editor on Edge), the   characters don't get copied, either. I needed to copy the code from the jsFiddle editor in Chrome to finally see the problem.
Also, if you hit the "Tidy" button in the editor using the original code, spaces will be added between the lines.

A: The empty cells have to be inserted, you'll not get it by default, just adding the HTML and body tag fixed the bottom gap issue:

.header {
    grid-area: hd;
}
.footer {
    grid-area: ft;
}
.content {
    grid-area: main;
}
.sidebar {
    grid-area: sd;
}
.empty-cell1 {
    grid-area: ec1;
}
.empty-cell2 {
    grid-area: ec2;
}
* {box-sizing: border-box;}

.wrapper {
    border: 2px solid #f76707;
    border-radius: 5px;
    background-color: #fff4e6;
    max-width: 940px;
    margin: 0 auto;
}

.wrapper > div {
    border: 2px solid #ffa94d;
    border-radius: 5px;
    background-color: #ffd8a8;
    padding: 1em;
    color: #d9480f;
}
.wrapper {
    display: grid;
    grid-template-areas:
      "hd hd ft"
      "sd ec1 ft"
      "sd main ft"
      "sd ec2 ft";
}
<!DOCTYPE html>

Header

Sidebar

Content

Footer


Q: Is setting my webserver to https, also securize my ajax call? Imagine I have a small webpage I browse in https with a signed certificate that load data with an ajax call like this:
$.ajax(
    {
type:"POST",
url:"ressource/js/load_footer.php",
data:"page="+variable,
success:
    alert("poney");
    }
)

Can I assume that this ajax call is secure by https ? or does it communicate by http ?

A: As mentionned in the comment of my question:

Since it is a relative URL, it will use the protocol of the page it is executed in. But instead of asking, you could also have found this out easily yourself by just looking at the request in the net panel of your browser’s developer tools … –  CBroe 4 mins ago


Q: How to use mechanize to fill search form and get results back? i am trying to use mechanize with python to search for a keyword using a a search form.
this is the form code :
<form id="searchform" action="http://www.example.com/" method="get">
<input id="s" type="text" onfocus="if (this.value == 'Search') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Search';}" name="s" value="Search">
<input type="image" style="border:0; vertical-align: top;" src="http://www.example.com/wp-content/themes/SimpleColor/images/search.gif">
</form>

i want to be able to submit and get the results back so i can extract the info from the results.
Thanks in advance.

A: From the official page, you create a browser object by br = mechanize.Browser() and follow a link with the object - br.open("http://www.example.com/"), and then you select a form by br.select_form(name="searchform") and you can pass an input by br["s"] = #something and submit it resp = br.submit() use the resp object like you wish.


Q: Boundary conditions of the Electric field of a conducting transmission line Solving Maxwell's Equations for the Electric Field of a linear-isotropic cylindrical conductor leads to the electric field being proportional to the Bessel function of the first kind (see below).
Maxwell's Equations:
\$ Div[E] = \frac{\rho}{\epsilon_{ps}} \$-> 0 (reasonable approximation of no free charge in conductor)
\$ Div[B] = 0 \$
\$ Curl[E] = -\frac{d}{dt}[B] \$   ... (i)
\$ Curl[B] = \mu J + \mu\epsilon_{ps}\frac{d}{dt}[E] \$  ... (ii)
Take Curl of (i):
\$ Curl[Curl[E]] = Grad[Div[E]] - Laplacian[E] = -\frac{d}{dt}[Curl[B]] \$
Since Div[E] ~ 0,
\$ Laplacian[E] = \frac{d}{dt}[Curl[B]] = \frac{d}{dt}[\mu J + \mu espilon_{ps} E]
\$
The assumption of a linear, isotropic material prompts us to treat eps, mu, and rho as frequency-dependent scalars (rather than tensors). Also, we make the assumption of J = rho*E, a rough approximation of Ohm's law that follows from the kinetic theory of charges in the context of the Drude model.
So: \$ Laplacian[E] = d/dt[\mu\rho E + \mu\epsilon\frac{d}{dt}[E]] \$
which is a basic wave-equation with a dampening terms via \$ \mu\rho \frac{d}{dt}[E] \$....
Representing Laplacian[E] in cylindrical coordinates to suit the geometry of the line, and solving the PDE by separation of variables (E[r,t] = R[r]*T[t]*Z[z]) leads to:
\$ R[r] = BesselJ[0,\lambda r] \$ (which is the r-spatial component of E).
In math/physics, it is here that we would typically quantize lambda using a boundary condition on the E-field at r = a (a being the radius of the line), and then employ some initial conditions to derive the required Bessel-Fourier series representation of the solution. Does this act of assigning boundary condition(s) apply to such wire systems, and if so, what form of boundary condition(s) on E[a] should we use? >> Are the standard boundary conditions of electromagnetism sufficient?
In mathematics, a boundary condition is typically specified and a Bessel-fourier series is then used to determine the nature of the field in the line. In electrical engineering, what type of boundary conditions are applied to a conductor carrying a current in the direction of the E-field?

A: If you assume the conductive elements are perfect (\$\rho=0\$), then the boundary condition is that the E field tangent to the surface goes to 0. This is often called "perfect conductor boundary conditions".
If you want to model a real conductive material (\$\rho > 0\$), then you will have to model the fields and currents inside the conductive region also. The boundary condition will be that the tangential component of \$\vec{E}\$ is continuous across the boundary.


Q: T5Tokenizer and T5EncoderModel are used to encode sentences then nn.TransformerDecoder to decode to a 2-label tensor. It gives error Used T5Tokenizer to tokenize a sentence then T5EncoderModel to encode. Finally, used the pytorch nn.TransformerDecoder to decode it. The target vector is a torch.tensor [y1, y2] where y1 and y2 have binary value. But it returns an error RuntimeError: DataLoader worker (pid(s) 723820) exited unexpectedly. The dataset class is given below.
tokenizer=T5TokenizerFast.from_pretrained('t5-base')
MAX_LEN = tokenizer(balanced_sentences[max_idx]).input_ids
class MyDataset(Dataset):
    def __init__(self, sentences, labels):
        self.labels = labels
        self.sentences = sentences
        self.tokenizer = tokenizer
    def __len__(self):
        return len(self.labels)

    def __getitem__(self, idx):
        sentence = self.sentences[idx]
        label = self.labels[idx]
        tokenized = tokenizer(self.sentences[idx],
                             max_length=MAX_LEN,
                             padding='max_length',
                             truncation=True,
                             add_special_tokens=True,
                             return_tensors="pt")
        sample = {"input_id": tokenized['input_ids'].flatten(),
                  "attention_mask":tokenized['attention_mask'].flatten(),
                  "label": label}
        return sample

The model is created in the following way
class MyModel(pl.LightningModule):
    def __init__(self):
        super().__init__()
        self.encoder = T5EncoderModel.from_pretrained("t5-base", return_dict = True)
        dec_layer = nn.TransformerDecoderLayer(d_model=512, nhead=8, batch_first=True)
        self.decoder = nn.TransformerDecoder(dec_layer, num_layers=6)
        self.loss_fc = nn.BCELoss()

    def forward(self, input_id, attention_mask, label=None):
        encoded_sentence = self.encoder(input_id, attention_mask)#.last_hidden_state.mean(dim=1)
        loss, output = self.decoder(label, encoded_sentence)
        return loss, output

    def training_step(self, batch, batch_idx):
        input_id = batch['input_id']
        attention_mask = batch['attention_mask']
        label = batch['label']
        loss, output = self(input_id = input_id,
                            attention_mask=attention_mask,
                             label = label)
        self.log('train_loss', loss, prog_bar = True, logger = True)
        return loss

    def validation_step(self, batch, batch_idx):
        input_id = batch['input_id']
        attention_mask = batch['attention_mask']
        label = batch['label']
        loss, output = self(input_id = input_id,
                            attention_mask=attention_mask,
                             label = label)
        self.log('train_loss', loss, prog_bar = True, logger = True)
        return loss

    def configure_optimizers(self):
        return torch.optim.Adam(self.parameters(), lr=0.001)

trainer = pl.Trainer(logger = logger,
                     num_sanity_val_steps=0,
                     max_epochs = N_EPOCHS,
                     gpus = 1,
                     progress_bar_refresh_rate = 20)

trainer.fit(model, data_module)

A: If you're use VSCode it sounds like the data loader has multiple workers and it can't create more threads. Set the number of workers to 0.
See: VSCode bug with PyTorch DataLoader?


Q: What is the correct way to encapsulate factory methods from derived classes when implementing factory in base class? I am trying to create simple class with ability to register derived classes for creation from base class. However I cannot find a good way to encapsulate this functionality from descendants.
Class variables looks for me a bad idea because they available everywhere in inheritance chain. So I try do something with class instance variables. Perfectly it will be that all class methods will be inaccessible except register_as
class A
  @registered = {}
  class << self
    def register_as(name)
      A.registered[name] = self
    end

    def known
      A.registered
    end

    protected
    attr_accessor :registered
  end

  def helpful_method
  end

end

class B < A
  class << self
    def reg_trash
      A.registered[:trash] = :trash
    end
  end
  B.register_as :b
end

B.reg_trash
p A.known

However registered is still accessible from B class.
Currently looks like the only one possible option is to split A class to dedicated Factory class and A class will hold only helpful instance methods.
Maybe it is possible to do something via .inherited and .undef_method, isn't it?

A:
Maybe it is possible to do something via .inherited and .undef_method, isn't it?

Yes, it is possible. But the idea smells, as for me - you're going to break substitutability.
If you don't want the "derived" classes to inherit the behavior of the parent, why do you use inheritance at all? Try composition instead and mix in only the behavior you need. For example, something like this could work (very dirty example, but I hope you got the idea):
class A
  module Registry
    def register_as(name)
      A.register_as(name, self)
    end
  end

  @registered = {}

  def self.register_as(name, klass)
    @registered[name] = klass
  end

  def self.known
    @registered
  end
end

class B
  extend A::Registry
  register_as :b
end

class C
  extend A::Registry
  register_as :c
end

A.known # => {:b => B, :c => C}


Q: Clarity on Docker Container IP addresses for API requests I want to be able to connect to a third-party .NET API I am running as a docker image within a container. When I connect to the ip address and port on my browser it works though when I try and run a get request in python it does not. I am not sure what I am doing wrong.
The Django python application is an image within the container using 0.0.0.0:8000.
This is the docker-compose.yml file for a .NET image I am running from within a container:
mt4rest:
    image: mt4rest:latest
    ports:
      - "0.0.0.0:5000:80"

Here are the ports as per docker inspect
  "Ports": {
                "443/tcp": null,
                "80/tcp": [
                    {
                        "HostIp": "0.0.0.0",
                        "HostPort": "5000"
                    }
                ]
            },

When I run
http://0.0.0.0:5000/Ping

or
http://127.0.0.1:5000/Ping

in my browser, I get OK though when I run the same endpoints in Python:
response = requests.get('http://0.0.0.0:5000/Ping')

or
response = requests.get('http://127.0.0.1:5000/Ping')

I receive the following error:
requests.exceptions.ConnectionError: HTTPConnectionPool(host='0.0.0.0', port=5000):
Max retries exceeded with url: /Ping (Caused by
NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fe7aa5af640>:
Failed to establish a new connection: [Errno 111] Connection refused'))

or
requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=5000):
Max retries exceeded with url: /Ping (Caused by
NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f6322e2b640>:
Failed to establish a new connection: [Errno 111] Connection refused'))

I understand this to mean that the address for the request is not found.
I am not sure what I am doing wrong.

A: Lets call your host as HOST_BASE.
You are having two containers, one is exposing 5000 on host. Its HOST_BASE:5000.
Other is your python-app container.
Now, you are running another python-app in container on host HOST_BASE. And try to hit: http://0.0.0.0:5000, which is not accessible. Note: its 0.0.0.0 is localhost of the container itself.
You want to connect to HOST_BASE:5000, which is not localhost or 0.0.0.0
You need to configure networking between your two containers. Or, for simplicity, use --network host while running both of your container.
Hope that helps.

A: There is an acceptable answer for this question on stackoverflow which solves the problem:
Python requests in Docker Compose containers


Q: Error: Transaction has been reverted by the EVM Following a tutorial online to learn about minting NFTs - https://blog.logrocket.com/how-to-create-nfts-with-javascript/
I keep getting this error, and I've tried reviewing different posts but I still can't seem to bypass it.
(node:28474) UnhandledPromiseRejectionWarning: Error: Transaction has been reverted by the EVM:
{
  "transactionHash": "0x70b857fb9adf1539b7b8e9612c1c5e2a470b4db9bc4060b943bcd75b85ca36d9",
  "blockHash": "0x79f98597420377cf932ac053db4051c76c40347337413949c0e61044a3c490dc",
  "blockNumber": 11554713,
  "contractAddress": null,
  "cumulativeGasUsed": 22945,
  "effectiveGasPrice": "0x4a817c800",
  "from": "0x6031679a1230b03acb601bd5d643de4dfe93ac1c",
  "gasUsed": 22945,
  "logs": [],
  "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
  "status": false,
  "to": "0xfcacbb204e0d93776cfd9a7f26f8333547e11dde",
  "transactionIndex": 0,
  "type": "0x0"
}
    at Object.TransactionError (/Users/x224631/Applications/LlamaClub/node_modules/web3-core-helpers/lib/errors.js:87:21)
    at Object.TransactionRevertedWithoutReasonError (/Users/x224631/Applications/LlamaClub/node_modules/web3-core-helpers/lib/errors.js:98:21)
    at /Users/x224631/Applications/LlamaClub/node_modules/web3-core-method/lib/index.js:393:57
    at processTicksAndRejections (internal/process/task_queues.js:94:5)
(node:28474) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 7)
(node:28474) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Here's my smart contract file (.sol)
//Contract based on https://docs.openzeppelin.com/contracts/3.x/erc721
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

// implements the ERC721 standard
// import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
// keeps track of the number of tokens issued
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

// Accessing the Ownable method ensures that only the creator of the smart contract can interact with it
contract TorNFT is ERC721URIStorage, Ownable {
    using Counters for Counters.Counter;
    Counters.Counter private _tokenIds;
    mapping(string => uint8) hashes;

    // the name and symbol for the NFT
    constructor() public ERC721("LlamaClub", "TOR") {}

    // Create a function to mint/create the NFT
    // receiver takes a type of address. This is the wallet address of the user that should receive the NFT minted using the smart contract
    // tokenURI takes a string that contains metadata about the NFT

    function createNFT(
        address receiver,
        // string memory hash,
        string memory tokenURI
    ) public returns (uint256) {
        _tokenIds.increment();

        uint256 newItemId = _tokenIds.current();
        _mint(receiver, newItemId);
        _setTokenURI(newItemId, tokenURI);

        return newItemId;
    }
}


Q: Shell program to print the first and last parameter and their sum I want to make a shell program which prints out the first and the last parameter, then it prints out their sum. Here is my code, but it gives an error and doesn't work, can anybody help?
echo "How many parameters do you want?"
read param
echo "You entered $param parameters"
first = $param
last = `echo $*|cut –f$# -d" "`
sum = `$first + $last`
echo "The sum of the two parameters are $sum"

A: Here is an approach for you:
first="$1"
last="${@: -1}"
echo "first: $first"
echo "last: $last"
sum=$((first + last))
echo "The sum of the two parameters are $sum"

You can run like this:
./program.sh 1 2 3 4
first: 1
last: 4
The sum of the two parameters are 5


Q: c# 6.0 and reflection, getting value of Property Initializers I've been trying to experiment with reflection and I have a question.
Lets say I have a class, and in this class I have a property initilized with the new feature of c# 6.0
Class MyClass()
{
   public string SomeProperty{ get; set; } = "SomeValue";
}

Is there any way of getting this value, with reflection, without initilizating the class?
I know I could do this;
var foo= new MyClass();
var value = foo.GetType().GetProperty("SomeProperty").GetValue(foo);

But what I want to do is something similiar to this ;
typeof(MyClass).GetProperty("SomeProperty").GetValue();

I know I could use a field to get the value. But it needs to be a property.
Thank you.

A: It's just a syntax sugar.
This:
class MyClass()
{
   public string SomeProperty{ get; set; } = "SomeValue";
}

will be unwrapped by compiler into this:
class MyClass()
{
   public MyClass()
   {
       _someProperty = "SomeValue";
   }

   // actually, backing field name will be different,
   // but it doesn't matter for this question
   private string _someProperty;

   public string SomeProperty
   {
        get { return _someProperty; }
        set { _someProperty = value; }
   }
}

Reflection is about metadata. There are no any "SomeValue" stored in metatada. All you can do, is to read property value in regular way.

I know I could use a field to get the value

Without instantiating an object, you can get values of static fields only.
To get values of instance fields, you, obviously, need an instance of object.

A: Alternatively, if you need default value of property in reflection metadata, you can use Attributes, one of it from System.ComponentModel, do the work: DefaultValue. For example:
using System.ComponentModel;

class MyClass()
{
   [DefaultValue("SomeValue")]
   public string SomeProperty{ get; set; } = "SomeValue";
}
//
var propertyInfo = typeof(MyClass).GetProperty("SomeProperty");
var defaultValue = (DefaultValue)Attribute.GetCustomeAttribute(propertyInfo, typeof(DefaultValue));
var value = defaultValue.Value;


Q: Using Generate Near Table and keep the ID attributes I try to use near table between two datasets to calculate the nearest distance. The original data is as the right one, and the near table generated is as the left one. The problem is the attribute of "IN_FID" and "NEAR_FID", none of them keep the correct values from the data. The ID number is important to me, how can I keep it? I have tried to join the attribute, but it turns out "Null" values.
Can anyone help me?

A: "NEAR_FID" and "IN_FID" fields always refer to OBJECTID field of the feature class (in case of shapefile it is usually OID field). Every feature class has this field. This field is bounded to feature class and has not relation to your data.
So if you wish to join your near table to your data by custom id field, you must firstly join near table to your layer with OBJECTID field and then layer to your data by your custom ID field.


Q: Why no output from Kendo-UI template? I am trying to use Kendo-UI templates to display values from a JavaScript array, but nothing is appearing in the HTML.

A: I found three problems: 1) the template(tableData) must be set to a DOM element, as in $("#output").html(template(tableData)); and 2) that the variable name inside the template must be data; and 3) the code that loads the template must be executed after the DOM is ready. Here is the complete and corrected code:
<!DOCTYPE html>

    <title></title>
    <link href="Content/kendo/2012.2.710/kendo.common.min.css" rel="stylesheet" />
    <link href="Content/kendo/2012.2.710/kendo.default.min.css" rel="stylesheet" />

    <form id="form1" runat="server">

    </form>


Q: вывод неографа в Graphviz c++ #include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <boost/graph/graphviz.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/iteration_macros.hpp>
#define _SCL_SECURE_NO_WARNINGS
using namespace std;

int main()
{
    setlocale(LC_ALL, "Russian");
    ifstream in("input.txt");
    ofstream out("output.txt");
    out << "graph { " << endl;
    int m;//кол-во ребер
    int n;//кол-во вершин
    in >> n;
    in >> m;
    int x, y, z;//считываем дуги и вес
    vector < pair < int, pair<int, int> > > g(m); // вес - вершина 1 - вершина 2

    vector < pair<int, int> > res;//массив для хранения дуг остовного дерева

    for (int i = 0; i < m; i++)
    {
        in >> x >> y >> z;
        g[i].first = z;
        g[i].second.first = x;
        g[i].second.second = y;
    }
    int tree_weight = 0;
    int cost = 0;
    sort(g.begin(), g.end());

    vector<int> tree_id(n);

    for (int i = 0; i < n+1; i++) {
        tree_id.push_back(NULL);
    }
    for (int i = 0; i < n+1; ++i)
        tree_id[i] = i;
    for (int i = 0; i < m; ++i)
    {
        int a = g[i].second.first, b = g[i].second.second, l = g[i].first;
        if (tree_id[a] != tree_id[b])
        {
            cost += l;
            res.push_back(make_pair(a, b));
            int old_id = tree_id[b], new_id = tree_id[a];
            for (int j = 0; j < n+1; ++j)
                if (tree_id[j] == old_id)
                    tree_id[j] = new_id;
        }
    }
    cout << "Ребра минимального остовного дерева: " << endl;
    for (int i = 0; i < res.size(); i++) {
        out << res[i].first << "--" << res[i].second<<";"<<endl;
        cout << res[i].first << " , " << res[i].second << endl;
    }
    out << "}";
    cout << "Вес минимального остовного дерева: "<<cost<<endl;
    system("dot output.txt -Tpng -og.png");
}

Сделал алгоритм крускала. Вывел граф в текстовый файл в таком виде:
graph {
2--4;
3--4;
1--2;
3--5;
4--6;
}
Пишет syntax error in line 7. То есть это там, где скобка. А что не так здесь?Я в файл все это пустых строчек писал(просто тут нельзя так вписать).


Q: In SignalR Core how can i exclude a connection from being notified The scenario is as follow:
I have multiple WPF clients that have a SignalR connection with a server. One WPF client calls a REST API to generate an order. The server would like to notify all WPF clients that an order was placed except for the WPF client that created the order.
Note that the my notification logic is put outside of the hub class.
What is the best approach to solve this?

A: There is a build-in Hub.Clients.Others to achieve your requirement.
Here is a sample:
public class ChatHub : Hub
{
    public async Task SendMessage(string user, string message)
    {
        await Clients.Others.SendAsync("ReceiveMessage", user, message);
    }
}

Reference:
https://learn.microsoft.com/en-us/aspnet/core/signalr/hubs?view=aspnetcore-3.1#the-clients-object


Q:  inside cfscript component I'm making components for a site and I'm wondering if I can return a cfform inside a return variable from a component and force coldfusion to output it parsed.
Obviously using "writeOutput(")" doesn't work.
How could I achieve this?
Thanks for your time!

A: You can't return a cfform, because tags can't be used inside of a CFScript based component. You're far better off doing something like this with a custom tag, which then references your component to get pieces to build out the form.
I would avoid (if at all possible) putting any cfform related pieces into a component, script-based or not.
If you did want to ultimately go this route, you'd need to put the cfform (and it's relevant pieces) either in another component that gets called by the script based one, or in an include that then is saved to a variable. All of the solutions related to trying to get the cfform into your CFC are going to be messy.

A: If you absolutely must do this (though I would shy away from it myself) you might want to have a look at this:
http://www.madfellas.com/blog/index.cfm/2011/1/26/Using-CFML-tags-in-cfscript-C4X-prototype


Q: Separating DOM elements for click events I have a website which displays search results. The results are displayed with headline information of the full item. The html of each search result looks like this:
<article class="search_result" onclick="location.href='#';" style="cursor: pointer;">

// Search result data

</article>

As you can see, I have made it so that you can click anywhere and access the result in more detail
However, within the search result, I have also included a button which performs another function.
The problem I have is when you click on the button, both the button and the search result receive the click event and act upon it. If the button is clicked, I dont want the search result to handle it as well.
How can I sort this?

A: JavaScript events bubble up the DOM by default, so events triggered on a children will be triggered on the parent.
To prevent this, you need to stop the propagation of the event.
This is done by:
event.stopPropagation();

Note that event is usually passed as a parameter to your callback functions. (Meaning, don't use onclick="" attributes so you get function callback)
Full documentation: https://developer.mozilla.org/en-US/docs/Web/API/event.stopPropagation
(IE < 8 fallback: Prototype Event.StopPropagation for IE >= 8)