text:
Q: Dividing integer polynomial by an integer in point value representation Let $p(x) \in \mathbb{Z}[x]$ be represented in point-value representation. Is there a method to divide $p(x)$ by an integer, say $a$, without converting back to coefficient representation. What if $a$ does not divide every coefficient in $p(x)$, is it possible to obtain the quotient of the division?

A: At the risk of stating the obvious, if $q(x) = p(x) / a$, then for any point $r$, $q(r) = p(r) / a$.

Based on the comments, the actual question is more like

I know how to represent sufficiently small integers in terms of integers modulo $N$; what about rational numbers?

Rational reconstruction is a thing you can do — and there are variations to get more precision all the rational numbers share a common denominator.
(note that if $N$ is not relatively prime to the denominator, if you still really wanted to do this you'd have to use some sort of $p$-adic floating point notation for each offending prime)
However, you're likely much better off representing a rational polynomial in some numerator-denominator form — that is, as an integer polynomial (represented in your favorite manner) for the numerator and an integer (represented in your favorite manner) for the denominator.
In any case, you need to be careful with the available precision; exact arithmetic with rational numbers tends to consume precision rapidly unless you're careful about what calculations you're doing.

Note that there is no hope of doing approximate division in this manner; e.g. rounding coefficients to the nearest integer. Your only options in that case are:

*

*Convert back to coefficient form

*Use a representation where values are floating point complex numbers rather than modular integers.

Some mixed floating-point and modular integer representation might be possible, but if so it would be very complicated to get right.

redpajama_set_name: RedPajamaStackExchange


text:
Q: To what extent it is necessary to assume "complete regularity" on $X$ to induce this locally convex topology on $C(X)$? I found the following example in Conway's Functional Analysis Book:

Suppose $X$ is a completely regular space and let $C(X)=$ all continuous functions from $X$ into $\Bbb{C}$. If $K$ is a compact subset of $X$, define $p_K(f)=\sup \{|f(x)|: x \in K\}$. Then $\{p_K: K \text{ compact in }X \}$ is a family of seminorms that makes $C(X)$ into a LCS.

Now for any space $X$ (not necessarily completely regular), $C(X)$ is a vector space. So, once we prove that family $\{p_K: K \text{ compact in }X \}$ of seminorms separates points on $C(X)$ then it would induce a locally convex topology on $C(X)$. Now for $f\in C(X)\setminus \{0\}$ there is $x_0\in X$ so that $f(x_0)\ne 0$. But then $p_{\{x_0\}}(f)=|f(x_0)| \ne 0$. This implies that family of seminorms separates points on $C(X)$ (we didn't use "complete regularity"!) and hence define a locally convex topology on $C(X)$.
My question: Isn't the case that  the space $C(X)$ for any topological space $X$, not necessarily completely regular, satisfies the assertion of that example with the same family of seminorms? If so then is there any specific reason for restricting our attention to "completely regular" spaces $X$?? I mean, I know that "completely regular" spaces are "nicer" than general topological spaces, but can anyone mention some important property/result (related to this locally convex topology) on $C(X)$ that wouldn't hold without the "complete regularity" on $X$.
I want to realize the importance of assuming "complete regularity" condition in this case.
Thanks

A: It's not necessary but it doesn't hurt: if $(X, \tau)$ is any space at all, we can define a new topology $\tau'$ on the set $X$ so that $Y:=(X,\tau')$ has the same set of continuous functions as $(X, \tau)$ and $(X,\tau')$ is completely regular. And the identity $i:X \to Y$ is continuous and $C(Y) \to C(X)$ defined by $f \to f \circ i$ is a ring isomorphism (and a linear isomorphism too).
So for the study of spaces of the type $C(X)$ (as rings, as is also commonly done, or as linear spaces) it is enough to restrict to completely regular spaces.
Moroever, if $X$ is Tychonoff, there is a more direct connection between properties of the space $X$ and its $C(X)$. We get points from its Cech-Stone compactification $\beta X$ by considering maximal ideals in $C(X)$ as a ring etc. Most spaces that occur in analysis are Tychonoff (all separated TVS, etc) anyway and many $C(X)$ properties are studied for locally compact Hausdorff spaces (also Tychonoff), e.g. the dual via Riesz representation theorems. So the analysis theory is often nicer for such spaces.


text:
Q: Use off() inside event jquery $(function(){
    $("#selector").on("someevent", function(){
        let variable = some_value;
        $("#anotherselector").click(function(){
            //code involving variable here
            if(condition){
                $(this).off(reference to click event here);
            }
        });
    });
});

Is there any way to turn off an event from inside its handler? I'm trying to do something like the code above, and I need it to turn off ONLY that specific click event (each click event is different).

A: To reference the click event, you can simply pass it 'click' and the selector for which to disable the event:
$(function(){
    $("#selector").on("someevent", function(){
        $("#anotherselector").click(function(){
            if(condition){
                $('#anotherselector').off('click');
            }
        });
    });
});

let numHandler = 0;
$('#register').click(function () {
  let counter = 0;
  let num = ++numHandler;
  $('#clickme').click(function handler () {
    counter++;
    console.log(`Handler ${num} clicked!`);
    if (counter == 3) $('#clickme').off('click', handler);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="clickme">Click me!</button>
<button id="register">Register new handler</button>

You can read more about the off function in the jQuery documentation.


text:
Q: Deja Dup Device Name Issue My Linux desktop is 4 years old. I originally named it "foo", but 2ish years ago renamed it "bar". I turned on backups for the first time today using Deja Dup, and it used the old computer/hostname from 4 years ago, "foo", as opposed to the current name "bar". I cannot figure out where the old hostname is coming from. I've verified the name is correct in the following locations:

*

*/etc/hosts

*/etc/hostname

*hostname

*hostnamectl

*Settings > About > Device Name

*python -c 'import socket; print socket.getfqdn()'

*uname -n
I'm at a loss. I'm not sure where the old hostname would still be stored, and how Deja Dup is attempting to discern the computer name for the backup path. Any ideas?!

A: I was having a similar problem with Deja Dup using my public IPv6 address. I solved it by changing /etc/hosts to this:
127.0.0.1   localhost
127.0.1.1   computerName
::1         localhost ip6-localhost ip6-loopback

The backups are now getting named properly to computerName and no longer changing.
Related links:
Backup stops because of claim 'Computer name changed', which is it not true
Deja Dup resolves host name incorrectly, adds ISP hostname


text:
Q: Программный код ученика Задание: Найдите ошибки.
<?php
 $MV = mysql_connect("localhost", 'igolka97', '******')
if(!mysql_select_db("igor",$MV)){
    die();
}
$queryID="SELECT MAX(id) FROM `tovari` ";
$u=mysql_query($queryID,$MV);
$i=1;
while($i<=$u) {
$queryNAME="SELECT name FROM `tovari` WHERE id=$i";
$queryOPISANIE="SELECT opisanie FROM `tovari` WHERE id=$i";
$queryCENA="SELECT cena FROM `tovari` WHERE id=$i"
        $name=mysql_query($queryNAME,$MV);
        $opisanie=mysql_query($queryOPISANIE,$MV);
        $cena=mysql_query($queryCENA,$MV);
echo "
";
echo "
".$name."	".$opisanie."	".$cena."
";
$i++;
}
mysql_close($MV);
?>

A: Проблемы/ошибки/замечания:

*

*Кто сказал, что id идут по порядку?

*$u содержит ссылку на ресурс, а не число

*Ужасная организация работы с БД ( select в цикле - зачем??? зачем 3 запроса для 3х полей??? )

*Тег таблицы (
 ) создаётся в цикле

*Нет закрывающего тега для таблицы

*$name, $opisanie, $cena содержат ссылки на ресурсы, а не результаты выборки

*Передавать переменную подключения ( $MV ) есть смысл, если у вас несколько одновременных подключений к БД.

*Нет единого стиля для строк ( кавычки), sql запросов

*Нет логики в отступах, именах некоторых переменных ( $u например )

Я-бы делал, как минимум, так:
<?php
  $dbc = mysql_connect( 'localhost', 'igolka97', '******' );
  mysql_select_db( 'igor', $dbc) or die( 'no db' );

  $query = mysql_query(
    'SELECT `name`, `opisanie`, `tovari` FROM `tovari` ORDER BY `id` DESC'
  );

  echo '
';
  while( $row = mysql_fetch_array( $query ) ){
    echo ''.
      '
'.
        ''.$row['name'].'	'.
        ''.$row['opisanie'].'	'.
        ''.$row['cena'].'	'.
      '
';
  }
  echo '
';

  mysql_close( $dbc );
?>

P.S: Переписывание || Написание кода - это исключение, а не правило
A: $u = mysql_query($queryID, $MV); // вернет данные типа resource

Таким образом:
while($i<=$u) {} // отработает не так как планировалось программистом
// целочисленным значением ресурса $u будет его идентификатор а не максимальный id
// таблицы товаров

Для того чтобы исправить эту ситуацию надо было написать как-то так:
$lastIdData = mysql_fetch_assoc(mysql_query($queryID));
$u = $lastIdData['MAX(id)'];

Примерно так-же выборку с БД надо обрабатывать везде, соответственно выводить echo mysql_query('QUERY ...'); - приведет к выводу строки вида resource #id
Это с точки зрения синтаксиса... А что касается кода в целом - ужас каких мало.
Ну и, конечно-же - принцып обработки всех записей таблицы это нечто...
PS: ну зачем вы людям праздник портите таким кодом? :D
A: 3 запроса в цикле... за такое пальцы отрывать надо
Вот как должен был выглядеть данный код:
<?php
$connect = mysql_connect("localhost", 'igolka97', '******') or die("Ошибка подключения к БД");
$db = mysql_select_db("igor" , $connect)) or die("Ошибка выбора БД!");

$query = mysql_query("SELECT * FROM `tovari`");

while($result = mysql_fetch_assoc($query)){
    echo "
";
    echo "
".$result['name']."	".$result['opisanie']."	".$result['cena']."
";
}
?>


text:
Q: Ionic-Deep Linking I am using cordovaSocialSharingSource plugin to share a link and customUrlScheme to create a custom url.
cordova plugin add cordova-plugin-customurlscheme --variable URL_SCHEME=mycoolapp

mycooapp:// is not clickable.
How do I make it clickable?

A: Many places you would be putting a link will not recognize custom URL schemes as valid, clickable URLs. The best workaround is to embed that custom URL address inside a normal http:// link, and then do an automatic redirect. The new App Links (Android 6+) and Universal Links (iOS 9+) standards also help with this, because you're able to register a normal website URL to open your app instead of (or in addition to) using a custom URL scheme.
This is the approach we take at Branch.io. If you don't want to deal with building this out yourself, we have a Cordova SDK :)

A: Ionic just rolled out their own support for deep linking so make sure you check that out in the official docs. The repo is on Github.


text:
Q: Can't get sass + compass + susy installed due to version conflict I'm working with Sass, Compass and Susy on OSX / Terminal. But I can't get Susy to work together with Sass and Compass. What I've done:
sudo gem install sass
sass -v

Returns: Sass 3.3.0 (Maptastic Maple)
sudo gem install compass

This seems to also install sass-3.2.14.gem, then the compass-0.12.3.gem.
compass -v

returns: Compass 0.12.3 (Alnilam)
Everything until this point seems to work fine; I can create a Compass project and work with it. Then I try to install Susy:
sudo gem install susy --pre

or just
sudo gem install susy

This seems to install susy-2.0.0
Than I run:
compass create /Users/tom/Thomas/htdocs/susi4-test -r susy -u susy

And I get this error:
Gem::LoadError on line 2064 of /Library/Ruby/Site/1.8/rubygems/specification.rb: Unable to activate susy-2.0.0, because sass-3.2.14 conflicts with sass (~> 3.3.0)
Run with --trace to see the full backtrace

So there seems to be a problem with the compatibility of the different versions. What can I do to resolve this error?

A: The dependencies are incompatible: susy 2.0.0 depends on sass ~> 3.3.0 whereas compass 0.12.3 depends on sass = 3.2.14.
The error message says the same:

Unable to activate susy-2.0.0, because sass-3.2.14 conflicts with sass (~> 3.3.0)

You can a) downgrade susy to a version that's working with sass 3.2.14 or b) upgrade compass to a version compatible with sass 3.3.x.
A compatible version is compass 1.0.0 (or later) depending on sass < 3.5, >= 3.3.13. You can install it via
gem update compass

It might be easier to use a gem manager like Bundler. It automatically resolves dependencies and installs the appropriate versions.

A: gem install compass --pre

when you install compass lastest version will have error like:
ERROR:  While executing gem ... (Gem::UnsatisfiableDependencyError)
    Unable to resolve dependency: 'compass (= 1.0.0.alpha.19)' requires 'compass-core (~> 1.0.0.alpha.19)'

You should install compass-core first
gem install compass-core

A: The best way without a doubt is to install Susy via the Compass Susy Plugin. This will avoid conflicts with other Compass projects that require the current version.
Commands:
gem install compass
gem install compass-susy-plugin


text:
Q: Null data column returns input string was not in a correct format error I am working on an event calendar in which time values (start, end) are not always required and are often Null. I'd like the format for times that are entered to read hh:mm tt. I have the code check for null values using the following if statement:
<td>
    @If item.StartTime IsNot Nothing Then
        @item.StartTime.ToString("h:mm tt")
    Else
        @Html.DisplayFor(Function(modelItem) item.StartTime)
    End If
</td>

I still get the following error espite the if statement:
[FormatException: Input string was not in a correct format.]
Microsoft.VisualBasic.CompilerServices.Conversions.ParseDouble(String Value, NumberFormatInfo NumberFormat) +224
Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(String Value) +92

[InvalidCastException: Conversion from string "h:mm tt" to type 'Integer' is not valid.]
Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(String Value) +248
ASP._Page_Views_EaglesEvents_Index_vbhtml.Execute() in C:\Users\Iluvw\Documents\Visual Studio 2017\Projects\MVC Projects\Eagles3555\Eagles3555\Views\EaglesEvents\Index.vbhtml:49
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +105
System.Web.WebPages.StartPage.RunPage() +17
System.Web.WebPages.StartPage.ExecutePageHierarchy() +73
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +78
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +235
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +291
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +56
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +420
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +52
System.Web.Mvc.Async.<>c__DisplayClass3_6.<BeginInvokeAction>b__4() +198
System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__1(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +48
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +11
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +48
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +45
System.Web.Mvc.<>c.<BeginExecute>b__151_2(IAsyncResult asyncResult, Controller controller) +13
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +48
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +28
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +48
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.<>c__DisplayClass7_0.<InvokeEndHandler>b__0() +32
System.Web.StepInvoker.Invoke(Action executionStep) +107
System.Web.<>c__DisplayClass4_0.<Invoke>b__0() +23
Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule.OnExecuteRequestStep(HttpContextBase context, Action step) +64
System.Web.<>c__DisplayClass284_0.<OnExecuteRequestStep>b__0(Action nextStepAction) +56
System.Web.StepInvoker.Invoke(Action executionStep) +91
System.Web.CallHandlerExecutionStep.InvokeEndHandler(IAsyncResult ar) +123
System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +128

The line highlighted in red is @item.StartTime.ToString("h:mm tt"). What did I do wrong?
EDIT: My model code for the time fields:
<Display(Name:="Date")>
<DisplayFormat(DataFormatString:="{0:yyyy-MM-dd}", ApplyFormatInEditMode:=True)>
<DataType(DataType.Date)>
Public Property EventDate As DateTime
<Display(Name:="Start Time")>
<DisplayFormat(DataFormatString:="{0:hh:mm:ss}", ApplyFormatInEditMode:=True)>
<DataType(DataType.Time)>
Public Property StartTime As DateTime?

A: The reason for the exception is that you are using a Nullable DateTime which does not have a ToString() method that accepts a format string.  If you are first doing a null check then you can address this by performing the ToString() on the Value of the Nullable which will be the DateTime:
@If item.StartTime IsNot Nothing Then
        @item.StartTime.Value.ToString("h:mm tt")
// ...


text:
Q: LatinIME dictionary I want to add Czech dictionary to LatinIME (it is only missing part, UI and keyboard are already here).
I found source of LatinIME in source of android itself. There is a sample.xml file which show correct structure for creating dictionaries, but there is a point I got stuck. What do I have to do next?

A: This guy made a dutch dictionary, and it's simple to understand.
It's what you're looking for:
http://blog.cone.be/2010/08/20/creating-dutch-dictionary-for-android/
I'm trying to build one for Serbian. Good luck.

A: I have starting reading about this about a week ago.
I think you should read code from this link. He did something similiar but in Greek.
Hope it's useful.


text:
Q: Removing commented lines from InnerText i'm currently using the below code which extracts the InnerText, however, what happens is i'm stuck with a bunch of comment out lines of html <--  how do I remove these using the code below?
HtmlWeb hwObject = new HtmlWeb();
HtmlAgilityPack.HtmlDocument htmldocObject = hwObject.Load(htmlURL);

foreach (var script in htmldocObject.DocumentNode.Descendants("script").ToArray())
    script.Remove();
HtmlNode body = htmldocObject.DocumentNode.SelectSingleNode("//body");
resultingHTML = body.InnerText.ToString();

A: Just filter the nodes by comment nodes and call remove on them.
var rootNode = doc.DocumentNode;
var query = rootNode.Descendants().OfType<HtmlCommentNode>().ToList();
foreach (var comment in query)
{
    comment.Remove();
}

A: This is probably a better answer:
public static void RemoveComments(HtmlNode node)
{
    foreach (var n in node.ChildNodes.ToArray())
        RemoveComments(n);
    if (node.NodeType == HtmlNodeType.Comment)
        node.Remove();
}


text:
Q: Power Automate - Azure DevOps Integration - Work Item Getting Created In Project Backlog and Area Path Backlog I am using power automate for Azure DevOps integration. Here is what I want to achieve. I want to create a new work item when an email arrives in a project but in a specific Area Path for the team.
I am providing Area Path and Iteration Path in my flow configuration, but when the flow triggers, it creates work item both in Project Backlog and Area Path backlog, where as I only want it to create the issue in the specific Area Path.
Can someone kindly help? Thanks, Bee

A: At the moment, here is how I resolved this duplication issue.

*

*Provide all the necessary configuration in your workflow.

*Include your area-path in the workflow

*Provide a unique parent-id you want to link your work-item. Feature or an EPIC.

Seen the screenshot below.

After I provide a unique parent/child relationship, it stopped creating duplicate backlog items in my Project backlog and area path backlog.
Hope this helps everyone.
Thank you


text:
Q: Azure Service Bus Forward Dead Letter Message Forwarding I have a queue setup in Azure Service Bus with a message TTL of 5 seconds(is this too short? I noticed it will stay in the Active status for much longer than 5 seconds).
After it expires I would like it to be forwarded to another queue for processing(timeout queue). I've set the ForwardDeadLetteredMessagesTo property to the timeout queue's name, but when the message expires on the original queue it just goes into that original queues dead letter queue instead of going into the timeout queue.
Am I misunderstanding how this is supposed to be working?
My use case is I've got some consumers that are only listening on the main queue at certain times of the day. If nothing is listening on the main queue, I'd like it to expire and get pushed to the timeout queue. The timeout queue always has a consumer so it should then pick up that message and process it correctly. I can have multiple main queues, so I'd like to have all the main queues forward their expired messages to the timeout queue so I don't have to have a consumer for each main queue's dead letter queue.

A: The scenario sounds reasonable. Setting DefaultMessageTimeToLive and/or Message.TimeToLive with Dead-Letter auto-forwarding is not enough. You actually have to get those expired messages into dead-letter first. For that, you'll need to set EnableDeadLetteringOnMessageExpiration as well for the scenario to work.

I noticed it will stay in the Active status for much longer than 5 seconds).

That's normal. For expired messages to be removed from the queue, there's got to be an active listener. Therefore be careful not to overflood your queue if you have many messages that expired and not a single consumer trying to receive non-expired messages.


text:
Q: Registering two 3D point clouds I have one point cloud that describe an object (let's say, a blob of clay). I have another point cloud that describes the same object, but a portion of the object has changed (i.e, let's say that someone ripped off a small piece of clay from the blob).
I'm trying to figure out how to register the two point clouds, so that I can figure which portions of the 1st object are still intact, and which are missing.
I'm very new to registration techniques, so any ideas on how to approach this problem would be appreciated.

A: This 1990's algorithm, called iterative closest point, is a good start:

Besl, Paul J., and Neil D. McKay. "Method for registration of 3-D shapes." Robotics-DL. International Society for Optics and Photonics, 1992.

It has been cited quite frequently since then (cf. Google Scholar).

A: Since you know that point clouds are identical, calculate few invariants and align them.
For exaple, calculate centroids so you know the translation.
Then you can calculate few eigen vectors so you know rotations  etc.


text:
Q: how to translate text without using google api? is there any alternative to translate text form one language to another (like english,spanish etc.) of google api as they are paid?
i have used LOCALE but they do not translate perfectly for ex. hello in English remains hello in spanish also any hep will be very helpful. thank you in advance.
suppose i want to build something like this.
THIS IS NOT MY APP....
http://www.freeimagehosting.net/uploads/73620ad386.png

A: Usually when submit your App to Google Play you get an option to translate, I'm not sure on the working, but the other alternative is to translate all the text yourself and use separate values.xml for each lang.
EDIT:
Mygengo Translation API
Microsoft Translator APIs
Speaklite Translate API
WebServiceX Translate API


text:
Q: unable to understand how Angular maps a json to an object I was sending the following json to Angular client
{
result:"success"
additional-info:"something"
}

I was mapping the above json to an object of the following class
export class ServerResponseAPI{ //should this be an interface?
  constructor ( public result:string,
               public additionalInformation:string){
  }
}

eg. let jsonResponse:ServerResponseAPI = res.body
When I tried to access jsonResponse.additionalInformation key, I got the error that it is undefined. I suppose it was because the javascript converted the json to an object with keys result and additional-info (lets call it jsonObject and when this object was assigned to object of type ServerResponseAPI (lets call it apiObject), additional-info didn't map to additionalInformation due to different names. I corrected the code as follows and it worked
export class ServerResponseAPI{
  'additional-info':string;
  constructor ( public result:string,
               public additionalInformation:string){
    this['additional-info'] = additionalInformation;
  }
}

But I don't understand well why the initial code didn't work but the latter one did. If Angular creates an the apiObject with two properties - result and additionalInformationand notices that jsonObject has not got additionalInformation property, it keeps additionalInformation undefined. Then why doesn't this['additional-info']=additionalInformation also make additional-info undefined?

A: As far as I know about Angular and Typescript is that Angular parses your JSON to an object and Typescript does the validation.
The thing is that when you're working classes you need to create new instances with the new keyword.
The Interfaces in Typescript are useful for types validation in coding time (they don't add additional code to your compiled code), and they are ideal for this scenario, which is to provide a way of "defining" the structure of the object which will be returned from your API.
This is how the Interface is used:
let jsonResponse:ServerResponseAPI = res.body
This is how the Class is used:
let jsonResponse = new ServerResponseAPI(res.body.result, res.body['additional-info'])
Using the interface allows you to map the types directly from the object.
Hope it helps


text:
Q: What does refering to someone as a "garden shed" mean? http://youtu.be/a9GgU3hzGGw?t=1m54s
In the following video, a talk host watches an acting performance, and refers to the actor as a "garden shed".
I've never heard that expression before.  I am also not British.
I imagine it means someone who can do anything, though I can't find a source for it anywhere on the Internet.  Am I correct in this assumption?  Is this a commonly used expression in the United Kingdom?

A: It's a reference to the cut, which featured the Doctor (played by John Hurt) in what could loosely be described as a garden shed.
No meaning beyond that, I'm afraid!

A: According to one site 'garden shed' is rhyming slang for a 'locked thread', which would seem to fit with the way it is used in the video. Was the speaker complaining sarcastically that they had cut the trailer at the interesting point?


text:
Q: Разделить ссылку от запятой пробелом Есть сайт на WordPress. Есть кастомная форма комментариев. При написании комментария, если пользователь сразу после ссылки поставит любой знак препинания (, или . или ! и тд.), то при публикации знак препинания станет частью ссылки, и естественно ссылка будет не рабочей. Можно ли как-то устранить проблему? Приведу часть кода:

<?php
    if (!empty($comment_html)) {
        $m = '|([\w\d]*)\s?(https?://([\d\w\.-]+\.[\w\.]{2,6})[^\s\]\[\<\>]*/?)|i';
        $r = '<noindex>$0</noindex>';

        $comment_html = preg_replace($m, $r, $comment_html);
    }
    if (empty($comment_html)) {
        $m = '|([\w\d]*)\s?(https?://([\d\w\.-]+\.[\w\.]{2,6})[^\s\]\[\<\>]*/?)|i';
        $r = '<noindex>$0</noindex>';

        $comment_html = preg_replace($m, $r, $comment->comment_content);
    }
    if ($comment_html == "Комментарий удален.") {
        echo '' . $comment_html . '';
    } else {
        echo $comment_html;

    }
?>

A: Подправьте регулярное выражение. Замените строку
$m = '|([\w\d]*)\s?(https?://([\d\w\.-]+\.[\w\.]{2,6})[^\s\]\[\<\>]*/?)|i';

на
$m = '|(https?://([\d\w\.-]+\.[\w\.]{2,6})[^\s\W\D]*/?)|i';


text:
Q: How to correct inject map of bean in spring context I am using component-scan in my spring application. So in spring context I created map:
<util:map id="mapByName" map-class="java.util.concurrent.ConcurrentHashMap">
    <entry key="Name1" value-ref="MyCustomClassName1" />
</util:map>

and in my class annotated by @Service I want to inject this property:
@Inject
private Map<String, MyCustomClassName1> mapByName;

this is still working. Problem just in name of key. When I print this property I got [MyCustomClassName1=org.my.package.service.MyCustomClassName1@cb52f2]
so as you can see name of key is changed from Name1->MyCustomClassName1 (Name of this class). So my question is how to define custom key name in map property ?

A: If I were you, I would use Java Config to create a Map, since Java is the best way to create a Java object :) :).
Your configuration code would look like this:
@Bean(name = "mapBean")
public Map<String, MyCustomClassName1> mapBean() {
    Map<String, MyCustomClassName1> map = new HashMap<>();
    //populate the map here - you will need to @Autowire the references if they are not defined in this configuration
    return map;
}

And then I would inject it into wherever it's needed like so:
@Resource(name="mapBean")
private Map<String, MyCustomClassName1> map;

Note the use of @Resource instead of @Autowired or @Inject

A: Quote from the documentation:

An autowired Maps values will consist of all bean instances that match the expected type, and the Maps keys will contain the corresponding bean names.

I think that just changing @Inject with @Resource will do it.


text:
Q: Extension .json for Http Requests I'm trying to consume and use a third party REST Json based API.
I have done SOAP consumption and wsdl but never REST based on json or XML for that matter.
Anyway I'm trying to understand in some documentation what this .json extension is in examples of the api request urls they are showing me.  For example:
http://someuri/api/version/customer.json
what is that?  I'm going to be sending HttpWebRequest requests via .NET but then I also wonder what this .json extension has to do with me sending requests over.
Also should I be sending request params in the Header or via querystring when trying to consume a REST json based 3rd party API from .NET?

A: We cannot answer your questions without being able to see the documentation. Your questions about Headers/Query string should be in the documentation of the service.
The extension .json is specific to the service. It may be using that to set the accept header on your behalf, but that's just a guess.


text:
Q: Specific reasons for still using Subversion? I want to choose a version control system for my company. So far I know I have Git, Subversion and Mercurial.
These days I see that Git is the most used, so I'm left wondering: would there be any specific reason to still use Subversion, or should I go directly to Git?

A: SVN is not dead at all.  It's is still in extremely wide use, and it's not going anywhere anytime soon.  SVN is much simpler to use than distributed version control, especially if you're not actually running a distributed project that needs distributed version control.
If you only have one central repository (which is all your company will need if they're still small enough to get by without source control so far), it's much simpler to use SVN to interact with it.  For example, with SVN you can pull changes from the repository, or commit your local changes to it, with a single operation, whereas HG and Git require two or three steps to do the equivalent work.
And with the recent revisions, SVN has fixed a lot of the performance issues that made people prefer HG and Git.  It's significantly faster now than it was a couple years ago, and at this point, there's really no good reason to look at HG or Git for your project unless you actually need the advanced features of distributed version control.

A: "If you have a task that can be done on six hours, it is better to write a tool that does it in 20 minutes, even when creating the tool takes six hours?"
Distributed Version control is a different beast to tackle. It requires substantial learning for each developer. If you have the buffer to accommodate the learning process for each developer, you should move to a good distributed version control system. Once the learning phase is over Distributed Version Control is much better than Centralized Version Control.
Distributed Version Control seems to be an eventuality. It is here to stay for a very long time, it is better that we adapt to it sooner than later. I remember the same discussion when SVN was new and people were used to CVS, lots of arguments were given for not using SVN, but eventually SVN became the most popular version control system.
If the company is well established with a lot of source code in the existing version control system, moving to a new system is a big task, but if the company is small or starting up, moving to a new version control is very easy. But if you stick to an older version control (in a new setup) you will hit the bottleneck somewhere in future where you will have to eventually plan a version control migration anyway.
I have seen a lot of pro SVN comments, but all of them tend to be of the nature "SVN is not bad" rather than "SVN is better". So I would strongly recommend that you choose a Distributed Version Control (such as Git) for your project.
EDIT
Advantages of GIT over SVN

*

*No dedicated server required Actually, both can be used w/o a server.

*Can continue development even without a network connection.

*Branch management is much easier.

*Better support from CI tools such as Bamboo

Someone mentioned tooling (for visual studio) as a reason to stick to SVN. http://gitscc.codeplex.com/ provides GIT support for Visual Studio.

A: With SVN you can easily checkout parts of a repository down to the folder level, whereas with git, you get the whole repository, including all the history.
Depending on the situation this may have some advantages for SVN
(this also has some big drawbacks such as the hidden ".svn" garbage all the way up your folder tree).

A: Client tooling hasn't been mentioned yet. You can certainly do everything with a command line script but having GUI integration can be a real productivity boost.
We work mostly with Visual Studio; integration into the IDE is definitely better with SVN than with Git right now. This may change in the future, but I'd certainly weigh this into your decision just as much as the version control functions.
Just like everything else, a version control system isn't a goal in itself, just a tool to get you where you're going. Pick the one that's going to get you there fastest based on your situation.

A: I'm a Git fan. Recently I had to admit that one of the downsides of Git is that it identifies versions with hashes as opposite to svn's release numbers. The release number can be easier passed on by phone or something like that.
And that's the only pro I can imagine. If you really want to rely on that feature you can have it in a distributed and/or centralized VCS Bazaar. In Git there are tags that can serve the purpose.
Anyway I just couldn't imagine developing without quick branch switching, and stashing. These two features alone beat SVN, where as far I remember the same task required creating and checking out a whole tree into separate directories to achieve the same goal.
Those so called "advanced features of distributed version control" come with the time, and you don't have to learn them at the very beginning. Don't be scared of them. They are here to help you, not to get in the way. And there's no problem to set up a central repository for a DVCS.

A:
would there be any specific reason to use Subversion those days

Apart from tooling support in IDEs (which I don't use) – not really, no. Of course SVN may be more familiar but that's about the only reason, and I've found both Hg and Git very easy (and very fast) to learn.
Yes, there are all those complex guides out there which describe how Git is trivial once you understand that branches are just homeomorphic endofunctors mapping submanifolds of a Hilbert space.1
I don't understand that. But you know what? It doesn't matter. You don't need to know any of that stuff to use Git.
For the most part, Git and Hg are easy to use and they have definitive advantages over SVN. The elephant in the room is of course branching: branches just work in Git and Hg. By contrast, in SVN they are painful at best and broken at worst (merging multiple heads).
Of course you can still use SVN. You can also still use Windows XP. However, the majority of users who have tried both agree that one of the alternatives is vastly superior.

1 Yes I get that this is a joke. I think.


text:
Q: Is there a Netbeans plugin or issue tracker that provides connectivity to Fogbugz? I would like to be able to create FogBugz cases directly straight from the editor in NetBeans.  Specifically, I would like to be able to look at a JUnit run in the IDE, examine the failures and create cases directly using the information that is right in front of me (rather than cutting and pasting into a web browser, etc).
I see that NetBeans 6.5.1 ships with Bugzilla available by default and JIRA connectivity in some sort of beta form.  Is there an equivalent FogBugz issue tracker?
PS: I am aware of the new plugin architecture of FogBugz 7.  However, I have a realistic appreciation of the time that I would be able to commit to creating my own plugin for either NetBeans and / or FogBugz and I suspect that I would be able to make just enough of a partial solution to make my life worse rather than better.

A: It appears you may need to write one yourself, as they have plugins for Eclipse and Visual Studio, but not Netbeans.
http://www.fogcreek.com/fogbugz/blog/post/Eclipse-Plugin-For-FogBugz.aspx

A: I am not aware of such plugin. You're right that it is not trivial effort to write full-featured connector, but getting basic one is not that hard ... especially if you're already familiar with NetBeans plugin architecture. If you decide to go for it, take a look at FogBugz API instead of new FogBugz plugins. FogBugz API is used to talk to remote FogBugz repositories.


text:
Q: constexpr constructor must initialize direct base class (Visual Studio) I have someone else's code that I shouldn't alter:
struct Parent { int thing1, thing2; };

and want to make my inherited class usable with constexpr:
struct Child: public Parent
{
    constexpr Child() {}                                          //error
    constexpr Child(int t1, int t2) { thing1 = t1; thing2 = t2; } //error
    constexpr Child(const Child& c) = default;
};

When I compile this in Visual Studio (with /std:c++-latest), the marked ctors give an error:
E2433: constexpr constructor must initialized direct base class

It still compiles (despite reporting this as error, not warning). It also compiles fine in g++ 10 (using -std=c++2a).
(Also, I can make the error go away by explicitly calling the Parent's default ctor -- but I don't think that should be a requirement?
    constexpr Child() : Parent () {}
    constexpr Child(int t1, int t2) : Parent () { thing1 = t1; thing2 = t2; }

)
So, for the C++20 standard, who's right: VS, or g++?  Is there an approved way to give my class constexpr ctors, while inheriting from (or incorporating as a member variable) a base class that does not have constexpr ctors?

A: Until c++20, your Parent class is not constexpr constructible, since there are no default initializers for the data members. I believe it's a gcc bug that allows it to compile.
You can make Parent constexpr constructible like this:
struct Parent { int thing1{}, thing2{}; };  // provide default values for members

Note that you can require Parent's constructor to be constexpr, like this:
struct Parent {
  int thing1, thing2;
  constexpr Parent() = default;
};

and now gcc will fail to compile this as well.
From c++20, this restriction has been removed, by permitting default initialization for trivially default constructible types (such as ints) in constexpr contexts. See this paper for the rationale.
So your code should compile in c++20, but as with many such features, some compilers may not have implemented it yet.


text:
Q: Error 1004 en una macro He creado la siguiente macro:
Sub Extraer1()
'Definir origen y destino que utilizaremos
Dim OrigenHoja As Excel.Worksheet, _
    DestinoHoja As Excel.Worksheet, _
    OrigenCelda As Excel.Range, _
    DestinoCelda As Excel.Range

'Definir las hojas origen y destino
   Set OrigenHoja = Worksheets("Origen")
   Set DestinoHoja = Worksheets("Destino")

'Definir las celdas origen y destino
Const celdaOrg = "A1"
Const celdaDst = "A1"

'Indicar los rangos origen y destino
Set OrigenCelda = OrigenHoja.Range(celdaOrg)
Set DestinoCelda = DestinoHoja.Range(celdaDst)

'Seleccionar los rangos
ActiveSheet.Unprotect
OrigenCelda.Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy

'Pegar en destino
DestinoCelda.PasteSpecial xlPasteValues
Application.CutCopyMode = False

End Sub

Cuando ejecuto me muestra el error '1004' en tiempo de ejecución. Error en el método Select de la clase Range.
Alquien me puede decir donde se encuentra el error.
Gracias.

A: Debes activar antes la hoja en la que está el Rango OrigenCelda.
Justo antes de ActiveSheet.Unprotect escribe OrigenHoja.Activate


text:
Q: Want to put three programs ino one, and ask the user which he wants to proceed Here's the three programs I wrote, into one. But it doesn't work...Could you please help me? I've been looking all over the internet for help, but nothing! The thing is, I can't use anything advanced- so just using if and while... Why isn't this working? here's the program:
   import java.util.Scanner;

public class Threeinon {

public static void Adding (int A, int B)
{
    int C, D;

    if (A>0 && B>0)
       {
       C=A;
       D=B;
       while (D!=0) {
            D=D-1;
            C=C+1 ;
       }
       System.out.println("The summation is: " + C);
       }

       if (A>0 && B<0)
       {
           C=A;
           D=B;

           while (D!=0)
           {
               C=C-1;
               D=D+1;
           }
           System.out.println("The summation is: " + C);
       }

       if (A<0 && B>0)
       {
           C=A;
           D=B;

           while (D!=0) {
               C=C+1;
               D=D-1;

           }
           System.out.println("The summation is: " + C);
       }

       if (A<0 && B<0)
       {
           C=A;
           D=B;

           while (D !=0)
           {
               C=C-1;
               D=D+1;

           }
           System.out.println("The summation is: " + C);
       }
}

public static void Multiplying (int A, int B)
{
    int C, D;

     if (A>0 && B>0 )
       {
           C=0;
           D=A;
           while (D!=0){
                D=D-1 ;
                C=B+C;
                System.out.println("The result is:" +C);
                System.out.println("The second result is true.");
           }
       }
       if (A==0)
       {
           System.out.println("The result is 0");
       }
       {
       if (B==0)
       {
           System.out.println("The result is 0");
       }

       if (A<0 )
       {
           C=0;
           D=B;
           while (D != 0) {
               C=C+A;
               D=D-1;
           }
           System.out.println("the result is:"+C);
       }
       if (B<0 )
       {
           C=0;
           D=A;
           while (D != 0){
               C=C+B;
               D=D-1;
           }
           System.out.println("the result is:"+C);
       }

       if ( A<0 && B<0 )
       {
           C=0;
           D=B;
           while (D!=0){
               C=A+C;
               D=D+1;
               System.out.println("the result is:" +C);
               System.out.println("Only the first result is correct which is positive");
           }
       }

       }
}

public static void Dividing (int A, int B)
{
    int C, D;
    if (A>0 && B>0){
           C=0;
           D=A;
           while (D>=B){
                D=D-B ;
                C=C+1;
           }
           System.out.println("the result is:" + C);

           }

           if (A<0 && B>0)
           {
               C=0;
               D=-A;

               while (D>=B)
               {
                   D=D-B;
                   C=C-1;

               }
               System.out.println("the result is:" +C);
           }

           if (A>0 && B<0 )
           {
               C=0;
               D=A;

               while (D !=0 )
               {
                   C=C-1;
                   D=D+B;

               }
               System.out.println("the result is:" +C);
           }

           if (A<0 && B<0 )
           {
               C=0;
               D=-A;

               while (D != 0)
               {
                   D=D+B;
                   C=C+1;
               }
               System.out.println("the result is:" +C);
           }

}

public static void main(String[] args){

    int A=0, B=0;
    int n;

    Scanner scan = new Scanner(System.in);
    System.out.println(" Enter 1 for multiplying");
    System.out.println(" Enter 2 for adding");
    System.out.println(" Enter 3 for dividing");
    n= scan.nextInt();

    if ( n==1 )
    {
        Multiplying (A, B) ;
    }
    else {
        if ( n==2 )
    {
        Adding (A, B);
    }
        else {
            if ( n==3 )
    {
        Dividing (A, B);
    }
        }

    }

       System.out.println("Ignore the two 0 you see, proceed");
       System.out.println("Enter first number:");
       A = scan.nextInt();
       System.out.println("Enter second number:");
       B = scan.nextInt();

      Adding (A, B);
      Multiplying (A,B);
          Dividing (A, B);
    }

}

A: Why do you call your methods twice?
Maybe you try it this way:
public static void main(String[] args){

int A=0, B=0;
int n;

Scanner scan = new Scanner(System.in);
System.out.println(" Enter 1 for multiplying");
System.out.println(" Enter 2 for adding");
System.out.println(" Enter 3 for dividing");
n= scan.nextInt();
System.out.println("Enter first number:");
A = scan.nextInt();
System.out.println("Enter second number:");
B = scan.nextInt();

if ( n==1 )
{
    Multiplying (A, B) ;
}
else {
    if ( n==2 )
    {
        Adding (A, B);
    }
    else {
        if ( n==3 )
        {
            Dividing (A, B);
        }
    }

}
}

By the way, don't you think it's much more easy if you shorten your methods a little bit? Or is this your purpose?
For Example:
public static void Adding (int A, int B)
{
       System.out.println("The summation is: " + (A + B));
}
...

You can use the mathematical operators just as you are used to use them. +, -, *, /.
But pay attention to the division /. The result doesn't have to be an int, so better use double for your result.

A: You don't ask the user to input A and B before you call Multiplying, Adding or Dividing. With the values initialized at zero, you won't get very interesting results this way.
As a stylistic side note, you should rename the methods to begin with a lowercase letter to better follow the usual convention.

A: You are calling your choice of methods Adding, Multiplying and Dividing before A and B have been set to anything.  I suggest asking for A and B before attempting to perform an operation on them.

A: int A=0, B=0;
    int n;

    Scanner scan = new Scanner(System.in);
    System.out.println(" Enter 1 for multiplying");
    System.out.println(" Enter 2 for adding");
    System.out.println(" Enter 3 for dividing");
    n= scan.nextInt();
 System.out.println("Enter first number:");
       A = scan.nextInt();
       System.out.println("Enter second number:");
       B = scan.nextInt();
    switch(n){
      case 1:Multiplying(A,B);
      break;
      case 2:Adding(A,B);
      break;
      case 3:Dividing(A,B);
      break;
    }


text:
Q: How to install NetSurf web browser in ubuntu 14.04 I am using 64 bit Ubuntu 14.04 OS.

I want to install NetSurf web browser in
  Ubuntu 14.04

This browser supports Linux(mentioned in official site of NetSurf )
The only providing .deb binary for Debian

I downloaded .deb ,from this download link,provided at official site of net surf browser.

I tried to install downloaded deb file using
sudo dpkg -i pakagename  method
But installation failed...

What is the easy and correct way to install
  NetSurf browser
  in Ubuntu 14.04 (64 bit)

A: Go and download the source (preferably the top, most recent link on that page), and compile it yourself by extracting the archive to ~/netsurf then:
cd ~/netsurf
sudo make
sudo make install

or simply , download  *.deb file(binary file) from  official website of NetSurf

and install it, by using software centre or by Gdebi package installer or
cd into directory which consists downloaded binary file and then, install it using below command
sudo dpkg -i package_name.deb

here, package_name is downloaded package name.

if you encounter any problems dependency problems  ,
run,
sudo apt-get update && sudo apt-get -f install

for me,
the above command solved problem occurred during installation process.

A: NetSurf web browser is available in the Ubuntu repository. Therefore, the easiest way for users is to install from the Ubuntu repository (universe).
sudo apt-get install netsurf-gtk

In Ubuntu 14.04, NetSurf version is 2.9-2, which is slightly newer than the Debian Squeeze binary version 2.7 provided by the official website.
Unless you prefer the latest version, which requires to download and compile the source code from the official website, installing from Ubuntu repository is always easier.


text:
Q: Renaming copy of multiple files in C# in a uniform format I'm working with C# in ASP.net framework. I need to make a copy of files and save them.
File.Copy("fileFirst.txt", "fileSecond.txt"); seems to work for that.

However I have multiple files and I need to do this for every single file. Instead of having to type the names for every single file how can I simply have a copy of the file such that it has the original filename with a -new appended on it's back.
Original file:      fileFirst.txt
Copy of the file:   fileFirst-new.txt

NOTE: It has to to do this for as many files as I have and not just one.

A: This code lists all the files in a directory and copies them to the same folder but with a different name.
    private static void RenameDirectoryFiles()
    {
        string pathfile = @"M:\_downloads\";

        string[] filePaths = Directory.GetFiles(pathfile);

        foreach (string filePath in filePaths)
        {
            try
            {
                string dire = Path.GetDirectoryName(filePath);
                string name = Path.GetFileNameWithoutExtension(filePath);
                string exte = Path.GetExtension(filePath);

                File.Copy($"{filePath}", $"{pathfile}\\{name}-New{exte}");
            }
            catch (Exception e)
            {
                Console.WriteLine("Error File Copy");
            }
        }
    }


text:
Q: How to order the items of a list and remove duplicates based on a property? I've this class:
public class User
{
    public long Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Username { get; set; }

    public int Contributions { get; set; }
}

My List<User> can contain multiple items with same Id but different Contributions value.
I want to have distinct values based on Id, but with the highest Contributions value for that Id. How can I do that? thanks.
I tried this but it's only a part of what I want:
list.OrderByDescending(x => x.Contributions);

A: list.GroupBy(u => u.Id) // Distinct
    .Select(g => g.OrderByDescending(u => u.Contributions).First()); // Highest contributions


text:
Q: Python get coordinates of the vector path from .svg file So for a school project Iam supposed to program a so called "V-Plotter", my team built it and I managed to program all calculations and so on, basicly I can make it move to a certain x/y coordinate and lift/raise the pen. I converted an Image with potrace to an .svg file and as far as I understood it, the file should contain a certain path which the plotter would follow.
My idea here would be to read the vector path and save it in multiple vectors via an Array, then simply make an loop going through those arrays and thus drawing the vectors.
Or simply said:
Loop variable i=0
Loop:

*

*pen up

*move to (x1/y1) of Array i

*pen down

*move to (x2/y2) of Array i

*increase i by 1
(this is not program code, but easy to program)

But i can not find any way to read the vector coordinates, shouldn't it be easy to get the coordinates where a vector starts (x1/y1) and where it stops (x2/y2)?

A: SVGs are very simple formats, you could simply open it with a notepad and see the xml code for it. The xml tag is the type of curve you need to plot, and it can have some metadata inside it. You can directly use python to read this XML if you want.
But SVGs aren't as easy as you're assuming it to be - it isn't simply a bunch of vectors (not the classical vectors anyway)
In SVG, you basically define shapes - like Line, Arc, CubicBezier, etc. You'd need to implement each of these into your program, because something that shows an SVG image is expected to understand these already.

Now, as your question asked about the packages, I'm adding packages that are useful for SVG handling in python:
svg.path - https://pypi.python.org/pypi/svg.path - is a great library to create paths and also to get the XML info and convert into usable classes like Line, Arc etc. But I dont think they have support to read complete svg files.
pysvg - https://pypi.python.org/pypi/pysvg/0.2.2 - is another utilitiy i used a while back which can import an svg and make classes like PolyLine circle ellipse etc.


text:
Q: How to explicitly apply percent escapes to a URL in nginx? I have the following configuration:
location ~ ^/((index\.php|robots\.txt|admin|static|uploads|api)(/.*)?)$ {
    proxy_set_header Host $http_host;
    proxy_pass http://localhost:1337/$1?$args;
}

I want to apply percent escaping to $1, so e.g. /admin/foo%20bar would forward as /admin/foo%20bar and not as /admin/foo bar. How can I do this?

A: Try to use nginx http_set_misc_module#set_unescape_uri
eg:
location ~ ^/((index\.php|robots\.txt|admin|static|uploads|api)(/.*)?)$ {
    set_unescape_uri $1;

    proxy_set_header Host $http_host;
    proxy_pass http://localhost:1337/$1?$args;
}

A: You can use set directive which keeps encoding intact or you can say re-encodes decoded uri.
location ~ ^/((index\.php|robots\.txt|admin|static|uploads|api)(/.*)?)$ {
    set $query $1;
    proxy_set_header Host $http_host;
    proxy_pass http://localhost:1337/$query?$args;
}


text:
Q: Stack overflow in grails caused by obscure def recursion this is a pretty strange issue.
I have a many-to-many relationship between two classes, Subscription & Scenario. Thing is I'm trying to delete the relation between them when either is deleted using "beforeDelete" in each of these classes.
ScenarioSubscription is the class representing the junction table.
This is what my beforeDelete def looks like in Scenario.
 def beforeDelete = {
    //Delete rows in junction table
    def example = new ScenarioSubscription(scenarioId:id)
    def scenSub = ScenarioSubscription.findAll(example)
    scenSub*.delete(flush:true)
}

It works in the Subscription class but not in Scenario. Instead, when calling *.delete() the "beforeDelete" def is called recursively. I checked the variable when debugging and scenSub is a list of ScenarioSubscription. Crazy?!
Any idea of what is going on is very much appreciated.

A: So, it sounds like your ScenarioSubscription domain object has two properties, Scenario and Subscription.  When you try to delete the link domain object, it tries to cascade the delete down to the Scenario which fires the beforeDelete closure (and repeats till crash)
I think you'll need to define a custom cascade mapping for your ScenarioSubscription properties, or, couldn't you define a custom mapping for this Scenario domain object, and get rid of your beforeDelete entirely?
ie:
static mapping = {
  subscriptions cascade:"all-delete-orphan"
}

This question might be of help as well


text:
Q: How to allow all third party in chrome using javascript or python? Is it possible to do following operation using javascript or python?
Enter this in url box. chrome://settings/cookies
In cookies and other site data -> General settings -> Allow all cookies

A: Ypu can do something like this. Just need to find out exact xapth element.
from selenium import webdriver
import time
driver = webdriver.Chrome(executable_path='C:\\temp\\chromedriver.exe')
driver.get('chrome://settings/cookies')
time.sleep(3)
driver.find_element_by_xpath("<xpath locator>").click()


text:
Q: jquery - click functionality - small problem I have a short question, please :)
I have a script where i make 5 images visible.
The user controls the order in which he clicks the images.
So what I'm trying to accomplish:
If the last image is clicked, there should be a div displayed.
How does jQuery knows if the 5th image is clicked?
The rest (fade-in the div) i figured out already.
Could you please be so kind and give me a little hint on that? :)

A: You should be able to use $('.myImages').is(":visible") to test all of the images.
Here's the jquery docs for .is().
It might look something like this (not exactly, I think):
var allVisible = true;

$.each($('.myImages'), function(index, value){
    if( $(value).is(":visible") && allVisible )
    {
        //that's nifty, move on
        continue;
    }
    else
    {
        allVisible = false;
    }
});

if( allVisible )
{
    $('#myDiv').show();
}

A: If you make your click handler add a class when an image is clicked.
$(this).addClass("hasBeenClicked");

then you can then check the number of clicked images thus
if ($("img.hasBeenClicked").length === 5) { alert("All 5 have been clicked"); }

To break it down,
img.hasBeenClicked

is CSS selector syntax for "all the <IMG> elements that have the hasBeenClicked class".  You can test this out by adding the CSS <style>img.hasBeenClicked { border: 4px solid red }</style> to your HTML and seeing what gets a fat red border.
$("img.hasBeenClicked")

then just invokes the jQuery query operator, $, to fetch an array of the <IMG> elements that have that class.
$("img.hasBeenClicked").length

uses the array .length property to get the number of <IMG> elements with that class.
$(this).addClass("hasBeenClicked");

is just book-keeping that puts the hasBeenClicked class on images when they're clicked.  It won't overcount, since no matter how many times a single image is clicked, it only counts once in the array of nodes returned by $.

A: Say one of your divs is declared like this:
<div id="div5">
<!-- img tag -->
</div>

Then you can say $('#div5').click(function(){ $('#div5').show(); });


text:
Q: Ubuntu 16.04 "Cheese" HD Video Recording Choppy When I record videos using "Cheese" the picture keeps freezing while I am recording a video for a fraction of a second.  It has the effect of making my lips and audio seem out of sync.  (Example: frame 22 being displayed instead of different pictures on frames 23 through 30, yet the audio is consistent with what was recorded)
I had this issue before.  Updating the video editing software "Kdenlive runtime environment" resolved this.  Then it started again about 6 weeks ago immediately after I ran updates.  Running updates during the past 6 weeks hasn't resolved it.
I don't want to paste extraneous information here.  If you will tell me what details I need to provide in order to find a solution I will gladly do so.
I am unsure of how to proceed.


text:
Q: I have performance issues with the code I'm using to detect collision between items I managed to make this work and do what I needed after a while but now my problem is performance. As you can see I need it for 14+ items. I tested at first for 5 items and it worked ok but after I added more the performance dropped a lot. As for the collision detection class, I assume you know what it does and how it works(that I managed to make it work since the registration point only works when set to upper left side of the movie clip and mine was in the middle)
If you need any other details or information please don't hesitate to ask and I will try my best to provide it.
So in a few words what is need is:
 -

*

*I have 14+ objects and need to display them

*I need a unique random position for every object

*Make new random position and check to see if it's shape collides with the other objects

*If that object doesn't collide with the other object displayed the movieClip

*If that object collides with another movieClip get another random position

*Check again the object with the other objects to see if it collides

*If YES find another position / If NO show the object

*Do this until all the objects are positioned without colliding with each other

I believe I'm missing something and that this code could be better but really don't have any other good ideas and didn't find anything on the internet that might help. Please give me a hand.
*** Also keep in mind that I don't want the grid solution for collision detection

private var objArray : Array = new Array (movieClip1, movieClip2, movieClip3, movieClip4, movieClip5, movieClip6, movieClip7, movieClip8, movieClip9, movieClip10, movieClip11, movieClip12, movieClip13, movieClip14);
private function init():void
    {
        trace("[TRACE]:Init GameScreen");
        addEvents();
        startTimerCollision();
    }
private function addEvents():void
    {
        _timer.addEventListener(TimerEvent.TIMER, timer); //Listen for the Timer event _timer and trigger the function timeLeft.
        Repository.STAGE_REF.addEventListener(Event.ENTER_FRAME, frameRate);
    }
private function startTimerCollision():void
    {
        _timer.start();                         //start the timer

        _collisionCheck = new CollisionTest();
    }
private function frameRate(event:Event):void
    {
        //add 1 to the frame count every frame
        _frame++;
    }
function timer(event:TimerEvent):void
    {
        timpul--
        _TimerSound.play();

        showObjs();
    }
private function randomPosition(obj:MovieClip):void
    {
        obj.x = obj.width + Math.random() * (stage.stageWidth - obj.width * 2);
        obj.y = obj.height + Math.random() * (stage.stageHeight - obj.height * 2);
    //  trace(obj + " RANDOM POS= " + "x: " + obj.x + " / y:" + obj.y);
    }

    private function randomALLPositions():void
    {
        for (var i = 0; i < objArray.length; i++)
        {
            randomPosition(objArray[i]);
        }
    }

    private function checkAllCollision(obj:MovieClip):Boolean
    {
        var collisionStatus : Boolean;
        for (var i = 0; i < objArray.length; i++)
        {
            if (obj != objArray[i])
            {
                if (_collisionCheck.complex(obj, objArray[i]))
                {
                    collisionStatus = true;
//                  trace("collision detected: " + obj + " and " + objArray[i]);
                    randomPosition(obj);
                    checkAllCollision(obj);
                }
                else
                {
                    collisionStatus = false;
                }
            }
        }
        return collisionStatus;
    }

    private function showObjs():void
    {

        ////////////////////////////////////////////////////////ONLINE
        var i:int = 0;
        var j:int;
        var l:int = objArray.length;

        for (i; i < l; i++)
        {
            randomPosition(objArray[i]);
            for (j = 0; j < l; j++)
            {
                if (objArray[i] != objArray[j])
                {
    //              trace("OBJ " + (i+1) + " with OBJ " + (j+1) + "---------> CHECKING");
                    //while (checkAllCollision(objArray[i]))
                    if(checkAllCollision(objArray[i]) == true)
                    {
    //                  trace("OBJ " + (i+1) + " with OBJ " + (j+1) + "---------> Collision DETECTED");
                        randomPosition(objArray[i]);
    //                  trace("OBJ "+ (i+1) + " NOW= " + "x: " + objArray[i].x + " / y:" + objArray[i].y);
                    }
    //              trace("OBJ " + (i+1) + " with OBJ " + (j+1) + "---------> OK");
                }
            }
            addChild(objArray[i]);

        }
        ////////////////////////////////////////////////////////ONLINE

        for (var z = 0; z < objArray.length; z++)
        {
            TweenLite.to(objArray[z]["gime" + (z+1)], /*time:*/ 0, {scaleX:0, scaleY: 0});
            TweenLite.to(objArray[z]["gime" + (z+1)], /*time:*/ 0.5, {scaleX:1, scaleY: 1});
        }
    }

A: I have a couple ideas

*

*Random offset to populate possible locations

make an array of points and each point is offset from the previous point by the minimum amount needed to keep it from colliding with an object that is placed at that point. Then you'll have this nice array of points and you can randomly select and none of them will overlap.
That's the idea any way. Do this for the x offset. Then for y offset you'll have to do some more trickery that I haven't figured out yet.

A: Like Neal Davis mentioned the bottleneck is probably the checkAllCollision function that is called over and over again. A few more optimizations I can think of:

*

*You have movieclips A and B and loop trough all of them. You check if A collides with B. Then you check if B collides with A again (you have already checked that in the previous step). So might be a good idea to remember what MC combinations were already checked to not check it again the other way around. Maybe some hashtables for that ?

*Your collision detection apparently checks for complex shapes and it is very slow. Might be better if you quickly check if the bounding box collides (this should be much faster) and if so investigate further by checking for the complex shape.


text:
Q: Mongo-java-driver-3.2 mongoexport How can I do mongoexport from java program? I've googled a lot on this topic but didn't find any good explanations on this problem..
I tried this as a test(if it did work I could dump it via mongo command line)
            Runtime.getRuntime().exec("mongo");
            Runtime.getRuntime().exec("use market");
            Runtime.getRuntime().exec("db.fruits.insert({name:\"banana\"})");`

But it gave me this
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(ProcessImpl.java:386)
at java.lang.ProcessImpl.start(ProcessImpl.java:137)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
... 25 more


text:
Q: Best way to deploy a Click Once application on a network I am trying to install an Outlook 365 Add In that I have developed. I have published the application as a click once which can be installed by running the setup file.
I need the application to be installed on all company computers, so the best place to host the application would be the company network.
How can I deploy my application to all users and allow the application to automatically update every time there is a new version published?
I greatly appreciate any help with this issue. This is the first large application deployment that I have undertaken.

A: I can't advise on the specific mechanism for deploying an "installed" version of your solution - I imagine you can accomplish that with most application deployment systems.  Otherwise users will have to run the setup.exe from your network deployment.  When you do have an update you simply copy the new files to a new versioned folder and existing installations will detect the change of version number in the deployed manifest and auto-update.  See also: https://msdn.microsoft.com/en-us/library/bb772100.aspx


text:
Q: How to make symlinked git repositories respect their parent project in Projectile? I'm completely new to spacemacs and emacs in general. I switched to spacemacs from vim in hopes to have better project support for non-"sibling" directories.
I am currently working with folders inside an installation of a Source Dedicated Server so there are thousands of files and folders that are out of my control and which I do not care about. Read as: Do not, will not ever want nor need to see, search or edit. I can safely pretend these files do not exist.
For context, the installation directory of my SRCDS instance is /mnt/c/dayz/
The only folders I want to see in Projectile (and neotree) are as follows:
/mnt/c/dayz/garrysmod/gamemodes/dayz
/mnt/c/dayz/garrysmod/addons/dz_chernarus
/mnt/c/dayz/garrysmod/addons/fas2-sweps
/mnt/c/dayz/garrysmod/addons/gdbc
/mnt/c/dayz/garrysmod/addons/willbox
/mnt/c/dayz/garrysmod/addons/xmod

Note that each of these directories contain a git repository in their roots.
I have tried to create a folder inside ~/projects/dayz with an empty .projectile file with symlinks to those folders I want (view ls output below). However, it seems symlinks are being followed to their origin and projectile/neotree automatically go "into" those projects (Editing /mnt/c/dayz/garrysmod/gamemodes/dayz/dayz.txt will move me to the /mnt/c/dayz/garrysmod/gamemodes/dayz project rather than keeping me within ~/projects/dayz
~/projects/dayz/ > ls

.projectile
dayz -> /mnt/c/dayz/garrysmod/gamemodes/dayz
dz_chernarus -> /mnt/c/dayz/garrysmod/addons/dz_chernarus
fas2-sweps -> /mnt/c/dayz/garrysmod/addons/fas2-sweps
gdbc -> /mnt/c/dayz/garrysmod/addons/gdbc
willbox -> /mnt/c/dayz/garrysmod/addons/willbox
xmod -> /mnt/c/dayz/garrysmod/addons/xmod

I have also considered inverting my symlinks so that the sources reside in my ~/projects directory, which I would actually love to do, but then I ultimately end up back to my first attempted solution where it will automatically switch projects due to symlink expansion as well as break the search functionality.
Furthermore, opening the ~/projects/dayz/ project, I am unable to search the symlinked subdirectories using SPC p f
I have created the following .projectile file in /mnt/c/dayz/ containing
+garrysmod/gamemodes/dayz
+garrysmod/addons/xmod
+garrysmod/addons/gdbc
+garrysmod/addons/willbox
+garrysmod/addons/fas2-sweps
+garrysmod/addons/dz_chernarus
+garrysmod/data/dayz-data

-*.vvd
-*.vtx
-*.phy
-*.mdl
-*.vtf
-*.vmt
-*.png
-*.gma
-*.jpg
-*.exe
-*.dll

This works to an extent. However, the +'d directories seem to take precedence over the -*'d extensions, so I still end up seeing binary files when doing SPC p f and with the huge drawback that it has to search thousands of file and match them against the rules (which is very slow) I have another project which uses symlinks to some of the addon directories above as well, so this solution isn't much of an option.
Ideally, I would like to make my first attempted solution work (or with the inverted symlinks as mentioned) without Projectile automatically switching to them, but I have no idea where to begin.


text:
Q: Why does this symfony code not work? I am trying to pass parameters from one action (foo) to another (foobar).
In action foo, I set the arguments thus:
$request->getParameterHolder()->set('arg1', 'alice');
$request->getParameterHolder()->set('arg2', 'bob');

In action foobar, I try to retrieve the params thus:
$arg1 = $request->getParameter('arg1');
$arg2 = $request->getParameter('arg2');

$this->forward404Unless($arg1 && $arg2); //always forwarded

Note: I am aware that I can save the params into the user session variable - but I dont want to do that. I want to pass them as parameters - any ideas how to get this to work?

A: You can simply try this:
    $this->redirect('module/action2?'.
      http_build_query(array("arg1"=> "alice", "arg2"=>"bob")));

A: greg0ire's answer sounds like it's what you are asking for but there are a couple of other approaches that might be worth looking at if passing query string parameters isn't a hard requirement.
You could use a forward if you want the foobar action to execute after foo.  Unlike a redirect this will live in the same request cycle so you can pass variables without touching the session.
You don't say why you don't want to use the session but there is a halfway house in Symfony: flash attributes.  These are stored in the session but are guaranteed not to live beyond the next request which may be a suitable compromise.


text:
Q: Postgresql - large delete from 500Gb DB / auto-vacuum? I need to delete around 80% of my 500Gb Postgresql DB.
I have successfully run a delete command for around 50Gb of rows so far, and paused before proceeding. (This took a long time, perhaps one hour)
I notice that after deleting around 50Gb of data, no extra disk space is freed up, but some memory intensive postgres processes can be observed when I run 'htop'. Am I correct in assuming this is down to dead rows, which need to be vacuumed before the disk space is released?
Second part of this question is, if I am not mistaken about the first part, am I better off deleting all the rows and then allowing auto-vacuum to take place? It appears auto-vacuum (or some other intensive background process) has started by itself before I had a chance to continue my row deletion command list. Do I just proceed or should I gracefully tell it to stop first?

A: After a big delete, autovacuum is sure to run. That is as designed and should not interfere with you deleting still more rows.
While autovacuum frees the dead space in the tables, it does not return the space to the operating system. Rather, it remains as free space in the table and can be reused for future inserts.
If you want to shrink the tables, run VACUUM (FULL) on them, but be warned that this rewrites the table, so it temporarily uses additional storage space and blocks all concurrent activity on the table.
If you have to do mass deletes like that regularly, consider partitioning the table. It makes bulk deletes painless.

A: A better solution would be to TRUNCATE the table.
In my scenario i deleted a specific row that was taking up a lot of disk space but it was too much data for VACUUM to clear in a reasonable amount of time.
I ended up duplicating the table:
CREATE table dupe_table AS (SELECT * FROM table);

Truncating the original table:
TRUNCATE table

Finally moving the data back:
INSERT INTO table(column1, column2, column3)
SELECT column1, column2, column3
FROM dupe_table

NOTE: that you could lose data if you transaction happening between the creation of the duplicate table and the truncating of the original table


text:
Q: vs code not working properly when pressing enter I am using vs-code along with vscodevim extension and seeing strange behaviour and I am not sure what's causing that behaviour.
Suppose I have a following code and imagine _ represents cursor position
sample = {

    "key": "some value",_  #my cursor is at the end of line
    "another_key": some value"
}

When I press enter at the end of the line, the comma moves to next line instead of staying on the same line
sample = {

    "key": "some value"
    ,                                #when pressed enter it inserts new line and moves comma to new line
    "another_key": some value"

How can prevent this behaviour and make the comma stay at same line.
Here are my keybindings file and vscodevim settings file:
// keybindings.json
[
    {
        "key": "\\ a",
        "command": "workbench.view.explorer",
        "when": "!editiorTextFocus",
    }
    ,
]

//vscodevimsettings.json
{
    "vim.vimrc.path": "filepath",
    "vim.leader": "<space>",
    "vim.normalModeKeyBindingsNonRecursive": [
        {
            "before": [
                "<leader>",
                "a"
            ],
            "commands": [
                "workbench.view.explorer"
            ]
        }
    ],
    "vim.smartRelativeLine": true
}

A: One work around is "ctrl + Enter" instead of only pressing enter. Try this

A: I had the same issue but on MacOS, thought it might be helpful for you to check https://marketplace.visualstudio.com/items?itemName=adammaras.overtype.

A: Solution
In your settings.json add
"editor.acceptSuggestionOnEnter": "on"

Or,
"editor.acceptSuggestionOnEnter": "smart"

If you want to turn it off ( I don't know why would you do that )
"editor.acceptSuggestionOnEnter": "off"

Reload vscode and you're good to go
Explanation
editor.acceptSuggestionOnEnter
Controls whether suggestions should be accepted on Enter, in addition to Tab. Helps to avoid ambiguity between inserting new lines or accepting suggestions.


text:
Q: Meta-regression with two control variables I want to calculate meta regressions with the meta package. But the regression must be controlled for two variables x and y. Does anyone know how I can bring my control variable into the calculations?
library(meta)
meta_regr <- metareg(meta_analysis, ~year)
Thanks for your help!

A: Just add covariates with formula notationn as you would with normal regression with lm() function and family.
library(meta)
meta_regr <- metareg(meta_analysis, ~ year + x + y)


text:
Q: How do I get an order collection in admin order view using the email address of the current order? I am trying to build an order history table to display previous orders (order number/date/items ordered, etc) from a customer order in the admin order view (Magento\Sales\Block\Adminhtml\Order\View\Info). This table should list all previous orders that used the email from the current order regardless if they are a guest or have an account.
I did this in Magento 1.9 by calling the model directly in the template and running through the loop for orders and items for those orders:
<?php
$orderCollection = Mage::getModel('sales/order')->getCollection()->addFieldToFilter('customer_email',$_order->getCustomerEmail())->addFieldToSelect('*')->setOrder('entity_id', 'desc');
$recordNumber = 1;
if ($orderCollection->getSize() >= 2) {

$orderCollection->getSelect()->limit(20);
foreach($orderCollection as $order){
$history_id = Mage::getModel('sales/order')->loadByIncrementId($order->getIncrementId())->getId();
$orders = Mage::getModel("sales/order")->load($order->getId());
$orderHistoryDate = $this->formatDate($order->getCreatedAtStoreDate(), 'medium', true);
$items = $orders->getAllVisibleItems();

//list orders (order number, date, status)

foreach($items as $item):

//list items in orders (qty ordered, item name, sku)

endforeach;

}
}

How can I do this with dependency injection on Magento 2?

A: You can add dependency injection like this :
protected $order;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Sales\Model\Order $order,
        array $data = []
    ) {
        $this->order = $order;
        parent::__construct($context, $data);
    }

and get collection like:
$orderCollection = $this->order->getCollection()->addFieldToFilter('customer_email',$_order->getCustomerEmail())->addFieldToSelect('*')->setOrder('entity_id', 'desc');
$recordNumber = 1;
if ($orderCollection->getSize() >= 2) {

$orderCollection->getSelect()->limit(20);
foreach($orderCollection as $order){
$history_id = $this->order->loadByIncrementId($order->getIncrementId())->getId();
$orders = $this->order->load($order->getId());
$orderHistoryDate = $this->formatDate($order->getCreatedAtStoreDate(), 'medium', true);
$items = $orders->getAllVisibleItems();

//list orders (order number, date, status)

foreach($items as $item):

//list items in orders (qty ordered, item name, sku)

endforeach;

A: How I ended up solving this:
app/code/WSS/OrderHistory/registration.php
<?php \Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE, 'WSS_OrderHistory',
__DIR__
);

app/code/WSS/OrderHistory/etc/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Sales\Block\Adminhtml\Order\View\Info">
        <plugin name="customer_order_history" type="WSS\OrderHistory\Plugin\Block\Adminhtml\OrderHistory" sortOrder="15"/>
    </type>
</config>

app/code/WSS/OrderHistory/etc/module.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="WSS_OrderHistory" setup_version="0.0.1">
</module>
</config>

app/code/WSS/OrderHistory/Plugin/Block/Adminhtml/OrderHistory.php
<?php

namespace WSS\OrderHistory\Plugin\Block\Adminhtml;

class OrderHistory extends \Magento\Framework\View\Element\Template
{
protected $_orderCollectionFactory;

public function __construct(
    \Magento\Backend\Block\Template\Context $context,
    \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory,
    array $data = []
)
{
    $this->_orderCollectionFactory = $orderCollectionFactory;
    parent::__construct($context, $data);
}

public function getOrderCollection($email)
{
    $collection = $this->_orderCollectionFactory->create()
            ->addAttributeToSelect('*')
                    ->addFieldToFilter('customer_email', $email)
            ->setOrder('entity_id','desc');
    return $collection;
}
}

app/code/WSS/OrderHistory/view/adminhtml/layout/sales_order_view.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

<referenceBlock name="order_additional_info">
        <block class="Magento\Backend\Block\Template" name="custom_block" template="WSS_OrderHistory::order/view/history.phtml" />
</referenceBlock>

</page>

app/code/WSS/OrderHistory/view/adminhtml/templates/order/view/history.phtml
<?php
$currentOrder = $block->getLayout()->createBlock('\Magento\Sales\Block\Adminhtml\Order\View\Info')->getOrder();
$historyBlock = $block->getLayout()->createBlock('WSS\OrderHistory\Plugin\Block\Adminhtml\OrderHistory');
$currentEmail = $currentOrder->getCustomerEmail();
$orderCollection = $historyBlock->getOrderCollection($currentEmail);
if ($orderCollection->getSize() >= 2) {
?>

<?php /* @escapeNotVerified */ echo __('Order History / ') ?>
<?php
if ($orderCollection->getSize() > 20) echo 'Last 20 Orders (';
echo $orderCollection->getSize() . ' Total';
if ($orderCollection->getSize() > 20) echo ')';
?>

<?php
echo '
';
echo '
';
//orders
$orderCollection->getSelect()->limit(20);
foreach($orderCollection as $order){
    $history_id = $order->getEntityId();
    $orderHistoryDate = $order->getCreatedAt();
    $items = $order->getItemsCollection();

    echo '
' . $orderHistoryDate . ' (Order#: getUrl('sales/order/view', array('order_id' => $history_id)) .  '">' . ltrim(ltrim($order->getIncrementId(),"1"),"0") . ') [Status: ' . $order->getStatus() . ']
';
    // items
    foreach($items as $item):
        echo '
' . round($item->getQtyOrdered(), 0) . 'x - ' . $item->getName() . ' (Part#: getProduct()->getProductUrl() . '" target="_blank">' . $item->getSku() . ')
';
    endforeach;
}
?>

<?php
}
?>


text:
Q: Resharper - Comment behind if-clause // What I want
if (condition) // explanation
{

}

// What I get
if (condition)
    // explanation
{

}

Do you know an option to reach this? Can't find something fitting in this scenario.

A: You are probably having a large condition. That is why resharper is putting your comment in the next line.


text:
Q: Mysql update query tooks too long with magento catalog_product_entity_decimal table I am having problem in update query with magento "catalog_product_entity_decimal" table. I need to update product prices dynamically every one hour and the store has ~50k products right now. So i didnt followed the magento way of product price save to bulk update, instead I followed direct product price update in "catalog_product_entity_decimal" table which is giving results.
My query is like this $query               = "UPDATE catalog_product_entity_decimal val SET  val.value = '$final_rounded_price' WHERE val.attribute_id = 75 AND val.entity_id = $product_id";
It took 1307.1874998760223 seconds to update to 47701 products. Which is nearly 20 minutes - which is too slow when we do in the live site update.
It did reflects in the store correctly but takes too long to update which is big problem. also without this query update the time taken for this process is mili seconds only. So this table is the problem for taking time then i tried updating some dummy table update which has the nearly same records for my own purpose which took 8.5674998760223 seconds  to update to 47701 products.
That query is something like this
$query        = "UPDATE product_attributes val SET  val.price = '$final_rounded_price' WHERE val.attr_id = $attr_id AND val.product_id = $product_id";
I tried with different server which is more or less same result. So i see "catalog_product_entity_decimal" this table has so many references which must be the reason for taking long time.
I am not an expert in mysql side and i couldnt able to reduce the mysql update time with this table. Please kindly advice how can i run update query on table "catalog_product_entity_decimal" faster to update prices in bulk.
Attached the screenshot of the table "catalog_product_entity_decimal" for reference.

Development Server configuration :
Cent os 6 with php 5.3,
8 GB RAM,
Magento environment - 1.7.02 - Running default store without any change in code/db.


text:
Q: Pytest not finding all tests in subdirectories I'm having trouble getting pytest to run all my test cases in all sub directories
When I run pytest -v -s in the Project directory, it only ends up finding all the test cases in ComponentB and can't find ComponentA test cases.
Test cases run fine when I navigate to the respective component directories and run the pytest command. Why is pytest skipping ComponentA when run at the top level?
Project/
|____ComponentA/
|   |____srcs
|   |____tests
|        |__test_A_1.py
|        |__test_A_2.py
|        .
|        .
|        .
|____ComponentB/
|   |____srcs
|   |____tests
|        |__test_B_1.py
|        |__test_B_2.py
|        .
|        .
|        .

A: I assume the file names in your question are just examples but check if your real file names match the conventions for test discovery:

Pytest implements the following standard test discovery:

*

*If no arguments are specified then collection starts from testpaths (if configured) or the current directory. Alternatively, command line arguments can be used in any combination of directories, file names or node ids.

*Recurse into directories, unless they match norecursedirs.

*In those directories, search for test_*.py or *_test.py files, imported by their test package name.

*From those files, collect test items:

*

*test prefixed test functions or methods outside of class

*test prefixed test functions or methods inside Test prefixed test classes (without an init method)


text:
Q: Importing a file from a function in another file I need to call a list that I made in a function that's in another file. I was trying attempting this below, but I am getting the error cannot import name 'names' from 'backend'. Does anyone know how this can be achieved without making a class?
import backend
from backend import names
word = names
print (word)

Error message:
File "C:/Users/user/OneDrive/Desktop/Pokemon/weather.py", line 52, in <module>
  from backend import names
  builtins.ImportError: cannot import name 'names' from 'backend'

The code form the other file is
import const

SEP = ','

def get_pokemon_stats():
    """Reads the data contained in a pokemon data file and parses it into
    several data structures.

    Args:
        None

    Returns: a tuple of:
        -a dict where:
            -each key is a pokemon name (str)
            -each value is a tuple of the following stats:
                -pokemon name (str)
                -species_id (int)
                -height (float)
                -weight (float)
                -type_1 (str)
                -type_2 (str)
                -url_image (str)
                -generation_id (int)
                -evolves_from_species_id (str)
        -a dict where:
            -each key is a pokemon species_id (int)
            -each value is the corresponding pokemon name (str)
        -a list of all pokemon names (strs)
        -a dict where:
            -each key is a pokemon type (str). Note that type_1 and type_2
            entries are all considered types. There should be no special
            treatment for the type NA; it is considered a type as well.
            -each value is a list of all pokemon names (strs) that fall into
            the corresponding type
    """
    name_to_stats = {}
    id_to_name = {}
    names = []
    pokemon_by_type = {}
    DATA_FILENAME = 'pokemon.csv'

    with open(const.DATA_FILENAME) as f:
        header_to_col_num = parse_header(f)
        for line in f:
            info = line.split(const.SEP)
            name = (info[(header_to_col_num['pokemon'])])
            col_names = ('pokemon', 'species_id', 'height', 'weight', 'type_1',
            'type_2',
            'url_image', 'generation_id', 'evolves_from_species_id',)
            value = [info[header_to_col_num[col]] for col in col_names]
            value[1] = int(value[1])
            value[2] = float(value[2])
            value[3] = float(value[3])
            value[7] = int(value[7])
            value = tuple(value)

            name_to_stats[name] = value

            species_id = int(info[(header_to_col_num['species_id'])])
            id_to_name[species_id] = name
            names.append(name)

        for name, info in name_to_stats.items():
            type1 = info[4]
            type2 = info[5]
            if type1 in pokemon_by_type:
                pokemon_by_type[type1].append(name)
            else:
                pokemon_by_type[type1] = [name]
            if type2 in pokemon_by_type:
                pokemon_by_type[type2].append(name)
            else:
                pokemon_by_type[type2] = [name]

        return name_to_stats, id_to_name, names, pokemon_by_type

A: According to Python's documentation:

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function's body, it's assumed to be a local unless explicitly declared as global.

Thus, the reason why you can't import your names list from another file is because names is inside your get_pokemon_stats function scope and it is not a global variable.
You can make names global putting it outside your function and declaring it as global to use inside your function:
...
names = []
def get_pokemon_stats():
    ...
    global names
    ...

However, you should consider carefully if you really want to do this. names will only contain actual values once you call your get_pokemon_stats function. Nevertheless, you should avoid just declaring variables globally if you don't really understand how local and global variables work and when we should use them.
I recommend that you consider doing the following code instead:
from backend import get_pokemon_stats
_, _, word, _ = get_pokemon_stats()
print (word)

A: You need to call the get_pokemon_stats function. It returns four values, and the third value is names.
import backend
name_to_stats, id_to_name, names, pokemon_by_type = backend.get_pokemon_stats()
print(names)


text:
Q: How to add Newtonsoft 9.0.1 in a .NET 4.6.1 project? I'm unable to install Newtonsoft 9.0.1 package in a 4.6.1 project via nuget. In .NET Core projects it seems to be OK.
Error message:

    PM> Install-Package Newtonsoft.Json -verbose

    GET https://www.nuget.org/api/v2/FindPackagesById()?id='Newtonsoft.Json'
    OK https://www.nuget.org/api/v2/FindPackagesById()?id='Newtonsoft.Json' 179ms

    Attempting to gather dependency information for package 'Newtonsoft.Json.9.0.1' with respect to project 'ClassLibrary1', targeting '.NETFramework,Version=v4.6.1'
    Package Newtonsoft.Json from source nuget.org gathered from cache.
    Total number of results gathered : 2
    Gathering dependency information took 1,32 ms
    Summary of time taken to gather dependencies per source :
    Attempting to resolve dependencies for package 'Newtonsoft.Json.9.0.1' with DependencyBehavior 'Lowest'
    Resolving dependency information took 0 ms
    Resolving actions to install package 'Newtonsoft.Json.9.0.1'
    Resolved actions to install package 'Newtonsoft.Json.9.0.1'
    Retrieving package 'Newtonsoft.Json 9.0.1' from 'nuget.org'.
    For adding package 'Newtonsoft.Json.9.0.1' to project 'ClassLibrary1' that targets 'net461'.
    For adding package 'Newtonsoft.Json.9.0.1' to project 'ClassLibrary1' that targets 'net461'.
    Adding package 'Newtonsoft.Json.9.0.1' to folder 'C:\Users\robson.silva\documents\visual studio 2015\Projects\ClassLibrary1\packages'
    Added package 'Newtonsoft.Json.9.0.1' to folder 'C:\Users\robson.silva\documents\visual studio 2015\Projects\ClassLibrary1\packages'
    Install failed. Rolling back...
    Package 'Newtonsoft.Json.9.0.1' does not exist in project 'ClassLibrary1'
    Removing package 'Newtonsoft.Json.9.0.1' from folder 'C:\Users\robson.silva\documents\visual studio 2015\Projects\ClassLibrary1\packages'
    Removed folder 'C:\Users\robson.silva\documents\visual studio 2015\Projects\ClassLibrary1\packages\Newtonsoft.Json.9.0.1\lib\portable-net40+sl5+wp80+win8+wpa81'.
    Removed folder 'C:\Users\robson.silva\documents\visual studio 2015\Projects\ClassLibrary1\packages\Newtonsoft.Json.9.0.1\lib\portable-net45+wp80+win8+wpa81'.
    Removed folder 'C:\Users\robson.silva\documents\visual studio 2015\Projects\ClassLibrary1\packages\Newtonsoft.Json.9.0.1\lib\netstandard1.0'.
    Removed folder 'C:\Users\robson.silva\documents\visual studio 2015\Projects\ClassLibrary1\packages\Newtonsoft.Json.9.0.1\lib\net20'.
    Removed folder 'C:\Users\robson.silva\documents\visual studio 2015\Projects\ClassLibrary1\packages\Newtonsoft.Json.9.0.1\lib\net35'.
    Removed folder 'C:\Users\robson.silva\documents\visual studio 2015\Projects\ClassLibrary1\packages\Newtonsoft.Json.9.0.1\lib\net40'.
    Removed folder 'C:\Users\robson.silva\documents\visual studio 2015\Projects\ClassLibrary1\packages\Newtonsoft.Json.9.0.1\lib\net45'.
    Removed folder 'C:\Users\robson.silva\documents\visual studio 2015\Projects\ClassLibrary1\packages\Newtonsoft.Json.9.0.1\tools'.
    Removed folder 'C:\Users\robson.silva\documents\visual studio 2015\Projects\ClassLibrary1\packages\Newtonsoft.Json.9.0.1\lib'.
    Removed file 'Newtonsoft.Json.9.0.1.nupkg' from folder 'C:\Users\robson.silva\documents\visual studio 2015\Projects\ClassLibrary1\packages\Newtonsoft.Json.9.0.1'.
    Removed folder 'C:\Users\robson.silva\documents\visual studio 2015\Projects\ClassLibrary1\packages\Newtonsoft.Json.9.0.1'.
    Removed package 'Newtonsoft.Json.9.0.1' from folder 'C:\Users\robson.silva\documents\visual studio 2015\Projects\ClassLibrary1\packages'
    Executing nuget actions took 548,1 ms
    Install-Package : Failed to add reference to 'Newtonsoft.Json'.
    At line:1 char:1
    + Install-Package Newtonsoft.Json -verbose
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [Install-Package], Exception
        + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand

    Time Elapsed: 00:00:01.6617616

Is it a bug in the Newtonsoft version?


text:
Q: Starting mjpg stream from a PHP file with shell_exec I am trying to start the mjpg process from inside a PHP file on my Raspberry Pi. This is the code I am using in the PHP file.
<?php
//this execution does not work, nor does it echo anything if i try and echo it
$cmd = 'mjpg_streamer -i "/usr/local/lib/input_uvc.so -d /dev/video0 -y -r 640x480 -f 10" -o "/usr/local/lib/output_http.so -p 8090 -w /var/www/mjpg_streamer"';
shell_exec($cmd);
?>

<img src = "http://ip:8090/?action=stream" />

The command works if I execute it directly from the shell and the stream also works in this case, but I want the process to start whenever I access the page, which is not happening right now.
What's the mistake?

A: The mistake is (almost certainly) due to a permission based problem.
More than likely when you execute the mjpg_streamer library from the CLI you're logged in as someone with sudoer permissions or the like, who can easily execute this.
You must realize that the user who will be making the request to execute the mjpg_streamer library will be the same user that owns the instance of Apache handling the request.
In this scenario, the easiest way to troubleshoot this would be to log into the CLI and then su www-data (likely who owns your instance of apache) and check if you can then run it. If you get a permission denied, then you'll need to change how access to that library is granted. Changing ownership of the library is probably not the best bet, but you could likely get away with modifying the group.