text:
Q: pgf stacked bar plot not displayed correctly - wrong intersection with x-axis I'm trying to generate a bar plot with the code below. As you can see does the bar plot not start at zero, as it should. It starts below zero!!! Can anybody help me?
\documentclass[a4paper,11pt,twoside,openright]{scrreprt}
\usepackage{tikz} %used for pgfplots
\usepackage{pgfplots, pgfplotstable} % to create diagrams, plots, ...
\usepackage{filecontents}

\begin{document}

% Results IPPC
\begin{filecontents}{labelIPPC.dat}
X   start  Container    T-DO        T-MRF   MRF     T-Rec   label
1   0      335489       4894217     536423  944172  82159   \space
2   0      428004       101754      1033659 3289363 64989   \space
3   0      508863       101754      739925  1040748 89001   \space
4   0      254431       101754      739925  1040748 89001   IPPC\space 2013
5   0      254431       101754      683838  1016135 86948   \space
6   0      254431       101754      652601  991521  85590   \space
\end{filecontents}

\begin{figure}[!htbp]
\centering
\caption{Results of ecological analysis for future scenarios}
\begin{tikzpicture}
\pgfplotsset{
    ybar stacked,
    %set layers,
    width=0.7\textwidth,
    every axis legend/.append style={nodes={right}},
    legend style={at={(0.5,-0.30)}, anchor=north, legend columns=1},
    x tick label style={rotate=90},
    xticklabels={Scenario 1,Scenario 2,Scenario 3,Scenario 4,Scenario 5,Scenario 6},
    xtick={1,...,6},
    point meta=explicit symbolic, % label und nicht zahl darstellen
    }

\begin{axis} [
scale only axis,
axis y line*=left,
y tick label style={/pgf/number format/1000 sep=',
        /pgf/number format/fixed,
        /pgf/number format/sci},
scaled ticks=false,
ylabel near ticks,
ylabel={UBP (Eco-points)},
ybar,
bar shift=-0.34cm, % half of bar width
bar width=0.6cm,
]
%\addplot + [color=red!50!white] table[x=X, y=start, meta=label] {labelIPPC.dat};

\addplot + [color=red!50!white] table[x=X, y=Container, meta=label] {labelIPPC.dat};
\addlegendentry{Container}

\addplot + [color=green!50!white]  table[x=X, y=T-DO, meta=label]                       {labelIPPC.dat};
\addlegendentry{Transport to drop-off site}

\addplot + [color=blue!50!white]  table[x=X, y=T-MRF, meta=label] {labelIPPC.dat};
\addlegendentry{Transport to MRF}

\addplot + [color=orange!50!white]  table[x=X, y=MRF, meta=label] {labelIPPC.dat};
\addlegendentry{Material recovery facility}

\addplot + [color=black!50!white, nodes near coords, every node near coord/.append style={rotate=90, anchor=west}]  table[x=X, y=T-Rec, meta=label] {labelIPPC.dat};
\addlegendentry{Transport to recycling facility}

\end{axis}
\end{tikzpicture}
\label{fig:Results_Scenarios}
\end{figure}
\end{document}

If included the commented \addplot, it starts at zero, but then the legend is out of order. I really hope someone can help me.
Thanks very much

A: I had the same problem and building on the comments by darthbith the following worked for me (and also fixes your example):
Additionally to the ymin=0, which let's the bar start right at the axis, you add an additional enlargelimits=true to the axis options, to get the whitespace back between the axis and the start of the bars.
What still eludes me, though, is that I have one stacked bar plot where I do not need these options explicitly and another that only worked with these explicit options. The only difference between those plots is that the first has additional addplot commands, thus its bars consist of more segments.
I hope this helps.


