Q:

Using the stix font for \mathcal and \mathscr only

How do I limit the stix font package to only affect certain symbols? In my case I want to only change the font associated to \mathcal{} and \mathscr{}.

A:

One has to go to stix.sty and extract the relevant information:
\documentclass{article}
\usepackage{amsmath}

\makeatletter
\DeclareFontEncoding{LS1}{}{}
\DeclareFontEncoding{LS2}{}{\noaccents@}
\DeclareFontSubstitution{LS1}{stix}{m}{n}
\DeclareFontSubstitution{LS2}{stix}{m}{n}
\makeatother

\DeclareMathAlphabet\mathscr{LS1}{stixscr}{m}{n}
\SetMathAlphabet\mathscr{bold}{LS1}{stixscr}{b}{n}
\DeclareMathAlphabet\mathcal{LS2}{stixcal}{m}{n}
\SetMathAlphabet\mathcal{bold}{LS2}{stixcal}{b}{n}

\begin{document}

This is \verb|\mathscr|: $\mathscr{A}\mathscr{B}$

This is \verb|\mathcal|: $\mathcal{A}\mathcal{B}$

\boldmath

This is \verb|\mathscr|: $\mathscr{A}\mathscr{B}$

This is \verb|\mathcal|: $\mathcal{A}\mathcal{B}$

\end{document}

Output of pdffonts:
name                                 type              emb sub uni object ID
------------------------------------ ----------------- --- --- --- ---------
HHWGLO+CMR10                         Type 1            yes yes no       4  0
DTZOCG+CMTT10                        Type 1            yes yes no       5  0
LUIFQC+STIXMathScript-Regular        Type 1            yes yes no       6  0
OBDLAV+STIXMathCalligraphy-Regular   Type 1            yes yes no       7  0
GYLRUW+STIXMathScript-Bold           Type 1            yes yes no       8  0
UVZWHB+STIXMathCalligraphy-Bold      Type 1            yes yes no       9  0

For comparison
\documentclass{article}
\usepackage{amsmath}
\usepackage{mathrsfs}

\begin{document}

This is \verb|\mathscr|: $\mathscr{A}\mathscr{B}$

This is \verb|\mathcal|: $\mathcal{A}\mathcal{B}$

\boldmath

This is \verb|\mathscr|: $\mathscr{A}\mathscr{B}$

This is \verb|\mathcal|: $\mathcal{A}\mathcal{B}$

\end{document}


Q:

Feature importance based on extremely randomize trees and feature redundancy

I am using the Scikit-learn Extremely Randomized Trees algorithm to get info about the relative feature importances and I have a question about how "redundant features" are ranked.
If I have two features that are identical (redundant) and important to the classification, the extremely randomized trees cannot detect the redundancy of the features. That is, both features get a high ranking.  Is there any other way to detect that two features are actualy redundant?

A:

Maybe you could extract the top n important features and then compute pairwise Spearman's or Pearson's correlations for those in order to detect redundancy only for the top informative features as it might not be feasible to compute all pairwise feature correlations (quadratic with the number of features).
There might be more clever ways to do the same by exploiting the statistics of the relative occurrences of the features as nodes in the decision trees though.


Q:

Mixing c++ and assembly cant pass multiple paramaters from C++ function to assembly

I've been frustrated by passing parameters from a c++ function to assembly. I couldn't find anything that helped on Google and would really like your help. I am using Visual Studio 2017 and masm to compile my assembly code.
This is a simplified version of my c++ file where I call the assembly procedure set_clock
int main()
{
    TimeInfo localTime;
    char clock[4] = { 0,0,0,0 };
    set_clock(clock,&localTime);
    system("pause");
    return 0;
}

I run into problems in the assembly file. I can't figure out why the second parameter passed to the function turns out huge. I was going off my textbook, which shows similar code with PROC followed by parameters. I don't know why the first parameter is passed successfully and the second one isn't. Can someone tell me the correct way to pass multiple parameters?
.code
set_clock PROC,
    array:qword,address:qword
    mov rdx,array   ; works fine memory address: 0x1052440000616
    mov rdi,address ; value of rdi is 14757395258967641292
    mov al, [rdx]
    mov [rdi],al    ; ERROR: cant access that memory location
    ret
set_clock ENDP
END

A:

MASM's high-level crap is biting you in the ass.  x64 Windows passes the first 4 args in rcx, rdx, r8, r9 (for any of those 4 that are integer/pointer).
mov rdx,array
mov rdi,address

assembles to
mov  rdx, rcx    ; clobber 2nd arg with a copy of the 1st
mov  rdi, rdx    ; copy array again

Use a disassembler to check for yourself.  Always a good idea to check the real machine code by disassembling or using your debuggers disassembly instead of source mode, if anything weird is happening with assembler macros.

I'm not sure why this would result in an inaccessible memory location.  If both args really are pointers to locals, then it should just be loading and storing back into the same stack location.  But if char clock[4] is a const in static storage, it might be in a read-only memory page which would explain the store failing.
Either way, use a debugger and find out.

