text:
Q: Icon and text in a flat line on a list Hi guys so basically I am trying to putt some social media logo and next to it i want to write the account detailes or any kind of text next to the icon i am strugling with that because i want to have some movement when someone put the mouse on the icon and here everything screw up so if someone know how to make the text and the icon next to each other at the same time both of them get the same effect when someone putt the mouse on the icon or the text
https://jsfiddle.net/asda12321/9mj5q8k4/1/
`

Facebook

Whatsapp

Instgram

Email

`

Css
#bottom{
    padding-bottom: 100px;
    background-color: turquoise;
}

#socia-midea-logo {
    width: 1em;
    position: relative;
    top: 0.5em;
    left: 1.5em;
    margin: 5em 0em 0em 0em;
    width: 4em;
}

#socia-midea-logo ul{
    list-style: none;
}

#socia-midea-logo li a:hover{
    position:relative;
    background-color: rgb(255, 255, 255);
    padding: 3.7em 2.7em 1.5em 0em;
    align-items: center;
    border-radius: 50em;
    transition: 0.2s;
}

Always the text goes below the icon only

A: You have a lot of bugs in Yopurs code.

*

*You can't mix H1 and LI elements

*You cant use one id id="socia-midea-logo" in more than one element.

*You should not use H1 without text section. This is not forbidden but it is still small document structure bug.

I suggest do it like this: https://jsfiddle.net/6jt94pab/
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

Facebook

WhatsApp

Email


text:
Q: Passing Non-ID Variable Through Rails Routes Rails 2.3, Ruby 1.8.7
I'm trying to pass a variable through a rails route. I haven't been able to find a case where anyone was doing this with something that wasn't an id of a model. I'm not certain if that's the source of the problem.
In the view:
reference_string = "string of random letters and numbers"
something_path(reference_string)

In routes.rb:
map.something 'something/:reference_string', :controller => :my_controller, :action => "my_action", :reference_string => "reference_string"

In my_controller:
def my_action(reference_string)
  ...
end

I end up getting an Argument Error:
wrong number of arguments (0 for 1)
Thanks in advanced

A: Controller actions do not accept arguments.
Update your controller action so it looks like this:
def my_action
  ...
end

Then, to access reference_string, try params[:reference_string] anywhere in the controller or views. As an example, you could do this:
def my_action
  redirect_to root_url, :notice => "You sent us the reference string #{params[:reference_string]}!"
end

redpajama_set_name: RedPajamaStackExchange


text:
Q: mysql query for timezone conversion is there a way to convert from unix timestamp to GMT in mysql while running the query itself??
My query is as follows:
SELECT
    r.name
  , r.network
  , r.namestring
  , i.name
, i.description
  , r.rid
  , i.id
  , d.unixtime                  // this is the unix time i am asking to print
  , d.ifInOctets
FROM range AS r
INNER JOIN intranet AS i
ON r.rid = i.rid
INNER JOIN 1279080000_1_60 AS d
ON i.id = d.id
AND unixtime BETWEEN 1279113600 AND 1279115400   // range of unix time
WHERE r.network = "ITPN"
AND i.status = "active"
GROUP BY i.id AND d.unixtime

I was working with it in jdbc and tried numerous ways suggested in this forum to do the conversion but it does not seem to help.
Can I convert it directly and print out while running the query itself?
I want to display the date in hour:minutes. eg: 9:20.
Please help or if there is any link I can follow that would be great too.
Thank you,

A: Using FROM_UNIXTIME converts a UNIX timestamp to a MySQL DATETIME:
FROM_UNIXTIME(r.unixtime)

Then you can use CONVERT_TZ to get the DATETIME in a different timezone:
CONVERT_TZ(FROM_UNIXTIME(r.unixtime), ?, 'GMT')

Problem is, you need to know the original timezone is - you have to update the ? with the correct timezone...


text:
Q: How to Verify reCAPTCHA I'm trying to implement reCAPTCHA on a contact form & I'm stuck. The function is showing up on my page (that was easy) but now I'm confused as to how to verify the CAPTCHA. I have a "send-mail.php" file that verify's the input data & then sends it to a specified email address. Should I somehow include the reCAPTCHA verification within this file? If so, how do I do so?
Link to contact form
Your help is much appreciated.

A: Assuming you're using the "official" PHP plugin (http://recaptcha.net/plugins/php/), this is what I used to use:
<?php
    # Get a key from http://recaptcha.net/api/getkey
    $publickey = "";
    $privatekey = "";

    @require_once( 'path/to/recaptchalib.php' );

    # the response from reCAPTCHA
    $resp = null;

    # was there a reCAPTCHA response?
    if( $_POST["recaptcha_response_field"] )
    {
        $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);

        if( $resp->is_valid )
        {

        }
        else {
            if( $resp->error == 'incorrect-captcha-sol') {

            }
        }
    }
?>

This is pretty much copy-pasta from the source docs, if I recall - to be honest, I switched to Akismet a while ago...


text:
Q: git detecting move when it shouldn't I've physically deleted a file and created a new one somewhere else with a new name. I do not want the history from the old file to carry over to the new file. I want the old file to be seen as deleted and the other file to be seen as new.
If git picks these up as a move when I stage the two files, how can I tell it to not automatically detect moves for just those files?
I'm using git 1.9.2 on Windows.

A: On a move operation git won't follow the history unless you use the --follow flag.  As far as Git is concerned, since its mostly the same contents, it is a "move".
There is a good summary of what a "move" is here


text:
Q: How can I refresh with AJAX and JQuery my JSP without reloading the whole page? I have a web applicaton with java jsp servlet.
On the right side of my web frontend i have a list with links on the right side. (This is my sidebarright.jsp)
If i push the minus picture a pop window will be open (The popup window is also a jsp page named deletelink.jsp).
In the popup page i have a list of a links, and i can choose with checkboxes which links i want to delete.
So if i delete a link, in the database its allright, but i have to update with F5 the startside. Only then i will see that i have delete a link.
So i want to update with Ajax and Jquery the linklist(sidebarright.jsp), without refreshing the whole start side.
My ajax and jquery part in my deletelink.jsp page to delete links is this:
$(document).ready(function(){
    $('#setdeletefilelink').submit(function(){

        var  id=5;

          $.ajax({
                 url: '<%=request.getContextPath()%>/issues?action=uploaddeletelink&wherestatement='+id,
                 type: 'POST',
                 dataType:'json',
                 data: $('#setdeletefilelink').serialize(),
                 success: function(data){
                     alert ("success in ajax");
                     alert(data);
                     //sideBarRight.location.reload();
                    //alert("hallo");
                  //If you want to return anything in jsp.
                   },
                  error:function(xhr, ajaxOptions, thrownError){
                     alert(xhr.status);
                     alert(thrownError);

                     alert("failure");
                     $("#result").html('there is error while submit');
                 }
                 });
    //    close();

    });

});

My response from the servlet is this
    if (lstrAction.equalsIgnoreCase("uploaddeletelink")){
        String wherestatement;

            try{
                LinkUploadService linkUploadService= new LinkUploadService();

                    linkUploadService.deleteLink(wherestatement);

                    //Sende anfrage wieder zurück zur JSP
                    response.setCharacterEncoding("text/json");
                    response.setCharacterEncoding("UTF-8");
                    response.getWriter().println("Hallo ich bin ein Servlet");

                    response.getWriter().write(new Gson().toJson("TEST"));
                }
                else{
                    wherestatement = "";
                }

            }catch(Exception e){

            }
            this.checkAndDoBackgroundAction(request);
        }

After the action in the servlet a don't get the repsone in my success section in the ajax script part. I don't know why ?
and the otherthing is: how i can say to refresh the right side bar jsp.