text:
Q: .NET Open Source Package Manager Hornget is gone, are there any other package managers like hornget that you can download the trunk versions of NH3 / FluentNH together?
Manually putting the two together is tedious and from what i can tell neither Nu or OpenWrap have the two trunks together :(

A: Horn being dead only means that it's not being developed anymore, however what it was able to do 5 months ago it can still do now. The bits are still there, you can still use horn as a tool to build NHibernate 3 + Fluent NHibernate.
Or you can also get the combo here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to add Hibernate dependency I am trying to create a new Maven project with Java and Spring Boot. To do this I used Spring Initializr with the following dependencies: Web, JPA, Mysql.
Along with those I want to use Hibernate(which I initially thought that would be brought by JPA dependency). My problem is that I don't have any Hibernate dependency in my pom.xml file and, when I try to add it, the configuration files(hibernate.cfg.xml) are not created.
How can I add Hibernate to this project?
Thank you

A: To answer your question you need to understand a bit more of how Spring Boot Started are packaged.
In your initializer project's POM, you will see the following being added for JPA,
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

This is not a physical jar being included, this is a collection of other libraries, all added to another POM file. (You can scroll to the source a file)
In the spring-boot-starter-data-jpa POM you will see that Hibernate is already added as a dependency.
<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-core</artifactId>
  <version>5.2.17.Final</version>
</dependency>

Therefore you already have the hibernate dependencies added to your project.
Secondly, please have a look at
https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/
It is a tutorial that uses Spring-Boot's JPA and shows you how to configure it.


text:
Q: How to insert a row in a Pandas multiindex dataframe? I have a Pandas dataframe with a multiindex (Reg, Type, Part, IsExpired)-
Reg        Type      Part     IsExpired    Quantity
APAC       Disk      A        False        10
                              True         12
EMEA       Disk      A        False        22
EMEA       Disk      B        False        13
                              True         17

I want to make sure that every (Reg, Type, Part) tuple has True and False for IsExpired. E.g. I'd like to insert a row for (EMEA, Disk, A, True)-
Reg        Type      Part     IsExpired    Quantity
APAC       Disk      A        False        10
                              True         12
EMEA       Disk      A        False        22
                              True         0   <-- inserted row
EMEA       Disk      B        False        13
                              True         17

A: Have you considered just adding the relevant row? Since you're really just adding one cell of a value you could do it efficiently like this:
df.at[('EMEA', 'DISC', 'A', False), 'Quantity'] = 0

A: You could unstack and then fillna:
In [11]: df2
Out[11]:
                          Quantity
Reg  Type Part IsExpired
APAC Disk A    False            10
               True             12
EMEA Disk A    False            22
          B    False            13
               True             17

In [12]: df2.unstack()
Out[12]:
               Quantity
IsExpired         False True
Reg  Type Part
APAC Disk A          10    12
EMEA Disk A          22   NaN
          B          13    17

In [13]: df2.unstack().fillna(0)
Out[13]:
               Quantity
IsExpired         False True
Reg  Type Part
APAC Disk A          10    12
EMEA Disk A          22     0
          B          13    17

Perhaps it makes sense to keep this as a column? Otherwise stack it back:
In [14]: df2.unstack().fillna(0).stack()
Out[14]:
                          Quantity
Reg  Type Part IsExpired
APAC Disk A    False            10
               True             12
EMEA Disk A    False            22
               True              0
          B    False            13
               True             17


text:
Q: Vector Layer not visible in openlayers I'm trying to create a map where I have one wms layer and then a vector layer which is created from a kml file - held in the same directory as the web page.
I'm trying to implement the cluster strategy but to no avail. I think I might me going wrong even before the cluster strategy kick is in as I can't see the vector layer at all when I remove the wms layer?
This is the code for the vector layer:
var map;

function init() {
   map = new OpenLayers.Map('map_element', {});
   var wms = new OpenLayers.Layer.WMS(
    'WMS Layer Title',
    'http://vmap0.tiles.osgeo.org/wms/vmap0',
    {layers: 'basic'},
    {}
);

var masts = new OpenLayers.Layer.Vector("Masts", {
projection: displayProjection //EPSG:4326,
protocol: new OpenLayers.Protocol.HTTP({
url: "masts.kml",
format: new OpenLayers.Format.KML({
        extractStyles: true,
        extractAttributes: true
        })
}),
strategies: [
new OpenLayers.Strategy.BBOX(),
new OpenLayers.Strategy.Cluster()
],

styleMap: new OpenLayers.StyleMap({
"default": {
        fillColor: "#8aeeef",
        strokeColor: "#32a8a9"
        }
     })
});

var StaffTravel = new OpenLayers.Layer.Vector("StaffTravel", {
protocol: new OpenLayers.Protocol.HTTP({
    url: "staff.kml",
    format: new OpenLayers.Format.KML()
}),
strategies: [
    new OpenLayers.Strategy.Fixed(),
    new OpenLayers.Strategy.Cluster({distance: 15, threshold: 3})
]
});

map.addLayers([StaffTravel]);

Any ideas where I might be going wrong?

A: can you check out from console when adding my code to your app if your kml file is loaded or not? beside this you should glance at this example here and here.
var StaffTravel = new OpenLayers.Layer.Vector("StaffTravel", {
projection: displayProjection //EPSG:4326,
protocol: new OpenLayers.Protocol.HTTP({
    url: "staff.kml",
    format: new OpenLayers.Format.KML({
                extractStyles: true,
                extractAttributes: true
                })
}),
strategies: [
    new OpenLayers.Strategy.BBOX(),
    new OpenLayers.Strategy.Cluster()
],

styleMap: new OpenLayers.StyleMap({
    "default": {
                fillColor: "#8aeeef",
                strokeColor: "#32a8a9"
                }
                    })
});

map.addLayers([StaffTravel]);

i hope it helps you...


text:
Q: UIActivityIndicator is not moving up when scrolled in tableview I have a UITableviewcontroller and a activity indicator added to it.
When ever my table scroll, the indicator also moves up and goes out of bounds. Instead I want to display indicator even if the table scrolls
I checked this post: UIActivityIndicator scrolls with tableView which says I need to use UIViewcontroller instead of Tableviewcontroller.
Since I have many tableviewcontrollers added in application, isnt it possible to scroll indicator along with tableview.
My UIActivityIndicator is helper class across entire application where I control to display and remove spinner
extension UIViewController {
    class func displaySpinner(onView : UIView) -> UIView {
        let spinnerView = UIView.init(frame: onView.frame)
        spinnerView.backgroundColor = UIColor.init(red: 0.5, green: 0.5, blue: 0.5, alpha: 0.5)
        let ai = UIActivityIndicatorView.init(activityIndicatorStyle: .whiteLarge)
        ai.startAnimating()
        ai.center = spinnerView.center

        DispatchQueue.main.async {
            spinnerView.addSubview(ai)
            onView.addSubview(spinnerView)
        }

        return spinnerView
    }

    class func removeSpinner(spinner :UIView) {
        DispatchQueue.main.async {
            spinner.removeFromSuperview()
        }
    }
}

A: You can do it if it's not an extension say the code is inside the tableController and
let indicator = UIActivityIndicator()

then use
func scrollViewDidScroll(_ scrollView: UIScrollView) {
  // change frame of indicator by scrollview.contentOffset.y
}

You can also extend
class MyTableConWithIndicator:UITableViewController {

   let indicator = UIActivityIndicator()

   func scrollViewDidScroll(_ scrollView: UIScrollView) {
     // change y'frame of indicator by scrollview.contentOffset.y
   }
   func addIndicator() {}
   func removeIndicator() ()
}

Then extend from it in every tableController
class MyTable:MyTableConWithIndicator {}


text:
Q: Разбиение проекта на модули в GitHub Есть проект на GitHub (не оставляю ссылку, так как на картинке наглядней), структура проекта выглядит так:

Так выглядит структура проекта в IntelliJ IDEA.

Как видно на последней картинке специально изображена корневая папка проекта, так я хочу, что бы и на GitHub так было, к тому же в Intellij IDEA надо добавить новый модуль, в итоге на GitHub структура из модулей должна выглядеть так:

Как так сделать?


text:
Q: Проблема при настройке удаленного доступа по ssh к гостевой Ubuntu Server на облаке Задача: получить доступ к установленной в облаке гостевой ОС - Ubuntu Server.
На данный момент удалось настроить NAT для доступа к интернету из гостевой ОС.
Для доступа ssh были введены следующие настройки(последняя строка на картинке).
ssh на сервере установлен и запущен, служба активна. Порт 22.
Внешний ip  с другого компьютера пингуется, но по ssh подключиться не получается (через putty).
В чем может быть проблема? В настройках сети или в настройках ssh в гостевой ОС?
локальный ip гостевой ос 192.168.5.55
Настройки NAT в облаке

Доступ в интернет на гостевой ОС работает. Настроить ssh не удается.


text:
Q: Placeholder is showing like dots insted of placeholder text(Default text) Placeholder is not working in below IE10 browsers, meanwhile i wrote following code it is working fine.
But problem is in password field it shows dots instead of placeholder text. Please find the attached screen shot.
Here is my code, could you please  help is there any solution for fixing the password field placeholder visible.
//Default text in login page.
(function ($) {
    $.support.placeholder = ('placeholder' in document.createElement('input'));
})(jQuery);

//fix for IE7 and IE8
$(function () {
    if (!$.support.placeholder) {
        $("[placeholder]").focus(function () {
            if ($(this).val() == $(this).attr("placeholder")) $(this).val("");
        }).blur(function () {
            if ($(this).val() == "") $(this).val($(this).attr("placeholder"));
        }).blur();

        $("[placeholder]").parents("login").submit(function () {
            $(this).find('[placeholder]').each(function() {
                if ($(this).val() == $(this).attr("placeholder")) {
                    $(this).val("");
                }
            });
        });
    }
});![enter image description here][1]

A: Use this below, it will help you
$(function () {
  var input = document.createElement("input");
  if (('placeholder' in input) == false) {
    $('[placeholder]').focus(function () {
      var i = $(this);
      if (i.val() == i.attr('placeholder')) {
        i.val('').removeClass('placeholder');
        if (i.hasClass('password')) {
          i.removeClass('password');
          this.type = 'password';
        }
      }
    }).blur(function () {
      var i = $(this);
      if (i.val() == '' || i.val() == i.attr('placeholder')) {
        if (this.type == 'password') {
          i.addClass('password');
          this.type = 'text';
        }
        i.addClass('placeholder').val(i.attr('placeholder'));
      }
    }).blur().parents('form').submit(function () {
      $(this).find('[placeholder]').each(function () {
        var i = $(this);
        if (i.val() == i.attr('placeholder'))
          i.val('');
      })
    });
  }
});


text:
Q: AngularJS scroll directive - How to prevent re-rendering whole scope I have an AngularJS Application with a scroll directive implemented as the following:
http://jsfiddle.net/un6r4wts/
app = angular.module('myApp', []);

app.run(function ($rootScope) {

    $rootScope.var1 = 'Var1';
    $rootScope.var2 = function () { return Math.random(); };

});

app.directive("scroll", function ($window) {
    return function(scope, element, attrs) {
        angular.element($window).bind("scroll", function() {
            if (this.pageYOffset >= 100) {
                 scope.scrolled = true;
            } else {
                 scope.scrolled = false;
            }
            scope.$apply();
        });
    };
});

The HTML looks the following:

        {{var1}}

        {{var2()}}

I only want the class scrolled to be added to the div once the page is scrolled more than 100px. Which is working just fine, but I only want that to happen! I don't want the whole scope to be re-rendered. So the function var2() should not be executed while scrolling. Unfortunately it is though.
Is there any way to have angular only execute the function which is bound to the window element without re-rendering the whole scope, or am I misunderstanding here something fundamentally to AngularJS?
See this fiddle:
http://jsfiddle.net/un6r4wts/
Edit:
This seems to be a topic about a similar problem:
Angularjs scope.$apply in directive's on scroll listener

A: If you want to calculate an expression only once, you can prefix it with '::', which does exactly that. See it in docs under One-time binding:
https://docs.angularjs.org/guide/expression
Note, this requires angular 1.3+.
The reason that the expressions are calculated is because when you change a property value on your scope, then dirty check starts and evaluates all the watches for dirty check. When the view uses {{ }} on some scope variable, it creates a binding (which comes along with a watch).


text:
Q: web view in cocso2d how can I use web view in cocso2d

A: webView = [[WebView alloc] initWithFrame:NSMakeRect(0,0,580,400)
                               frameName:@"mainFrame"
                               groupName:nil];
[webView setAcceptsTouchEvents:YES];

[view addSubview:webView];

[[CCDirector sharedDirector].openGLView addSubview:view];

NSURL*url=[NSURL URLWithString:@"http://www.google.com"];
NSURLRequest*request=[NSURLRequest requestWithURL:url];
[[webView mainFrame] loadRequest:request];


text:
Q: My website in VisualStudio works well but on IIS did not? In my website I use Add Service Reference , I read some SharePoint lists,
For the first time I turn on my computer , in VS an error occur !!!
After that it works , and when I want to try on my IIS or Server ISS , the same error occur and did not fix :
Server Error in '/' Application.
Unauthorized
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.Services.Client.DataServiceClientException: Unauthorized

Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:
[DataServiceClientException: Unauthorized]
   System.Data.Services.Client.QueryResult.Execute() +656
   System.Data.Services.Client.DataServiceRequest.Execute(DataServiceContext context, QueryComponents queryComponents) +349

[DataServiceQueryException: An error occurred while processing this request.]
   System.Data.Services.Client.DataServiceRequest.Execute(DataServiceContext context, QueryComponents queryComponents) +562697
   System.Data.Services.Client.DataServiceQuery`1.Execute() +113
   System.Data.Services.Client.DataServiceQuery`1.GetEnumerator() +22
   _default.Page_Load(Object sender, EventArgs e) in c:\Users\user\Desktop\TPPG\tppg.com\default.aspx.cs:58
   System.Web.UI.Control.LoadRecursive() +71
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3178

And this error occur on foreach loop where I want to read data from SharePoint lists !
what can I do !?
this is my code, after Add Service Reference in page load :
    ServiceReference1.TPPDataContext obj = new ServiceReference1.TPPDataContext(new Uri("http://sharepoint/_layouts/viewlsts.aspx/_vti_bin/ListData.svc"));
    obj.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
    var sourc = obj.Announcement;

    foreach (var item in sourc)
    {
        if (item.WF1 == "Management1" && item.AnnounceTypeValue == "Management")
        {
            Place[0] = item.Text1;
        }
        else if (item.WF1 == "Sharepoint1" && item.AnnounceTypeValue == "Sharepoint")
        {
            Place[1] = item.Text1;
        }
        else if (item.WF1 == "Admin1" && item.AnnounceTypeValue == "Admin")
        {
            Place[2] = item.Text1;
        }
        else if (item.WF1 == "Training1" && item.AnnounceTypeValue == "Training")
        {
            Place[3] = item.Text1;
        }
        else if (item.WF1 == "Others1" && item.AnnounceTypeValue == "Others")
        {
            Place[4] = item.Text1;
        }
    }

A: Maybe it doesn't work because the application on IIS runs under the IIS user or it's set to the anonymous user. You could try 2 things:

*

*Try setting the app in IIS to integrated authentication, if your user has permission.

*(OR) Instead of DefaultCredentials, set the user with permissions to SharePoint:
obj.Credentials = new System.Net.NetworkCredential("user",
                                                "password",
                                                "domain");


text:
Q: Files with "sh" extension on windows Our Apache web server works in a Linux environment.
The cgi executables are called via a sh file (for example /cgi-bin/iwsblogin.sh).
The call "/cgi-bin/iwsblogin.sh" is in an html file.
Now I want to make a development and testing environment for this web server on windows.
I do not want to change the calls in the html files from "iwsblogin.sh" to "iwsblogin.bat" just for testing purposes.
Is there a way to configure windows in such a way, that files with the extension ".sh" are treated as executables the same way as ".bat" and ".exe" files?
The contents of this .sh file is for example:
- ms dos commands for setting some environment variables.
- Path of an exe file which should be called.
I know that there exist similar questions on stackoverflow where user suggest using cygwin, but this is NOT an option for me!
Thanks alot in advance

A: There are some ways to do this.

*

*If the .sh file works when you rename it to .bat, you can use "run as" and select C:\Windows\System32\cmd.exe as default program

*Use a sh emulator. For example, msysgit includes one or you can use cygwin (possibly the same source?).

I know you don't want to use cygwin, but why not? Please explain why this isn't an option. It is hard to look for an answer if we don't know why regular answers won't work.


text:
Q: Why is the polynomial $f(x)=x^3+x^2+x+1$ monotonic? I have to argue why the polynomial $f(x)=x^3+x^2+x+1$ has a reverse function $f^{-1}$ which is defined in on the whole of $\mathbb R$. I'm certain the argument would simply be that because $f(x)$ is monotonic on $\mathbb R$ it is also injective on $\mathbb R$. However I can not argue why $f(x)$ would be monotonic. A nudge in the right direction would be appreciated.
English is not my first language, please do say if my terminology is off.

A: HINT:
$f'(x)=3x^2+2x+1=(x+1)^2+2x^2>0$

A: I think you could consider the derivative and show it is always positive on $\mathbb{R}$, using the fact that it (the derivative) has no real roots, if calculus is acceptable for this problem.

A: Without calculus, you could look at $f(y)-f(x)=(y-x)(x^2+xy+y^2+x+y+1)$, and show that the right-hand side is positive whenever $y>x$.


text:
Q: javascript: will window.location make any warnings? If I use window.location = ""; to redirect a user, will any browsers give the user a warning message (since the page is redirecting without the user's consent)?
Should I use window.location = "" or window.location.href = ""?

A: No you can redirect the window location on your own. The only similarly related thing you can't do automatically is click a link for the user with an event.
You might be thinking of this type of notice:
window.onbeforeunload = function() {
    return "Are you sure you want to navigate away?";
}

A: AFAIK window.location and window.location.href should be pretty much eqivalent.
It's been a while since I've used it, but I don't remember ever seeing a prompt before leaving the page. Most of the time when I have been prompted it's been because I explicitly put a confirmation in, such as when clicking a link to delete something.

A: Setting window.location shouldn't cause any issues with redirection. However, if there is a hash, then some browsers may deal with it differently.
From the MDN spec:

Note: The example above works in situations where window.location.hash does not need to be retained. However, in Gecko-based browsers, setting window.location.pathname in this manner will erase any information in window.location.hash, whereas in WebKit (and possibly other browsers), setting the pathname will not alter the the hash. If you need to change pathname but keep the hash as is, use the replace() method instead, which should work consistently across browsers.

There shouldn't be any difference between location and location.href since whenever a property of the location object is modified, a document will be loaded using the URL as if window.location.assign() had been called with the modified URL.
Source: https://developer.mozilla.org/en/DOM/window.location

A: No. You will not get any warning (like you do if you close the window). And I have never seen any difference in location and location.href, but I use the last :)


text:
Q: How to estimate minimal efforts required to update trajectory of a moving ball? Let's imagine we've got a uniformly sampled curved trajectory of a moving ball in 3D space without gravity. Let's assume that some dynamic force is applied to the moving ball to update its trajectory between samples. Is it possible to estimate minimal efforts required to update trajectory of the moving ball between samples?
For example:

In case A there was no force applied between t and t+1 because the ball moved with constant speed.
In case B some dynamic force changed position of the ball from P(t) to P(t+1)
I would like to know the way to estimate minimal efforts required to move the ball from P(t) to P(t+1) in general case.
Edit:
One possible interpretation of "effort" might be the time integral of the magnitude of the force applied. This would quantify the total "scalar impulse" applied on the ball. This is also the relevant quantity when you want to perform a maneuver in a spacecraft by consuming the least amount of fuel (assuming the change in the mass of the spacecraft is negligible)

A: You can numerically estimate the acceleration of the path, by interpolating the data using a cubic spline or some other method in order to estimate the time derivatives of the positions. Then do it again to estimate the acceleration needed to follow the path. Finally, if you know the mass of the object, you can $\vec{F} = m \vec{a}$ to estimate force needed.
Below is an example using a single coordinate X as input (blue), and evaluating the speed Xp (red) and acceleration Xpp (green) in Excel.

I am using my own custom array function Derivative(x_range,y_range) to do the job.

Depending on what programming environment you have access to, try to find interpolating functions. They exist for MATLAB, C, Fortran, Python, Java, C# and all other major programming languages. You can try porting the C code from NRBOOK in section 3.3 relating to Cubic Splines.


text:
Q: Pushing nested objects to next object in array [functional style] I'm trying to get from an object that looks like this
[{current: [1], queue: []}, {current: [2], queue: []}, {current: [3], queue: []}]

to this:
[{current: [], queue: [3]}, {current: [], queue: [1]}, {current: [], queue: [2]}]

Basically, I want to push the item in "current" to the next item's queue.
I would like to use lodash or ramda.js to do this in the functional style. I'm quite new to functional style programming and I'm running into a wall with how to do this, especially handling the arr[2] -> arr[0] case. I thought about using a reduce but I'm not sure if that's the optimal way to solve the issue.

A: You can use lodash#map to achieve this.
var result = array.map(function(value, index) {
  // get previous array value
  var prev = array[(index - 1 + array.length) % array.length];
  return Object.assign(
    {}, // Makes sure that we don't mutate the original array
    value, // retain properties that are not `current` and `queue`
    { current: prev.queue, queue: prev.current } // override
  );
});

var array = [{
  current: [1],
  queue: []
}, {
  current: [2],
  queue: []
}, {
  current: [3],
  queue: []
}];

var result = array.map(function(value, index) {
  // get previous array value
  var prev = array[(index - 1 + array.length) % array.length];
  return Object.assign(
    {}, // Makes sure that we don't mutate the original array
    value, // retain properties that are not `current` and `queue`
    { current: prev.queue, queue: prev.current } // override
  );
});

console.log(result);
.as-console-wrapper { min-height: 100%; top: 0; }

A: A fun ramda solution:

*

*Create a new array that prepends the last item (e.g.: [1, 2, 3] to [3, 1, 2, 3])

*Use aperture to create pairs (e.g.: [[3,1], [1,2], [2,3]])

*Use a merge function to make a new item from a pair (e.g.: [4, 3, 5])

The mergePair and loop functions can probably be written differently... I couldn't find the right candidates in the docs.
const data = [{current: [1], queue: []}, {current: [2], queue: []}, {current: [3], queue: []}];

const mergePair = ([left, right]) =>
({ current: [], queue: concat(right.queue, left.current) })

const loop = arr => prepend(last(arr), arr);

const updateQueue = pipe(
  loop,
  aperture(2),
  map(mergePair)
)

updateQueue(data);

Try it here

A: One simple way is make a deep copy and move last item to first position in that copy.
Then iterate original to update each queue to matching index in rearranged copy

var data = [{current: [1], queue: []}, {current: [2], queue: []}, {current: [3], queue: []}],
    // make a copy of array
    copy = JSON.parse(JSON.stringify(data));
    // move last to first in copy
    copy.unshift(copy.pop());

data.forEach((el,i)=> {
  el.queue = copy[i].current;
  el.current.length = 0;
});

console.log(data)


text:
Q: Size of matplotlib plot in tkinter GUI depends on the primary monitor I am getting some behaviour I do not understand when I put a matplotlib plot in a tkinter GUI on macOS. The size of the plot seems to depend on whether I have an external monitor plugged in or not.
If the external monitor (27" 1440p) is plugged in, the plot is small; if only the internal monitor (14" 3024x1964) is used, the plot is bigger.
External:

Internal:

To show that the size of the plot is different, here is the GUI opened on the external monitor and dragged onto the internal monitor:

I really do not understand what is going on here as the size of the figure (fig_size in inches) doesn't seem to correspond to anything, but the size of the plot is modulated by changing the dpi parameter.
I would like some way to keep the size of the plot consistent in regard to the rest of the GUI. Note that the size of the plot changes in relation to the 'WIDGET' label.
Minimal working example used to produce the screenshots:
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
from tkinter import ttk
import tkinter as tk

class Application(tk.Frame, object):

    def __init__(self, master=None):
        # Call baseclass constructor.
        super(Application, self).__init__(master)

        self.fig_size = (6.5, 4)
        self.dpi = 100

        self.notebook = ttk.Notebook(root)
        self.notebook.pack(pady=10, expand=True)

        ## Buid window with tabs ##

        width = 600
        height = 400

        self.main = tk.Frame(self.notebook, width=width, height=height)
        self.main.pack(fill='both', expand=True)
        self.notebook.add(self.main, text='TAB 1')

        ttk.Style().map("TNotebook.Tab", foreground=[("selected", "#000000")])

        self.initialise_main(self.main)

    def initialise_main(self, tab):

        lbl = tk.Label(tab, text='WIDGET')

        self.fig, self.ax = plt.subplots(
            1, 1,
            figsize=self.fig_size,
            dpi=self.dpi,
        )

        self.line, = self.ax.plot([], [])  # empty graph
        self.ax.clear()

        self.GUIFig = FigureCanvasTkAgg(self.fig, tab)

        self.ax.ticklabel_format(useOffset=False)

        lbl.grid(row = 0, column=0)
        self.GUIFig.get_tk_widget().grid(row=1, column=0)

if __name__ == '__main__':

    root = tk.Tk()
    app = Application()
    app.master.title('MRE')
    app.mainloop()

NOTE: this example may not be completely miminimal but I wasn't sure if the OOP approach would change anything so I wanted to keep that consistent.

A: I haven't had frame size changing on me, but to keep my plots within the frame, I get the dpi and set figure size relative to that and the frame size, and fill the frame with the plot.  I also restrict the frame from changing size by setting self.frame2_fileplot.grid_propagate(False)
# get frame size parameters (update frame parameters first)
self.frame2_fileplot.update()
dpi = self.root.winfo_fpixels('1i')
plotwidth = self.frame2_fileplot.winfo_width() / dpi
plotheight = self.frame2_fileplot.winfo_height() / dpi

# create plot
self.plot_figure_fileplot_main = Figure(figsize = (plotwidth, plotheight),
                                   dpi = dpi, frameon = False, tight_layout = True)


text:
Q: Why is this javascript if condition not working as expected? I am doing a comparison on dates in javascript. In this case date1 is empty "" and I can see the same in firebug. As per the code below, the first alert shouldn't be called because date1 == "", but for some reason the alert alert(" This is called...."); is invoked. What is wrong here?
if(date1 != null || date1 != ""){

        if( (date1 != null || date2 != "") && (date1 < date2)){
                alert(" This is called....");
                break;
        }
        else{
            alert(" That is called....");
            break;
        }

    }

The above if condition is inside a for loop, hence the break.

A: I think you mean to be using && instead of || in your first comparision to make sure that both conditions are true and I think you have typo where you're using date1 instead of date2 in the second test.  Further, you can just use if (date1) to simultaenously rule out null and "" and undefined and 0 and NaN and any other falsey value.
I think you want something like this:
if (date1) {
    if(date2 && date1 < date2) {
        alert(" This is called....");
    } else {
        alert(" That is called....");
    }
    break;
}

If what you're really trying to do is make sure that date1 and date2 are legal numbers, then I'd suggest you do this:
if (typeof date1 == "number") {
    if(typeof date2 == "number" && date1 < date2) {
        alert(" This is called....");
    } else {
        alert(" That is called....");
    }
    break;
}

Or, if they're supposed to be Date objects, then you can test for that:
if (date1 instanceof Date) {
    if(date2 instanceof Date && date1 < date2) {
        alert(" This is called....");
    } else {
        alert(" That is called....");
    }
    break;
}

A: It looks correct to me. This statement evaluates to true because of the OR (||), since date1 is not null:
if(date1 != null || date1 != ""){

(it simplifies to if (true || false) { which is always true.
and the following statement evaluates to true as well because "" is not equal to null, and, presumably, date1 is less than date2:
if( (date1 != null || date2 != "") && (date1 < date2)){

A: I want to suggest you this syntax
if(  (x==5) || (x==6)  || (x==7) || (x==8) )

this is best answer for checking OR condition using JavaScript and JQuery.

A:
date1 is empty ""

Look at this condition:
date1 != null || date1 != ""

date1 is != null, the second term (date1 != "") isn't even evaluated because the first one passes - and the whole expressions evaluates to true.
Furthermore this condition:
date1 != null || date2 != ""

is also met (see above) - did you mean date2 != null this time? Nevertheless your This is called is displayed. BTW break has no sense in this context.
Finally you might consider simply:
if(date1) {

Not 1:1 equivalent, but pretty close.

A: Maybe that's a case where you should think about readability of your code. Here is my interpretation of your code:
if(!isBlank(date1){
    if(dateXIsSmallerThanDateY(date1, date2))
        alert(" This is called....");
    else
        alert(" That is called....");
}

function isBlank(date) {
    return date != null || date != "";
}

function dateXIsSmallerThanDateY(x,y) {
     return (x != null || y != "") && (x < y);
}

do you see a problem in dateXIsSmallerThanDateY? I can see one. What is that supposed to mean: x != null || y != ""? Probably it should read y != null || y != "", which in turn can be shortend to !isBlank(y).
Additionally the isBlank function does not check for beeing blank. Look what it does: It thinks that your date is blank if it is either not null or if it is not an empty string. Ok, maybe that is hard to read, so reverse this method:
function isNotBlank(date) {
    return date == null && date == "";
}

Positive comparisions are way easier to read. Do you see what is happening here? Can date be null and "" AT THE SAME TIME? No? Good. Than I guess you know what to do:
function isNotBlank(date) {
    return date != null && date != "";
}

Or in reverse:
function isBlank(date) {
    return date == null || date == "";
}


text:
Q: Pip upgrade issue && Pytest Problems && MAC OS being uncooperative Issue
1. Where my computer points to when trying to run things via python
Whenever I attempt to run a python command in my terminal, the computer defaults to attempting to use Python 3.7, even though I have Python 3.8.1 installed on my laptop. This has caused issues when I try to install and use packages on my laptop for projects. The work around up till now has been to use a a virtual env, but this no longer seems to be working in my favor.
2. The Current Issue: Attempting to use Pytest for some class work assignments, but getting: ...venv/lib/python3.8/site-packages/_pytest/_code/code.py", line 942, in <module> @attr.s(eq=False) TypeError: attrs() got an unexpected keyword argument 'eq'. After doing some looking around online to find a solution, it APPEARS to me that I simply needed to update a few out of date packages to get things running. Primarily  it seemed to be that I needed to update attrs and py.
This is where my second issue kicked off, as I tried to use the pip3 install --upgrade attrs command and pip3 install --upgrade py command and it would give:
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
pytest 6.2.2 requires py>=1.8.2, but you have py 1.8.0 which is incompatible.

or
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
pytest 6.2.2 requires attrs>=19.2.0, but you have attrs 19.1.0 which is incompatible.

Finally Ending with a nice Successfully installed attrs-20.3.0 or Successfully installed py-1.10.0
Note: This was done in and out of virtual environment
3. Yet the packages didn't update
Upon running the command pip3 list --outdated though - after running so many different commands for updating the packages - it would show that both attrs and py were still outdated (along with many others)
I have run up and down every site and thread that seemed related to the issue I have been facing, tried updating using every command I found, uninstalled and re-installed packages and pytest, and yet nothing seems to be working. Is there anyone out there who has faced a similar issue and can help point me in the right direction
Simplification
I need to run pytest, my computer tries to use the wrong python version if I'm not in a virtual environment, I'm getting errors from packages supposed to help run pytest, and those packages won't get updated no matter what I do.


text:
Q: Drawable reset when scroll in recyclerview today i need help from you!
I have a recyclerview with some data(get from json), with adapter.
I have some button(with id) with a drawable left, and onclick on the button i execute this for the clicked button :
Drawable image = ContextCompat.getDrawable(context, R.drawable.active);
image.setBounds(0, 0, 70, 70);
Button.setCompoundDrawables(image, null, null, null);

I Change the drawable with a new drawable.
My question is now.
When i click on some button in the list, and i scroll, the button return to default drawable... WHY?
Thanks every one for help!
Resolve with movies.add(new Costructor("","","","","","",""));

A: When you scroll RecyclerView then all data reset with Adapter's data.
When you click and change Drawable with R.drawable.active, It will change only in screen for temporary.
Please update Adapter's data.


text:
Q: How to use generic type methods in C# when the generic type is absract, TSymmetricAlgorithm I am trying to call this method:
public string Decrypt5<TSymmetricAlgorithm>(string input) where TSymmetricAlgorithm : SymmetricAlgorithm, new()
    {
        var pwdBytes = Encoding.UTF8.GetBytes(_seed);
        using (TSymmetricAlgorithm sa = new TSymmetricAlgorithm())
        {
            ICryptoTransform saDec = sa.CreateDecryptor(pwdBytes, pwdBytes);

            var encBytes = Convert.FromBase64String(input);

            var resultBytes = saDec.TransformFinalBlock(encBytes, 0, encBytes.Length);
            Debug.WriteLine(Encoding.UTF8.GetString(resultBytes));
            return Encoding.UTF8.GetString(resultBytes);
        }
    }

By calling Decrypt5<TSymmetricAlgorithm>("myEncryptedStringBlahblahxyz");
But I keep getting an error that I must use a non-abstract type with a public parameter-less type instead of TSymmetricAlgorithm. Is there a default TSymmetricAlgorithm subclass that I can use. What am I doing wrong? Thank you.

A: Turns out using RijndaelManaged object type did the trick. I found this out through trial and error. If anyone knows a fast way to find out all the native classes in C# that subclass a certain parent abstract class (SymmetricAlgorithm in this case), please feel free to let me know in comments for future reference. I'm new to C# :-)


text:
Q: Medir tiempo ejecución algoritmo en Swift (iOS) Necesito medir el tiempo en el que se ejecuta un algoritmo en iOS. Por ejemplo: quiero comparar la velocidad en que se obtiene el Factorial de un número hecho por recursividad y hecho sin este.
Este es mi programa:
import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var numberInput: UITextField!
    @IBOutlet weak var resultLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func factorial(sender: AnyObject) {
        let numberInt = Int(numberInput.text!)
        if numberInt != nil!{
            let number = numberInt!
            let fact = factorial2(number)
            resultLabel.text = "El factorial es: \(fact)"
        } else{
            resultLabel.text = "Por favor, introduce un número"
        }
    }

    func factorial2(number: Int) -> (Int) {
        if (number <= 1) {
            return 1
        }
        return number * factorial2(number - 1)
    }
}

Gracias!

A: Puedes hacer una marca de tiempo:
var inicio = NSDate()

Al finalizar la ejecución realizas nuevamente una marca de tiempo y mediante el metodo timeIntervalSinceDate de NSDate evaluas la diferencia.
var inicio = NSDate()
// codigo
var fin = NSDate()
fin.timeIntervalSinceDate(inicio);

Esto retornara la diferencia en segundos.


text:
Q: Error in webview "net::ERR_UNKNOWN_URL_SCHEME" in flutter I encountered a problem in the webview (flatter) that I cannot solve in any way. When I go to the checkout page, I get the following error "intent://". I was looking for a solution to this problem but could not find it. Has anyone faced this problem??

          body: WebView(
            javascriptMode: JavascriptMode.unrestricted,
            initialUrl: widget.dateFromOrder.urlForPay,
            onWebViewCreated: (WebViewController webViewController) {
              controller = webViewController;
            },
            onPageFinished: (url) {
              url;
            },
          ),


text:
Q: Remote ref changes Suppose we have a branchA. The last commit in its remote version was by me, say c1.
Then somebody did some changes (based on a patch that I provided) and pushed on the remote (or rather "updated" my commit c1).
Now I wanted to sync the remote with my local branch, and I did git fetch origin but then I saw the message
Your branch and 'origin/branchA' have diverged,
and have 1 and 1 different commits each, respectively.
  (use "git pull" to merge the remote branch into yours)
nothing to commit, working tree clean

The way that I solved it was by executing git reset --hard HEAD~1 and then I run
git fetch origin && git merge
which brought me to the desired position of being in sync with the remote.
My question is: was that a correct handling? If not, what would be the optimal?

A: Nobody can update any commit.  That means they didn't, and you won't either.
You can, however, have the illusion of updating some commit.  It's an illusion!  It did not really happen!  Always remember that, otherwise none of this makes any sense.
Git finds a commit by hash ID.  The hash ID of some commit depends on the exact content of the commit.  Once you, or whoever, has made the commit, that hash ID means that commit.  It means that now.  It means that tomorrow.  It means that next year.  It always means that commit, and no other commit, ever.
Humans, however, don't use hash IDs.  (Quick: what are the hash IDs of the last ten commits you made?  I don't know any of mine either.  I don't even remember the special empty tree hash ID.)  Humans use branch names: I made a commit on branchA.  That's what you said, more or less.
We have Git store hash IDs in branch names.  Your branchA stored the hash ID of your commit.  Then you gave your commit, with its permanently-assigned forever ID, to some other Git in charge of some other repository.  Because every Git computes hash IDs the same way, their hash ID for that commit was the same hash ID.  They put that in their repository and it had the same hash ID and they set up their name branchA to record the same big ugly hash ID.
Later, someone—not you—came along and squinted hard at that particular commit and said something like: Hah, I can do better!  They took that commit off of their branchA—the branchA that is in that other Git repository that you have your Git talk to; your Git uses the name origin/branchA for this—using some Git command, perhaps git reset --hard HEAD~1.  We don't know, or really care for that matter, exactly what Git command they used.
Having ripped that commit off that branch—it's still there in their Git repository, it's just not at the end of that branch now—they then added their "new and improved" version of that commit to their branchA.  We can draw that situation, that occurs in their Git repository, like this:
          H   <-- ???
         /
...--F--G--I   <-- branchA

The uppercase letters here stand in for the actual Git hash IDs (which we don't know, or really care about that much since we never memorize any of them).  Your commit H, which used to be the last commit on branchA, is now floating free in space, with no name that finds it.  Their new-and-improved version of your commit, which we're calling I, is now the last commit on their branchA.
This is not how Git is supposed to be used
Suppose for a moment that they had not torn your commit out by the roots, and instead, just added a commit.  (This is how Git is supposed to be used, in general.)  If they had done that, their Git repository would now have this sequence of commits in it:
...--F--G--H--I   <-- branchA

That is, they'd have a new commit I, but the parent of commit I would be your commit H.  Their name branchA would remember the hash ID of their commit I, and their commit I would remember the hash ID of your commit H.
You would then be able to run:
git fetch origin

which, in your own Git repository, would result in this:
...--F--G--H   <-- branchA
            \
             I   <-- origin/branchA

Remember, your Git uses the name origin/branchA to remember the hash ID they're remembering with their name branchA.  The things that actually matter to Git are the commits with their commit hash IDs, but Git gives us these names to help us find the hash IDs.  Each repository has its own names: their name branchA is for them to use, and your name branchA is for you to use.
Had they added a commit on like this, you could then have your Git "slide your name forward" (and down) so that you would have, in your repository:
...--F--G--H
            \
             I   <-- branchA, origin/branchA

Your Git and their Git would now both agree that the last commit in the branch named branchA is commit I (whatever its actual hash ID is).  Your Git would hang on to your own name branchA and your name origin/branchA, but both would now point to existing commit I.
If you need to fix up commit I, you simply add a new commit J to your repository:
...--F--G--H--I   <-- origin/branchA
               \
                J   <-- branchA

Note how your new commit points back to the (now-shared) existing commit I, which adds on.  You can now have your Git send new commit J back, and ask them to set their branchA name to point to commit J.
Faking it: the illusion of changing or removing commits
This is the normal way to use Git: everyone adds commits to the collection, and nobody takes any way.  Some people find this messy (because it is messy) and prefer to fake things as if the development happened much more cleanly.  There's nothing really wrong with that.  If commits H and I have no real value, and only commit J should remain, we don't need to preserve H and I for all time: we can make a new and improved commit that's like J, but that has G as its parent:
          H--I--J   <- ???
         /
...--F--G--J'  <-- branchA

(in your Git repository, with origin/branchA not shown).  Suppose we now send commit J' to the other Git, and force it to set its name branchA to point to J'.  Then they, too, will have:
          H--I--J   <-- ???
         /
...--F--G--J'  <-- branchA

in their Git repository.  Anyone who looks up commits by name only, and uses the name branchA, will see commit J', and from J', will reach back to commit G.  It is as if commits H and I and J never happened.
If you have the hash IDs of commits H, I, and J memorized, or written down on paper or a whiteboard or something, you can still find these commits for as long as they stick around in each Git repository.  How long that is depends on a number of factors.  A standard "ordinary user" Git repository keeps these commits for at least 30 days by default.  But if you don't know their hash IDs, how will you find these commits?  The name branchA won't let you find them, because the way Git works, it turns a branch name into the hash ID of the last commit on the branch, and then works backwards from there.  The commit that comes before J' is G.  It's not the hash ID of any of the now-invisible commits.
This is what you and your co-worker are doing.  I do not know why you are doing it.  If you both like it, you can keep doing it.  It's more difficult and error-prone than just adding new commits, and it's easy to completely lose a commit, if you don't know all the secret ways of finding lost commits.  I don't recommend working this way—but if you want to, now you know what you are doing.


text:
Q: Using Firefox with https and a self signed certificate With FF39 I've got an issue with our firewall. After enabling deep content inspection, on  https websites there comes an error sec_error_untrusted_issuer.
The selfsigned cert from the firewall is imported to the browser.
Using IE10 don't show this problem on the same machine.
Can this be a bug in FF, or is it configuration error?
Thanks in advance for your answers.
Regards
Catweazle30169


text:
Q: Delete a matching line from a .txt file using python I'm creating a delete function.
my customerlist.txt
[1. 'Yuvin Ng', 'Columbia College', 778]
[2, 'Ali', 'Douiglas College', 77238]
[3, 'Nancy', 'Douglas College', 7783390222]

If I want to delete Yuvin Ng and its whole line, how can I do it?
My plan was to create an empty list which will return the whole thing as "" and save it back into the .txt file.
my code
def deletecustomer(file_name,name):
    f=open(file_name,"r+")
    c=""
    for line in f:
        if name in line:
      - - - -- - --  -  -- #how can i make it read every line at position list[0] from list
     - ------ -- - -- - - -#take the selected list of the and erase by replacing the whole list with " "

I can't come up with any way to solve this problem.

A: If I understand correctly, you want to return content of the file minus the deleted line
ret = []
for line in f:
    if name != line[1]:
        ret.append(line);
return ret

A: new_file = open(nf,'w')
with open(fn) as f:
    for l in f:
        if not 'Yuvin Ng' in l:
            new_file.write(l)


text:
Q: schema / structured data I am trying to figure out the best way to use schema / structured data on two types of pages.  One is an image gallery and one is a video page.
Here is data that is present on each type of page:

*

*Title of gallery

*Description of gallery

*Name, picture and profile link of the person who submitted the gallery

*Review Text

*Name, picture and profile link of the reviewer

*Date gallery was posted

*Average rating of the gallery

*Individual images in the gallery

*Individual comments left by viewers of the gallery

Video page have almost the same information minus:
Individual images in the gallery
Instead, it has the video, video thumbnail and video duration
I'm a novice at using structured data and I'm hoping if I can get to grips with a single type of schema, I'll be able to apply it to other areas of my site like forums, blogs, etc.
Thank you.

A: This is a complex question because it involves using multiple types of structured data definitions. Either microdata or rdf are recommended by google. Start with the basics and add in other elements once you have them working. Google's testing tool and the Structured data linter will check them for you.
This generator will help, just remove the photographed by part.
The https://schema.org/ImageGallery schema exists, which will contain one or more images (images use http://schema.org/ImageObjects). Example from photoswipe with the images each including a link to a larger image:

    <meta itemprop="width" content="300">
    <meta itemprop="height" content="600">

        Long image description

        Photo: AP

Long image description

 ...

Each of the following things are properties of ImageObject, so put these in where they are in your code, e.g. for Title of gallery use the property headline as follows:
My trip to Paris

Properties of ImageGallery you can use:

*

*about A description of gallery

*aggregateRating average rating, eg "3.5"

*dateCreated Date gallery was posted

*comment use either another Thing for each (which would let you give the person's name and other details separately - using http://schema.org/Comment) or fill out one comment line per comment.  Individual comments left by viewers of the gallery

Complex ones using more Things (more structured data) -

*

*author with Name, picture and profile link -  either just add a link to their own page or social media profile, or use the http://schema.org/Person schema (name, url and image properties) as below

Joe bloggs
 &nbsp
View Profile

Review TextName, picture and profile link of the reviewer
This can be done like the author one above, but using the http://schema.org/Review schema


text:
Q: getStaticProps error with Typescript, Next js So I have this code:
export const getStaticProps: GetStaticProps<HomeProps> = async () => {
    const firstCategory = 0;
    const { data }: AxiosResponse<MenuItem[]> = await axios.post(
        process.env.NEXT_PUBLIC_DOMAIN + '/api/top-page/find',
        {
            firstCategory,
        }
    );
    return {
        props: {
            data,
            firstCategory,
        },
    };
};

interface HomeProps extends Record<string, unknown> {
    menu: MenuItem[];
    firstCategory: number;
}

But I had an error:
Type '() => Promise<{ props: { data: MenuItem[]; firstCategory: number; }; }>' is not assignable to type 'GetStaticProps<HomeProps, ParsedUrlQuery>'.
  Type 'Promise<{ props: { data: MenuItem[]; firstCategory: number; }; }>' is not assignable to type 'GetStaticPropsResult<HomeProps> | Promise<GetStaticPropsResult<HomeProps>>'.
    Type 'Promise<{ props: { data: MenuItem[]; firstCategory: number; }; }>' is not assignable to type 'Promise<GetStaticPropsResult<HomeProps>>'.
      Type '{ props: { data: MenuItem[]; firstCategory: number; }; }' is not assignable to type 'GetStaticPropsResult<HomeProps>'.
        Type '{ props: { data: MenuItem[]; firstCategory: number; }; }' is not assignable to type '{ props: HomeProps; revalidate?: number | boolean | undefined; }'.
          Types of property 'props' are incompatible.
            Property 'menu' is missing in type '{ data: MenuItem[]; firstCategory: number; }' but required in type 'HomeProps'.ts(2322)

And I really don't know what is the ParsedUrlQuery. I tried to import it(import { ParsedUrlQuery } from 'querystring';). But it doesn't help.
What should I do?

A: HomeProps contains menu: MenuItem[], but then you're trying to return data: MenuItem[]. If the type is correct, then update the code to return this:
return {
  props: {
    menu: data,
    firstCategory,
  },
};

Or if the code is correct but the type is wrong, update the type:
interface HomeProps extends Record<string, unknown> {
    data: MenuItem[];
    firstCategory: number;
}

A: replace process.env.NEXT_PUBLIC_DOMAIN with the domain itself
const { data }: AxiosResponse<MenuItem[]> = await axios.post('https://your domain/api/top-page/find',
    {
        firstCategory,
    }
);

The problem is that the response does not come with the variable process.env.NEXT_PUBLIC_DOMAIN


text:
Q: Integration Testing with GraphQL (Nexus, Apollo), Prisma, and PostgreSQL I am trying to follow this tutorial to establish integration tests on our web application. Our stack currently includes Nexus, Next, Apollo, Prisma, and PostgreSQL.
I am using ApolloClient in place of GraphQLClient from graphql-request, I opted to use ApolloClient instead, especially since our web application is server less.
This is currently what I have inside the helper.ts, and the ApolloClient does work when I execute mutations. However, after executing a mutation on ApolloClient and checking if the data persists through Prisma, I get a null value.
Did I do these adjustments correctly? I am definitely missing something if Prisma is not querying correctly. Maybe there is a disconnect here between ApolloClient and Prisma or ApolloClient and the database? Any help would be much appreciated.
All of the code is below.
helper.ts
function graphqlTestContext() {
 let serverInstance: ServerInfo | null = null;

 return {
   async before() {
     const rootUrl = getRootUrl();

     const httpLink = createHttpLink({
       uri: rootUrl + "api/graphql",
       credentials: "include",
       fetch
     });

     const client = new ApolloClient({
       // ssrMode: typeof window === "undefined",
       link: httpLink,
       cache: new InMemoryCache(),
     });

     return client;
   },
   async after() {
     serverInstance?.server.close()
   },
 }
}

function prismaTestContext() {
 const prismaBinary = join(__dirname, '../../', 'node_modules', '.bin', 'prisma');
 let schema = '';
 let databaseUrl = '';
 let prismaClient: null | PrismaClient = null;

 return {
   async before() {
     // Generate a unique schema identifier for this test context
     schema = `test_${nanoid()}`;
     // Generate the pg connection string for the test schema
     databaseUrl = `${process.env.ROOT_DB_URL}/testing?schema=${schema}`;

     // Set the required environment variable to contain the connection string
     // to our database test schema
     process.env.DATABASE_URL = databaseUrl;

     // Run the migrations to ensure our schema has the required structure
     execSync(`${prismaBinary} migrate dev`, {
       env: {
         ...process.env,
         DATABASE_URL: databaseUrl,
       },
     });

     // Construct a new Prisma Client connected to the generated Postgres schema
     prismaClient = new PrismaClient();

     return prismaClient;
   },
   async after() {
     // Drop the schema after the tests have completed
     const client = new Client({
       connectionString: databaseUrl,
     });
     await client.connect();
     await client.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`);
     await client.end();

     // Release the Prisma Client connection
     await prismaClient?.$disconnect();
   },
 }

User.int.test.ts
const ctx = createTestContext();

describe("User", () => {
  it("creates a new user with REGISTER_MUTATION", async () => {
    const userResult = await ctx.client.mutate({
      mutation: gql`
      mutation Register(
        $firstName: String!
        $lastName: String!
        $email: String!
        $password: String!
      ) {
        registerUser(
          firstName: $firstName
          lastName: $lastName
          email: $email
          password: $password
        ) {
          user {
            email
            firstName
          }
        }
      }
      `,
      variables: {
        firstName: "FirstName",
        lastName: "LastName",
        email: "test@email.com",
        password: "password"
      }
    });

    expect(userResult).toMatchInlineSnapshot(`
Object {
  "data": Object {
    "registerUser": Object {
      "__typename": "UserLoginPayload",
      "user": Object {
        "__typename": "User",
        "email": "test@email.com",
        "firstName": "FirstName",
      },
    },
  },
}
`);
  });

  it("verifies that user persists", async () => {
    const persistedData = await ctx.prisma.user.findMany();

    expect(persistedData).toMatchInlineSnapshot(`Array []`);
  });
});

A: The reason is because graphql server is instantiated with different prisma client with its own db. And the prismaTestContext has its own prisma client with different db url.


text:
Q: Image gallery swipe UI in MonoTouch I am looking to create a UI experience almost identical to swiping through images in the Camera Roll on the iPhone.  I have 5 images that I simply want to be able to swipe through.  This view will be the first view of a Tab Bar Controller that I have in place.  This is my first iPhone (iOS) app attempt so if anyone feels this question needs to be broken down into smaller chunks, please let me know.

A: Here's an example of the paging control for MonoTouch I developed some time ago: https://github.com/escoz/monotouch-controls
Take a look at the PagedViewController. That code is actually used in my app, Quicklytics.

A: Use Pagecontroller.
In this example they have add label, instead of that you add your imageView.
EDIT:
For Monotouch.

A: The Photos module of Nimbus is exactly what you are looking for.
http://docs.nimbuskit.info/NimbusPhotos.html
The MonoTouch bindings can be found here.
https://github.com/theonlylawislove/MonoTouch.Nimbus


text:
Q: object junit is not a member of package org When running

sbt compile

in project root I get error:
object junit is not a member of package org
[error] import org.junit.Test

I have fully defined build.sbt:
libraryDependencies += "com.novocode" % "junit-interface" % "0.11" % "test"
testOptions += Tests.Argument(TestFrameworks.JUnit, "-q", "-v")
libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.0" % "test
libraryDependencies += "junit" % "junit" % "4.12" % "test"

File TestSingleLinkedList.scala is also in project root and has:
import org.junit.Test

A: It seems the only valid to put junit tests in sbt is:
├── built.sbt
├── src
│   └── test
│       └── scala
│           ├── X.scala

Otherwise - sbt will provide very uninformative and confusing error about junit not being included.
I found the answer from
ScalaTest on sbt not running any tests
where someone asked different question about sbt not running the tests.
In my case the sbt - was not compiling at all.


text:
Q: How to change A-record without ISP Manager I try to configure VDS server to run 3 PHP sites ( Debian Wheezy ). I choose the bundle Nginx + php-fpm + mysql. I can't understand how to change A-record, so domain name will point to my new VDS.
The domains registered on domain registrator, not on my hosting provider, so from there I only could change DNS. I already done this, because both VDS is on the same hosting provider.
On the previous VDS I have ISP Manager, and it's quite easy to change records from there. But is it possible to change records without any panel?

A: If you don't have access to a cPanel or the like, it is very difficult to change an A record, or any other record for that matter.
If by some chance you have access to the DNS server for your domain, you could ssh to telnet to it and configure Bind (or AD DNS directly).
Best option here is to contact your hosting provider as they really should provide you with an option to manage your DNS records. At the very least, they should be able to change or add records for you, if you explain to them via email or phone.


text:
Q: How to reduce the CPU utilization when google and bing crawls on magento site? I have been facing a weird situation for a while now and need a guidance regarding this.
Problem:
Since last two days we were experiencing very slow website as compared to what it was when we launched the server . We thought it was temperory issue . But now , it has gone dead slow & a page takes atleast 3 mins to load. I also checked that the CPU uitlization somehow reached 100% and believe that the crawling might doing this.
We are using some third party to do our SEO and google dynamic remarketing and advertising of our magento website. i firmly believe that these things needs to crawl my website for indexing over the search engine.
I have seen that google and bing crawls our website regularly. You may call it google bot and bing bot and suddenly it has seen a largest spike.
Have a look at the screenshot:
https://www.dropbox.com/s/2c4u04rhtbi99j0/Screenshot%202015-11-14%2014.16.41.png?dl=0
With the largest spike being caused by bing and google at the same time and the smaller ones appear to only be google bot.
So i just had a quick question regarding this?
Do you guys think that if a bot IP is whitelisted, will we have a problem with the SEO and google advertising and dynamic remarketing, because then it will not allow that IP to crawl on our website???
Is this a spam or the bots crawling our store which is causing store response time to reduce which can impact search engine ranking and conversions on our store??
Can a large instance type of AWS will help us solving our CPU-usage problem??
Note: We are already using m3.large instance type.

A: Is this a spam or the bots crawling our store which is causing store response time to reduce which can impact search engine ranking and conversions on our store??
Bots and crawlers can cause a sustainable traffic and resource spike for a single magento server. Regardless of what's in place to speed up magento's performance like: magento's default caching, nginx or apache settings, installed extensions etc...
Can a large instance type of AWS will help us solving our CPU-usage problem?? Note: We are already using m3.large instance type.
Absolutely -- a Burstable t2.large instance can be more cost effective and could better handle traffic spikes like those caused by bots. So long as you have a semi-predictable traffic pattern. Like higher traffic during the day and lower overnight, the instance will gain credits that it can use to burst above normal CPU capacity see this for a thorough explanation:
https://aws.amazon.com/blogs/aws/low-cost-burstable-ec2-instances/
The biggest help I saw was having a properly configured robots.txt for magento  It makes sure crawlers are directed to the right places making sure your server only has to serve up only the pages it needs to.  This post is a great place to start:
https://magento.stackexchange.com/questions/14891/how-do-i-configure-robots-txt-in-magento
In Google and Bing's webmaster tool once you verify your domain you can change the crawl rate if necessary.
You can also implement a referral spam blocking with Nginx see:
https://github.com/Stevie-Ray/referrer-spam-blocker


text:
Q: column validation in sharepoint list formula Dears,
Hopefully someone can help with composing a formula for a validation of a column in a sp list.
I've have 3 columns with the choice "pending" or "completed". The validation would take place on the 3rd column as it never can be completed if one of the 2's status is still pending.
Hope someone could help

A: say you have fields f1, f2, f3  -
F3 can be completed only if f1 AND f2 are completed.
all three are choice fields with pending or completed as valid values.
got to list settings - then in 'item validation' - put the following
=OR( AND(OR([@F1]="Pending", [@F2]="Pending"), [@F3]="Pending"), AND([@F1]="Complete", [@F2]="Complete", [@F3]="Complete") )
this is directly from excel (the best way to experiment with these things).
Plreace @F1 with F1, etc.
Note - this returns false if the two are pending and f3 is not complete but that would be easy to fix.
This returns the following (f1, f2, f3
Pending Pending Pending TRUE
Pending Complete    Pending TRUE
Complete    Pending Pending TRUE
Complete    Complete    Pending FALSE


text:
Q: NullPointerException when trying to read parcel ArrayList I've got a class Message that implements Parcelable. It partly contains an ArrayList, AttachmentsData is also one of my classes. When I'm trying to pass a Messageobject from my MainActivity to another activity I get NullPointerException when trying to read this ArrayList.
AttachmentsData also implements Parcelable.
The error:

FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start
  activity
  ComponentInfo{com.example.incentive/com.example.incentive.Comments}:
  java.lang.NullPointerException 1at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1967)
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992)
  android.app.ActivityThread.access$600(ActivityThread.java:127)
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
  android.os.Handler.dispatchMessage(Handler.java:99)
  android.os.Looper.loop(Looper.java:137)
  android.app.ActivityThread.main(ActivityThread.java:4441)
  java.lang.reflect.Method.invokeNative(Native Method)
  java.lang.reflect.Method.invoke(Method.java:511)
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
  com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
  dalvik.system.NativeStart.main(Native Method) Caused by:
  java.lang.NullPointerException
  android.os.Parcel.readTypedList(Parcel.java:1638)
  com.example.incentive.messagemodel.Message.readFromParcel(Message.java:88)
  com.example.incentive.messagemodel.Message.(Message.java:40)
  com.example.incentive.messagemodel.Message$1.createFromParcel(Message.java:103)
  com.example.incentive.messagemodel.Message$1.createFromParcel(Message.java:1)
  android.os.Parcel.readParcelable(Parcel.java:1992)
  android.os.Parcel.readValue(Parcel.java:1854)
  android.os.Parcel.readMapInternal(Parcel.java:2094)
  android.os.Bundle.unparcel(Bundle.java:223)
  android.os.Bundle.getParcelable(Bundle.java:1158)
  com.example.incentive.Comments.onCreate(Comments.java:70)
  android.app.Activity.performCreate(Activity.java:4465)
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1931)

In "public void writeToParcel(Parcel dest, int flags)" when I'm writing the ArrayList:
dest.writeTypedList(attachments);

And what seems to be causing the error, in "private void readFromParcel(Parcel in)":
in.readTypedList(attachments, AttachmentsData.CREATOR);

I've tried finding different ways of solving it and have tried some versions, one being:
in.readList(attachments, AttachmentsData.class.getClassLoader());

But the app crashes.. Does anyone have a clue what I'm doing wrong? Or rather, I'm obviously writing or reading the ArrayList in a way that's not correct, but what is the right way?
Thanks,
Kristina
EDIT
I may just have solved it,
I changed the in to
attachments = in.createTypedArrayList(AttachmentsData.CREATOR);

Seems to be working! I guess it may have the same effect as David Wasser's answer?

A: You need to set the attachments variable to a list before you call readTypedList(), like this:
attachments = new ArrayList<AttachmentsData>();

A: May be you have just declared your ArrayList< AttachmentsData>() globally. You have not initialized it.
So you have to initialize that before calling readTypedList()
And Globally declared as a
ArrayList<AttachmentsData> attachments ;

Like:
attachments = new ArrayList<AttachmentsData>();


text:
Q: How to update GTK for Kmoddo Editor in Ubuntu 12.04 I am trying to install latest Komodo Editor and when I run the setup in terminal, following shows up:
"Komodo requires version 2.24 or greater. Please update gtk-2.0. While Komodo will still install correctly, it may not run."
Ubuntu Software is up to date.there're no software updates to be install. How can i fix this?


text:
Q: Creating Hash-Map Clojure I have 2 list let say list of user (list-usr) and (usr-index), i want to create hash-map from these list much like
(def list-usr [196 186 244])
(def idx-usr  [0 1 2])

how can i form (hash-map {196 0 186 1 244 2}) from 2 list ?

A: ByanJati
The function for taking two vectors and interleaving to create hash map is zipmap.
It should provide what you want, keep in mind that you will be using integers as the keys:
(zipmap list-usr idx-usr)


text:
Q: Direction of static friction between objects, rolling without slipping
On a flat table, a uniform solid cylinder (C) with mass $m$ and radius $R$ lies on top of a long board (B) that also has mass $m$. There is sufficient friction between them to prevent slipping. The coefficient of kinetic friction between the table and the board is $μ$. The initial velocity of both objects is $V$ (to the right), which means that the cylinder is initially at rest with respect to the board. Describe how the cylinder moves.

I seem to lack the angle to handle this question, but here's my original attempt. Since B and C start at the same speed, and there is a static friction between, I imagine C will start to roll counterclockwise, meaning the friction from B on C is to the right. Accordingly, C slows down B with friction to the left, against the moving direction of B. Is my understanding correct?
My second thought: B will slow down because of the kinetic friction of the table. In response, C will roll forward (clockwise), which means the static friction from B to C is to the left. Accordingly, B gives C friction pointing to the right.
I feel my second analysis is correct, but not 100% sure.
P.S. I think I finally got it. Since C is moving to the right without slipping, it must be rotating clockwise, which means friction is to the left. Accordingly, C has a friction on B, pointing to the right. Problem solved.


text:
Q: Xpages how to get CSJS confirmation in SSJS I have a repeat control that contains a button that will process documents that a user selects. My first use case is for deletions. I detect whether or not the user selects at least one document and post an error message if they do not, using view.postScript.
I want to add a confirmation dialog box, confirming that the user wants to take the action on the documents (like delete them) but cannot find a way to do it.
Ideally I want to do this all in my current SSJS.
My code is below, with a stub in for where I want to ask the user for confirmation.
Any help would be greatly appreciated.
//Did the user select a document
var hasSelected:Boolean = false;
for (var id in SelectedDocs.getSelectedIDs()) {
        hasSelected = true;
        break
}

//If false then set a warning
if (hasSelected == false)
{
x="alert('Error\\n\\nPlease select one or more documents to delete.\\n\\n');";
view.postScript(x)
return
}

//If true then ask confirmation
if (hasSelected == true)
{
}

var rspView:NotesView = database.getView("(dbAllRpPCTasks)")

for (var id in SelectedDocs.getSelectedIDs()) {

        //Get each selected doc
        var doc:NotesDocument = database.getDocumentByID(id);

        //Get child docs and delete them
        var key:String = doc.getItemValueString("ID");
        var dc:NotesDocumentCollection = rspView.getAllDocumentsByKey(key);
        if (dc.getCount() != 0)
            {dc.removeAll(true);}

        //Delete the selected doc
        doc.remove(true)
        doc.recycle();
        SelectedDocs.setSelectedState(id,false);
}

Thanks for all the suggestions. I am responding to Frank's answer. Trying to write CSJS that will determine if the user selected docs and then proceed or not.
In the on click event of my button in the CSJS I have the following:
var dtList = document.getElementsByName("#{id:dataView1.getSelectedIds()}");
confirm("What is the length?" + dtList.length);
confirm("Can I get an item?" + dtList.item(0));

It returns a length of zero and the item is undefined.

A: Unlike LotusScript, XPages code cannot wait for user input. Think of it like calling an agent to run on server and adding a UIWorkspace.prompt() in there (which will throw an error, because user interaction is not allowed).
The best recommendation would be to add the confirmation prompt as CSJS to the button the users are initially clicking, e.g.
return confirm("Are you sure?");

If they've selected documents, they'll be prompted before they continue. If they have not, it might prompt some users to select the documents anyway. It's hard to have sympathy with complaints from a user who didn't select any documents, clicked that they wanted to continue, then complains at getting another dialog.

A: Have you tried using Simple Actions for the buttons?  I use Confirm Action to verify the user didn't hit a button by accident (a common issue unfortunately). Next, I validate my form and display any messages in a custom message area (Thanks to Tommy Valand) but you can use a normal Message area.
Create an Action Group and place your SSJS expression (or EL) to execute conditionally. Display the message within the page instead of a popup.

A: A bit of theory - every action can have these combinations:

*

*CSJS

*CSJS + SSJS

*CSJS + SSJS + CSJS

*SSJS

*SSJS + CSJS

So you have to combine one or more actions to accomplish what you want to do. Techniques usable to chain calls:

*

*XSP.partialRefreshGet/Post

*view.postscript (combined with the above)

*onComplete event's property

*inline CSJS computed at render phase

*hidden button initiated by CSJS (postscript/onComplete)

*ExtLib RPC call

My advice to your use-case is to detect in event's CSJS (before execution) whether user selected any document (DOM operations). If not, use return false; to stop event execution (with proper explanation in CSJS prompt).
Edit: exact use case
Divide your use cases to two problems: condition and execution.
1. Condition
Do you REALLY need to call SSJS to get that information? It depends on what you use to select documents - what is your SelectedDocs object? In some cases, you can render (literally) number of selected docs to DOM (assuming selection fires partial/full refresh) and use it in CSSJ before SSJS is called. So rethink your needs/approach.
2. Execution
Does it really need to be SSJS + CSJS + SSJS combination? I doubt so.
Here's example for your use case based on SSJS(+CSJS). It simulates 50:50 chance to show the prompt or delete documents. You get the idea, just update the first action group to get the selected count.
<?xml version="1.0" encoding="UTF-8"?>
<xp:view
    xmlns:xp="http://www.ibm.com/xsp/core"
    xmlns:xp_1="http://www.ibm.com/xsp/coreex">
    <xp:button
        value="Label"
        id="button1">
        <xp:eventHandler
            event="onclick"
            submit="true"
            refreshMode="partial" refreshId="button1">
            <xp:this.action>
                <xp:actionGroup>
                    <xp:actionGroup>
                        <xp:executeScript
                            script="#{javascript:requestScope.docnum = @Integer( @Random() * 2 );}">
                        </xp:executeScript>
                    </xp:actionGroup>
                    <xp:actionGroup
                        condition="#{javascript:requestScope.docnum == 0;}">
                        <xp:executeScript>
                            <xp:this.script><![CDATA[#{javascript:view.postScript('alert("No documents selected...");');}]]></xp:this.script>
                        </xp:executeScript>
                    </xp:actionGroup>
                    <xp:actionGroup
                        condition="#{javascript:requestScope.docnum != 0;}">
                        <xp:executeScript
                            script="#{javascript:// delete documents}">
                        </xp:executeScript>
                    </xp:actionGroup>
                </xp:actionGroup>
            </xp:this.action>
        </xp:eventHandler>
    </xp:button>
</xp:view>


text:
Q: Division in Python unintended output Working on a problem that uses a ratio of two parameters. I noticed some weird behavior with the division operator / with values < 1e-1 that have a multiple of three. For example
0.075 / 0.025 0.15 / 0.05 gives the output of 2.9999999999999996. I can't use this resultant in my solution as I have a check to ensure the ratio is a whole number. These parameters should work and confused about why this is the output.
Whereas something like 0.9 / 0.3 gives the correct output.


text:
Q: combobox wxpython program doesn't have time to make a choice I'm writing a program so I can send SMS via email and using wxpython.  Using Combobox to select which carrier the phone number is attached to.  However, the program continues with everything else before I have a chance to select a carrier.  Is there a way to make this halt until I make a choice?  Still learning how to copy/paste in here so forgive any indentation errors, it's all correct in my code.  Thanks everyone! :)
  if password.ShowModal() == wx.ID_OK:
      pwd =password.GetValue()
      phone_number = wx.TextEntryDialog(self,"Phone Number", "Phone Number", "")
      if phone_number.ShowModal() == wx.ID_OK:
        number = phone_number.GetValue()
        self.carrier = wx.ComboBox(self, -1, pos=(10, 50), choices=carriers, style=wx.CB_READONLY)
        self.carrier.Bind(wx.EVT_COMBOBOX, self.onCombo)
        if self.carrier.ShowModal() == wx.EVT_COMBOBOX:
           message = wx.TextEntryDialog(self,"Your Message", "Your Message", "")
           if message.ShowModal() == wx.ID_OK:

              msg = message.GetValue()
              smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
              smtpserver.ehlo()
              smtpserver.starttls()
              smtpserver.ehlo
              smtpserver.login(username, pwd)
              header = 'To:' + email + '\n' + 'From: ' + username + '\n' + 'Subject:testing \n'
              print header
              msg1 = header + msg
              smtpserver.sendmail(username, email, msg1)
              smtpserver.close()

 def onCombo(self, event):

    self.selection = self.carrier.GetValue()
    print self.selection
    print self.number
    self.email = number + selection
    print email
    return self.email

A: Right away I can tell you that self.carrier is of type wx.ComboBox and does not have a ShowModal() method. And if it did it wouldn't return wx.EVT_COMBOBOX. The ShowModal() method returns the ID of the button that was clicked. wx.EVT_COMBOBOX is an event, not an ID and thus would not be returned.
Only wx.Dialogs use ShowModal(). It looks like the dialog you want is a wx.SingleChoiceDialog (You can find a tutorial here but you'll need to scroll about 7/8 of the way down. Or just hit ctrl+f and search for "singlechoice"). This will show a list and prompt users to make a single selection.

Alternatively, you could create your own custom dialog (tutorials here and here) that contain all the information you need in a single convenient dialog (instead of three separate ones).
I wrote rough draft that you can find below. Just remember that I haven't tested it so there may be errors, but it should give you an idea of what you need to do. Also, you should probably place the objects in a sizer and organize the layout the way you want it.
class MyTxtMsgDialog (wx.Dialog):
    def __init__(self, parent):
        wx.Dialog.__init__(self, parent=parent, title="My Txt Message Dialog")

        self.number = wx.TextCtrl(self)
        self.carrier = wx.ComboBox(self, -1, pos=(10, 50), choices=carriers, style=wx.CB_READONLY)
        self.message = wx.TextCtrl(self, style=wx.TC_MULTILINE) #means this TextCtrl will be multiple lines, not just one
        self.okButton = wx.Button(self, wx.ID_OK, "OK")
        #Setting the ID to wx.ID_OK is important. Any of the wx.ID_* variables work natively with ShowModal()
        #but if you created your own ID using the wx.NewId() method then you will need to manually call
        #"self.EndModal(<your ID>)" when your button is clicked.

You'd then call it using:
txtMsgDialog = MyTxtMsgDialog(self)
if txtMsgDialog.ShowModal() == wx.ID_OK: #check to see if OK was pressed
    #save the values
    self.number = txtMsgDialog.number.GetValue()
    self.carrier = txtMsgDialog.carrier.GetGetValue()
    self.message = txtMsgDialog.message.GetValue()

    txtMsgDialog.Destroy() #close the dialog

One final note: as you can see in my example, it's a good idea to call the Destroy() method on all of your dialogs when you're done with them. This will close them and free the resources. Be careful though because after you call this method any variables you didn't already save will be gone.
I see the reason you aren't calling Destroy() is because of an answer to a question you asked previously. It's mostly a style issue but I think that other commenter was wrong and you should destory your dialogs when you are done with them. It closes the dialog, frees up your resources, and it's the way all the tutorials are written.


text:
Q: SSAS : An error occurred when instantiating a metadata object Aside from installing SSAS, I have no experience using it.
Our developers are saying that it is no longer possible to create a new aggregation, whatever the cube.

The error occurs when hitting Start.
Here is what I found in the msmdsrv file
Type: 3, Category: 289, Event ID: 0xC1210012
(7/30/2014 10:55:10 AM) Message: Errors in the metadata manager.
An error occurred when instantiating a metadata object from the file,
'\\?\E:\MSAS11.DWH_AS\OLAP\Data\Cube Fraude.0.db\MY_DATABASE OLAP.56.cub.xml'.
(Source: \\?\E:\MSAS11.DWH_AS\OLAP\Log\msmdsrv.log,
Type: 3, Category: 289, Event ID: 0xC1210012)

The file E:\MSAS11.DWH_AS\OLAP\Data\Cube Fraude.0.db\MY_DATABASE OLAP.56.cub.xml has 0kb, so should this file be removed?
Any help on resolving this issue would be appreciated.

A: The solution was removing the empty files E:\MSAS11.DWH_AS\OLAP\Data\Cube Fraude.0.db\MY_DATABASE OLAP.56.cub.xml which allowed the aggregation to continue


text:
Q: Как реализовать метод добавление в избранное? Нужно сделать так, чтобы данные отображались поверх других данных. При этом изменять данные в фейк эйпиай не надо.
У меня есть метод, который находится в файле App.js:
const handleToggleBookMark = (id) => {
    setUsers(
      users.filter((user) => {
        if (user._id === id) {
          user.bookmark = !user.bookmark
          return user
        }
        return user
      })
    )
  }

return (

      <Users
        onToggleBookMark={handleToggleBookMark}
      />

  )

А так же добавление в саму таблицу? в jsx файле:

    <BookMark status={bookmark} onClick={() => onToggleBookMark(_id)} />

И уже в другом компоненте мне нужна сама реализация.
const BookMark = ({ status, ...rest }) => {

}

export default BookMark

Кто подскажет как сделать?
Иконки я взял с буцтрапа в html файл уже подключил.

A: Решение нашел с помощью знакомого.
Реализация в файле bookmark.jsx
const BookMark = ({ status, onToggleBookMark, _id }) => {
  return (
     onToggleBookMark(_id)}
      class={status ? 'bi bi-star-fill' : 'bi bi-star'}
    >
  )
}

А в файле user.jsx

    <BookMark
     status={bookmark}
     onToggleBookMark={onToggleBookMark}
     _id={_id}
    />

Было сложно описать проблему. Может кому пригодится.


text:
Q: Is it possible to use starlette framwork to interact with elasticsearch? I am facing difficulty in accessing the elasticsearch index using starlette framework
My main.py is
from urllib.request import Request
from webbrowser import get
from elasticsearch import Elasticsearch, helpers
from starlette.applications import Starlette
from starlette.routing import Route
import time
import warnings
warnings.filterwarnings("ignore")

mapping = {
    "mappings": {
        "properties": {
            "item_name": {
                "type": "keyword"
            },
            "price": {
                "type": "float"
            }
        }
    }
}

index_name = "students"
# Password for the 'elastic' user generated by Elasticsearch
ELASTIC_PASSWORD = "xxxxx"

query = {"query": {"bool": {"must": {"term": {"item_name": "apple"}}}}}

def connection():
    url = "https://localhost:9200"
    es = Elasticsearch(url,
                       ca_certs="xxx",
                       basic_auth=("elastic", ELASTIC_PASSWORD))
    return es

def create_index():
    es = connection()
    index_name = "students"
    print("hello")
    try:
        index_exists = es.indices.exists(index=index_name)
        if not index_exists:
            es.indices.create(index=index_name, body=mapping)
            print("Index created successfully!")

    except Exception as err:
        print("Elasticsearch error:", err)

def home(request: Request):
    return True

routes = [Route("/", endpoint=home, methods=[])]

app = Starlette(
    routes=routes
)

@app.on_event("startup")
def on_startup():
    create_index()

while running this i am getting 500 internal server error
My questions are:

*

*how to create the route path for elastic search

*if it possible to create then in which port i can see the output (default port of elasticsearch or starlette)

kindly share some examples

A: Yes we can access the elastic db with the normal python commands


text:
Q: Unwanted space between 2 containers in Flutter Unwanted space between 2 containers
I want to remove this extra space between a text widget and a list View (Carousel Slider ). Both of these widgets are embedded in the Container Widget . I have not added any SizedBox or Spacer between these 2 widgets . I don't know why this extra space is coming !
Here is the sample code -
 class _DashBoardState extends State<DashBoard> {
   @override
  Widget build(BuildContext context) {
  return Scaffold(
    body: Column(
     children: [
       SizedBox(
         height: 50,
       ),
        Container(
         child: Text(
           'First Text Box',
           style: TextStyle(
             fontSize: 22,
           ),
         ),
       ),
       Container(
         height: 220,
        child: ListView(
          children: <Widget>[
            CarouselSlider(
              height: 180.0,
              enlargeCenterPage: true,
              autoPlay: true,
              aspectRatio: 16 / 9,
              autoPlayCurve: Curves.fastOutSlowIn,
              enableInfiniteScroll: true,
              autoPlayAnimationDuration: Duration(milliseconds: 800),
              viewportFraction: 0.8,
              items: [
                Container(
                  margin: EdgeInsets.all(5.0),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10.0),
                    image: DecorationImage(
                      image: NetworkImage(
                          "https://images.pexels.com/photos/2116475/pexels-photo-2116475.jpeg?
     auto=compress&cs=tinysrgb&dpr=2&w=500"),
                      fit: BoxFit.cover,
                    ),
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Text(
                        'Usable Flower for Health',
                        style: TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: 18.0,
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.all(15.0),
                        child: Text(
                          'Lorem Ipsum is simply dummy text use for printing and type script',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 15.0,
                          ),
                          textAlign: TextAlign.center,
                                         ],
            ),
           ],
         ),
         )
         ] ,
        ),
       );
     }
    }

A: I think the extra space comes from the default padding of a ListView.
From the documentation here:
"By default, ListView will automatically pad the list's scrollable extremities to avoid partial obstructions indicated by MediaQuery's padding. To avoid this behavior, override with a zero padding property."
Add:
padding: EdgeInsets.all(0)

In your ListView widget to set it to 0.
I tried it this with your sample of code, it removes the extra space correctly.


text:
Q: Problems with Android MediaPlayer I am making sound application in Android and when I click on button it play sound, it's working good but I have a little problem that I can't solve.
When I click on 1 button it play sound, but when I click on second button it also play sound simultaneously and both sounds are played at the same time.
How can I prevent this? To play only 1 sound at a time.
So I want it to when clicked on 1st button, start playing, when clicked on 2nd button stop sound on 1st button and start playing sound on 2nd button and so on
     final MediaPlayer mp = MediaPlayer.create(this, R.raw.kalas);
  ImageButton sound1=(ImageButton) findViewById(R.id.sound1);
  sound1.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (mp.isPlaying()) {
            mp.pause();
            mp.seekTo(0);
        }
        else {
            mp.start();
        }
    }
});

  //HEKLER
  final MediaPlayer mp2 = MediaPlayer.create(this, R.raw.hekler);
  ImageButton sound2=(ImageButton)findViewById(R.id.sound2);
  sound2.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if(mp2.isPlaying())
        {
mp2.pause();
mp2.seekTo(0);
        }
        else {
            mp2.start();
        }
    }
});

A: Check if one MediaPlayer is playing, and if so pause that one.
final MediaPlayer mp = MediaPlayer.create(this, R.raw.kalas);
ImageButton sound1=(ImageButton) findViewById(R.id.sound1);
sound1.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    if (mp.isPlaying()) {
        mp.pause();
        mp.seekTo(0);
    }
    else {
        if(mp2.isPlaying())
        {
            mp2.pause();
        }
        mp.start();
    }
}
});

A: pause first mediaplayer in click of second button if it is playing
if(mp!=null&&mp.isPlaying())
{
  mp.Pause();
  mp2.Start();
}else
   mp2.Start();

A:         final MediaPlayer mp = MediaPlayer.create(this, R.raw.kalas);
    final MediaPlayer mp2 = MediaPlayer.create(this, R.raw.hekler);

    ImageButton sound1 = (ImageButton) findViewById(R.id.sound1);
    sound1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (mp2.isPlaying()) {
                mp2.pause();
                mp.start();
            } else {
                mp.start();
            }
        }
    });

    ImageButton sound2 = (ImageButton) findViewById(R.id.sound2);
    sound2.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (mp.isPlaying()) {
                mp.pause();
                mp.seekTo(0);
                mp2.start();
            } else {
                mp2.start();
            }
        }
    });