BTW, rdi is a call-preserved (aka non-volatile) register in the x64 Windows convention. (https://msdn.microsoft.com/en-us/library/9z1stfyw.aspx).  Use call-clobbered registers for scratch regs unless you run out and need to save/restore some call-preserved regs.  See also Agner Fog's calling conventions doc (http://agner.org/optimize/), and other links in the x86 tag wiki.
It's call-clobbered in x86-64 System V, which also passes args in different registers.  Maybe you were looking at a different example?

Hopefully-fixed version, using movzx to avoid a false dependency on RAX when loading a byte.
set_clock PROC,
    array:qword,address:qword
    movzx    eax, byte ptr [array]
    mov      [address], al
    ret
set_clock ENDP

I don't use MASM, but I think array:qword makes array an alias for rcx.  Or you could skip declaring the parameters and just use rcx and rdx directly, and document it with comments.  That would be easier for everyone to understand.
You definitely don't want useless mov reg,reg instructions cluttering your code; if you're writing in asm in the first place, wasted instructions would cut into any speedups you're getting.


Q:

Working with a cookie-free sub-domain using Symfony2/3

I have two sub-domains:
www.example.com and static.example.com
The root domain example.com redirects to www.example.com.
How can I restrict cookies to www.example.com in Symfony2/3 and make static.example.com free of cookies. I didn't find any cookies section in config.yml.
How can I specify a specific subdomain when using the functions:
href="{{ asset('favicon.png') }}"
href="{{ path('blog_show') }}"
$this->generateUrl('blog_show',array('slug' => 'my-blog-post'));
PS: I also have full-control on Apache.

A:

framework:
    templating:
        assets_base_urls:
            http: static.example.com

http://symfony.com/doc/master/reference/configuration/framework.html#assets-base-urls
Edit:
You can group assets into packages, to specify different base URLs for them:
framework:
    templating:
        packages:
            avatars:
                base_urls: 'static.example.com'

http://symfony.com/doc/master/reference/configuration/framework.html#packages
For rest question: url generation, I'm not sure what mean cookie free route path.


Q:

Why does $5x^2+6xy+2y^2=2yz+z^2$ have no integer solutions?

Why does $5x^2+6xy+2y^2=2yz+z^2$ have no primitive integer solutions?
Modulo $2$ says that $x$ and $z$ are odd.
Modulo $3$ says that $x=0 \bmod 3$ and $y=-z \bmod 3$.
I cannot get anything modulo $5$.

A:

Look modulo 8.  Remember that odd squares are 1 more than a multiple of 8.
What are the possible remainders of $z^2-5x^2$?
What the the possible remainders of $2y(3x+y-z)$ if $y$ is odd? if $y$ is even?


Q:

Get supported Codec for Android device

Is there a way to ask an Android device what audio and video Codecs it supports for encoding?
I found devices that do not support some of the codecs listed as mandatory in
http://developer.android.com/guide/appendix/media-formats.html
and there seem to be devices supporting additional codec not listed there.

A:

That could be interesting for you:
 private static MediaCodecInfo selectCodec(String mimeType) {
     int numCodecs = MediaCodecList.getCodecCount();
     for (int i = 0; i < numCodecs; i++) {
         MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(i);

         if (!codecInfo.isEncoder()) {
             continue;
         }

         String[] types = codecInfo.getSupportedTypes();
         for (int j = 0; j < types.length; j++) {
             if (types[j].equalsIgnoreCase(mimeType)) {
                 return codecInfo;
             }
         }
     }
     return null;
 }

Found it here. AS you can see you get the number of installed codecs with MediaCodecList.getCodecCount();. With MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(i); you get information about a specific codec out of the list. codecInfo.getName() for example tells you title/name of the codec.

A:

Is there a way to ask an Android device what audio and video Codecs it supports for encoding?

I really wish there were, but there is not, at least through ICS.
Jelly Bean offers a MediaCodec class. While it does not have a "give me a list of supported codecs", it does have createEncoderByType(), where you pass in a MIME type. Presumably, that will throw a RuntimeException  or return null if your desired MIME type is not supported. And I cannot promise that just because MediaCodec reports that an encoder is available that it is guaranteed to work from, say, MediaRecorder.


Q:

ObjectParameter.Value InvalidCastException for null value

In SQL  procedure returs null for out parametr but in C# in if whene I try to check if id==null I got   System.InvalidCastException
This error drives me crazy becose in debuge mode id==null is TRUE but anyway System.InvalidCastException is throwen
 var outObj = new System.Data.Entity.Core.Objects.ObjectParameter("ID",typeof(int?));
            db.spGetSOFolderID(soid, branchId, outObj, kindID);
            int? id = null;
            id =(int?)outObj.Value;
  if (id==null) ///here error
            return null;

A:

FINALY found solution.
 var outObj = new System.Data.Entity.Core.Objects.ObjectParameter("FolderID", typeof(int?));
            db.spGetSOFolderID(soid, branchId, outObj, kindID);
            if (outObj.Value is DBNull)
                return null;
            int? id = (int?)outObj.Value;

So really the problem was in int? id = (int?)outObj.Value; But why I got InvalidCastException  erro on if(id==)  is still secret for me.


Q:

Alternative to BugSense for Windows Phone

It seems that BugSense is abandoned for Windows Phone. I still see the statistics in my dashboard, but can't find SDK for Windows Phone in docs(thats why i thought that BugSense for windows is closed).
Are there any good alternative for viewing error/trace reportings with some dashbord, showing internal information without needing me to mark it for logging?

A:

I'd encourage you to check out Crittercism. It's actively being developed and supported (last update was about a week ago):

https://www.nuget.org/packages/Crittercism
http://docs.crittercism.com/windows/windows.html


Q:

Refresh an UltraWinGrid from a separate form

I've got a form with a list of customers and another form where customers can be added. When I open the fAddCustomer form, from fCustomerList, I'm calling it using this code:
Dim f As New Form
f = New fAddCustomer(con, False)
f.MdiParent = Me.MdiParent
f.Show()

On fCustomerAdd, I've got a ToolStripButton to add the customer. When the form is closed, I need to refresh the UltraWinGrid that I have on fCustomerList to view the new data on the list automatically.
Because I'm using a ToolStripButton and the form uses f.MdiParent = Me.MdiParent, I can't use the same solution that was used in this answer here, as there is no DialogResult on a ToolStripButton, and you can't use ShowDialog when using MdiParents.
Is there any other way I can achieve this at all?

A:

One that you could achieve this without changing the DataSource passing as @Plutonix suggested is to do something like this:
Private Sub fAddCustomer_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing

Try
    If Application.OpenForms.OfType(Of fCustomerList).Any Then
       Application.OpenForms("fCustomerList").Close()
            Dim f As New fCustomerList()
            f.MdiParent = Me.MdiParent
            f.Show()
        End If

    Catch ex As Exception
        Debug.WriteLine(ex.Message)

    End Try
End Sub


Q:

TXT entry in DNS for both gmail and amazon ses

It seems adding a TXT entry in DNS about Google is a good practice (when using gmail to send mail) to prevent being considered as Spammer. So I could add a TXT entry in my DNS records to:
example.org TXT "v=spf1 include:_spf.google.com ~all"

But, this domain is also used to send mail via Amazon SES (I work for a web company that send mail via a web application). In other words, mails are sent from myname@example.org via Gmail and from noreply@example.org via Amazon SES. In order to avoid being considered as a spammer, should I:

Do not add a TXT entry about SPS at all.
Add a TXT entry for google "v=spf1 include:_spf.google.com ~all"
Build something for both Amazon and Google (but I don't know what).
Something else?

Side note: MX entry for google (aspmx.l.google.com, etc.) and TXT for Amazon SES (_amazonses._example.example.org TXT xxxyyyzzz) are already set.

A:

Using ~all means that mail will come from the servers listed in the SPF record, but may also come other sources. However, by just specifying the Google record some mailers could be more wary of your emails that come from Amazon.
Your best bet would be to specify both. A quick search found the page listing SPF configuration for Amazon -
http://docs.aws.amazon.com/ses/latest/DeveloperGuide/spf.html
So you'd end up with something like the following -
v=spf1 include:_spf.google.com include:amazonses.com ~all

You can also use -all if you are sure all your email comes from those 2 sources, although that can cause issues with badly configured forwarders.


Q:

Geocoder forceclose

I have this application that is supposed to get the address from longitude and latitude but it keeps forceclosing when I push the button to call the information.
Logcat Error:
10-25 14:33:51.802: ERROR/AndroidRuntime(11166):     at http.www.hotapp.com.timeandlocation.LocationManagerHelper.getAddress(LocationManagerHelper.java:51)

My Geocoder Code
public static boolean getAddress(){
  Geocoder geoCoder = new Geocoder(context);
  try {
    geoCoder.getFromLocation(getLatitude(), getLongitude(), 0);
  } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
  return true;
}

The logcat error is saying that the error is on the line with new Geocoder. please help.

A:

The context that you are using is probably wrong, it should be that of the calling Activity.


Q:

equal keys trigger cache load more than expected

Maybe I am totally misguided on how cache2k works. I want to cache results from very costly operations, but even with equal keys, the results are always generated again. First I thought, the keys weren't really equal, but even with an equals() returning true, the cache seems to think I want new results.
import org.cache2k.Cache;
import org.cache2k.CacheBuilder;
import org.cache2k.integration.CacheLoader;
import org.junit.Test;

import java.util.Date;
import java.util.concurrent.TimeUnit;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class MyCacheTest {

  private static int count = 0;

  Cache<MyCacheTest.MyKey, Integer> cache = (Cache) CacheBuilder.newCache(MyCacheTest.MyKey.class,
      Integer.class)
      .expiryDuration(1, TimeUnit.HOURS)
      .loader(new CacheLoader<MyCacheTest.MyKey, Integer>() {
        @Override
        public Integer load(MyCacheTest.MyKey p) throws Exception {
          return costlyOperation(p);
        }
      })
      .build();

  private Integer costlyOperation(MyKey p) {
    count ++;
    return 1;
  }

  public class MyKey {

    Date date;

    @Override
    public boolean equals(Object o) {
      return true;
    }
  }

  // OK
  @Test
  public void testEquals() {
    assertTrue(new MyKey().equals(new MyKey()));
  }

  // FAIL, somehow calls costlyOperation twice
  @Test
  public void testCostlyOperationCalledOnlyOnce() {
    cache.get(new MyKey());
    cache.get(new MyKey());
    assertEquals(count, 1);
  }
}

This is most likely a misunderstanding on my part, someone please explain why this isn't working as I expect.

A:

You implemented equals but not hashCode and this cache implementation uses hashCode.
Adding:
@Override
public int hashCode() {
    return 0;
}

to MyKey gives the expected behavior.
(tested with version 0.26-BETA)


Q:

Regex QueryString Parsing for a specific in BigQuery

So last week I was able to begin to stream my Appengine logs into BigQuery and am now attempting to pull some data out of the log entries into a table.
The data in protoPayload.resource is the page requested with the querystring paramters included.
The contents of protoPayload.resource looks like the following examples:
/service.html?device_ID=123456
/service.html?v=2&device_ID=78ec9b4a56

I am getting close, but when there is another entry before device_ID, I am not getting it. As you can see I am not great with Regex, but it is the only way I think I can parse the data in the query. To get just the device ID from the first example, I was able to use the following example.  Works great. My next challenge is to the data when the second parameter exists. The device IDs can vary in length from about 10 to 26 characters.
SELECT
RIGHT(Regexp_extract(protoPayload.resource,r'[\?&]([^&]+)'),
length(Regexp_extract(protoPayload.resource,r'[\?&]([^&]+)'))-10) as Device_ID
FROM logs

What I would like is just the values from the querystring device_ID such as:
123456
78ec9b4a56

A:

Assuming you have just 1 query string per record then you can do this:
SELECT REGEXP_EXTRACT(protoPayload.resource, r'device_ID=(.*)$') as device_id FROM mytable

The part within the parentheses will be captured and returned in the result.
If device_ID isn't guaranteed to be the last parameter in the string, then use something like this:
SELECT REGEXP_EXTRACT(protoPayload.resource, r'device_ID=([^\&]*)') as device_id FROM mytable


Q:

Javascript not treating buttons in loop individually

I have a loop that that retrieves rows from the db and spits it out in a table. For every row I have a button that is generated. So if I have 5 rows, 5 buttons appear. Currently when I press the first button, the function does what it's supposed to do which is hides the button and the puts "Button Pressed". The issue I am having is Ok, I pressed the first button, now I need to press the second button. When I press the second button, it hides the button and doesn't put any text. Also, if I press the second button first, it hides the button on the first AND second button and what used to be the first button now says "Button Pressed" when it wasn't really pressed. I want it where each button works individually. Is that possible?
function buttonpressed(button) {
   button.style.visibility = "hidden";
   document.getElementById("ChangeButton1").innerHTML="Button Pressed";
   window.open ('test2.html','newWin', 'width=400,height=400');
}

while($row = odbc_fetch_array($rs))
{
echo '

<input type="submit" name="buttonpressed" value="buttonpressed" onclick="SendEmail(this); return false;">

';
}

A:

You have duplicate IDs.
Instead, remove the id="ChangeButton" from the HTML, and change your JS to:
button.parentNode.innerHTML = "Button Pressed";
window.open(...);


Q:

How to rotate a translated texture around its center

I'm working on the following shader that

translates (on y)
rotates
repeats (tiles)

a texture:
uniform sampler2D texture;
uniform vec2 resolution;

varying vec4 vertColor;
varying vec4 vertTexCoord;

uniform float rotation;
uniform float yTranslation;

void main() {
  vec2 repeat = vec2(2, 2);
  vec2 coord = vertTexCoord.st;

  coord.y += yTranslation;

  float sin_factor = sin(rotation);
  float cos_factor = cos(rotation);
  coord += vec2(0.5);
  coord = coord * mat2(cos_factor, sin_factor, -sin_factor, cos_factor) * 0.3;
  coord -= vec2(0.5);

  coord = vec2(mod(coord.x * repeat.x, 1.0f), mod(coord.y * repeat.y, 1.0f));

  gl_FragColor = texture2D(texture, coord) * vertColor;
}

Current behavior

Desired behavior
I want the texture to always rotate around the center, no matter how far it has been translated.

Simply swapping the order of the steps results in weird behavior. What am I missing?

A:

Your problem statement in the question is really wrong:  Your addtional comment (to a now deleted answer):

I have a boat that always stays in the center of the screen, the water texture (controlled by this shader) under it moves to make it look like the boat is moving. The movement of the water texture is controlled by rotation (for steering) and yTranslation (for how far the boat has moved forwards/backwards)

makes it clear that you're asking for a different thing, and the approach described in the question is simply not going to solve your problem.
When your boat moves and rotates, it will basically travel on a curve (and you want the inverse of that curve to travel through texture space). But your 2dof parameters rotation and yTranslation are not capable of describing the curve. Your problem needs at least another parameter xTranslation - so in the end, you need a 2D vector describing the position of your boat + an angle describing the rotation. And you need to properly accumulate this data at each simulation step:

update the rotation accordingly
calculate the 2D vector your ship is heading tom as defined by the current rotation
scale it according to the velocity of the movement
accumulate it onto the position vector.

Then, your shader simply has to
  1. translate the texcoords by position  (or -position, whatever you store)
  2. Rotate around the pivot point (which is constant and only depends on how you layed out your texture space)

coord = vec2(mod(coord.x * repeat.x, 1.0f), mod(coord.y * repeat.y, 1.0f));

that's a waste of GPU ALU cycles, the TMUs will already do the mod for you with the GL_REPEAT wrap modes.
However, what you now have here is rotation, scaling and translation: so just use a single matrix for the whole texcoord transformation - the accumulation of the 2D position that I talked about earlier can nicely by done with the matrix representations. It will also remove the sin and cos from your shader, which is another huge waste right now.


Q:

how to check if a directory is writeable in win32 C/winapi?

I know of two methods which are not reliable:

_access() - doesn't work on directories (only checks existence)
CreateFile() - gives false positives in the presence of virtual store (AFAIK)

Most useful would be a code sample, because the win32 ACL access functions are extremely complicated. Please don't post links to msdn, I've been there and can't for the life of me figure out what I'm supposed to do with all those DACLs, SACLs and security descriptors - I work on a cross-platform app which needs this particular piece of functionality, but otherwise is platform-agnostic. Solutions simpler than accessing Windows ACLs more than welcome.
Edit: you can safely assume that directory permissions won't change while the app is running.

A:

you can disable location virtualization for your application in a manifest file (http://www.codeguru.com/csharp/csharp/cs_misc/designtechniques/article.php/c15455/) - this should make CreateFile reliable enough for your purposes.


Q:

How to fix this "Execution failed: These columns are out of bounds." error?

I've writen this function, but I'm getting an error "Execution failed: These columns are out of bounds." (in my translation). The line generating the error is var CellName = sheet.getRange(1, i+1);. And I got this result:

These are the logs:

And this the transcript:

The code is bellow. And my doubt is why the for loop stops at header7 and not all headers?
  var font_size = 12;
  var headers = "HEADER1 HEADER2 HEADER3 HEADER4 HEADER5 HEADER6 HEADER7 HEADER8 HEADER9";
  var arrayHeaders = headers.split(/[\s\t]+/);
     Logger.log("arrayHeaders = " + arrayHeaders);
    for (var i = 0; i < arrayHeaders.length; i++){
       Logger.log("arrayHeaders.length = " + arrayHeaders.length);
      var CellName = sheet.getRange(1, i+1);
      CellName.setValue(arrayHeaders[i]).setBackgroundRGB(34, 139, 34).setFontSize(font_size).setFontWeight("bold").setFontFamily("Arial");
      // There is no column 0, so i+1 to start
      sheet.setColumnWidth(i+1, 100);
    }

A:

Using your code in the following function the script completed with no errors and the expected column headers were in each cell in the spreadsheet:
function myFunction() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var font_size = 12;
  var headers = "HEADER1 HEADER2 HEADER3 HEADER4 HEADER5 HEADER6 HEADER7 HEADER8 HEADER9";
  var arrayHeaders = headers.split(/[\s\t]+/);

  Logger.log("arrayHeaders = " + arrayHeaders);

  for (var i = 0; i < arrayHeaders.length; i++){
    Logger.log("arrayHeaders.length = " + arrayHeaders.length);
    var CellName = sheet.getRange(1, i+1);
    CellName.setValue(arrayHeaders[i]).setBackgroundRGB(34, 139, 34).setFontSize(font_size).setFontWeight("bold").setFontFamily("Arial");
    // There is no column 0, so i+1 to start
    sheet.setColumnWidth(i+1, 100);
  }
}

I initially thought that because in the screenshot there were only 7 columns that getRange was failing because the column index it was attempting to get did not yet exist. During testing though I discovered that getRange creates new columns where needed.
I can only think that maybe you have protected ranges or frozen columns in your sheet? Try the function above in a fresh spreadsheet and see what happens.


Q:

Location of gatling load test project

Given I want to test with Gatling some micorservices project with one public API and every micro service has it's own git repository then what is the best locations for gatling load test project?
I wonder if I should create separate repository for that or just create directory in public API project repository.

A:

I don't see why you shouldn't publicly publish your load tests if your API is public.
Just beware of not publishing virtual users credentials and the likes, those should come from the environment.
If you have some DDoS countermeasure (and you probably should), just add some exception rules.
That's exactly what the BBC does.


Q:

How do I move stuff?

I want to place a piece of furniture but there is another piece of furniture in the way. I can't seem to find an option to move or remove. Is there something there that I am missing, or did I nail this thing to the floor forever?

A:

You have two options available if you want to move something:

The Remove option, under Install, to destroy the item, and then place it down in the new location.
The Rearrange option, which is directly underneath the Remove option.  You can freely move items from one apartment to another without a problem, but it will still cost you half of the original building cost to do so.

Obviously, Rearrange is cheaper than Remove and rebuilding, so I'd recommend that option.


Q:

B-spline algorithm

I have code for drawing Bezier curves. Is it posible to modify this code for drawing B-Spline curves?
Here is my code using DeCasteljau algorithm:
    private Point getPoint(int r, int i, double t)
    {
        if (r == 0) return points[i];

        Point p1 = getPoint(r - 1, i, t);
        Point p2 = getPoint(r - 1, i + 1, t);

        return new Point((int)((1 - t) * p1.X + t * p2.X), (int)((1 - t) * p1.Y + t * p2.Y));
    }

I found this code for B-Spline curves. It looks similar to my code, but I have XY points and there are only numbers. I don't know how to modify my code. I tried something but it doesn't work.
private double BasisFunction(int k, int i, ParameterCollection u, double t){
if(k==0)
 {
  if((u[i]<=t) && (t<=u[i+1]))
   return 1;
  else
   return 0;
 }
 else
{
 double memb1, memb2;
  if(u[i+k]==u[i])
   memb1 = 0;
  else
   memb1 = ((t-u[i])/(u[i+k]-u[i]))*BasisFunction(k-1, i, u, t);
  if(u[i+k+1]==u[i+1])
   memb2 = 0;
  else
   memb2 = ((u[i+k+1]-t)/(u[i+k+1]-u[i+1]))*BasisFunction(k-1, i+1, u, t);
  return memb1+memb2;
 }
}

Please help.

A:

The function BasisFunction() is for computing the value of B-spline basis function N(n,i)(t), where n is degree and i ranges from 0 to (m-1) with m is the number of control points. So, to use this function, you need to define the following for your B-spline:

degree.
m control points, denoting them as P[i][2] with i=0~(m-1)
knot sequence. This is the input "ParameterCollection" to the BasisFunction. You need to have (m+degree+1) knots in the knot sequence and the knot values need to be monotonically non-decreasing. An example of knot sequence for degree 3 B-spline with 5 control points is [0,0,0,0,u0,1,1,1,1], where u0 is any value between [0,1].

Then you can evaluate any point on the B-spline curve at parameter t by something like:
double point[2]={0.0}; // point on the B-spline curve
for (int ii=0; ii < m; ii++)  // loop thru all control points
{
    double basisVal = BasisFunction(degree, ii, knotSequence, t);

    point[0] += P[ii][0]*basisVal;
    point[1] += P[ii][1]*basisVal;
}


Q:

4017 counter: Why do some LEDs have multiple connections in this traffic light circuit?

Schematic (from here):

Why are four legs connected to the green LED and two to the amber LED in the 4017 traffic light circuit? Shouldn't it be able to do with only one leg per LED?

A:

Have a look at the LED truth table on the same page:

Each output is consecutively active for the same time. By wired-OR-ing outputs you can create longer active times. So the green LED will be on during 4 time units.
Normally you would have to wired-OR Q0 through Q4 for the red LED, but we have a carry output (here called ":10") which does just that, see the bottom trace of the timing diagram:


Q:

Reverse a list of list in F#

I want to reverse a function called revLists that takes a list of lists and reverses all the sub-lists.
Any suggestion will help.
This is my idea:
let revLists[[]] = List.map (fun [[]] -> List.rev);;
revLists[[1;2;3],[4;5]];;

A:

let lists = [[1;2;3];[4;5]]
let reverseLists list = list |> List.map List.rev

> reverseLists lists;;
val it : int list list = [[3; 2; 1]; [5; 4]]


Q:

Understanding matrix conditioning at a glance

I'm working on my Master's, in the field of computational fluid dynamics, where we have to solve the system $Ax = b$ a lot. As far as I can figure out, if the matrix $A$ is ill-conditioned it is possible that a small residual $r = |Ax-b|$ does not necessarily correspond with an accurate solution to the system.
Is there a "rule of thumb" as to how I can think about an ill-conditioned matrix? From what I can figure out, an ill-conditioned matrix may have large differences (close to machine precision) between some of its entries. Is this correct? And does diagonal dominance have any effects on conditioning?

A:

When $\det(A)$ has a very small value ($A$ is almost singular), there's a high possibility that you have an ill-conditioned matrix. How small you ask? You need a reference against which the determinant can be measured. The reference here is called the norm of the matrix $\|A \|$.
There are several "popular" norms in the literature:
$$\|A \|=\sqrt{\sum_i\sum_ja_{ij}^2}  \tag{Euclidean norm}$$
$$\|A \|=\sum_i\sum_j|a_{ij}|$$
$$\|A \|=\max_{i,j}\{a_{ij}\}$$
$$\|A \|=\max_i\sum_{j=1}^{n}|a_{ij}|$$
If you're using MATLAB for example, you can define $\text{cond}(A)=\|A \|  \|A^{-1} \|$(condition number). If $\text{cond}(A)$ is close to unity, then the matrix is well conditioned. And as $\text{cond}(A)\rightarrow \infty$ the matrix gets more ill-conditioned. However, for very large matrices, computing the norm is quite expensive, so in most cases, we're content with comparing the determinant with the magnitudes of the elements of the matrix.
Concerning diagonal dominance: to my knowledge, having a diagonally dominant matrix is helpful when you're solving a system using methods like Gauss elimination with scaled row pivoting. However a diagonally dominant matrix is not necessarily well-conditioned.


Q:

How can I get the hostname, aliases, ip address, and canonical name of a device (without asking a library to read /etc/hosts) using python?

I want to get these fields about a device given an identifier:
hostname, aliases, ip address, & canonical name
I can get these by using socket:
socket.gethostbyaddr('machine-name')

However, every socket call opens the hosts file (/etc/hosts) and reads it in. I want to skip this step.
Either I want socket to only open the hosts file once (and save the data), or I want socket to skip looking in the hosts file and do a DNS lookup (and I will read the hosts file myself).
I tried to do this with dnspython's resolver, but I can't figure out how to parse the returned result for my wanted fields.

A:

I ended up achieving this with pycares. It allowed me to resolve 100,000+ dns queries in under 18 seconds.
For the hosts file, I parsed it myself.


Q:

Why is the default IPv6 address changed after installing Docker and how to avoid it

I'm using Ansible to install Docker on a Debian system. And I need to identify the ansible_default_ipv6.address in some tasks. After installing Docker the setup task returns a different "default" (the docker0 interface) instead of the "eth0" or "ens18" or whatever. So it isn't really a problem with Docker but with changes on the network interfaces. Maybe this happens to, if you configure OpenVPN etc.
I don't understand, why the ansible_default_ipv6.address changed (maybe because "d" is earlier then "e"). I would expect that the "scope global" is more important then "scope global tentative" from docker0
But also - how could I avoid that behaviour? Is it best practice to define a per host variable about the interface or the IPs?

A:

You're correct, it IS because "d" is before "e":
In theory, Ansible selects the device with the default gateway as the "default" interface. In practice, it's often just the interface that comes first in the alphabet.
So before installing docker, eth0 is the default interface, but after installing docker there's a new docker0 interface (which comes before eth0 when sorted alphabetical), so Ansible now declares docker0 as the "default" interface.
Solution: Do not use ansible_default_ipv6 and use the interface specific facts instead (ansible_eth0["ipv4"]...)


Q:

How to create view/python reference on scipy sparse matrix?

I am working on an algorithm that uses diagonal and first off-diagonal blocks of a large (will be e06 x e06) block diagonal sparse matrix.
Right now I create a dict that stores the blocks in such a way that I can access the blocks in a matrix like fashion. For example B[0,0](5x5) gives the first block of matrix A(20x20), assuming 5x5 blocks and that matrix A is of type sparse.lil.
This works fine but takes horribly long too run. It is inefficient because it copies the data, as this reference revealed to my astonishment: GetItem Method
Is there a way to only store a view on a sparse matrix in a dict? I would like to change the content and still be able to use the same identifiers. It is fine if it takes a little longer as it should only be done once. The blocks will have many different dimensions and shapes.

A:

As far as I know, all of the various sparse matricies in scipy.sparse return copies rather than a view of some sort.  (Some of the others may be significantly faster at doing so than lil_matrix, though!)
One way of doing what you want is to just work with slice objects. For example:
import scipy.sparse

class SparseBlocks(object):
    def __init__(self, data, chunksize=5):
        self.data = data
        self.chunksize = chunksize
    def _convert_slices(self, slices):
        newslices = []
        for axslice in slices:
            if isinstance(axslice, slice):
                start, stop = axslice.start, axslice.stop
                if axslice.start is not None:
                    start *= self.chunksize
                if axslice.stop is not None:
                    stop *= self.chunksize
                axslice = slice(start, stop, None)
            elif axslice is not None:
                axslice = slice(axslice, axslice+self.chunksize)
            newslices.append(axslice)
        return tuple(newslices)

    def __getitem__(self, item):
        item = self._convert_slices(item)
        return self.data.__getitem__(item)
    def __setitem__(self, item, value):
        item = self._convert_slices(item)
        return self.data.__setitem__(item, value)

data = scipy.sparse.lil_matrix((20,20))
s = SparseBlocks(data)
s[0,0] = 1
print s.data

Now, whenever we modify s[whatever] it will modify s.data of the appropriate chunk. In other words, s[0,0] will return or set s.data[:5, :5], and so on.


Q:

Determinant of arbitrary sum of positive semidefinite hermitian matrices

Suppose that $A_i$, $i=1,\ldots,m$ are positive semidefinite Hermitian $n\times n$ matrices, with $a_i^{(j)}$ being the $j$-th eigenvalue of $A_i$. Let $A_0=I$.

QUESTION. Can we extend the result of M. Fiedler for $m=2$ (Bounds for the Determinant of the Sum of Hermitian Matrices, Proc. Amer. Math. Soc.
  30 (1971) 27-31) to establish the bound
  $$
\det \sum_{i=0}^mA_i \le\max_{\sigma_0,\dots,\sigma_m\in S_n}\prod_{j=1}^n\sum_{i=0}^m a_i^{(\sigma_i(j))}\,\,?
$$
  ($S_n$ is the group of permutations of $n$ elements)

Edit: it should be noted $A_0$ is superfluous, since the statement would hold for singular matrices too. I didn't want the answers below to have to consider the additional case.

A:

The previous answer was incorrect due to an incorrect use of majorization. I decided to replace it by a correct version below for completeness, and to remedy the embarrassing error (though now the answer becomes essentially equivalent to the OPs own answer, so feel free to ignore!).
$\newcommand{\da}{\downarrow} \newcommand{\ua}{\uparrow} \newcommand{\nlsum}{\sum\nolimits}$

Recall that for Hermitian matrices $A$ and $B$, Lidskii's eigenvalue majorization inequality implies that there exist doubly stochastic matrices $D_1$ and $D_2$ such that $\lambda(A+B)=D_1\lambda(A)+D_2\lambda(B)$.
Introduce the shorthand $a_{m+1}=\lambda(A_1+\cdots+A_m)$, and $a_j = \lambda(A_j)$ for $1\le j\le m$. Then, applying Lidskii's result repeatedly and noting that doubly stochastic matrices are closed under multiplication, it follows that there exist doubly stochastic matrices $D_1,\ldots,D_m$ such that
\begin{equation*}
  a_{m+1} = D_1a_1+\cdots+D_ma_m.
\end{equation*}
We wish to upper bound $\det(A_{m+1}):=\prod_i a_{m+1,i}$. Consider the function
\begin{equation*}
  f(D_1,\ldots,D_m) := \prod_i (D_1a_1+\cdots+D_ma_m)_i. % \le \left(\frac{\nlsum_i e_i^T(D_1a_1+\cdots+D_ma_m)}{n} \right)^n.
\end{equation*}
We now show that $f$ is maximized over permutation matrices. First, we make the change of variables $(D_l)_{ij}=D_{l,ij} = e^{u_{l,ij}}$. Moreover, we relax the doubly-stochastic constraints on each $D_l$ to
\begin{equation*}
  \Omega_n := \left\lbrace(U_1,\ldots,U_m) \in \mathbb{R}^{m\times n \times n}\mid \nlsum_i e^{u_{l,ij}} \le 1,\ \forall i,\quad \nlsum_j e^{u_{l,ij}} \le 1,\forall j, \quad\text{for}\ 1 \le l \le m\right\rbrace.
\end{equation*}
Then, we consider the optimization problem
\begin{equation*}
  \sup_{(U_1,\ldots,U_m) \in \Omega_n}\quad g(U_1,\ldots,U_m) := \nlsum_{i=1}^n \log\left(\nlsum_{lj} a_{l,j}e^{u_{l,ij}}\right).
\end{equation*}
Since all the matrices $A_1,\ldots,A_m$ are positive definite, each $a_{l,j}\ge0$. Thus, $g$ is a convex function of the $U_i$. Hence its supremum will be at an extreme point of $\Omega_n$. These points correspond to the permutation matrices. Thus, mapping back to the $D_i$ space, we observe that $f$ will be maximized at permutation matrices.
This reasoning immediately yields the desired inequality:
\begin{equation*}
  \det(A_{m+1})=\det(A_1+\cdots+A_m) \le \sup_{\sigma_1,\ldots,\sigma_m \in S_n}\prod_{i=1}^n\left(\nlsum_{l=1}^m a_{l,\sigma_l(i)} \right).
\end{equation*}

A:

Thank you to @FedorPetrov for helping me complete the proof.
Let $S=\sum_{i=0}^mA_i$, positive definite by its first term. Let its positive eigenvalues be $\lambda_i$ in any order, with corresponding eigenvectors $\textbf{v}_i$.
Let $\textbf{a}_i^{(j)}$ be the eigenvector of $A_i$ corresponding to the eigenvalue $a_i^{(j)}$. Since $\textbf{v}_k^\top\textbf{v}_k=1$, we have for any $k$:
$$
\textbf{v}_k^\top S\textbf{v}_k=\sum_{i=1}^n\sum_{j=1}^na_i^{(j)}\langle \textbf{a}_i^{(j)},\textbf{v}_k\rangle^2
$$
From now on, iterations will implicitly on $i\in[m]$ and $j,k\in[n]$.
We continue:
$$
\det S = \prod_k\lambda_k=\prod_k\sum_{ij}a_i^{(j)}\langle \textbf{a}_i^{(j)},\textbf{v}_k\rangle^2
$$
Next for a fixed ${i_*}$, let us consider the following function on $n^2$ parameters $\{b_{jk}\}_{jk}$, represented as the matrix $B$:
$$
f_{i_*} (B)=\prod_k\left(c_k+\sum_ja_{i_*}^{(j)}b_{jk}\right)
$$
For some constants $c_k,a_{i_*}^{(j)}$ positive. To prove the conjecture it would suffice to show the lemma that:
$$
f_{i_*}(B)\le\max_{\sigma\in S_n}f_{i_*}(P_\sigma)
$$
Where again $S_n$ is the permutation group of $[n]$ and $P_\sigma$ is the corresponding permutation matrix. Applying the above bound $m$ times would actually yield something better than the conjecture (since our iterative bound is at most the global one).
Since $\left\{\textbf{v}_k\right\}_k$ form a full basis, expressing $\textbf{a}_i^{(j)}$ in those coordinates implies for any $j$:
$$\sum_k\langle \textbf{a}_{i_*}^{(j)},\textbf{v}_k\rangle ^2=1$$
Similarly for the basis $\left\{\textbf{a}_{i_*}^{(j)}\right\}_j$ and any $k$:
$$\sum_j\langle \textbf{a}_{i_*}^{(j)},\textbf{v}_k\rangle ^2=1$$
The above two statements imply $B$ with $b_{jk}=\langle\textbf{a}_{i_*}^{(j)},\textbf{v}_k\rangle ^2$ is bistochastic. By the Birkhoff–von Neumann Theorem, the set of bistochastic matrices is the convex hull of $C=\{P_\sigma|\sigma\in S_n\}$, where $P_\sigma$ is the permutation matrix of $\sigma$.
Then, since $f_{i_*}$ is convex (at least on $[0,1]^{n\times n}$, a superset of the domain of bistochastic matrices), the maximum value must be on $\partial\,\text{hull}(C)$. Since the face of a simplex is just a lower-dimensional one, we repeat this logic, eventually finding that the maximum must be located at one of the boundary points, some element in $C$.


Q:

jqGrid record text alignment

Im pretty new to jqGrid and Im having a problem displaying the recordtext in the pager. Here is the picture:

As you can see the recordtext is not being fully displayed. I set the text to the right but I dont want it to be truncated. Here is the code:

gridMed.jqGrid({
            datatype: 'local',
            loadonce: true,
            colModel: gridMedColModel,
            height: '230',
            viewrecords: true,
            gridview: true,
            headertitles: false,
            pager: $('#pagerMedico'),
            recordtext: "Mostrando {0} - {1} de " + cantidadRegistros + mensaje,
            pgtext: null,
            pgbuttons: false,
            rowList: [],
            shrinkToFit: false
        }).navGrid('#pagerMedico', { edit: false, add: true, del: false, search: false, refresh: false });

Thanks in advance!

A:

You can try adding this:
loadComplete: function(){
    $('#pager2_left').css('width', 70); // this will make more space for text.
}

Here #pager2_left is the navGrid pagers parent td's id and the width is divided to them equally, so you have to give a lower width to the #pager2_left td, it will shrink little bit and more space will be available for the other one.


Q:

A remark about the map $\partial^*:H^{*}(A;V)\to H^{*+1}(X,A)$ of the l.e.S. in cohomology

My question is about a remark from lecture about the connecting-homomorphism of the long exact sequence in homology of a pair $(X,A)$.
Let $(X,A)$ a pair of topological spaces, $V$ be an abelian group and consider the long exact sequence in singular cohomology
$$..H^{n-1}(A;V)\xrightarrow{\partial^{n-1}}H^n(X,A)\to H^n(X;V)\to H^n(A;V)\xrightarrow{\partial^{n}}...$$
Let $\partial^*:H^{*}(A;V)\to H^{*+1}(X,A)$ be the connecting homomorphism in the sequence above.
In lecture we had the remark: The map $\partial^*:H^{*}(A;V)\to H^{*+1}(X,A)$ can be described as follows: Let $\alpha:C_n(A;\mathbb{Z})\to V$ be a cocycle. Extend $\alpha$ on $C_n(X;\mathbb{Z})$ by $\hat{\alpha}(\sigma )=0$ for $\sigma \in C_n(X;\mathbb{Z})$ with $\operatorname{im}(\sigma)\nsubseteq A$. Then we have: $$\partial^n [\alpha]=[d^n(\hat{\alpha})]=[\hat{\alpha} \circ d_{n+1}]\in H^{n+1}(X,A).$$
I don't understand this remark, in my opion there must be a mistake. Because if $d^n$ in the expression $[d^n(\hat{\alpha})]$ is the boundary map $d^n:C^{n}(X;V)\to C^{n+1}(X;V)$, then $[\hat{\alpha} \circ d_{n+1}]$ is not in $ H^{n+1}(X,A)$. If $d^n$ in the expression $[d^n(\hat{\alpha})]$ is the boundary map $d^n:C^{n}(X,A;V)\to C^{n+1}(X,A;V)$, $[d^n(\hat{\alpha})]$ is zero.
Where is the mistake? Is there a mistake on my thoughts or is the remark wrong? If the remark is wrong, what should be the correct version?
Best.

A:

You know, since $\alpha$ is a cocycle, that $\alpha \circ d^A_n = 0$. However, you do not know that $\hat\alpha \circ d^X_n = 0$! So $\hat\alpha$ is not even a cocycle. What you know is that, if $i_* : C_*(A) \to C_*(X)$ is the inclusion, then
$$\hat\alpha \circ d^X_n \circ i_{n+1} = \hat\alpha \circ i_n \circ d^A_n = \alpha \circ d^A_n = 0,$$
and so by definition of $C^{n+1}(X,A;V)$, it follows that $\hat\alpha \circ d^X_n \in C^{n+1}(X;V)$ is in fact in $C^{n+1}(X,A;V)$, i.e. it vanishes on $C_{n+1}(A)$, and it is a cocycle.
But it is not a coboundary in $C^*(X,A;V)$, because it would need to be the codifferential of something in $C^n(X,A;V)$; but $\hat\alpha$ does not vanish (in general) on $C_n(A)$, so in general $\hat\alpha$ is in $C^n(X;V)$ but not in $C^n(X,A;V)$. So you cannot conclude from this that $\hat\alpha \circ d^X_n$ is in the image of
$$\delta^n : C^n(X,A;V) \to C^{n+1}(X,A;V),$$
i.e. you cannot conclude that $\hat\alpha \circ d_n^X$ is a coboundary in $C^*(X,A;V)$. The remark is correct.

PS: This is a general construction known as the snake lemma, applied to:
$$\require{AMScd}
\begin{CD}
0 @>>> C^n(X,A) @>>> C^n(X) @>>> C^n(A) @>>> 0 \\
@. @VVV @VVV @VVV \\
0 @>>> C^{n+1}(X,A) @>>> C^{n+1}(X) @>>> C^{n+1}(A) @>>> 0
\end{CD}$$
The snake lemma is a very powerful tool in homological algebra.


Q:

Resolving components by name with a default fallback if name doesn't exist in Castle

I have a directory with multiple subdirectories:
/Xml
  /Documents
  /Registrations
  /Stuff
  /...

Users can drop xml files in these subdirectories, and I have a reactive FileSystemWatcher catching the files after some inactive time (to ensure that the files are ready to process).
The "Documents" folder needs a different process than the other folders so I created two components inheriting the same interface:
public interface IXmlMessageHandler { void ProcessMessage(FileInformation fi); }

public class DocumentsXmlMessageHandler: IXmlMessageHandler { /* SNIP ... */ }

public class DefaultXmlMessageHandler: IXmlMessageHandler { /* SNIP ... */ }

I'm used to the typed factories in Castle v3.2 so I decided to use the same pattern I usually reach for when some behaviors need to be routed: register a catch-all component as the default, then provide additional components for specific behaviors (here is an exemple where the Null Object Pattern is discussed). The difference was that I would need to route by folder instead of by type, but typed factories allow that easily by letting you define the components names at resolution time. What I was thinking was creating components whose name could match the folder they're linked to, and the default one would pop up when a non matching folder would be found.
So I created a typed factory, the factory selector, and registered my components
public interface IXmlMessageHandlerFactory {
    IXmlMessageHandler RetrieveMessageHandler(FileInformation fi);
}

public class XmlHandlerFactorySelector : DefaultTypedFactoryComponentSelector {
    protected override string GetComponentName(System.Reflection.MethodInfo method, object[] arguments) {
        return (arguments[0] as FileInformation).FolderName.ToLower();
    }
}

Classes.FromAssemblyInThisApplication()
.BasedOn<IXmlMessageHandler>().WithService.AllInterfaces()
.Configure(c => {
    var name = c.Implementation.Name.Replace("XmlMessageHandler", string.Empty).ToLower();
    c.Named(name);
    if (name == "default")
    {
        c.IsDefault();
    }
})

When I call my typed factory with a FileInformation coming from the "Documents" directory, the component is resolved correctly. But when I call the typed factory with any other directory name, it fails because it cannot find the name, but it doesn't seem to take into account the fact that there is a default implementation that could match it.
Any way to manage a named resolution of the component with a fallback on the default component if the name is not found?

A:

In the Breaking changes txt file for Castle V3 there is an explicit reference to this very problem:

change - Typed factory using DefaultTypedFactoryComponentSelector when
  resolving component by name will not fallback to resolving by type if
  component with that name can not be found and will throw an exception
  instead.

id - typedFactoryFallbackToResolveByTypeIfNameNotFound
impact - medium
fixability - easy

description - Original behavior from v2.5 could lead to bugs in cases
  when named component was not registered or the name was misspelleed
  and a wrong component would be picked leading to potentially severe
  issues in the application. New version adapts fail-fast approach in
  those cases to give dvelopers immediate feedback the configuration is
  wrong.
fix - Actual fix depends on which part of the behavior you want:

If you do care about the fallback behavior, that is get the component by name and if not present fallback to resolve by type, you
  can specify it explicitly when registering your factory: .AsFactory(new DefaultTypedFactoryComponentSelector(fallbackToResolveByTypeIfNameNotFound: true));

I don't really like that there is no alternate "official" way of doing this, since the property is marked as being present only for backward compatibility and its usage not being recommended, but at least it works.
If you know of a better way, I'd be very interested in hearing it :)


Q:

A student is cheating and I don't know how

I'm teaching a course at a community college called "Business Pre-Calculus", which is basically some varied rudimentary algebraic concepts integrated with some topics from basic economics and finance.
I give in-class exams for which calculators are provided and the use of a phone is prohibited. On the last exam, a student who had conceptual difficulty adding fractions, on the same test was able to solve a 3x3 linear system, a complicated rational equation, and an even more complicated rational inequality. His work in the space provided is mimnimal and makes absolutely no sense (I've already considered the "savant" possibility), and I cannot fathom how he could have come up with the correct solutions to each with any of these ridiculous "calculations". They resemble what you might see on a chalkboard in a cartoon: nonsense made to look like math to an ignorant observer. In all honesty, I feel like he gets the answers somehow, and then scribbles some "work" to avoid suspicion. But his answers are still correct, and seemingly out of nowhere.
I've watched him take the test, but didn't see anything suspect. What am I missing?
Thanks.
Update: I've removed the picture.

A:

First off, I challenge the framing of the question.  You seem to be seeking answers for the question

How did the student get the correct answer from this work?

Unfortunately, I don't think that there is any possible way to answer that question without being the student.  Maybe they cheated.  Maybe they got lucky.  Maybe they did some work in their heads but were unable to communicate that work in writing.  Maybe they saw that exact problem in a homework assignment or study guide somewhere and somehow managed to memorize a correct answer.  Without being in the head of the student, it is entirely impossible to know how they got that answer.
Instead, I think that there is a related question which can be answered:

If a student writes gibberish followed by a correct answer, what should I do?

In the classes that I teach, I strongly emphasize that most of mathematics is not about obtaining the correct answer, but about communicating to others how that answer was obtained.  If you cannot communicate how you arrived at an answer, then you haven't done the basic work necessary for conducting mathematics.
In an exam setting, I make it very clear (both on the syllabus and in the instructions for the exam) that correct answers without supporting work will receive no credit.  In this case, I don't see any work that I would be willing to give credit for (though I might be a harsh grader; Dave L Renfro sees some merit in a bit of what is there, and he isn't wrong; I do see an attempt to combine the terms with a common denominator—that is a reasonable start; that being said, I still probably wouldn't give it any credit).  I don't need to know how the student got the correct answer in order to know that they haven't explained that answer.
That being said, if the student came to my office to challenge the marking, I would be willing to hear them out.  If they could explain to me how to solve a similar problem that present to them on the fly, I would be willing to give them a handful of points on the exam (say 2-4 out of 10), with the admonition that, in the future, I won't be so generous (it is quite difficult to offer the option to revise a final, since grades are due pretty quickly after the final is graded).  I might even encourage this student to come and talk to me; not even under the "guise" of helping them—they clearly need help, whether it be help with their mathematical skills, or help with their cheating technique. ;)
I will also point out that I am very carefully avoiding the issue of cheating entirely.  Yes, it is very possible that the student cheated.  But if you don't have any evidence of that (other than some suspicious answers on an exam), accusing the student of cheating does absolutely nothing to resolve the situation.  It is probably better to assume good faith and let the student prove in office hours that they have no idea what they are doing.  Whether they are cheating or not, they aren't going to get credit for something that they don't understand.

A:

Do you give full credit for answers without clear work?? If you don't then I suggest you give partial credit and meet with the student in the guise of helping him write his work more clearly so that he can get full credit next time and possibly even a little more credit.  Put the responsibility on him to explain how he got his answer and help him write what he did clearly.  If he can't explain what he did, then explain that this is why he can't have any additional credit. IF he is interested, go over the method with him.  Find out if he has trouble writing down his thinking in general.
In my years as a teacher, I have seen students who can do all sorts of things in their heads and have no clue how to write it down.  These students didn't cheat, just learned and worked differently. All their thinking was done in their heads and trying to write things down interfered with their thinking. If you required that they wrote something down it rarely matched up with what they did in their head.

A:

From the picture you gave, it seems like he wasn't cheating. The whole solution, including how he got there, is there, even though in a bad style and wrong in some places:
He started by getting the left hand side on one fraction by multiplying the first one by
$$\frac{x+2}{x+2}$$ and the second one by $$\frac{x-1}{x-1}.$$
This is the first line of the calculations block on the right.
In the next line, we get this, namely
$$\frac{4x+8}{(x-1)(x+2)} - \frac{2x-2}{(x-1)(x+2)}.$$
Now we have an arrow pointing to the left in his solution, towards
$$\frac{4x+8}{2x+2}.$$
I don't see how he got that, maybe he did a mistake substracting the fractions, maybe it has something to do with the unreadable word he put there.
Now, he tries to test where this expression is positive or negative to get to the solution. I also don't see how he got $-1$ and $3$ here, but he surely had a reason...
All in all, I think he knew what he was doing. Of course there are some errors and the solution is almost unreadable, but still, I would not think that this student was cheating. I would think it is either that he thinks himself to clever to write such trivialities down, or he doesn't know how to properly document his work. Thus, I would suggest to talk to him, find out what is the case and then explain to him that he needs to properly write down things; both for you to understand it, and for him to avoid doing mistakes.
If possible you should teach him resp. your whole class that writing things down properly, even in seemingly easy cases, helps a lot with avoiding and tracking down calculation errors. And yes, such errors happen, to everyone.
Best example I can think of right now is the Gaussian algorithm to solve systems of linear equations. It might seem boring and students always want to be clever and do a really intelligent trick to solve the system faster, but in the end, just following the algorithm strongly reduces the number of errors due to slip of the pen.


Q:

My BindingContext event is not triggering when get new value

I'm setting up an easy form, and I want to get notified when some inputs of the form were changed, so I binded my model to the form and wrote some handlers for the BindingContextChanged event and each inputs change.
I have already tried to make the inputs two way binding and also by setting the binding context in every input change.

        private void ContextChanged(object sender, EventArgs e)
        {

            if(_oldContext == null)
            {
                _oldContext = BindingContext as MyModel;
            }

            var newContext = BindingContext as MyModel;

            if (newContext != _oldContext)
            {
               // Do something...
            }

        }

I'm really new to Xamarin.Forms.
I want to know which is the best form to actually do this. Thank you all!
Sorry about my english level, i'm working hard on it.

A:

I want to get notified when some inputs of the form were changed, so I binded my model to the form and wrote some handlers for the BindingContextChanged event and each inputs change.

I guess that you bind viewmodel to current page Bindingcontext,for example, there is one entry control in current page, now you want to BindingContext will update when you change Entry'Text?
If yes, I suggest you can implement INotifyPropertyChanged in model, in order to notify when Entry'text changed.
 <StackLayout>
        <Entry Text="{Binding str}" />

        <Button
            x:Name="btn1"
            Clicked="Btn1_Clicked"
            Text="btn1" />
    </StackLayout>

   public partial class Page1 : ContentPage
{

    public Page1()
    {
        InitializeComponent();
        this.BindingContext = new MyModel();
    }

    private void Btn1_Clicked(object sender, EventArgs e)
    {
        MyModel model = BindingContext as MyModel;
        Console.WriteLine("the string is {0}",model.str);
    }
}

public class MyModel: INotifyPropertyChanged
{
    private string _str;
    public string str
    {
        get { return _str; }
        set
        {
            _str = value;
            RaisePropertyChanged("str");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void RaisePropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

You can see some code above,Entry'Text bindind one property str, str in My Model class that implementing INotifyPropertyChanged, so when you change entry'text, BindingContext will update.


Q:

Part of click function not working on first click

I have a series of  elements within a table that, in my context, are "slots" of a space that a user can select. Each slot has an attribute (data-slot-stamp) that holds the ID (a timestamp) of the slot. When the user clicks a slot, that timestamp is added to another element's (.addButton) attribute data-selected-slots. If the user clicks the slot again, that slot is to be removed from the .addButton's data-selected-slots attribute.
The below snippet is working, except on the first click IF a user is removing the slot from their selection.
Example of desired behavior:

User clicks any slot
The value of that slot's data-slot-stamp attribute is added to the value of the data-selected-slots attribute of the .addButton element
If the user clicks that same slot again, the value of that slot's data-slot-stamp attribute should be removed from the value of the data-selected-slots attribute of the .addButton element.

What's happening in my case:

User clicks any slot
The value of that slot's data-slot-stamp attribute is added to the value of the data-selected-slots attribute of the .addButton element
If the user clicks that same slot again (but ONLY if it was the FIRST slot clicked since a page refresh) the value of that slot's data-slot-stamp attribute is NOT removed, but stays in the value of the data-selected-slots attribute.
On subsequent clicks of any slot, the functionality works as expected but the initially clicked slot's data is never removed.

Html Structure:

                Slot 1

                Slot 2

                Slot 3

                     Add Button

Relevant jQuery:
    $('.spacesTable').on('click', '.slot.used', function() {
        var curAtts = $(this).siblings('.addButton').attr('data-selected-slots');
        var clickedStamp = $(this).attr('data-slot-stamp');

        if ($(this).hasClass('unselected')) {
$(this).addClass('selected').removeClass('unselected');
            //Add to the values stored in the data-selected-slots attr of the button for this row
            var spacer = ',';
            if (!curAtts) {
                curAtts = '';
                spacer = '';
            }
            $(this).siblings('.addButton').attr('data-selected-slots', clickedStamp+spacer+curAtts);

        } else if ($(this).hasClass('selected')) {
$(this).removeClass('selected').addClass('unselected');
            //check to see if the slot timestamp is in the button's data-selected-slots attr, and if so, remove it
            var findStamp = curAtts.indexOf(clickedStamp);
            if (findStamp != -1) {
                curAtts = curAtts.replace(clickedStamp+',','');
                $(this).siblings('.addButton').attr('data-selected-slots', curAtts);
            }

        }
     });

A:

Because the ","
change this:
curAtts = curAtts.replace(clickedStamp+',','');

with something like:
if (curAtts.indexof(",") > 0) {
    curAtts = curAtts.replace(clickedStamp+',','');
}else{
    curAtts = curAtts.replace(clickedStamp,'');
}

hope it helps


Q:

cloudformation ecs force new deployement

What is the equivalent of --force-new-deployment flag in cloudformation ?
(aws ecs update-service --cluster  --service  --force-new-deployment)
In my cloudformation template, my docker image tag is latest. However I want to be able to force the redeployment if I replay the stack.
Thanks you

A:

Think of CloudFormation as just a provisioning service or an orchestrator.
Specifying an Image as repository-url/image:tag will definitely fetch the specified image with specific tag from your repo but only upon a stack operation. Once a stack operation is finished, any changes to service will be depending on the next stack operation.
What you can do here is either having either

Cloudwatch Event based rule targeting a Lambda Function whenever there is an image upload to ECR.
Or in case of using some other repo than ECR, have a hook configured in a way that will invoke update-service --cluster --service --force-new-deployment ... command whenever there is a new image upload.

Considerations:

This can lead your stack being in DRIFTED status.
Just make sure to keep your stack's Image property's value in sync with the latest one running within service, whenever you plan to update the stack.


Q:

#1130 - Host ‘localhost’ is not allowed to connect to this MySQL server

I issued a command of:
DROP USER 'root'@'localhost'; GRANT ALL PRIVILEGES ON . TO 'root'@'%';

...in PhpMyAdmin. Immediately after the execution, I was forced out PhpMyAdmin.  I got:
error

#1130 - Host 'localhost' is not
  allowed to connect to this MySQL
  server,

how to resolve my problem?

A:

Use the IP instead:
DROP USER 'root'@'127.0.0.1'; GRANT ALL PRIVILEGES ON . TO 'root'@'%';

For more possibilities, see this link.
To create the root user, seeing as MySQL is local & all, execute the following from the command line (Start > Run > "cmd" without quotes):
mysqladmin -u root password 'mynewpassword'

Documentation, and Lost root access in MySQL.


Q:

Is there any way to check which baud rates are supported on a serial device?

Is there any way to check which baud rates are supported for a serial device on Linux?
I've poked around the /sys/class/tty/ttyS0 directory, but I can't see anything in there that lists this type of information.

A:

Little bash script:
From sawdust's answer, there is my solution:
for bauds in $(
    sed -r 's/^#define\s+B([1-9][0-9]+)\s+.*/\1/p;d' < \
        /usr/include/asm-generic/termbits.h ) ;do
    echo $bauds
    stty -F /dev/ttyS0 $bauds && echo Ok.
done  2>&1 |
    pr -at2

Will render on my host:
50                              Ok.
75                              Ok.
110                             Ok.
134                             Ok.
150                             Ok.
200                             Ok.
300                             Ok.
600                             Ok.
1200                                    Ok.
1800                                    Ok.
2400                                    Ok.
4800                                    Ok.
9600                                    Ok.
19200                                   Ok.
38400                                   Ok.
57600                                   Ok.
115200                                  Ok.
230400                                  Ok.
460800                                  Ok.
500000                                  Ok.
576000                                  Ok.
921600                                  Ok.
1000000                                 Ok.
1152000                                 Ok.
1500000                                 Ok.
2000000                                 stty: /dev/ttyS0: unable to perform
2500000                                 stty: /dev/ttyS0: unable to perform
3000000                                 stty: /dev/ttyS0: unable to perform
3500000                                 stty: /dev/ttyS0: unable to perform
4000000                                 stty: /dev/ttyS0: unable to perform

That is, but this won't mean it will work!
You have to test them with your cable and your device...

A:

You can check the device baud rate using the "stty" command on the console:
$ stty < /dev/tty..      (where tty... is the device file you are listening)

output:
speed 9600 baud; line = 0;
-brkint -imaxbel

You can also change the baud rate with the following command:
$ sudo stty -F /dev/tty... 9600    (or whatever baud rate number)

A:

You seem to be asking two different questions.

Is there any way to check which baud rates are supported on a serial device?

The answer would depend on (1) the capabilities of the hardware, i.e. the UART/USART/SCC,  and the range of divisors that the device driver can use in the baud rate generator; consult the device data sheet; (2) the frequency of the clock/oscillator connected to the serial port device; consult the board documentation.

Is there any way to check which baud rates are supported on Linux?

The one of the defined baud rates in include/asm-generic/termbits.h for the c_cflag member of the terminal control structure is the typical method that the serial port (i.e. UART/USART) device driver receives for the baud rate configuration value.
#define  B0     0000000         /* hang up */
#define  B50    0000001
#define  B75    0000002
#define  B110   0000003
#define  B134   0000004
#define  B150   0000005
#define  B200   0000006
#define  B300   0000007
#define  B600   0000010
#define  B1200  0000011
#define  B1800  0000012
#define  B2400  0000013
#define  B4800  0000014
#define  B9600  0000015
#define  B19200 0000016
#define  B38400 0000017

#define    BOTHER 0010000
#define    B57600 0010001
#define   B115200 0010002
#define   B230400 0010003
#define   B460800 0010004
#define   B500000 0010005
#define   B576000 0010006
#define   B921600 0010007
#define  B1000000 0010010
#define  B1152000 0010011
#define  B1500000 0010012
#define  B2000000 0010013
#define  B2500000 0010014
#define  B3000000 0010015
#define  B3500000 0010016
#define  B4000000 0010017

Serial port drivers typically do not have any means of reporting/advertising which of these baud rates are actually supported/configurable/implemented.  There is a capabilities value for attributes like FIFO and sleeping but not for baud rates.  A driver could define an ioctl() call to configure (nonstandard) baud rates, although that would make programs using it non-portable.


Q:

Are there drawbacks between reading stories from ebooks rather than paper books?

Talking of story books:
The ebooks are much cheaper than the paperbacks of the same title.
I am not rich so I am considering buying ebooks for the child and let her read on the laptop rather than the paperbacks.
Are there serious drawbacks with regards to children reading from ebooks verses paperbacks?
Is some age factor involved here?
My infant can't read right now.

A:

The only thing that really matters is that you read with her regularly as part of a bedtime or playtime routine.
If you find a way to make the laptop work for you so that you both can read it together comfortably before bed, that is excellent. Books themselves are so much less important than enjoying reading that it doesn't even compare. There is no harm at all in using the laptop and if it doesn't work, trying something else.

With that said, for learning to read at the infant level, books are probably better (see below), and there are cheaper options than buying new that you can easily take advantage of.
If you don't have much money, my recommendation is to seek out local public libraries, charities, and parent's groups.
Public libraries are free except for the time cost (and the children's section is a great place to take your child, just as a meeting area), and local charity stores (at least in the UK) normally have a books section where the books are going for literal pennies. If that's below your threshold (and even if it's not), you probably qualify for a free book scheme like Booktrust (if you're in the US, I found this list of potential charities that do the same stuff).
As for parent's groups, if someone in our children's group was looking for books, we'd be happy to offload a library's worth of books we no longer need for our daughter (besides promoting reading, we could use the space). Ask around. Anyone who's moving or whose child has grown out of their baby books will jump at the chance to do something positive with them.

In terms of your original question, there are several issues with replacing children's books with ebooks.
One is that for the very young or those who are just learning to read, the tactile sensation of turning pages makes books attractive. This is probably the least relevant in some ways, as kids also love buttons for the interactivity, but it matters. You can trace words on a page in a way that you don't really on a computer screen.
The second is that children's books are generally big, bright, bold pictures and small amounts of text per page. This isn't what dedicated e-readers are designed to do, and the ebook market reflects that. Books for the very young or early readers simply don't come out on Kindle etc. The only device that successfully compares is the iPad, and that's just too expensive. (Although the Reading Rainbow app is apparently excellent).
And unless you're using a dedicated e-reader like a Kindle or a Nook, the light coming out of a computer screen makes it hard to read for long periods. Couple that with the low resolution of most computer screens, which has a far greater relative effect on text than on pictures, and you get a very poor reading experience. That could well have an effect on how comfortable they are with reading, and how much they look forward to/avoid it.
And a laptop isn't a great reading experience anyway. I can curl up in a chair with a Kindle quite happily, but my laptop really requires me to be sitting at a desk. I can't carry my laptop around like I do a book.
Another issue is that the computer will never be "hers", and a book can be. I've come in to find my daughter leafing through one of her books saying "Readingreadingreading". That's wonderful. If I came in to find her punching the buttons on my laptop saying the same, not so much. The books can stay in her room, they can be available when I need to work on the laptop, they are in essence her books which I read to her until she's ready to read. That has an effect.
But the most critical is that laptops do more interesting things. If you're using the same device for videos and for reading, you may well find that your child doesn't want to read when the computer could be showing Spongebob instead. And she will want to press the keys, which is far more interruptive than when she tries to turn the pages of a book.
Also, in terms of expense, my daughter has trashed at least one e-Reader already and has changed settings on my laptop I didn't even know existed (who knew Vista could turn the screen sideways if you hit the correct key sequence?), but her best attempts to destroy books have been easily countered with some tape, and nothing significantly damages a cardboard baby book, not even drowning it in the bath. I've returned children's books to the library with pages taped back in and they've been fine with it, it's budgeted for. Your savings on books may be replaced by a catastrophic expense when she pulls your laptop off the table for "stories".
Regarding age, the tactile stuff is less relevant to a child that's already happy and comfortable with reading, although some studies suggest paper-based information is more easily retained. A 10-year old is likely to be as happy with a screen as with a printed page.
But as I said at the start, the important thing is to make regular reading something your child is comfortable and happy with, and that they associate reading with that experience. What they read is far less relevant, and what they read it even less. And the best way to do that is to read with her.


Q:

How to remove a UIViewController?

At some point in my application workflow, I have one showing UIViewController. And as I press the Home button, I leave the application, leaving it running in the background.
However, when I return to the app, I would like the showing UIViewController not to appear again. I would like it to be removed or destroyed or anything like that.
How can I accomplish that?

A:

You may add observer to UIApplicationDidEnterBackgroundNotification in your viewcontroller class. Try this in the init method:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];

then in the enterBackground method, you can pop or dismiss your viewcontroller.
remember call this
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];

in the dealloc


Q:

Protecting the contents of an image from enclosing tikz style specifications

Consider an image created by the following fig.tex:
\documentclass{standalone}
\usepackage{tikz}

\begin{document}
  \begin{tikzpicture}
    \draw[thick,solid,->] (0,0) -- (1,0);
    \draw[thick,solid,->] (0,0) -- (0,1);
    \draw[thick,solid,->] (0,0) -- (-1,-1);
  \end{tikzpicture}
\end{document}

Let's compile it with latex -> dvips -> ps2pdf to create fig_latex.pdf and with pdflatex to create fig_pdflatex.pdf.
Then include these figures in the following:
\documentclass{standalone}
\usepackage{graphicx}
\usepackage{tikz}

\begin{document}
  \begin{tikzpicture}
    \draw (0,0) node[draw] {regular: \includegraphics{fig_latex.pdf}};
    \draw (0,-3) node[draw, dashed] {dashed latex: \includegraphics{fig_latex.pdf}};
    \draw (0,-6) node[draw, dashed] {dashed pdflatex: \includegraphics{fig_pdflatex.pdf}};
  \end{tikzpicture}
\end{document}

All we're doing is defining TikZ nodes and including the images inside. Now the problem is that for the image compiled with latex the enclosing dashed specification gets transferred to the image itself, something that doesn't happen with the image compiled with pdflatex:

Is there a way to protect the contents of the image on the enclosing level, without having to, say, recompile the existing image file using pdflatex?

A:

Well you can reset the dash pattern with \pdfliteral{ [] o d}. But I'm not sure if this is worth it. There can be other graphic parameters which can be wrong. See also Tikz changes included graphics
\documentclass{standalone}
\usepackage{graphicx}
\usepackage{tikz}
\begin{document}
  \begin{tikzpicture}
    \draw (0,-3) node[draw, dashed] {dashed latex: \includegraphics{fig-latex.pdf} };
    \draw (0,-6) node[draw, dashed] {dashed latex: \pdfliteral{ [] o d}\includegraphics{fig-latex.pdf} };
  \end{tikzpicture}
\end{document}


Q:

Overwrite HQL-generation for FetchMany()

I know that I can extend NHibernates HQL-generation to support new methods as described in this article. If I implement IRuntimeMethodHqlGenerator it will also work for generic methods.
But is there a way to overwrite NHibernate's default behavior for already supported methods? In this specific case I want to overwrite how NHibernate deals with calls to FetchMany().
Just hooking up a custom generator doesn't work as it is never called.

A:

I'm not sure exactly what you're trying to accomplish, but you might want to have a look at the NHibernate Linq Inner Join Fetch provider project for guidance.


Q:

How can I create a triangulated sphere using 'isosurface' function of MATLAB

How can I create a Triangulated sphere with faces of triangles with the same area each one.
I want something like this,
http://imageshack.us/a/img198/5041/71183923.png
and I searched and saw I could use the function isosurfaceof MATLAB, but the triangles don't have equal area and form and they are essentially squares divided in two with the square diagonal.
here's my code:
>> [X,Y,Z] = meshgrid(-10:10,-10:10,-10:10);
>> V = sqrt(X.^2+Y.^2+Z.^2);
>> fv = isosurface(X,Y,Z,V)
>> p = patch(fv);
>> set(p,'EdgeColor','g')

and the result is below:
http://imageshack.us/a/img818/7125/72103297.png

A:

Use this function from file exchange
function [p, t] = TriSphere(N, R)
% TRISPHERE: Returns the triangulated model of a sphere using the
% icosaedron subdivision method.
%
% INPUT:
% N (integer number) indicates the number of subdivisions,
%   it can assumes values between 0-inf. The greater N the better will look
%   the surface but the more time will be spent in surface costruction and
%   more triangles will be put in the output model.
%
% OUTPUT:
% In p (nx3) and t(mx3) we can find points and triangles indexes
% of the model. The sphere is supposed to be of unit radius and centered in
% (0,0,0). To obtain spheres centered in different location, or with
% different radius, is just necessary a traslation and a scaling
% trasformation. These operation are not perfomed by this code beacuse it is
% extrimely convinient, in order of time perfomances, to do this operation
% out of the function avoiding to call the costruction step each time.
%
% NOTE:
% This function is more efficient than the matlab command sphere in
% terms of dimension fo the model/ accuracy of recostruction. This due to
% well traingulated model that requires a minor number of patches for the
% same geometrical recostruction accuracy. Possible improvement are possible
% in time execution and model subdivision flexibilty.
%
% EXAMPLE:
%
%  N=5;
%
%  [p,t] = TriSphere(N);
%
%  figure(1) axis equal hold on trisurf(t,p(:,1),p(:,2),p(:,3)); axis vis3d
%  view(3)

% Author: Giaccari Luigi Created:25/04/2009%
% For info/bugs/questions/suggestions : giaccariluigi@msn.com
% ORIGINAL NAME: BUILDSPHERE
%
% Adjusted by Rody Oldenhuis (speed/readability)

    % error traps
    error(nargchk(1,1,nargin));
    error(nargoutchk(1,2,nargout));
    if ~isscalar(N)
        error('Buildsphere:N_mustbe_scalar',...
            'Input N must be a scalar.');
    end
    if round(N) ~= N
        error('Buildsphere:N_mustbe_scalar',...
            'Input N must be an integer value.');
    end

    % Coordinates have been taken from Jon Leech' files

    % Twelve vertices of icosahedron on unit sphere
    tau = 0.8506508083520400; % t   = (1+sqrt(5))/2, tau = t/sqrt(1+t^2)
    one = 0.5257311121191336; % one = 1/sqrt(1+t^2)  (unit sphere)
    p = [
        +tau  +one  +0     % ZA
        -tau  +one  +0     % ZB
        -tau  -one  +0     % ZC
        +tau  -one  +0     % ZD
        +one  +0    +tau   % YA
        +one  +0    -tau   % YB
        -one  +0    -tau   % YC
        -one  +0    +tau   % YD
        +0    +tau  +one   % XA
        +0    -tau  +one   % XB
        +0    -tau  -one   % XC
        +0    +tau  -one]; % XD

    % Structure for unit icosahedron
    t = [
         5  8  9
         5 10  8
         6 12  7
         6  7 11
         1  4  5
         1  6  4
         3  2  8
         3  7  2
         9 12  1
         9  2 12
        10  4 11
        10 11  3
         9  1  5
        12  6  1
         5  4 10
         6 11  4
         8  2  9
         7 12  2
         8 10  3
         7  3 11 ];

    % possible quick exit
    if N == 0, return, end

    % load pre-generated trispheres (up to 8 now...)
    if N <= 8
        S = load(['TriSphere', num2str(N), '.mat'],'pts','idx');
        p = S.pts; t = S.idx;
        if nargin == 2, p = p*R; end
        return
    else
        % if even more is requested (why on Earth would you?!), make sure to START
        % from the maximum pre-loadable trisphere
        S = load('TriSphere8.mat','pts','idx');
        p = S.pts; t = S.idx; clear S; N0 = 10;
    end

    % how many triangles/vertices do we have?
    nt = size(t,1); np = size(p,1); totp = np;
    % calculate the final number of points
    for ii=N0:N, totp = 4*totp - 6; end
    % initialize points array
    p = [p; zeros(totp-12, 3)];

    % determine the appropriate class for the triangulation indices
    numbits   = 2^ceil(log(log(totp+1)/log(2))/log(2));
    castToInt = ['uint',num2str(numbits)];

    % issue warning when required
    if numbits > 64
        warning('TriSphere:too_many_notes',...
            ['Given number of iterations would require a %s class to accurately ',...
            'represent the triangulation indices. Using double instead; Expect ',...
            'strange results!']);
        castToInt = @double;
    else
        castToInt = str2func(castToInt);
    end

    % refine icosahedron N times
    for ii = N0:N
        % initialize inner loop
        told  = t;
        t = zeros(nt*4, 3);
        % Use sparse. Yes, its slower in a loop, but for N = 6 the size is
        % already ~10,000x10,000, growing by a factor of 4 with every
        % increasing N; its simply too memory intensive to use zeros().
        peMap = sparse(np,np);
        ct    = 1;
        % loop trough all old triangles
        for j = 1:nt

            % some helper variables
            p1 = told(j,1);
            p2 = told(j,2);
            p3 = told(j,3);
            x1 = p(p1,1); x2 = p(p2,1); x3 = p(p3,1);
            y1 = p(p1,2); y2 = p(p2,2); y3 = p(p3,2);
            z1 = p(p1,3); z2 = p(p2,3); z3 = p(p3,3);

            % first edge
            % -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

            % preserve triangle orientation
            if p1 < p2, p1m = p1; p2m = p2; else p2m = p1; p1m = p2; end

            % If the point does not exist yet, calculate the new point
            p4 = peMap(p1m,p2m);
            if p4 == 0
                np = np+1;
                p4 = np;
                peMap(p1m,p2m) = np;%#ok
                p(np,1) = (x1+x2)/2;
                p(np,2) = (y1+y2)/2;
                p(np,3) = (z1+z2)/2;
            end

            % second edge
            % -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

            % preserve triangle orientation
            if p2 < p3; p2m = p2; p3m = p3; else p2m = p3; p3m = p2; end

            % If the point does not exist yet, calculate the new point
            p5 = peMap(p2m,p3m);
            if p5 == 0
                np = np+1;
                p5 = np;
                peMap(p2m,p3m) = np;%#ok
                p(np,1) = (x2+x3)/2;
                p(np,2) = (y2+y3)/2;
                p(np,3) = (z2+z3)/2;
            end

            % third edge
            % -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

            % preserve triangle orientation
            if p1 < p3; p1m = p1; p3m = p3; else p3m = p1; p1m = p3; end

            % If the point does not exist yet, calculate the new point
            p6 = peMap(p1m,p3m);
            if p6 == 0
                np = np+1;
                p6 = np;
                peMap(p1m,p3m) = np;%#ok
                p(np,1) = (x1+x3)/2;
                p(np,2) = (y1+y3)/2;
                p(np,3) = (z1+z3)/2;
            end

            % allocate new triangles
            %   refine indexing
            %          p1
            %          /\
            %         /t1\
            %      p6/____\p4
            %       /\    /\
            %      /t4\t2/t3\
            %     /____\/____\
            %    p3    p5     p2
            t(ct,1) = p1; t(ct,2) = p4; t(ct,3) = p6; ct = ct+1;
            t(ct,1) = p4; t(ct,2) = p5; t(ct,3) = p6; ct = ct+1;
            t(ct,1) = p4; t(ct,2) = p2; t(ct,3) = p5; ct = ct+1;
            t(ct,1) = p6; t(ct,2) = p5; t(ct,3) = p3; ct = ct+1;

        end % end subloop
        % update number of triangles
        nt = ct-1;
    end % end main loop

    % normalize all points to 1 (or R)
    p = bsxfun(@rdivide, p, sqrt(sum(p.^2,2)));
    if (nargin == 2), p = p*R; end
    % convert t to proper integer class
    t = castToInt(t);

end % funciton TriSphere


Q:

Is it safe putting a Task, with scoped service dependencies, in a Singleton queue?

I am pretty much using the example provided in Microsoft docs for queuing background tasks.
In this queue I am adding a Func<Task>, to be executed later by QueuedHostedService.
Controller - HTTP POST
...
Func<Task> workItem = () => _mockService.DoWorkAsync(guid);
_queue.QueueBackgroundWorkItem(workItem);
return Ok();

MockService.DoWorkAsync
var data = await _insideMockService.GetAsync();
await _anotherService.Notify(data);

BackgroundTaskQueue.QueueBackgroundWorkItem
private ConcurrentQueue<Func<Task>> _workItems
private SemaphoreSlim _signal = new SemaphoreSlim(0);
public void QueueBackgroundWorkItem(Func<Task> workItem)
{
    if (workItem == null)
    {
        throw new ArgumentNullException(nameof(workItem));
    }
    _workItems.Enqueue(workItem);
    _signal.Release();
}

QueuedHostedService.ExecuteAsync
_currentTask = await _queue.DequeueAsync(cancellationToken);
try
{
    await _currentTask();
...

BackgroundTaskQueue.DequeueAsync
public async Task<Func<Task>> DequeueAsync(CancellationToken cancellationToken)
{
    await _signal.WaitAsync(cancellationToken);
    _workItemsById.TryDequeue(out var workItem);
    return workItem;
}

Startup.ConfigureServices
services.AddScoped<IMockService, MockService>(); // Implements DoWorkAsync
services.AddScoped<IInsideMockService, InsideMockService>(); // DoWorkAsync requires this dependency
services.AddScoped<IAnotherService, AnotherService>(); // DoWorkAsync requires this dependency
services.AddHostedService<QueuedHostedService>();
services.AddSingleton<IBackgroundTaskQueue, BackgroundTaskQueue>();

IMockService.DoWorkAsync method use scoped services. Ref to this method is added to a queue which resides in a singleton service. This queue is later read by a HostedService which is also a singleton.
Is there any chance that the service-references in DoWorkAsync will be disposed before being handled by HostedService? If we exclude the scenarios that the application is gracefully(or ungracefully) shut down.
Some local testruns with maybe a hundred requests (and some added Task.Delay in DoWorkAsync) seems to be working fine but I'm not sure if I'm missing something..

A:

The main problem here is not that reference to Func will be garbade-collected.
Problem is that any scoped service it use can be disposed.
When requests finishes, scope is disposed with all his disposable content. If your services will implement IDisposable - they will be disposed too. And your queued task will try to call disposed service(s) and fail.
And even if your service will not implement IDisposable itself - it may use, directly or indirectly, some other IDisposable object that will be disposed (for example, DbContext).
To make sure this stuff will not fail at some day - you should carefully control all objects/services (and their sub-objects/sub-services) used during DoWorkAsync. In this case - why not you register MockService istelf as singleton? :)
Correct way for background task is to capture IServiceScopeFactory instance, and call CreateScope() before any real job, and obtain any scoped services from it.


Q:

JOptionPane.JOptionDialog get value of input for use in if statements

I have a program that has 2 options in an option dialog and one option should execute one part, the other should execute another part. (I will do this with if statements)
Object reply1;  //Variable that Should be not an object???

    Object[] option = { "Choose a Random Number", "Input a Number"};   //option labels

    JOptionPane pane1;
    pane1 = new JOptionPane.showOptionDialog(null,
        "Text explaining which option to choose\n",
        "Title",
        JOptionPane.YES_NO_OPTION,
        JOptionPane.PLAIN_MESSAGE,
        null,
        option,
        option[0]);

           reply1 = pane1.getInputValue();  //this is the problem.

How do I set a variable to equal a the option chosen and what type of variable should it be?
It has been initialized as an int, String, and Object when I was debugging.

A:

You can simply use an int return value:
int reply1 = JOptionPane.showOptionDialog(null,
   "Text explaining which option to choose\n",
   "Title",
   JOptionPane.YES_NO_OPTION,
   JOptionPane.PLAIN_MESSAGE,
   null,
   option,
   option[0]);

   if (reply1 == JOptionPane.YES_OPTION) {
      // option 1
   } else if (reply1 == JOptionPane.NO_OPTION) {
      // option 2
   }

Related: JOptionPane


Q:

forward declaration not working

My forward declaration doesnt work if i do it like this:
class Manager::TagManager;

namespace UI
{

    class Example
    {
    public:
    ...

    Manager::TagManager* tagManager_;

    };
}

it says use of undefined type. However it works fine like so:
namespace Manager
{
     class TagManager;
}

//same stuff follows

So whats the difference?
is "class Manager::TagManager;" not a declaration of TagManager in namespace Manager?

A:

A rhetorical question: how would you expect the compiler to know whether class Manager::TagManager is a declaration of class TagManager in namespace Manager or a declaration of nested class TagManager in enclosing class Manager? The compiler never heard about Manager before. It has no idea whether it is a class or a namespace. This is what the compiler is trying to tell you by that error message. It actually assumes that Manager is a class type (not a namespace), which has not been defined.
However, even if it knew what Manager was, it still wouldn't work. In C++ qualified names like Name1::Name2 can only be used to refer to existing (i.e. already declared) entities. You cannot use qualified names to declare new entities.
That means that a forward declaration of an entity that belongs to a namespace can only be done by reopening that namespace. A forward declaration of an entity that is nested into a class can only be done inside the definition of the enclosing class.
With entities in namespaces it is relatively easy, since you can reopen namespaces as many times as you want. With nested entities in classes you get only one chance.


Q:

Error on compiling C files generated ya YaCC and Lex

I have two files which I am using to try and generate a parser.
File 1 : drive.l
%{
#include<stdio.h>
#include<string.h>
#include"y.tab.h"
/*
#define START   1
#define STOP    2
#define FWD     3
#define BACK    4
#define UP      5
#define DOWN    6
#define TURN    7
#define LEFT    8
#define RIGHT   9
#define SET     10
#define VAR     11
#define DEGREE  12
#define EQUAL   13
  */
struct VarTab{
    char VarName[50];
    int Id;
    struct Vartab* next;
    };
struct DegTab{
    int Deg,Min,Sec;
    int Id;
    struct DegTab* next;
    };

struct VarTab* VHead=NULL;
struct DegTab* DHead=NULL;
int VTop = 0;
int DTop =0;
%}

delim           [ \t]
ign             {delim}+
var             [a-zA-Z]+[a-zA-Z0-9]+
num             [0-9]
degree          {num}+((\.{num})|(\.{num}\.{num}))?

%%
{ign}           /**/
\n              {printf("\n");}
START           {printf("<STR> ");return(START);}
STOP            {printf("<STP> ");return(STOP);}
FWD             {printf("<FWD> ");return(FWD);}
BACK            {printf("<BAK> ");return(BACK);}
UP              {printf("<UP> ");return(UP);}
TURN            {printf("<TUR> ");return(TURN);}
LEFT            {printf("<LFT> ");return(LEFT);}
RIGHT           {printf("<RGT> ");return(RIGHT);}
SET             {printf("<SET> ");return(SET);}
=               {printf("<EQL> ");return(EQUAL);}
{var}           {printf("<VARIABLE> ");RegVar();return(VAR);}
{degree}        {printf("<DEG> ");RegDeg();return(DEGREE);}
%%

int RegVar(){
    /*
    int i;
    char var[50];
    char* rd = yytext;
    for(i=0;i<=yyleng;i++){
        var[i-1] =  *rd;
        i++;
        rd++;
        }
    var[i-1]='\0';
    VTop++;
    struct VarTab* tmp;
    tmp->Id = VTop;
    strcpy(tmp->VarName,var);
    tmp->next = NULL;
    if(VHead==NULL)
        VHead = tmp;
    else{
        struct VarTab*  parse = VHead;
        while(parse->next!= NULL)
            parse = parse->next;
        parse->next = tmp;

        }*/
    return VTop;
    }

int RegDeg(){
    /*
    int D=0,M=0,S=0;
    int st = 0;
    int i;
    char* rd;
    for(i=1;i<=yyleng;i++){
        if(st==0){
            if(*rd != '.')
                D = (D*10) + (*rd - 48);
            else
                st =1;
            i++;
            rd++;
            }
        if(st==1){
            if(*rd!='.')
                M = (M*10) + (*rd -48 );
            else
                st =2;
                rd++;
                i++;
            }
        if(st==2){
            if(i<=yyleng){
                S = (S*10) + (*rd -48);
                rd++;
                i++;
            }
            }
        }

        DTop++;
        struct DegTab* tmp;
        tmp->Deg = D;
        tmp->Min = M;
        tmp->Sec = S;
        tmp->Id = DTop;
        tmp->next = NULL;
        if(DHead == NULL)
            DHead = tmp;
        else{
            struct DegTab* parse;
            parse = DHead;
            while(parse->next!=NULL)
                parse = parse->next;
            parse->next = tmp;

            }*/

File 2: drive.y
%{
#include<stdio.h>
#include<string.h>

/*#define START   1
#define STOP    2
#define FWD     3
#define BACK    4
#define UP      5
#define DOWN    6
#define TURN    7
#define LEFT    8
#define RIGHT   9
#define SET     10
#define VAR     11
#define DEGREE  12
#define EQUAL   13
*/
void yyerror(const char *str)
{
        fprintf(stderr,"error: %s\n",str);
}

int yywrap()
{
        return 1;
}

main()
{
        yyparse();
}

%}

%token TURN START STOP FWD BACK UP DOWN  LEFT RIGHT SET VAR  EQUAL DEGREE

%%

command :
            /*Empty*/
            | statuscode
            | valuecode
            | motioncode
            ;
statuscode:
            START
            {
                printf("Started.\n");
            }
            | STOP
            {
                prinf("Stoping.\n");
            }
            | UP
            {
                prinf("Up phase.\n");
            }
            | FWD
            {
                print("Forward.\n");
            }
            | BACK
            {
                printf("Backward.\n");
            }
            ;
valuecode:
            SET VAR EQUAL DEGREE
            {
                printf("Initialized a variable:\n");
            }
            ;
motioncode:
            TURN direction
            {
                printf("OK \n");
            }
            ;
direction:
            LEFT DEGREE
            {
                printf("Turning left with value - ");
            }
            | RIGHT DEGREE
            {
                printf("tunring Right with value -");
            }
            | LEFT VAR
            {
                printf("Turning Left with Variable -");
            }
            | RIGHT VAR
            {
                printf("Turning Right with Variable\m");
            }
            ;

%%

I tried to compile the code using the following commands and received and error.
$lex drive.l
$ yacc -d drive.y
$ cc lex.yy.c y.tab.c  -o ex -lfl
drive.y: In function ‘yyparse’:
drive.y:98:24: warning: unknown escape sequence: '\m' [enabled by default]
/tmp/ccMVHgWf.o: In function `yyparse':
y.tab.c:(.text+0x35e): undefined reference to `prinf'
y.tab.c:(.text+0x36c): undefined reference to `prinf'
y.tab.c:(.text+0x37a): undefined reference to `print'
collect2: error: ld returned 1 exit status

I could not find the error, It would be great help if someone could help me solve this problem.

A:

At least 3 errors are easily spotted:

You forgot to use -Wall on your cc command line to get warnings (or whatever your compiler uses to enable warnings)
One of your strings (the one on line 98) has the escape sequence \m, which is meaningless. You probably meant \n
You attempt to call a function prinf (which is not defined) in 2 places.  You probably meant to call printf.  You also attempt to call the undefined print once.