A: You said the popup is a diffrent file. Is it opend in a iframe then?
The success function isn't called, because the form gets submitted, maybe this would help there:
$('#setdeletefilelink').submit(function(e){
    e.preventDefault();

a form without a action, is submitting to its self, maybe if you try this:
$('#setdeletefilelink').submit(function(e){
    //...Ajax call here
    e.preventDefault();
    return false;
});

otherwise, you have to check in firebug, if there is an error or an ajax reqeust anyways..
As the right side, is on the same page, it should go like this, when you get the success to work:
success: function(data){
    //an identifire for the right side would be nice
    $("#ID_ofTheRightSide", parent.document).html(data); //depending on what you getting back...
}


text:
Q: Convert to JS normal code after complied the code to deploy? I'm following NodeJS Tutorial on Udemy
When I run npm run build for Frontend Code, I got my normal code changed to this code
(this["webpackJsonpnode-complete-social-network-prep"]=this["webpackJsonpnode-complete-social-network-prep"]||[]).push([[0],[,,,,,,,,,,,,,,function(t,e,a){},,,function(t,e,a){t.exports=a(43)},,,,,function(t,e,a){},function(t,e,a){},function(t,e,a){},function(t,e,a){},function(t,e,a){},function(t,e,a){},function(t,e,a){},,,function(t,e,a){},function(t,e,a){},function(t,e,a){},function(t,e,a){},function(t,e,a){},function(t,e,a){},function(t,e,a){},function(t,e,a){},function(t,e,a){},function(t,e,a){},function(t,e,a){},function(t,e,a){},function(t,e,a){"use strict";a.r(e);var n=a(0),o=a.n(n),s=a(6),i=a.n(s),r=a(47),l=(a(22),a(48)),d=a(15),c=a(46),h=a(49);a(23);var m=t=>o.a.createElement(n.Fragment,null,o.a.createElement("header",{className:"main-header"},t.header),t.mobileNav,o.a.createElement("main",

How can I convert it to the normal code?

A: your code is minified.
Try using a tool like https://beautifier.io/ to beautify it.


text:
Q: Download legit copy of Fifa 16 without activation key I purchased a Fifa 16 key from an online seller, but haven't got a copy of Fifa 16.
Is there any way to download Fifa 16 from origin without paying for the key, again?

A: Assuming by "Origin" you mean the EA digital distribution client, you can just right-click the icon in your task tray, select "redeem product code" and then activate the key in there.
If you don't have the client, you can download it from https://www.origin.com/en-us/download. You'll need a free EA account to use it.


text:
Q: Is OxyPlot.Wpf compatible with .NET Core? Does OxyPlot.Wpf work on .NET Core?
My application uses .NET Framework 4.8.  I am considering switching to .NET Core 3.1.5 which was released in 2020 June.
Note OxyPlot has an assembly called OxyPlot.Core but it has nothing to do with .NET Core from what information I have gathered. OxyPlot.Core is "the core library... you also need to add a platform-specific OxyPlot package". This makes it seem that OxyPlot.Wpf depends upon OxyPlot.Core and in fact if you try to uninstall OxyPlot.Core the error will be "unable to uninstall OxyPlot.Core.2.0.0 because OxyPlot.Wpf.2.0.0 depends on it".  The online documentation does not seem to tell you this but fortunately NuGet will prevent the uninstall.
This means OxyPlot.Core is the core of OxyPlot and its existence does not necessarily tell you anything explicit about .NET compatibility.

A: I'd say yes it is compatible. Based on the nuget link https://www.nuget.org/packages/OxyPlot.Wpf

A: Think you Will find OxyPlot works fine with Wpf .NET Core .. but I cannot say the same for a Winforms .NET Core project I have; at the present time I am having (the usual) enormous difficulty in making it work


text:
Q: Is libc.so.2 required to be located in /usr/lib? I have a directory with the following contents:
bin/busybox
lib/ld-linux.so.2
lib/libc.so.6

and when I invoke:
chroot . bin/busybox sh

it fails with the following:
/bin/busybox: error while loading shared libraries: libc.so.6: cannot open shared object file: No such file or directory

When I move lib/libc.so.6 to usr/lib, it works fine.
Why is libc required to be in /usr/lib? When I invoke:
objcdump -p bin/busybox | grep NEEDED

I get:
NEEDED        libc.so.6

So I thought, as only the soname of the library is used without slashes etc. the loaded will be able to find it in the standard folders, which is /lib and /usr/lib. Apparently, this is not the case.
To make matters even more confusing, ld-linux.so.2 seems to have to be in /lib because when it is moved to /usr/lib, chroot fails with:
chroot: failed to run command '/bin/busybox': No such file or directory

which I learned is actually an error that the loader cannot be found, not the busybox binary.
Is the issue with libc.so.2 distro specific? If this is important, I'm using Arch Linux.

A: The location of the loader (typically something like /lib/ld-linux.so) is hard-coded in the binary. There's no search process for this component — if it cannot be found, the binary won't run at all.
(The exact path depends on what libc and architecture you're using. It's at /lib64/ld-linux-x86-64.so.2 for glibc on x86_64, for instance.)
The locations that will be searched for dynamic libraries are configurable in /etc/ld.so.conf. If you don't have that file in the chroot, though, some of the standard paths may not be configured!


text:
Q: Automating nonsignificant term removal from linear models Im working on a data set that includes categorical and continuous independent variables and want to find out what the minimum adequate model is.
This is the starting model:
mod1 <- lm(Richness ~ Distances*Flower*Veg*Canopy*factor(Vines), data = Data)
anova(mod1)

I am then removing nonsignificant interaction terms and variables by a manual process like so:
mod2 <- update(mod1, ~.-Canopy:factor(Vines))
anova(mod2)

Is there a way of automating this process?
Thank you for your help.

A: Following what @nongkrong suggested about the step function I think I found a solution:
model.null = lm(Abundance ~ 1,
            data=data) #define the null model#
model.full = lm(Abundance ~ Distances*Flower*Veg*Canopy*factor(Vines),
            data = data) #define the max model#

step(model.full, #start at the full model#
 scope = list(lower = model.null), # the lower limit of model it can produce#
 direction = "backward", #work by deleting terms until you get to the minimum model #
 data = data
)

It seems to work so far, if anyone sees a problem with this code please comment.


text:
Q: How can I upload to a PPA without .changes file? So, I'm developing an app for the Ubuntu Showdown, and as quickly is still very buggy (I had problems using it), I decided to do my app entirely from scratch, using Python/GTK+3. I've done my app and I've just packaged it using only fakeroot dkpg-deb --build.
The problem is that I can't create a .source file, as I don't have a changelog file and the debian folder cannot be used in debuild, as is uncorrectly organized. The text shown by ls -l -R:
.:
total 16
-rw-rw-r-- 1 francisco francisco    2 jul  3 17:48 compat
drwxrwxr-x 2 francisco francisco 4096 jul  3 20:37 DEBIAN
drwxrwxr-x 3 francisco francisco 4096 jul  3 18:36 opt
drwxrwxr-x 3 francisco francisco 4096 jul  3 20:40 usr

./DEBIAN:
total 36
-rwxr-xr-x 1 francisco francisco 1327 jul  3 20:26 control
-rwxr-xr-x 1 francisco francisco 1329 jul  3 20:17 control~
-rwxr-xr-x 1 francisco francisco   10 jul  3 20:20 postinst
-rwxr-xr-x 1 francisco francisco   10 jul  3 20:36 postrm
-rwxr-xr-x 1 francisco francisco  121 jul  3 20:35 postrm~
-rwxr-xr-x 1 francisco francisco   10 jul  3 20:20 preinst
-rwxr-xr-x 1 francisco francisco   10 jul  3 20:20 prerm
-rwxr-xr-x 1 francisco francisco  530 jul  3 20:37 rules
-rwxr-xr-x 1 francisco francisco  530 jul  3 20:37 rules~

./opt:
total 4
drwxrwxr-x 3 francisco francisco 4096 jul  3 18:36 espectalll123

./opt/espectalll123:
total 4
drwxrwxr-x 2 francisco francisco 4096 jul  3 18:36 virtuam

./opt/espectalll123/virtuam:
total 28
-rw-rw-r-- 1 francisco francisco 12614 jun 27 13:58 assistant.glade
-rwxrwxr-x 1 francisco francisco   758 jun 30 17:53 virtuam
-rwxr-xr-x 1 francisco francisco  6285 jul  3 17:39 vui.py

./usr:
total 4
drwxrwxr-x 4 francisco francisco 4096 jul  3 20:46 share

./usr/share:
total 8
drwxrwxr-x 2 francisco francisco 4096 jul  3 20:46 applications
drwxrwxr-x 2 francisco francisco 4096 jul  3 20:40 pixmaps

./usr/share/applications:
total 4
-rwxrwxr-x 1 francisco francisco 304 jul  3 20:43 virtuam.desktop

./usr/share/pixmaps:
total 188
-rw-r--r-- 1 francisco francisco 189478 jun 30 17:42 virtuam.svg

So, this is the question: can I upload my app to the PPA without the .source file? If not, how can I create it?

A: Use
    debuild -S -k<Your pgp key ID>

That should generate you the file you can then dput to your ppa

A: Unluckly, there are just two ways: to package it manually (horrible, as I've seen myself) or to restart the project with another environment. I did the second one.


text:
Q: DataGridTemplateColumn find no binding root I am trying to put a user control, named simpleChart, into a DataGridTemplateColumn. I bind the DataGrid to an ObservableCollection<Index> (where Index is an INotifyPropertyChanged class that I created for display). But somehow, the binding cannot find the root item. To check my binding, I put a textColumn aside the templateColumn, and it works just fine. Here is the relevant code:
<Window x:Class="TechniqueAnalysis.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="" Height="549" Width="1744"
    xmlns:diagnostics="clr-namespace:System.Diagnostics;assembly=WindowsBase"
    xmlns:local="clr-namespace:Charts"
    xmlns:simpleChart ="clr-namespace:ChartOnGird;assembly=ChartOnGird"
    WindowState="Maximized" Closing="Window_Closing">
<Grid>
<DataGrid Margin="0,60,0,0" Name="dataGridWei" CanUserResizeColumns="False"  ItemsSource="{Binding}">
<DataGridTemplateColumn Header="2 day"  Width="100">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
           <simpleChart:SimpleChart X ="{Binding Path=X1, diagnostics:PresentationTraceSources.TraceLevel=High}"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="Value" Binding="{Binding Path=X1, diagnostics:PresentationTraceSources.TraceLevel=High, StringFormat=N2}"/>
</DataGrid>
</Grid>
</Window>

The databinding is through background code which binds the ObservableCollection to the datagrid's DataContext.
And I get the following output for the template column:
System.Windows.Data Warning: 58 : BindingExpression (hash=45649854): Default mode resolved to OneWay
System.Windows.Data Warning: 59 : BindingExpression (hash=45649854): Default update trigger resolved to PropertyChanged
System.Windows.Data Warning: 60 : BindingExpression (hash=45649854): Attach to ChartOnGird.SimpleChart.X (hash=40977533)
System.Windows.Data Warning: 65 : BindingExpression (hash=45649854): Resolving source
System.Windows.Data Warning: 68 : BindingExpression (hash=45649854): Found data context element: SimpleChart (hash=40977533) (OK)
System.Windows.Data Warning: 76 : BindingExpression (hash=45649854): Activate with root item ''
System.Windows.Data Warning: 106 : BindingExpression (hash=45649854):   At level 0 - for String.X1 found accessor <null>
System.Windows.Data Warning: 106 : BindingExpression (hash=45649854):   At level 0 - for EnumerableCollectionView.X1 found accessor <null>
System.Windows.Data Warning: 102 : BindingExpression (hash=45649854): Replace item at level 0 with {NullDataItem}, using accessor {DependencyProperty.UnsetValue}
System.Windows.Data Warning: 78 : BindingExpression (hash=45649854): TransferValue - got raw value {DependencyProperty.UnsetValue}
System.Windows.Data Warning: 86 : BindingExpression (hash=45649854): TransferValue - using fallback/default value '9'
System.Windows.Data Warning: 87 : BindingExpression (hash=45649854): TransferValue - using final value '9'
System.Windows.Data Warning: 54 : Created BindingExpression (hash=32948864) for Binding (hash=33575416)

But for the text column, I get the following warning:
System.Windows.Data Warning: 58 : BindingExpression (hash=32948864): Default mode resolved to OneWay
System.Windows.Data Warning: 59 : BindingExpression (hash=32948864): Default update trigger resolved to PropertyChanged
System.Windows.Data Warning: 60 : BindingExpression (hash=32948864): Attach to System.Windows.Controls.TextBlock.Text (hash=6303902)
System.Windows.Data Warning: 65 : BindingExpression (hash=32948864): Resolving source
System.Windows.Data Warning: 68 : BindingExpression (hash=32948864): Found data context element: TextBlock (hash=6303902) (OK)
System.Windows.Data Warning: 69 : BindingExpression (hash=32948864): DataContext is null
System.Windows.Data Warning: 63 : BindingExpression (hash=32948864): Resolve source deferred
System.Windows.Data Warning: 65 : BindingExpression (hash=8194399): Resolving source
System.Windows.Data Warning: 68 : BindingExpression (hash=8194399): Found data context element: TextBlock (hash=33203677) (OK)
System.Windows.Data Warning: 76 : BindingExpression (hash=8194399): Activate with root item Index (hash=33903126)
System.Windows.Data Warning: 106 : BindingExpression (hash=8194399):   At level 0 - for Index.X1 found accessor RuntimePropertyInfo(X1)
System.Windows.Data Warning: 102 : BindingExpression (hash=8194399): Replace item at level 0 with Index (hash=33903126), using accessor RuntimePropertyInfo(X1)
System.Windows.Data Warning: 99 : BindingExpression (hash=8194399): GetValue at level 0 from Index (hash=33903126) using RuntimePropertyInfo(X1): '1'
System.Windows.Data Warning: 78 : BindingExpression (hash=8194399): TransferValue - got raw value '1'
System.Windows.Data Warning: 82 : BindingExpression (hash=8194399): TransferValue - implicit converter produced '1.00'
System.Windows.Data Warning: 87 : BindingExpression (hash=8194399): TransferValue - using final value '1.00'
System.Windows.Data Warning: 65 : BindingExpression (hash=32948864): Resolving source
System.Windows.Data Warning: 68 : BindingExpression (hash=32948864): Found data context element: TextBlock (hash=6303902) (OK)
System.Windows.Data Warning: 76 : BindingExpression (hash=32948864): Activate with root item Index (hash=49245678)
System.Windows.Data Warning: 105 : BindingExpression (hash=32948864):   At level 0 using cached accessor for Index.X1: RuntimePropertyInfo(X1)
System.Windows.Data Warning: 102 : BindingExpression (hash=32948864): Replace item at level 0 with Index (hash=49245678), using accessor RuntimePropertyInfo(X1)
System.Windows.Data Warning: 99 : BindingExpression (hash=32948864): GetValue at level 0 from Index (hash=49245678) using RuntimePropertyInfo(X1): '1'
System.Windows.Data Warning: 78 : BindingExpression (hash=32948864): TransferValue - got raw value '1'
System.Windows.Data Warning: 82 : BindingExpression (hash=32948864): TransferValue - implicit converter produced '1.00'
System.Windows.Data Warning: 87 : BindingExpression (hash=32948864): TransferValue - using final value '1.00'

It seems that the templatecolumn fails to find a correct root item. The question is what is a proper way to help it to find the proper one? I tried to add an RelateSource but did not figure out how. My class "Index" is under the MainWindow class. Please help me.  I have spend 2 days on it. I believe I am almost there but there is just something that I cannot figure out without help.

A: I'm guessing the problem is your simpleChart UserControl. Probably you set the DataContext for this control in the wrong manner and that's why the bindings will not find the Row.DataContext but rather the UserControl.DataContext.
Take a look at this Simple Pattern for Creating Re-useable UserControls to do it the right way.


text:
Q: Characteristic of an integral domain must be either $0$ or a prime number.
Proposition: Characteristic of an integral domain must be either $0$ or prime number.

I'm confused by this proposition.
I think the characteristic of an integral domain should be always $0$.
Suppose it has characteristic $n$.
Then $n * a = 0$ for all a of the integral domain.
since n is not $0$ and, if $c * d = 0$ in integral domain, it means $c=0$ or $d=0$,
a should be $0$. Hence $n * a$ is not $0$ when $a$ is nonzero. Therefore, characteristic should be always $0$.
What's wrong with my thought?

A: Hint $\ $ Whenever you have problems understanding such an abstract statement you should look at concrete instances. For example $\,\rm \Bbb Z\ mod\ 3\ $ has characteristic $3$ because $ 3n := n + n + n \equiv 0\ $ for $ n\equiv 0,1,2.\:$ See how you argument breaks down in this simple concrete case, then generalize.
Note that $\,m\cdot a\,$ does not denote an element obtained by applying the ring multiplication to two elements of the ring. Rather, the $m$'th multiple $\,m\cdot a\,$ is the additive analog of the $m$'th power $a^m.$ In the first case we add $m$ copies of $a$ to obtain $\,m\cdot a\,$ and the second we multiply them to get $\,a^m.\,$ They are both well-defined operations in any ring.
One may rigorously define such operations by recursion, viz.
$$\begin{eqnarray} 0\cdot a \,&=&\, 0 \\ (1+n)\cdot a\,&=&\, a + n\cdot a\end{eqnarray}$$

A: You are correct - $m$ is not an element of the integral domain D. $m$ is a natural number.
But then of course a fair question to consider is how $m \cdot a$ is defined. Somewhere in your text it should define $m \cdot a$ in which $m$ is a natural number and $a$ is an element of an integral domain D as $a$ added to itself $m$ times.
Consider the integral domain $\mathbb{Z}_5$ with addition and multiplication modulo $5$. $\mathbb{Z}_5$ is finite characteristic because each element may be added to itself a number of times (modulo $5$) to reach $0$.

*

*$0 \equiv 0$ (mod $5$)

*$1+1+1+1+1 = 5 \equiv 0$ (mod $5$)

*$2+2+2+2+2 = 10 \equiv 0$ (mod $5$)

*$3+3+3+3+3 = 15 \equiv 0$ (mod $5$)

*$4+4+4+4+4 = 20 \equiv 0$ (mod $5$)

A: In a ring $R$ we define $p*x= {(1_R+1_R+1_R+\cdots+1_R)}x= \sum\limits_{i=1}^p x $, so even if $p= 1_R+1_R+1_R+\cdots+1_R=0 $ as a ring element, it is not necessarily $0$ in $\Bbb Z$.
$ \mathbb F_p$ (the integers modulo $p$ a prime, see here) is an integral domain with characteristic $p$. If $R$ was a ring with characteristic $mn$ then $m \ne 0$ and $ n \ne 0$ but $mn$=0, so $R$ could not be an integral domain.
Note in $\Bbb F_p$ the equivalence class of an integer $n \equiv 0 \mod p$ if and only if $n=pm$ for some $m \in \Bbb Z$, now if $xy \equiv 0 \mod p $ then $p|xy$. By primality of $p$ then $p|x$ or $ p|y$. So either $x$ or $y \equiv 0 \mod p$.

A: The integer is not an element of $D$. You have the canonical $\mathbb{Z}$-action ($0_\mathbb{Z}a = 0_D$, and $(k+1)a = ka + a$) on the abelian group $(D,+)$, and for that $\mathbb{Z}$-action, you have $ma = 0$ for all $a \in D$.


text:
Q: C# in Async Task change Label Text The following Code does not change the Text and stops executing the Task
private void button1_Click(object sender, EventArgs e)
    {
        label1.Text = "Test";
        Task.Run(() => MyAsyncMethod());
    }

    public async Task MyAsyncMethod()
    {
        label1.Text = "";
        //everything from here on will not be executed
    }

would be really handy if you could use async together with the UI

A:
would be really handy if you could use async together with the UI

The design of async was carefully done so you can use it naturally with the UI.

in my code i run a function that does a lot of IO and stuff that takes a long time

If you have asynchronous I/O methods (which you should), then you can just do this:
private async void button1_Click(object sender, EventArgs e)
{
  label1.Text = "Test";
  await MyMethodAsync();
}

public async Task MyMethodAsync()
{
  label1.Text = "";
  await ...; // "lot of IO and stuff"
  label1.Text = "Done";
}

That's the most natural approach.
However, if you need to run code on a background thread (e.g., it's actually CPU-bound, or if you just don't want to make your I/O operations asynchronous like they should be), then you can use IProgress<T>:
private void button1_Click(object sender, EventArgs e)
{
  label1.Text = "Test";
  var progress = new Progress<string>(update => { label1.Text = update; });
  await Task.Run(() => MyMethod(progress));
}

public void MyMethod(IProgress<string> progress)
{
  if (progress != null)
    progress.Report("");
  ...; // "lot of IO and stuff"
  if (progress != null)
    progress.Report("Done");
}

Under no circumstances should modern code use Control.Invoke or (even worse) Control.InvokeRequired.

A: for accessing a GUI control through a second thread you need to invoke.
following example shows how to set a label's text properly
  private void setLabel1TextSafe(string txt)
  {
       if(label1.InvokeRequired)
           label1.Invoke(new Action(() => label1.Text = txt));
       else
           label1.Text = txt;
  }

I hope this solves your problem

A: Task.Run is used to envelope an Action (that is not async) into a Task. Any Task that you want to execute should be awaited. Thus, that Task.Run of yours is rigorously doing nothing.
Mark that button1_Click event handler of yours as async. Then remove that Task.Run and instead do await MyAsyncMethod().

A: Try this. You don't need to fire a new thread to invoke the async method. compiler will do it for you.
private void button1_Click(object sender, EventArgs e)
    {
        label1.Text = "Test";
        MyAsyncMethod();
    }
public async Task MyAsyncMethod()
{
    return await Task.Run(() =>{
    label1.Text = "";
    //everything from here on will not be executed
     }
}

A: I think both the questions and some of the answers are not clear. Depending on where in the task thread you need to update the label you have to use invoke. Otherwise you can leverage await and leverage the standard semantics.
    private async void button1_Click(object sender, EventArgs e)
    {
        label1.Text = "Starting to run a long task... carry on...";
        await snooze(3);
        label1.Text = "Done with long task";
    }

    public Task<int> snooze(int seconds)
    {
        label1.Text = "zzzz...";
        return Task.Run(
        () => {
            label1.Invoke(new Action(() => label1.Text = "For some reason I need to alert you here.. bad dream perhaps...direct access to label1 will fail"));
            Thread.Sleep(seconds * 1000);
            return  seconds;
           });

    }


text:
Q: State Diagram for Turing Machine to compute next string in lexicographical order What would the state diagram look like for a Turing Machine that computes the next string in lexicographical order over alphabet Σ = {1, 2, 3}?
String size is 4, i.e ---1, ---2, ---3, --11, --12, etc...
Already tried figuring it out from Michael Sipser's Introduction to Theory of Computation with no luck.
Also tried to look it up online, again with no luck.
Thanks in advance!

A: If I have understood correctly, you want a TM to take as input a string over {1, 2, 3} of length up to four, and to overwrite this number with the string over the same alphabet which comes next in lexicographic order. Here is a strategy for this problem.

*

*move right three times so we're looking at the fourth symbol on the tape.

*if this is blank, our input is malformed and we die. otherwise, if the symbol is 1, write 2 and halt-accept; if 1, write 2 and halt-accept; if 3, write 1 and move left in state "carry2"

*if this is blank, 1 or 2, write 1, 2 or 3, respectively, and halt-accept. if 3, write 1 and move left in state "carry3"

*if this is blank, 1 or 2, write 1, 2 or 3, respectively, and halt-accept. if 3, write 1 and move left in state "carry4"

*if this is blank, 1 or 2, write 1, 2 or 3, respectively, and halt-accept. if 3, the input was the number 3333 and there is no lexicographically larger 4-digit string over {1, 2, 3}… so either crash or wrap and write ---1 to the tape.

Note that this does not verify the tape contents are sane... since we are using blanks to encode "missing" high-order digits we can just reasonably assume there's nothing after position 4 on the tape (defining what our TM does carefully to avoid implying we did anything after there). Furthermore, we are not sanitizing the front, so mixing symbols and blanks improperly could be an issue... so we could either run some steps first to validate the input or just require the input be well-formed when we get it.


text:
Q: Restlet css and javascript files WebContent
   - resources
       - css
           - style.css
WEB-INF
   - index.html
public synchronized Restlet createInboundRoot() {
    Router router = new Router(getContext());
    router.attach("/", IndexResource.class);
    return router;
}

The IndexResource executes an HTML Respresentation (index.html)
In my index.html I have specified a css file. The problem is that it cannot be found.
  <link href="/resources/css/style.css" rel="stylesheet" type="text/css">

I think /resources/css/style.css is going via restlet and not the actual file path. How do I stop the resources folder executing as a servlet (restlet)?

A: Must your css file need to be served by Restlet? If so, you should consider using the Directory class as described below (in your application class):
public Restlet createInboundRoot() {
    Router router = new Router(getContext());
    (...)
    router.attach("/resources", new Directory(getContext(), "file://<STATIC_DIR>"));
}

In this case you need to have css/style.css under the  folder.
Hope it helps you.
Thierry


text:
Q: Difference between PHP expression return value and variable Why does it make a difference if a function's return value (a variable) is passed and not a variable directly?
In the PHP documentation for the empty() function it is stated that

5.5.0: empty() now supports expressions, rather than only variables.

But why would that make a difference anyway?
If the given expression has a variable as a return value - in my eyes - both statements would be exactly the same.

A: Prior to PHP 5.5, the returned value is a value, not a variable because when you say
return $value;

in your called function, $value is only valid in the scope of the function; it ceases to exist as a variable as soon as the function terminates its execution, so the calling code only receives the value


text:
Q: Where can I get real data of big network topology? I want to model how traffic will flow on real networks (not just the internet, also, say, Intel's internal LAN).
Is there a place I can get real network topologies data I can use?

A: In addition to the source listed by JohnRos, the association for social network analysis (INSNA) have a lot of data (sometimes the datasets are missing, though).
Another source might be Tore Opsahl's website (the airline data are a good candidate, as the forum data are). Finally, Mark Newman's page is another source.
If you have an interest in open source software, FLOSSmole might be another place to fish for large network datasets (but I do not know if there is information about flow in there).
This thread gives a lot of other potential sources

A: Stanford Large Network Dataset Collection. Which is part of the Stanford Network Analysis Project, SNAP.


text:
Q: findOne() not returning data in nestjs typeorm mongodb i'm using typeorm with mongodb on nestjs , findone() is not working , i tried findOne(where:{email:email}) , findOne({email:email}), findOne(email)
 async findUser(email: string): Promise<User> {
   return await this.userRepo.findOne({ email: email });
 }


text:
Q: What are the possible causes for an SSIS package execution having an "ended unexpectedly" status I have a SQL Agent job that runs an SSIS 2012 package every 30 seconds to export a small amount of data to a CSV file. There is often nothing to export, but when there is, the business wants it done ASAP.
This has been running fine for months without error, but over the weekend it had 3 failures:
Start Time: 7/25/2015, 11:43:13 PM, End Time: 7/25/2015 11:44:36 PM, Status: Ended Unexpectedly
Start Time: 7/25/2015, 11:52:05 PM, End Time: 7/25/2015 11:53:13 PM, Status: Ended Unexpectedly
Start Time: 7/26/2015,  5:01:31 PM, End Time: 7/25/2015  5:01:31 PM, Status: Failed

In each case, there were no records in internal.operation_messages for the operation_id. The All Executions report also showed no Messages and no entries under Execution Overview. Normal durations for this package are in the 4 - 26 second range. So the Ended Unexpectedly executions had unusually long durations. The Failure execution had a duration of zero. There are no maintenance jobs of any kind running at the time of these failures.
I found this in the Application Event Log that correlates to the time of the Failed execution:

The operation 414582 (GUID:82f992bf-ed2a-4d82-b25d-92a9d3052cd9)
  terminated because the AppDomain 488 is unloaded. Try restarting the
  execution.

I don't know what this means.
I found instances of this message that correlate to the "ended unexpectedly" executions:

The SSIS Execution Process could not write to the IS catalog:
  MyInstance:SSISDB Error details: Timeout expired. The timeout period
  elapsed prior to completion of the operation or the server is not
  responding

What are some possible causes for these?


text:
Q: how to combine cfif and cflnclude in Coldfusion I have a ColdFusion program which needs to switch to another page, but which page depends on a condition.  It would be nice to write code such as
<cfif a GT 5>
 <cfinclude template = 'pageone.cfm'>
<cfelse>
 <cfinclude template = 'pagetwo.cfm'>
</cfif>

The problem is, if I include pageone or pagetwo the final </cfif> disappears from ColdFusion's radar, and I get an error.  Can anyone suggest a way to accomplish what I'm trying to do above?

A: Change your approach to something like this:
<cfset a = 6>

<cfif a GT 5>
    <cfset templateTarget = 'pageone.cfm'>
<cfelse>
    <cfset templateTarget = 'pageTwo.cfm'>
</cfif>

<cfinclude template = '#templateTarget#'>


text:
Q: can other control cover on webview WebView has the characteristic that other UI regions such as controls cannot be rendered on top of the WebView.
Does this mean that there is no way I can put other control (like popup ) on top of it?

A: You are right. Currently, (25.04.2012) there is no way to overlay the WebView provided in the public SDK for Windows 8. The problem is basically that the WebView is technically a instance of Internet Explorer running in its own HWND inside of other Metro Style apps. Actually, the WebView is not a proper XAML control at all.
If you need to show static (non-interactive) HTML in your app, you can use the WebViewBrush.
I am currently looking for a solution myself: HTML/CSS Renderer for Metro-Style Apps
Basically, we have the following options right now:
- MSFT "fixes" the WebView Control
- Other Browser vendors (Mozilla, Google, Opera, etc.) provide a reuseable XAML Control
- We develop our own port of WebKit
Maybe someday, the issue will be resolved...
See my thread here:
http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/23a235a2-b0a3-4161-bc74-c42289c61264
Other ressources:
http://nerddawg.blogspot.de/

A: May be it's a new class, there is a class called WebViewBrush for this purpose. Here is the link.
WebViewBrush


text:
Q: How to stop inline ckeditor div resizing I have a div with contenteditable set to true and I am making editable with an inline CKEditor instance.
As I type in the div, it naturally grows in the vertical direction as the text fills up or when I press return.
If I set the height and max-height CSS of the editor div then, the div itself doesn't grow BUT the editor carries on letting me enter text all the way down the page (it breaks out of the div).
What I want to be able to do is lock the inline editor area to, say, 100px in height and, ideally, not allow any more lines to be inserted.
Any ideas much appreciated.

A: After some playing around I found the answer and it was simple.  Just apply a height and overflow-y:auto to the css of the containing div.  Works a treat :)

A: Configure height and turn off auto grow:
config.autoGrow_onStartup = false,
config.resize_enabled = false,
config.height = '500px';

A: You have to set hight and width during intializing the ckeditor
config.height = 500;        // 500 pixels high.
config.height = '25em';     // CSS unit (em).

To Disable resizing
config.resize_enabled = false;

Reference: http://docs.ckeditor.com/#!/guide/dev_size


text:
Q: Binary Search/Insert Methods not inserting correctly I need to have a Student database that is sorted alphabetically, so I decided that I would keep the students sorted by inserting them correctly. So I decided to implement a binary search with an insert method to keep it sorted as it inserts.
However, for some reason it inserts incorrectly, and the database is no longer sorted. I know it has something to do with my logic with the .compareToIgnoreCase() method. Here is my code:
private Student[] binaryInsert(Student student, int min, int max) {
    int mid = (min + max) / 2;
    if (min > max) {
        return insert(studentDatabase, student, -1);
    }
    if (min == max) {
        if (studentDatabase[mid].compareToIgnoreCase(student)) < 0) {
            return insert(studentDatabase, student, mid + 1);
        } else {
            return insert(studentDatabase, student, mid - 1);
        }
    } else if (studentDatabase[mid].compareToIgnoreCase(student)) < 0) {
        return binaryInsert(student, mid + 1, max);
    } else {// last possibility: a[mid] > x
        return binaryInsert(student, min, mid - 1);
    }
}

public Student[] insert(Student[] database, Student object, int i) {
    Student[] newDatabase = new Student[database.length + 1];
    if (i == -1) {
        for (int j = 1; j < newDatabase.length; j++) {
            newDatabase[j] = database[j - 1];
        }
        newDatabase[0] = object;
    } else {
        for (int x = 0; x < i; x++) {
            newDatabase[x] = database[x];
        }
        newDatabase[i] = object;
        for (int x = i + 1; x < newDatabase.length; x++) {
            newDatabase[x] = database[x - 1];
        }
    }
    return newDatabase;
}

And My Input:
STUDENT/NAD86/RAFAEL/NADAL/1986/SPAIN
STUDENT/DJO87/NOVAK/DJOKOVIC/1987/SERBIA
STUDENT/FED81/ROGER/FEDERER/1981/SWITZERLAND
STUDENT/STA86/ALEX/STAIRS/1998/AMERICA

And my output
FED81: ROGER FEDERER, 1981, SWITZERLAND, 0.0
DJO87: NOVAK DJOKOVIC, 1987, SERBIA, 0.0
NAD86: RAFAEL NADAL, 1986, SPAIN, 0.0
STA86: ALEX STAIRS, 1998, AMERICA, 0.0

FED81 is the problem child. If I rearrange the input around, it does work, but I can't do that.
Thanks for the help in advance!
EDIT: It should be noted that I tried the same process, but with integers, and it worked in all of my tests.

A: Thanks to Joop Eggen, I was able to get it working. The solution was to take out the "- 1" from the insert(studentDatabase, student, mid - 1) method call.
The fix was due to the fact that the insertion point before a[i] is at i, not i - 1.
Credit to Joop Eggen!


text:
Q: PhpMyAdmin auto refresh MySQL table When I Run update or select query within phpmyadmin local page, I get table results pop up with the "GO" button. But for using *.php file from a server I have to use refresh button to see the newly incoming data on my table, create view didn't help, or I may be missing something. How can I view them like an auto refresh/update style! any help?
while (($data = fgetcsv($handle, 1000)) !== FALSE) {

    $sql2 = "INSERT INTO `tabl_nam` (
                `col_1` ,
                `col_2`
                 )
                VALUES ('" . $data[0]. "', '" . $data[1] . "')";
    }
mysqli_query($link,$sql2);
$sql1 = "UPDATE `tabl_nam` SET `col_1`= '" . $data[0]. "',`col_2`='" . $data[1]. "'";
//$sql1 = "SELECT `col_1`, `col_2` FROM `Cr_view` WHERE 1";

//"Cr_view" is  my create view table on phpmyadmin
//$sql1 = "SELECT `col_1`, `col_2` FROM `Cr_view` WHERE 1";//I tried 'SELECT' query as well
mysqli_query($link,$sql1);
mysqli_close($link);

//both the above select and update queries worked on phpmyadmin console

If not PhpMyAdmin, is there any solution (S.W or code or query)for auto updating the view when uploading a new data for at least a single table.

A: Create a bookmark with this "address":
javascript:setInterval(function() { $('a:contains("Refresh")').click(); }, 10000);
After opening the phpMyAdmin, click on this bookmark (or run this snippet directly from URL bar) and from now, tables will be auro-refreshed every 10 seconds.

A: If the above bookmarklet doesn't work try this one. It fixes the browser navigating to a page instead of clicking the Refresh link (at least in Firefox).
javascript:var _x=setInterval(function(){$('a:contains("Refresh")').click();},10000);


text:
Q: Cascade index.php in nginx "try_files" In Apache it is possible to redirect everything to the closest index.php, using .htaccess
Example folder structure:
/Subdir
/index.php
/.htaccess

/Subdir
/Subdir/.htaccess
/Subdir/index.php

If I access /something it will redirect to the root index.php, and if I access /Subdir/something it will redirect to Subdir/index.php
Can this be done in nginx as well?
It should be possible, because in nginx documentation it says If you need .htaccess, you're probably doing it wrong :)
I know how to redirect everything to the root index.php:
location / {
  try_files $uri $uri/ /index.php?$query_string;
}

But how to check for index.php in every parent directory until / ?
edit:
I found that these rules do what I want:
location / {
  try_files $uri $uri/ /index.php?$query_string;
}

location /Subdir{
  try_files $uri $uri/ /Subdir/index.php?$query_string;
}

But is there a way to make it abstract, like
location /$anyfolder{
  try_files $uri $uri/ /$anyfolder/index.php?$query_string;
}

?

A: The index directive should take care of most of that
server {
    index index.php;
    ...
}

If your setup dictates using try_files, then this should work for you:
location / {
    try_files $uri $uri/ $uri/index.php?$query_string =404;
}

You can also capture the location and use as a variable:
location ~ ^/(?<anyfolder>) {
    # Variable $anyfolder is now available
    try_files $uri $uri/ /$anyfolder/index.php?$query_string =404;
}

Edit
I see from your comment that you want to try the subject folder's index.php file first and go on to the one in the root folder if there isn't one in the subject folder.
For that, you could try something like...
location / {
    try_files $uri $uri/ $uri/index.php$is_args$args /index.php$is_args$args;
}

Note: $is_args$args is better than ?$query_string if there is a chance there might not be arguments.
Edit 2
Okay. Got the bounty but kept on feeling I was missing something and that your query was not actually addressed. After reading and rereading, I now think I finally fully understand your query.
You want to check for index.php in the target folder. If found, this will be executed. If not found, keep checking parent folders up the directory tree until one is found (which may be the root folder).
The answer I gave in "EDIT" above just jumps to the root folder but you will like to check intervening folders first.
Not tested but you could try a recursive regex pattern
# This will recursively swap the parent folder for "current"
# However will only work up to "/directChildOfRoot/grandChildOfRoot"
# So we will add another location block to continue to handle "direct child of root" and "root" folders
location ~ ^/(?<parent>.+)/(?<current>[^\/]+)/? {
    try_files /$current /$current/ /$current/index.php$is_args$args /$parent;
}

# This handles "direct child of root" and "root" folders
location / {
    try_files $uri $uri/ $uri/index.php$is_args$args /index.php$is_args$args;
}


text:
Q: MySQL join two tables where date between two dates I'm having a table that contains 6 columns: id (PK, A_I), systemID (varchar(32)), total (varchar(32)), difference (varchar(16)), updated (datetime), error (int).
The table is updated every hour and right now there are over 2 million records. Therefore I want to split the table up into one containing just todays values and one containing historical data. Every day at midnight data from todays table is moved to historical. So far so good.
Problem is that the user has the option to view the difference values in day view, week view, month view and year view. I don't know how to join the today table with the historical table, so they act as one. Presently the query for week view is:
SELECT difference FROM productionlog
WHERE systemID = '$id'
AND DATE(updated) BETWEEN '$weekStart' AND '$weekEnd'
ORDER BY updated

How do I join the today table with the historical table and achieve the above result?

A: Try this query,
SELECT difference FROM productionlog WHERE systemID = '$id' AND DATE(updated) BETWEEN '$weekStart' AND '$weekEnd'
UNION ALL
SELECT difference FROM productionlog_today WHERE systemID = '$id' AND DATE(updated) BETWEEN '$weekStart' AND '$weekEnd' ORDER BY updated

Also read UNION

A: As mentioned above, you've done a union and your seperate queries are returning their results in their own order. You can put the whole query into brackets, and then order the overall results:
SELECT * FROM (
    (SELECT difference, updated FROM productionlog WHERE systemID = '$id' AND DATE(updated) BETWEEN '$weekStart' AND '$weekEnd')
UNION ALL
    (SELECT difference, updated FROM productionlog_today WHERE systemID = '$id' AND DATE(updated) BETWEEN '$weekStart' AND '$weekEnd' ORDER BY updated)
) as result

ORDER BY result.updated


text:
Q: "unfair" pandas categorical.from_codes I have to assign a label to categorical data. Let us consider the iris example:
import pandas as pd
import numpy as np
from sklearn.datasets import load_iris

iris = load_iris()

print "targets: ", np.unique(iris.target)
print "targets: ", iris.target.shape
print "target_names: ", np.unique(iris.target_names)
print "target_names: ", iris.target_names.shape

It will be printed:

targets:  [0 1 2] targets:  (150L,) target_names:  ['setosa'
  'versicolor' 'virginica'] target_names:  (3L,)

In order to produce the desired labels I use pandas.Categorical.from_codes:
print pd.Categorical.from_codes(iris.target, iris.target_names)

[setosa, setosa, setosa, setosa, setosa, ..., virginica, virginica,
  virginica, virginica, virginica] Length: 150 Categories (3, object):
  [setosa, versicolor, virginica]

Let us try it on a different example:
# I define new targets
target = np.array([123,123,54,123,123,54,2,54,2])
target = np.array([1,1,3,1,1,3,2,3,2])
target_names = np.array(['paglia','gioele','papa'])
#---
print "targets: ", np.unique(target)
print "targets: ", target.shape
print "target_names: ", np.unique(target_names)
print "target_names: ", target_names.shape

If I try again to transform the categorical values in labels:
print pd.Categorical.from_codes(target, target_names)

I get the error message:

C:\Users\ianni\Anaconda2\lib\site-packages\pandas\core\categorical.pyc
  in from_codes(cls, codes, categories, ordered)
      459
      460         if len(codes) and (codes.max() >= len(categories) or codes.min() < -1):
  --> 461             raise ValueError("codes need to be between -1 and "
      462                              "len(categories)-1")
      463
ValueError: codes need to be between -1 and len(categories)-1

Do you know why?

A:
Do you know why?

If you will take a closer look at the error traceback:
In [128]: pd.Categorical.from_codes(target, target_names)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-128-c2b4f6ac2369> in <module>()
----> 1 pd.Categorical.from_codes(target, target_names)

~\Anaconda3_5.0\envs\py36\lib\site-packages\pandas\core\categorical.py in from_codes(cls, codes, categories, ordered)
    619
    620         if len(codes) and (codes.max() >= len(categories) or codes.min() < -1):
--> 621             raise ValueError("codes need to be between -1 and "
    622                              "len(categories)-1")
    623

ValueError: codes need to be between -1 and len(categories)-1

you'll see that the following condition is met:
codes.max() >= len(categories)

in your case:
In [133]: target.max() >= len(target_names)
Out[133]: True

In other words pd.Categorical.from_codes() expects codes as sequential numbers starting from 0 up to len(categories) - 1
Workaround:
In [173]: target
Out[173]: array([123, 123,  54, 123, 123,  54,   2,  54,   2])

helper dicts:
In [174]: mapping = dict(zip(np.unique(target), np.arange(len(target_names))))

In [175]: mapping
Out[175]: {2: 0, 54: 1, 123: 2}

In [176]: reverse_mapping = {v:k for k,v in mapping.items()}

In [177]: reverse_mapping
Out[177]: {0: 2, 1: 54, 2: 123}

building categorical Series:
In [178]: ser = pd.Categorical.from_codes(pd.Series(target).map(mapping), target_names)

In [179]: ser
Out[179]:
[papa, papa, gioele, papa, papa, gioele, paglia, gioele, paglia]
Categories (3, object): [paglia, gioele, papa]

reverse mapping:
In [180]: pd.Series(ser.codes).map(reverse_mapping)
Out[180]:
0    123
1    123
2     54
3    123
4    123
5     54
6      2
7     54
8      2
dtype: int64


text:
Q: Can I determine whether it is night at a location by calculating only the sun's elevation? There are many formulas for determining sunrise and sunset times for locations, but for my application I only need to know if it is day or night (given a time, latitude and longitude).
After studying the terms azimuth, altitude/elevation, and zenith, I am curious if I can calculate the sun's elevation, and use that value to determine day/night status alone.
As I understand it, any value below the horizon (taking into consideration the various values for twilight) should tell me that it is night. I should be able to use -6 for civil twilight, -12 for nautical twilight, etc.
Do I need to worry about azimuth also?

A: Yes, knowing the sun's elevation is generally enough to determine how dark it is, at least to a first approximation.
However, if you're using a simple geometric formula for the elevation, keep in mind that you may need to adjust it for atmospheric refraction.  Wikipedia's sunrise article has a pretty nice explanation of this:

"Sunrise occurs before the Sun actually reaches the horizon because the Sun's image is refracted by the Earth's atmosphere. The average amount of refraction is 34 arcminutes, though this amount varies based on atmospheric conditions.
Also, unlike most other solar measurements, sunrise occurs when the Sun's upper limb, rather than its center, appears to cross the horizon. The apparent radius of the Sun at the horizon is 16 arcminutes.
These two angles combine to define sunrise to occur when the Sun's center is 50 arcminutes below the horizon, or 90.83° from the zenith."

In general, if you're just comparing the elevation to some fixed threshold, it's enough to adjust the threshold to account for this.

A: All you need is altitude. Azimuth is strictly what compass heading to look toward to hunt for the Sun.


text:
Q: How do I set secure `_cfuid` cookies in Rails 5 how do I enable the secure flag for the _cfuid cookie in Rails 5?
I've already added config.force_ssl = true in production.rb, my app is served with a valid ssl certificate from Heroku, and the Mozilla Observatory gives my app a security score of 'A'
But when I try checking out the site in Postman I get this:

A: This cookie is set by CloudFlare and has nothing to do with rails:
Read about the cookie here. Updating the question to clarify.


text:
Q: What does the notation "$x_{\cdot n}$" mean? I'm currently taking a first course in abstract algebra (group theory), and came across this in a problem:

Let $n$ be a positive integer. Prove that $(x_{\cdot n}y_{\cdot n})z = x_{\cdot n}(y_{\cdot n}z)$ for all $x,y,z \in \mathbb{Z}$

Now I get that it's proving associativity, but I haven't a clue about what $x_{\cdot n}$ means.. Can anyone educate me?

A: Probably $x_{\cdot n}$ means $\underbrace{\left(\left(\ldots\left(x\cdot x\right)\ldots\right)\cdot x\right) \cdot x}_{\text{$n$ times}}$ with $x$ multiplied by itself $n$ times.

A: Apparently:

$${x_{\cdot n} y} = {xy\bmod n}$$


text:
Q: Цикл выдает на одну строку меньше Данная конструкция выдает на один пост меньше при подзагрузке. Сразу на index.php загружается первые 5 постов, потом через ajax догружаются еще. AJAX обращается к action.php Получается что-то вроде header24, header23, header22, header21, header20 загружаются сразу (при открытии страницы), при нажатии на кнопку "Загрузить еще" загружаются посты header18, header17, header16, header15. Куда пропадает header19?
index.php
action.php
Проверить, как работает можно здесь

A: Потому что у вас не правильная пагинация. Offset в MySQL должен принимать значение равное (количеству показанных записей - 1).
Добавьте в actions.php -1 при инициализации переменной $num:
$num = (int) $_GET['num'] - 1;


text:
Q: Why is Outlook application.Session null? application.Session is null but should have an object, and does for other users on the same machine.
When trying to access Globals.ThisAddIn.outlookApplication.Session I get a NullReferenceException on application.Session.
Redemption.RDOSession session = Redemption.RedemptionLoader.new_RDOSession();
session.MAPIOBJECT = Globals.ThisAddIn.outlookApplication.Session.MAPIOBJECT;

The same add-in works for other users on the same machine. This callback is hit from a click event on a ribbon button in Outlook. The user has a logged in session with Exchange and can interact with Exchange server normally.

A: This issue ended up being a corrupt user.settings file.


text:
Q: Different toolbar for each fragment or change Scroll Behaviour in new Coordinator Layout? I implemented the Navigation Drawer by using the template provided by Google in New Android Studio 1.4. Here it automatically created everything including the layout and class.
This is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:fitsSystemWindows="true" tools:openDrawer="start">

    <include layout="@layout/app_bar_main" android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView android:id="@+id/nav_view"
        android:layout_width="wrap_content" android:layout_height="match_parent"
        android:layout_gravity="start" android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main" app:menu="@menu/activity_main_drawer" />

</android.support.v4.widget.DrawerLayout>

app_bar_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:fitsSystemWindows="true"
    app:layout_scrollFlags="scroll|exitUntilCollapsed"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout android:layout_height="wrap_content"
        android:layout_width="match_parent" android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar android:id="@+id/toolbar"
            android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <RelativeLayout  android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:showIn="@layout/app_bar_main"
        app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed"
        tools:context=".MainActivity">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/frame_container">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Hell World"/>

        </FrameLayout>

    </RelativeLayout>

</android.support.design.widget.CoordinatorLayout>

You could see fragment_container above. I simply replace this with different fragment based on item click in the Navigation drawer.
There's no issue in this too.
 UpdatesFragment fragment = new UpdatesFragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.frame_container,fragment);
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();

Now, I would to have a different toolbar for each fragment. How could i get the different toolbar for each fragment in this new CoordinatorLayout?
Or, I mean I would like to have a different Scroll Behavior for each fragment. How can i achieve this


text:
Q: How to get object in WebGL 3d space from a mouse click coordinate I'm building a boardgame in WebGL. The board can be rotated/zoomed. I need a way to translate a click on the canvas element (x,y) into the relevant point in 3D space (x, y, z). The ultimate result is that I want to know the (x, y, z) coordinate that contains the point that touches the object closest to the user. For instance, the user clicks a piece, and you imagine a ray traveling through 3D space that goes through both the piece and the game board, but I want the (x, y, z) coord of the piece at the point where it was touched.
I feel like this must be a very common problem, but I can't seem to find a solution in my googles. There must be some way to project the current view of the 3D space into 2D so you can map each point in 2D space to the relevant point in 3D space. I want to the user to be able to mouse over a space on the board, and have the spot change color.

A: You're looking for an unproject function, which converts screen coordinates into a ray cast from the camera position into the 3D world. You must then perform ray/triangle intersection tests to find the closest triangle to the camera which also intersects the ray.
I have an example of unprojecting available at jax/camera.js#L568 -- but you'll still need to implement ray/triangle intersection. I have an implementation of that at jax/triangle.js#L113.
There is a simpler and (usually) faster alternative, however, called 'picking'. Use this if you want to select an entire object (for instance, a chess piece), and if you don't care about where the mouse actually clicked. The WebGL way to do this is to render the entire scene in various shades of blue (the blue is a key, while red and green are used for unique IDs of the objects in the scene) to a texture, then read back a pixel from that texture. Decoding the RGB into the object's ID will give you the object that was clicked. Again, I've implemented this and it's available at jax/world.js#L82. (See also lines 146, 162, 175.)
Both approaches have pros and cons (discussed here and in some of the comments after) and you'll need to figure out which approach best serves your needs. Picking is slower with huge scenes, but unprojecting in pure JS is extremely slow (since JS itself isn't all that fast) so my best recommendation would be to experiment with both.
FYI, you could also look at the GLU project and unproject code, which I based my code loosely upon: http://www.opengl.org/wiki/GluProject_and_gluUnProject_code

A: I'm working on this problem at the moment - the approach I'm taking is

*

*Render objects to pick buffer each with unique colour

*Read buffer pixel, map back to picked object

*Render picked object to buffer with each pixel colour a function of Z-depth

*Read buffer pixel, map back to Z-depth

*We have picked object and approximate Z for the pick coords

A: This is the working demo
function onMouseUp(event) {

    event.preventDefault();
    x_pos = (event.clientX / window.innerWidth) * 2 - 1;
    y_pos = -(event.clientY / window.innerHeight) * 2 + 1;
    z_pos = 0.5;

    var vector = new THREE.Vector3( x_pos , y_pos , z_pos );

    var projector = new THREE.Projector();
    projector.unprojectVector(vector, camera);
    var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize());
    var intersects = raycaster.intersectObjects(intersectObjects);

    if (intersects.length > 0) {

        xp = intersects[0].point.x.toFixed(2);
        yp = intersects[0].point.y.toFixed(2);
        zp = intersects[0].point.z.toFixed(2);
        destination = new THREE.Vector3( xp , yp , zp );

        radians =  Math.atan2( ( driller.position.x - xp) , (driller.position.z - zp));
        radians += 90 * (Math.PI / 180);
        console.log(radians);

        var tween = new TWEEN.Tween(driller.rotation).to({ y : radians },200).easing(TWEEN.Easing.Linear.None).start();

    }

weissner-doors.de/drone/

A: culted from one of the threads.
not sure about (x,y,z) but you can get the canvas(x,y) using

getBoundingClientRect()

function getCanvasCoord(){
  var mx = event.clientX;
  var my = event.clientY;
  var canvas = document.getElementById('canvasId');
  var rect = canvas.getBoundingClientRect();// check if your browser supports this
  mx = mx - rect.left;
  my = my - rect.top;
  return {x: mx , y: my};
}


text:
Q: NSXMLParser crashing when calling abortParsing from within delegate I have an NSXMLParser object+delegate inside the main of an NSOperation. The NSXMLParser delegate checks before executing each of its callbacks if a BOOL cancel; variable is set. If it is set it calls [parser abortParsing] and returns immediately.
What happens however is as soon as the return is executed my app crashes with an illegal memory access.
Here is the call stack for the crash:
#0  0x00080030 in -[MGTwitterHTTPURLConnection data] at .../Twitter/Twitter+OAuth/MGTwitterEngine/MGTwitterHTTPURLConnection.m:69
#1  0x35432808 in nodePush ()
#2  0x3543eb5a in xmlParseChunk ()
#3  0x3464ed64 in -[NSXMLParser parse] ()
#4  0x000510e2 in -[ItemTableParser parse:] ()

and the locals:
self    MGTwitterHTTPURLConnection *    0x0
_cmd    SEL 0x518fbf0

That Twitter stuff you see has NO relation whatsoever with the code I am running. It is just a random piece of memory where it crashes. I don't use any Twitter code whatsoever. The .m files are just there in my project and compiled.
Here a piece of code of one of the delegate methods:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
    if ( self.cancel )
    {
        [parser abortParsing];
        return;
    }  .....

Here the code where the parser is created and called
-(NSArray *)parse:(NSData *)data
{
    NSXMLParser * parser = [[NSXMLParser alloc]initWithData:data];
    [parser setDelegate:self];

    [parser parse];
    [parser release];
    parser = nil;
    return resultTable;
}

*

*What am I doing wrong?

*Is there a better way of stopping an NSXMLParser?

Thanks

A: By running [parser abortParsing] you only force the [parser parse] function to stop. Maybe you are trying to access the data in any way afterwards? It's hard to help you without seeing any code.

A: Seems like the data you provide for parsing is corrupted - maybe is already released

A: @Joris Mans NSXMLParser is now threadsafe. However, it is not reentrant on a given thread; don't call -parse or -abortParsing on an NSXMLParser from within a delegate callback of another NSXMLParser. So you have another way to call abortParsing method like this...Hope it helps you!
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
if ( self.cancel )
{
    dispatch_queue_t reentrantAvoidanceQueue = dispatch_queue_create("reentrantAvoidanceQueue", DISPATCH_QUEUE_SERIAL);
    dispatch_async(reentrantAvoidanceQueue, ^{
        [parser abortParsing];
    });
    dispatch_sync(reentrantAvoidanceQueue, ^{ });
    return;
}  .....


text:
Q: php redirect previous TWICE I have looked around on the web and have found a code to redirect previous ONCE, but I would like to redirect previous twice?
Is there a special function to do this?

A: The best way to do this would be via JavaScript.
<script>window.history.go(-2);</script>

Doing it via PHP would be tricky, as you'd have to keep track of the user's successive HTTP_REFERER values in a session or cookie or something, which'd be glitchy if the user had multiple tabs open on your site.


text:
Q: JS FB:Wall not working Im trying to integrate a facebook wall on my .net powered website using the following plugin.
http://www.neosmart.de/social-media/facebook-wall
Ive tried the following and nothing seems to be working, all the scripts are in the correct location and I cant seem to find a problem.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="facebook.aspx.cs" Inherits="facebook" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Facebook</title>

    <link href="_includes/css/jquery.neosmart.fb.wall.css" rel="stylesheet" type="text/css" />

hello

A: You might use the $(document).ready(function(){//your FB.wall code//}); this is the DOM-thing to make the code run when page is ready.


text:
Q: Update node folder I have a node modules folder called "mynode" which have several functions that I need to use for my node project.
in the package.json , I have it as dependencies such as
   "dependencies": {
       "mynode": "file:mynode"
    }

Now I add more functions into mynode folder, I seem can't use the new functions which I just add. It keep give me the error such as
     TypeError: myfunction.funcA is not a function

I dont know how can I make funcA available so that it can run in the project?
I tried to run
   npm install

to update the package.json but I still have the TypeError ... is no a function

A: If I understand correctly, You should module.exports your functions in a .js file, and then You should require it in the file, that you need it for.
there is no need to modify package.json.
Check this out:
https://www.sitepoint.com/understanding-module-exports-exports-node-js/


text:
Q: Java ArrayList, how to ignore a value from the object when using contains() I have a class like that:
public class Student implements Serializable{
  private String name;
  private int age;
  private Image img;
}

I store a few students in an ArrayList and write them to a file. When I restart the application I load them from that file again. However, the Image img variable is constantly changing. That means when I use arrayList.contains(studentA) it's not the same object anymore, so arrayList.remove(studentA) won't work.
Is there an easy way to either: Only check for the name of the student or ignore the Image field when using contains()?

A: Yes.
Just implement the equals/hashcode without the Image attribute.
public class Student implements Serializable {

    private String name;
    private int age;
    private Image img;

    @Override
    public boolean equals(final Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return age == student.age &&
                Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {

        return Objects.hash(name, age);
    }

}

A: Use JAVA Stream API for fun with lists without contains()
public static void main(String[] args) {
        List<Student> studentBaseList = Arrays.asList(
                new Student("Kent", 22, null),
                new Student("Jack", 25, null),
                new Student("Rick", 27, null)
        );

        List<Student> studentList = new ArrayList<>(studentBaseList);
        String NAME_FOR_SEARCH  = "Jack";

        // Remove student with name Jack from studentList
        studentList.removeIf( student -> NAME_FOR_SEARCH.equals(student.getName()));
        System.out.println(studentList);

        List<Student> studentList2 = new ArrayList<>(studentBaseList);
        // Check if student with name Jack present in the list
        boolean isPresentStudentWithNameJack
                = studentList2.stream().anyMatch(student -> NAME_FOR_SEARCH.equals(student.getName()));
        System.out.println(isPresentStudentWithNameJack);

        List<Student> studentList3 = new ArrayList<>(studentBaseList);
        // Filter students with name Jack and create new list with students with name Jack.
        List<Student> onlyJackStudents = studentList3.stream()
                .filter(student -> NAME_FOR_SEARCH.equals(student.getName())).collect(Collectors.toList());
        System.out.println(onlyJackStudents);
    }


text:
Q: Password shows in plain text using Jenkins credentials plugin I am trying to use Jenkins Credentials plugin to get user input and make use of it in Jenkinsfile for processing. Since the password field is highly sensitive, I was hoping credentials plugin would mask the password from displaying in the console output. However seems like password is displayed in plain text. I noticed an existing issue https://issues.jenkins-ci.org/browse/JENKINS-38181 that talks about echo statements outside of withCredentials block displays passwords in plain text, which is expected. But in my case, even echo statements inside withCredentials block is displayed plain.
Am i doing something wrong here? Should I just refrain from using echo?
Credentials Binding Plugin: 1.12
Credentials Plugin: 2.1.16
 node('someagent') {
    stage 'input'
    def userNameInput = input(
        id: 'UserName', message: 'input your username: ', ok: 'ok', parameters: [string(defaultValue: 'user', description: '.....', name: 'DB_USER')]
    )
    def userPasswordInput = input(
        id: 'Password', message: 'input your password: ', ok: 'ok', parameters: [string(defaultValue: 'password', description: '.....', name: 'DB_PASS')]
    )
    withCredentials(bindings: [usernamePassword(credentialsId: 'CREDS', usernameVariable: userNameInput, variable: userPasswordInput)]) {
     echo ("My Username: ${userNameInput}")
     echo ("My Password: ${userPasswordInput}")
    }
}

Console Output:
[Pipeline] {
[Pipeline] stage (input)
Using the 'stage' step without a block argument is deprecated
Entering stage input
Proceeding
[Pipeline] input
Input requested
Approved by UserId
[Pipeline] input
Input requested
Approved by UserId
[Pipeline] withCredentials
[Pipeline] {
[Pipeline] echo
My Username: user
[Pipeline] echo
My Password: password
[Pipeline] }
[Pipeline] // withCredentials
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

A: You don't understand the withCredentials usage correctly. When use withCredentials, means the credential had been added into Jenkins, withCredentials can extract the user and password value into Shell variables, then you can use them by refer the shell variables.
So there is no way to extract the user and password into your pre-defined Groovy variable.
The correct usage of withCredentials:
withCredentials([usernamePassword(
    credentialsId: 'CREDS', // the CREDS should be exist in Jenkins
    passwordVariable: 'pwd', // you need to use a string, not a Groovy variable
    usernameVariable: 'user') // you need to use a string, not a Groovy variable
]) {
    sh '''
    echo UserName: ${user} // the user and pwd injected into Shell Context as Environment variable
    echo Password: ${pwd} // will show as *** in jenkins console
    '''

    // If you user `"` or `"""` to wrapper a string,
    // Groovy will execute string substitution with Groovy variable if
    // same name variable exist in Groovy Context
    // otherwise the string keep nothing change

    sh """
     echo ${user}
     echo ${pwd}  // will show as *** in jenkins console
    """
    // because the user and pwd not exist Groovy context
    // so substitution will fail and the string keep no change
    // then execute the string in Shell by sh(),
    // the user and pwd can be found in Shell context
}

Actually your below code will execute string substitution by Groovy firstly.
This why you see the password show in plain text in jenkins console
 echo ("My Username: ${userNameInput}")
 echo ("My Password: ${userPasswordInput}")

 // because userNameInput and userPasswordInput exist in Groovy variables,
 // so the ${userNameInput} and ${userPasswordInput} will be replaced to
 // the value of Groovy variables before echo, as result ${userNameInput}
 // and ${userPasswordInput} used variable from Groovy, rather then from Shell


text:
Q: Is there a way to override the label and help text on a FieldPanel? I'd like to change the help text and the label for some of the Page fields in the admin interface. It seems like normally the FieldPanel picks up the label and help text from the model field, but since I'm wanting to change these values for fields on the Page model (title and search_description, specifically), I can't set verbose_name and help_text on the field itself
I tried passing in the heading and help_text keyword arguments to FieldPanel, but I'm still seeing the default label and help text in the admin interface.
class MyPage(Page):
    content_panels = [
        FieldPanel('title', heading='Name', classname='full'),
        FieldPanel('search_description', heading='Description',
                   classname='full',
                   help_text='Description used in indices and search results')
    ]

A: There is a way to overwrite the default help_text and label (called verbose_name) on a per-field basis.
MyPage._meta.get_field("title").help_text = "Help me Obi-Wan, you're my only help_text"
MyPage._meta.get_field("title").verbose_name = "Jedi Labelling"

There's this method. And then there's also the MultiFieldPanel's heading which Dan Swain had covered nicely in his answer.
And if all that doesn't quite work, there's always the Wagtail HelpPanel. More on that in the docs at http://docs.wagtail.io/en/v2.6.1/reference/pages/panels.html#helppanel
I've also created a YouTube video around this subject if you prefer to learn from videos.
Hope this helps!

A: I don't know of an easy way to add help text directly to an individual field, but you could wrap the fields in a MultiFieldPanel and put a heading on it:
class MyPage(Page):
    content_panels = [
        MultiFieldPanel([
            FieldPanel('title', heading='Name', classname='full'),
            FieldPanel('search_description', heading='Description',
                       classname='full',
                       help_text='Description used in indices and search results')
        ], heading="your help text")
    ]

In wagtail.core.models.py you will see:
from django.utils.translation import ugettext_lazy as _

class Page(AbstractPage, index.Indexed, ClusterableModel, metaclass=PageBase):
    title = models.CharField(
        verbose_name=_('title'),
        max_length=255,
        help_text=_("The page title as you'd like it to be seen by the public")
    )

Since Page is not an abstract class, you can't override its fields in your own Page-based classes even if you try to redefine title.  Also, notice the import of ugettext_lazy as _ and then the _('title') in the verbose_name declaration.  This answer explains that this code is getting the translated version of the title's verbose_name.

A: A suggestion from @KalobTaulien in the Wagtail Slack that seems to do the trick:
class MyPage(Page):
    pass

MyPage._meta.get_field('title').verbose_name = 'name'
MyPage._meta.get_field('search_description').help_text = 'Description used in indices and search results'


text:
Q: Reference Request- Summary of Common Loss Functions and their derivatives? I am creating a summary for my course (and in general for further studies) and I would like to include a part with a general summary over the most common loss functions and their derivatives (if they exist).
I wasn't able to find anything online and most textbooks scatter them throughout so that I am afraid to miss a few.
Any resources you can share are appreciated, thank you!

A: A good review article for deep learning: On Loss Functions for Deep Neural Networks in Classification and Normalized Loss Functions for Deep Learning with Noisy Labels.
As deep learning libraries tend to be more modular on this, checking what tensorflow/keras and pytorch supports from their documentation would also help to list loss functions and relevant references they cite.


text:
Q: AWS OpenVPN to connect Multi Region VPCs I followed the video tutorial here and as far as I can see everything is set up correctly.
When I run
ipsec status

it tells me that there are two established tunnels and in the AWS dashboard it also describes both tunnels as being UP.
I've tried using
nmap -Pn xxx.xxx.xxx.xxx

using the internal IP of the server in the VPC I want to connect to but it never successes.
Is there a better way of testing or do I have to use a different IP to force the connection to use the VPN rather than trying directly to access that IP address? I also feel like there's a chance I setup the VPN in the wrong direction so I have tested both ways using nmap with no luck.


text:
Q: как сделать так что бы при нажатии на кнопку персонаж прыгал? написал код о самом прыжке и на проверку есть ли под ногами земля.
на сам спрайт повесил button кинул своего перса и метод на прыжок в спрайт, однако ничего неработает, я знаю что нужно написать функцию о том что при нажатии на кнопку перс должен прыгать, но незнаю как
сцена:
скрипт:

A: Если это код из какого-то урока, то я не советую его смотреть дальше, а найти замену. Официальный курс от Unity подойдет лучше, чем другие.
Во-первых, вы пытаетесь определить столкновение с объектом, вызывая метод OnJumpButton в Update. Но ведь OnJumpButton должен вызываться только, когда кнопка прыжка нажата.
Во-вторых, вы при передвижении персонажа двигаете его через transform, а при прыжке через Rigidbody. Так делать не следует, используйте что-то одно(Rigidbody).
В-третьих, про метод AddForce можете забыть, он не нужен для перемещения персонажа.
Далее покажу и расскажу как сделать все правильнее.
using UnityEngine;

[RequireComponent(typeof(Rigidbody2D))]
public class Hero : MonoBehaviour
{
    [SerializeField] private Vector2 _jumpVelocity; // Ускорение при прыжке
    [SerializeField] private float _runSpeed; // скорость персонажа
    private bool _isGrounded = false;
    private Rigidbody2D _rb;

    private void Awake()
    {
        _rb = GetComponent<Rigidbody2D>();
    }

    private void Update()
    {
        var horizontal = Input.GetAxis("Horizontal");
        Run(horizontal);
    }

    private void OnCollisionStay2D(Collision2D collision)
    {
        foreach(var i in collision.contacts)
        {
            if (i.normal.y > 0.8)
            {
                _isGrounded = true;
                break;
            }
        }
    }

    private void OnCollisionExit2D(Collision2D collision)
    {
        _isGrounded = false;
    }

    public void Jump()
    {
        if (_isGrounded)
        {
            _rb.velocity += _jumpVelocity;
        }
    }

    private void Run(float direction)
    {
        if (direction == 0) return;
        if (_isGrounded == false) return;

        var velocity = _rb.velocity;
        velocity.x = _runSpeed * direction;
        _rb.velocity = velocity;
    }

}

По-порядку:
[RequireComponent(typeof(Rigidbody2D))] нужно для того, чтобы на скрипте в любом случае был компонент Rigidbody2D. Если этого компонента не будет, то он автоматически добавится.
[SerializeField] Этот атрибут нужен для того, чтобы видеть приватные поля в инспекторе и иметь возможность их менять.
_rb = GetComponent<Rigidbody2D>(); Здесь получаем компонент RigidBody, который навешан на объект. Обязательно делайте [RequireComponent(typeof(ТипКомпонента))], если получаете его через GetComponent.
В апдейте мы получаем значения горизонтальной оси и вызываем метод Run().
OnCollisionStay2D вызывается, пока есть столкновение с каким-либо коллайдером. Здесь мы в цикле проходим все точки соприкосновения и, если нормаль этой точки проходит через ограничение, то присваиваем значение true полю _isGrounded. Что такое нормаль, можете загуглить.
OnCollisionExit2D вызывается, когда объекты перестают соприкосаться. Здесь просто меняет _isGrounded на false.
Jump здесь все просто. Если персонаж на земле, то добавляем к ускорению значение поля _jumpVelocity. Не забудьте указать значение для этого поля в инспекторе. На кнопку прыжка этот метод навешивается точно так же, как и ваш.
Run(float direction) здесь все тоже предельно просто. Не делаем ничего, если направление равно нулю и персонаж в воздухе. В ином случае берем то, что указано в поле _runSpeed и умножаем на направление движения (Если direction будет отрицательным, то движение будет в противоположную сторону), далее просто присваиваем это все ускорению персонажа по оси X.
Ну и, естественно, на персонаже должен висеть компонент Rigidbody2D и любой коллайдер, а на земле просто коллайдер.
Как поворачивать спрайт, думаю сами разберетесь.


text:
Q: SIGSEGV/SEGV_ACCERR causes crash in GPUImage framework iOS I was getting the SIGSEGV/SEGV_ACCERR crash report from crittercism tool integrated in my app, this was because of taking a video capturing and leaving the app in sleep mode for 15-20 minutes after coming back from sleep mode the app crashed, this is blocker issue in my case .Please suggest the solution, thanks in advance
The following shows the sample code used:
GPUImageiOSBlurFilter   * blurFilterObj = [[GPUImageiOSBlurFilter alloc] init];
    blurFilterObj.blurRadiusInPixels = 4.5f ;
    blurFilterObj.downsampling = 2.5f ;
    blurFilterObj.saturation = 1.0f;

GPUImageVideoCamera  *liveVideo = [[GPUImageVideoCamera alloc] initWithSessionPreset:AVCaptureSessionPresetMedium cameraPosition:AVCaptureDevicePositionFront];
    liveVideo.outputImageOrientation = UIInterfaceOrientationPortrait;
    liveVideo.horizontallyMirrorFrontFacingCamera = YES ;

    //Add Targets to live video
    [liveVideo addTarget:blurView];
   [liveVideo addTarget:blurFilterObj];
 [blurFilterObj addTarget:blurView];

   CSBlurView  *blurView = [[CSBlurView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    [self.view addSubview:blurView];

GPUImageVideoCamera  *liveVideo = [[GPUImageVideoCamera alloc] initWithSessionPreset:AVCaptureSessionPresetMedium cameraPosition:AVCaptureDevicePositionFront];
    liveVideo.outputImageOrientation = UIInterfaceOrientationPortrait;
    liveVideo.horizontallyMirrorFrontFacingCamera = YES ;

    //Add Targets to live video
    [liveVideo addTarget:blurView];
   [liveVideo addTarget:blurFilterObj];
 [blurFilterObj addTarget:blurView];

The following represents the crash report
libGPUSupportMercury.dylib 0x322d48f6 gpus_ReturnNotPermittedKillClient + 1
IMGSGX543GLDriver 0x2c7e282d SubmitPackets + 125
GLEngine 0x2fc44c3d gliPresentViewES + 17
OpenGLES 0x2fc4f139 -[EAGLContext presentRenderbuffer:] + 65
0x0006f2a3 -[GPUImageContext presentBufferForDisplay] (GPUImageContext.m:196)
0x00074a75 -[GPUImageView presentFramebuffer] (GPUImageView.m:220)
0x0004e23d runSynchronouslyOnVideoProcessingQueue (GPUImageOutput.m:27
0x00074cdd -[GPUImageView newFrameReadyAtTime:atIndex:] (GPUImageView.m:385)
0x0002096f -[GPUImageVideoCamera      updateTargetsForVideoCameraUsingCacheTextureAtWidth:height:time:] (GPUImageVideoCamera.m:640)
0x00020ceb -[GPUImageVideoCamera processVideoSampleBuffer:] (GPUImageVideoCamera.m:738)
0x000216bf __74-[GPUImageVideoCamera  captureOutput:didOutputSampleBuffer:fromConnection:]_block_invoke  (GPUImageVideoCamera.m:966)
libdispatch.dylib 0x38246d1b _dispatch_call_block_and_release + 11
libdispatch.dylib 0x3824d273 _dispatch_queue_drain$VARIANT$mp + 375
libdispatch.dylib 0x3824d06b _dispatch_queue_invoke$VARIANT$mp + 43
libdispatch.dylib 0x3824dce1 _dispatch_root_queue_drain + 77
libdispatch.dylib 0x3824df59 _dispatch_worker_thread2 + 57
libsystem_pthread.dylib 0x38388dbf _pthread_wqthread + 299
libsystem_pthread.dylib 0x38388c84 start_wqthread + 8

A: I got the solution from BradLarson who develops the GPUImage filters api,he responded from the github resource. When we use the gpuimagevideocamera its always renders the opengl so when it goes to background mode or sleep mode also rendering the opengl then crash will happen so, before app moves to the background stop the camera capture and remove the filters added to the camera and picturewriter it solves the problem. Thank you


text:
Q: Как запустить python скрипт записанный в переменную Всем привет. У меня есть переменная с python скриптом:
Script=(
'''
Hello="Hello, world"
print(Hello)
'''
)

И мне нужно запустить этот скрипт в этом файле, а не записывать его в другой файл и вызывать с помощью:
import os
os.startfile("имя файла")

A: Для того что бы перевести строку в "cкрипт" используйте exec(). Например:
Script=(
'''
Hello="Hello, world"
print(Hello)
'''
)
exec(Script) #Hello, world

Это работает отлично но имеет проблемы с безопасностью, например если вы получаете строку от пользователя.


text:
Q: SharePoint 2010 change list permission I have a list contained in an SPWeb and when the web is provisioned an event receiver change the list permissions by using this code:
[...]
SPList theList = web.Lists[listName];
theList.BreakRoleInheritance(false);
SPGroup group = web.Groups["MyGroup"];
SPRoleAssignment ra = new SPRoleAssignment(group);
SPRoleDefinition roleDef = web.RoleDefinitions.GetByType(SPRoleType.Contributor);
ra.RoleDefinitionBindings.Add(roleDef);
list.RoleAssignments.Add(ra);
list.Update();

Later in the workflow I need to change the permission for the group to be Reader instead of Contributor. I have used the following code
SPList theList = web.Lists[listName];
foreach (SPRoleAssignment assignment in theList.RoleAssignments) {
    if (assignment.Member.Name == "MyGroup") {
        assignment.RoleDefinitionBindings.RemoveAll();
        SPRoleDefinition rda = web.RoleDefinitions.GetByType(SPRoleType.Reader);
        assignment.RoleDefinitionBindings.Add(rda);
    }
}

However this code is not working and does not change the permission on the list.
Could anybody help on understanding which is the right method to change permission for an existing principal?
Thanks

A: You need to do a theList.Update() after your foreach statement.


text:
Q: R: transposing and aggregating columns I have this dataframe with v1 as names of categories and v2 as items.

I need to aggregate v1 so fruit will appear only once, and all items in v2 will be transposed and placed in together in a single cell separated by comma.

Any assistance will be appreciated :)

A: You can easily do it using transpose in aggregate function.

dt<-aggregate(v2~v1,data=dt,fun=t)

However you will have some unwanted text in the rolled up string which you can easily removed using gsub function

dt$v2<-gsub("[c()]","",dt$v2))


text:
Q: Jquery calculating bouding box of a rotated rectangle I've already looked at some other posts about that but still can't figure out why the formula isn't working.
To calculate the bounding box of a rotated rectangle :
w' = sin(a)*h + cos(a)*w;
h' = sin(a)*w + cos(a)*h;

The problem is that I'm getting weird behaviours where w' and h' are not precise at all.

// calculate rotation angle of shape
function getRotationDegrees(obj) {
  var matrix = obj.css("-webkit-transform") ||
    obj.css("-moz-transform") ||
    obj.css("-ms-transform") ||
    obj.css("-o-transform") ||
    obj.css("transform");
  if (matrix !== 'none') {
    var values = matrix.split('(')[1].split(')')[0].split(',');
    var a = values[0];
    var b = values[1];
    var angle = Math.round(Math.atan2(b, a) * (180 / Math.PI));
  } else {
    var angle = 0;
  }

  if (angle < 0) angle += 360;
  return angle;
}

var shape = $('.shape'),
  shapeLeft = shape.position().left,
  shapeTop = shape.position().top,
  shapeWidth = shape.width(),
  shapeHeight = shape.height(),
  angle = getRotationDegrees(shape),
  // formula below
  height = Math.abs(shapeWidth * Math.sin(angle)) + Math.abs(shapeHeight * Math.cos(angle)),
  width = Math.abs(shapeHeight * Math.sin(angle)) + Math.abs(shapeWidth * Math.cos(angle));

$('#g1').css('width', width);
$('#g2').css('height', height);
.elements,
.element {
  position: absolute
}

#s2 {
  background: #333333;
  top: 60px;
  left: -25px;
  width: 300px;
  height: 100px;
}

What am I doing wrong ?

A: Two sources of error:

*

*(Minor) Rounding of the angle. (Don't know what you meant by "already a round number")

*(Major) You use the result of getRotationDegrees directly in Math.cos / sin. These functions require radians, i.e. the result directly returned by Math.atan2.

The snippet below adds the other two edges of the bounding box, and also the correct positional offset. I added a slider to change the rotation angle, in order to illustrate that this code is robust.

function getMatrix(obj) {
   var matrix = obj.css("-webkit-transform") ||
                obj.css("-moz-transform") ||
                obj.css("-ms-transform") ||
                obj.css("-o-transform") ||
                obj.css("transform");
   return (matrix == 'none') ? null : matrix.split('(')[1].split(')')[0].split(',');
}

// calculate rotation angle of shape
function getRotationRadians(matrix) {
   var angle = matrix ? Math.atan2(matrix[1], matrix[0]) : 0;
   if (angle < 0) angle += 2.0 * Math.PI;
   return angle;
}

// calculate translation
function getTranslation(matrix) {
   return matrix ? [matrix[4], matrix[5]] : [0, 0];
}

// calculate bounding box
function getBoundingBox(shape) {
   var shapeLeft = shape.position().left,
       shapeTop = shape.position().top,
       shapeWidth = shape.width(),
       shapeHeight = shape.height();

   var matrix = getMatrix(shape);

   var angle = getRotationRadians(matrix);
   var height = Math.abs(shapeWidth * Math.sin(angle)) + Math.abs(shapeHeight * Math.cos(angle));
   var width = Math.abs(shapeHeight * Math.sin(angle)) + Math.abs(shapeWidth * Math.cos(angle));

   var trans = getTranslation(matrix);
   var left = trans[0] - (width * 0.5);
   var top = trans[1] - (height * 0.5);

   return {'x': left, 'y': top, 'w': width, 'h': height};
}

formatBox($('.shape'));

function formatBox(shape) {
   var box = getBoundingBox(shape);

   var offx = 124, offy = 109;

   var g1 = $('#g1'), g2 = $('#g2'), g3 = $('#g3'), g4 = $('#g4');

   g1.css('width', box.w);
   g2.css('height', box.h);
   g3.css('width', box.w);
   g4.css('height', box.h);

   g1.css('left', offx + box.x);
   g2.css('left', offx + box.x);
   g3.css('left', offx + box.x);
   g4.css('left', offx + box.x + box.w);

   g1.css('top', offy + box.y);
   g2.css('top', offy + box.y);
   g3.css('top', offy + box.y + box.h);
   g4.css('top', offy + box.y);
}

var angleInp = document.getElementById("angleInp");
angleInp.addEventListener("change", function() {
   var shape = $('.shape');
   shape.css('transform', 'rotate(' + angleInp.value + 'deg)');
   formatBox(shape);
}, false);
.elements,
.element {
  position: absolute
}

#s2 {
  background: #333333;
  top: 60px;
  left: -25px;
  width: 300px;
  height: 100px;
}

   <input class="bar" type="range" id="angleInp" min="0" max="360" value="15" onchange="angleInp.value=value"/>


text:
Q: Cassandra tpstats and tuning On a six node Cassandra cluster [replication factor 2], we notice a single node being hotspotted [heavy load]. When Looking at tpstats, I could see that Flush writer and Replicate on write stages were having tasks that are all time blocked.
We have only one data directory [hence have configured cassandra to use only one flushwriter] and Queue size of memtable flush is 2
Heavily Loaded Node
Replicate-on-write-stage    32  4128    599249  48  371304
Flush-writer    0   0   85  0   24

Normal Node:
ReplicateOnWriteStage  0         0         753665         0      0
FlushWriter            0         0            137         0      25

Configuration of all the nodes are exactly the same and we use Murmur Partitioner.
Is there some other stats that I could refer to, to track down the CPU load issue and replicate on write stage blocked on single node?
Are these counters in tpstats a historical counter or do they refresh every N min?
From here it is mentioned that block can either because of IO not keeping or Huge rows and sorting [this increases cpu load]. Could the latter be the reason for unusual load in the one node out of entire cluster?

A: Increasing your heap size should be the solution. In your logs, if you were to see long GC times being posted, GC pause times could be the culprit.
Could you also post your logs, so that we could find a better solution.