Como exibir parte de um texto armazenado em uma coluna TEXT?

Question: Minha tabela possui um campo TEXT onde insiro texto com parágrafos que são lidos através da função nl2br do PHP.
Faço print de cada coluna da tabela através de mysql_fetch_array e tudo é exibido corretamente:
$res2 = mysql_query("SELECT * FROM `entrada` WHERE `id_destino` =".$_GET['id']);
$row2 = mysql_fetch_array($res2);
echo nl2br($row2['historia']);

Como disse anteriormente, meu texto possui vários parágrafos, mas gostaria de saber como faço para exibir apenas uma parte de tal texto ou um parágrafo apenas?
Não estou conseguindo / sabendo como aplicar essa exceção. Seria no $row2, echo, ou em nenhum dos dois? Poderiam me ajudar?
Comment: vc quer exibir por exemplo os 200 primeiro caracteres do texto ou é exibir somente um paragrafo aleatorio? Cada paragrafo é separado um por um ` `. Se possivel coloque um texto curto de exemplo.
Comment: leia o link: http://www.php.net/manual/pt_BR/function.explode.php e faça assim que acredito que resolva:

`$itens = explode("", nl2br($row2['historia']));`
`echo $itens[0];`
Answer: Seguem vários exemplos para ilustrar as possibilidades. Basta entender a lógica básica, e recombinar de acordo com o resultado desejado!
Soluções com PHP:
<?php
   $res2 = mysql_query("SELECT * FROM `entrada` WHERE `id_destino` =".$_GET['id']);
   $row2 = mysql_fetch_array($res2);

   $historia = $row2['historia'];

   // Mostrar os primeiros 300 caracteres:
   echo nl2br(
      substr($historia, 0, 300)
   );

   // Mostrar o primeiro parágrafo com PHP 5.3 ou maior:
   echo nl2br(
      strstr($historia, chr(10), true);
   );

   // Mostrar o primeiro parágrafo:
   echo nl2br(
      substr($historia, 0, strpos($historia, chr(10) ) - 1);
   );

   // Mostrar o primeiro parágrafo, ou o próximo,
   // se este tiver menos  de 100 caracteres:
   echo nl2br(
      substr($historia, 0, strpos($historia, chr(10), 100 ) - 1);
   );

   // Mostrar cerca de 300 caracteres, mas sem quebrar palavras:
   echo nl2br(
      substr($historia, 0, strpos($historia, ' ', 300 ) - 1);
   );

?>

Obs: caso vá utilizar textos em UTF-8, dê preferências às funções multibyte mb_substr e mb_strpos
Soluções com SQL:
$id = 0 + $_GET['id']; // SEU SCRIPT ORIGINAL É PORTA PARA SQL INJECTION!
                       // USE mysqli_ E BINDING NO LUGAR DE mysql_

//Primeiros 200 caracteres:
$query = "SELECT LEFT(`historia`,200) FROM `entrada` WHERE `id_destino` = $id"

//Primeiro paragrafo:
$query = "SELECT LEFT(`historia`,INSTR(`historia`,CHAR(10))-1) FROM `entrada` WHERE `id_destino` = $id"

//Cerca de 200 caracteres, quebrando entre palavras :
$query = "SELECT LEFT( `historia`, 199 + INSTR( SUBSTR( `historia`, 200 ),' ' ) ) FROM `entrada` WHERE `id_destino` = $id"

$res2 = mysql_query($query);
$row2 = mysql_fetch_array($res2);
echo nl2br($row2['historia']);

Answer: Você pode utilizar a função substr() da seguinte maneira:
string substr ( string $string , int $start [, int $length ] )

Fonte: Função substr (php.net)
Ficaria assim para mostrar os 30 primeiros caracteres:
echo substr(nl2br($row2['historia']), 0, 30);

ou
<?php
function textLimit($string, $length, $replacer = '...'){
  if(strlen($string) > $length)
  return (preg_match('/^(.*)\W.*$/', substr($string, 0, $length+1), $matches) ? $matches[1] : substr($string, 0, $length)) . $replacer;
  return $string;
}

echo textLimit($row2['historia'], 30);
?>

Answer: Uma alternativa contendo condicionais para evitar erro no terceiro parâmetro da função mb_strpos().
Desse modo não precisa se preocupar com a quantidade de caracteres da string original
/**
O limite de caracteres.
*/
$limit = 10;

/**
A string original
*/
$str = 'lorem ipsum lorem1 ipsum1';

/**
Obtém a quantidade de caracters da string original
*/
$str_l = mb_strlen($str);

/**
Verifica se o limite é menor que a quantidade de caracters.
Caso o limite seja maior, a função mb_strpos() retornará erro de OffSet, por isso, essa verificação é necessária.
*/
echo (($limit < $str_l)? substr($str, 0, mb_strpos($str, ' ', $limit)).'...' : $str);

O problema dessa técnica ou quaisquer outras que utilizam o caracter de espaço é  não ser válida em idiomas que não possuem o caracter de espaço. Portanto, não é uma solução internacionalizada.


Count in a series of 9 digits - javascript

Question: In javascript, how do you count an array with 9 being the highest digit?
Like so:
1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,1 etc...
Answer:

var i =0
while (i++ <= 300 )
 document.body.innerHTML += (((i-1)%9 )+ 1);

Use the % operator. You will need to take 1 away and add to it to get 1-9 instead of 0-8
Assuming a max of 300 ( thought I read 300 but can't see it now)


collecting from parallel stream in java 8

Question: I want to take an input and apply parallel stream on that, then I want output as list. Input could be any List or any collection on which we can apply streams.
My concerns here is that if we want output as map them we have an option from java is like
list.parallelStream().collect(Collectors.toConcurrentMap(args))

But there is no option that I can see to collect from parallel stream in thread safe way to provide list as output.
I see one more option there to use
list.parallelStream().collect(Collectors.toCollection(<Concurrent Implementation>))
in this way we can provide various concurrent implementations in collect method. But I think there is only CopyOnWriteArrayList List implementation is present in java.util.concurrent. We could use various queue implementation here but those will not be like list. What I mean here is that we can workaround to get the list.
Could you please guide me what is the best way if I want the output as list?
Note: I could not find any other post related to this, any reference would be helpful.
Comment: @OleV.V. No need. Collection object does not need to be thread-safe.
Comment: Can't you just pass it a `Collections.synchronizedList(new ArrayList<>())`?
Answer: The Collection object used to receive the data being collected does not need to be concurrent. You can give it a simple ArrayList.
That is because the collection of values from a parallel stream is not actually collected into a single Collection object. Each thread will collect their own data, and then all sub-results will be merged into a single final Collection object.
This is all well-documented in the Collector javadoc, and the Collector is the parameter you're giving to the collect() method:
<R,A> R collect(Collector<? super T,A,R> collector)

Comment: @VipulGoyal If the stream (input) and the collection (output) are both ordered, a concurrent collection won't help, because the values must be collected in order. However, if order does not have to be maintained, and collection is concurrent, then all the parallel threads can add to a single result collection, instead by building intermediate subresults that then needs to be merged.
Comment: @VipulGoyal this is obviously for optimization purposes. Merging big `HashMap`s can be quite expensive and `ConcurrentHashMap` was already there when they implemented streams, so why not just use it?
Comment: I think I missed that part. My initial understanding was that collection that we are passing will only collect as single. But my question here now is that then why we need `Collectors.toConcurrentMap` they could have used simple hash map and then combine, return.
Comment: @Eugene I agree with you that it is expensive to merge `HashMap`s. But what I am thinking now is that why we don't have any better implementation for concurrent list other then `CopyOnWriteArrayList ` which is quite expensive. What is the challenge there, or I am missing something? Anyways I got my answer that all together is different discussion.
Comment: @Vipul Goyal: merging two `HashMap`s implies rehashing all entries of one the the maps. In contrast, merging two `ArrayList`s implies a single plain memory transfer. Further, keep in mind that `Collectors.toList()` does not specify to return an `ArrayList`, not even a mutable list. So a future version could return a different `List` implementation, easier to merge when building, but unmodifiable afterwards…
Answer: But there is no option that I can see to collect from parallel stream in thread safe way to provide list as output. This is entirely wrong.
The whole point in streams is that you can use a non-thread safe Collection to achieve perfectly valid thread-safe results. This is because of how streams are implemented (and this was a key part of the design of streams). You could see that a Collector defines a method supplier that at each step will create a new instance. Those instances will be merged between them.
So this is perfectly thread safe:
 Stream.of(1,2,3,4).parallel()
          .collect(Collectors.toList());

Since there are 4 elements in this stream, there will be 4 instances of ArrayList created that will be merged at the end to a single result (assuming at least 4 CPU cores)
On the other side methods like toConcurrent generate a single result container and all threads will put their result into it.
Comment: ...assuming at least 5 CPU cores! Stream by default uses the ForkJoinPool and ForkJoinPool.commonPool() size by default is Runtime.getRuntime().availableProcessors() - 1
Comment: …assuming at least four CPU cores.
Comment: @Holger I am trying to be attentive to details, but you are way above that... :) thx so much for the comment!
Comment: I think you're right overall, but your reasoning was confusing to me. The [Collectors.toList](http://hg.openjdk.java.net/jdk10/jdk10/jdk/file/777356696811/src/java.base/share/classes/java/util/stream/Collectors.java#l275) implementation does (as you say) create a new `ArrayList` for each part of the stream being processed in parallel, but the merge uses a thread-unsafe `addAll` call to merge the second list into the first before returning the first list (rather than creating a new one), though this is still safe because it merges pairs so there's never 2 concurrent `addAll` calls on one list.
Comment: @CameronStone right. This is also called fold left. You can try `reduce` without creating a new list all the time for the merge function and see it breaking btw, in parallel
Comment: What about the part in `Stream#collect` javadoc saying "If the stream is parallel, and the `Collector` is concurrent, and ..., then a concurrent reduction will be performed (see `Collector` for details on concurrent reduction.)" `Collectors.toList()` creates an `Collector` implementation that is not concurrent. What does it mean then?
Comment: @Behnil what does "this mean"? which "this"? the answer or your question in the comments? can you clarify please
Comment: @Eugene I mean when they say "concurrent reduction will be performed only when parallel collector is used", and `Collectors.toList()` is not parallel, does use of `Collectors.toList()` together with parallel stream make any sense?
Comment: @Behnil `If the stream is parallel` ... `Collector is concurrent` ... `Collectors.toList()` is not a concurrent collector. where is the unclarity here?


Breadcrumb/block settings

Question: Should Views (that are setup as a Page) be able to inherit breadcrumbs/block visibility settings? When I create a Views page, set a path, add it to the menu (then adjust it to be a sub-menu of another parent item), when I am on the actual Views page, it looses (in this case) any block settings that should be shown on this page. From the screen shot below, you can see the menu block disappear (as well as the LEAD logo on the lower left side). More odd than that, is whenever I set the View to be added to a menu (as I have done in the Views settings), it doesn't show up (which is why I had to add it to the menu manually). I've gotten it to work with another Views page (the menu link showing up), but the blocks still disappear.
Also, once you click on an individual node, they also loose any type of breadcrumb/block visibility (even though I've set the URL to be the correct breadcrumb /about/faculty-staff/directory/USER_ID). Any help would be greatly appreciated. Thanks!
Current setup:
Drupal 7.5
Views: 3.0-rc1
Menu Block: 2.2

Screenshot Explanation:
Directory page (Views page - blocks missing from this page)
Main Faculty & Staff page (parent page)
User Profile view
Views config
Menu list
Menu config
Comment: The first thing to do is update to Drupal v7.9, your Views and Menu block look current. also, please clarify that you do not have any articles, pages etc. with the same URL. You can edit your question to reflect any changes in conditions this brings.
Comment: Hi @Joes,
Was fearing that'd be the answer ;) Views hasnt' come out with another RC in quite some time and hate to be mixed in with the madness of a development version - I'm assuming this wouldn't be a core Drupal issue... but maybe its' a combo of all of these freaking out. Thanks again.
Comment: Let us know if upgrading fixes the problem.  Note that interim upgrades usually fix bugs and do not add features.  Each new upgrade is an improvement not a renewed risk.  Moving on to a new Major version such as from 7 to 8 includes new features and more caution is advised.
Comment: Hi @Joes I upgraded Drupal to 7.9 as well as Views to the latest dev - but the issue is still there. I did some searching... http://drupal.org/node/1069502 could this be a core issue? Does my original question make sense? Nodes that are called from a Views listing should keep the block visibility settings of the View itself as long as their path is specified to match the Views page? Thanks.
Comment: That link does look like the same breadcrumb problem.  As for the blocks disappearing, you may have two issues here. What theme are you using?  Have you tried another to see if anything changes (try seven theme - its very basic). I agree that the view settings should work, blocks are dumb, I don't think they change anything. The block is apparently not being called (why? :}).  You may need to start backtracking the call for the blocks through the templates (something I am only beginning to research).  I'm very interested in where this issue goes.
Answer: To your first problem, the menu disappearing on about/faculty-staff/directory:

Check how the menu block is configured.
Check if there is another menu item in another menu that links to this page. It could be that Drupal picks this up and thinks we are in another menu.

(There is a more general solution that I am going to post in another answer)
Answer: A generally useful way to fix all of this:

Use Crumbs to generate the breadcrumbs.
Use Menupoly instead of Menu block, to have your submenus expand for items that are in the breadcrumb trail, even if the current page itself is not in any menu.

Configure Crumbs (7.x-2.*):

Visit the configuration at Admin > Structure > Crumbs > Plugin weights,
Make sure the menu plugin for this specific menu is enabled (or some parent plugin wildcard key). If necessary, give this specific menu a higher priority than other menus.
Go to Admin > Structure > Crumbs > Entity parent > User,
Set about/faculty-staff/directory as the parent path for users with "staff" role.
Alternative: Use the "Path alias" plugin, where the parent path is based on the url alias.

Note.
You could also use Easy Breadcrumbs or Breadcrumbs by path to get breadcrumbs based on url alias. This would be equivalent with only having the "url alias" plugin enabled in Crumbs. But it does not do anything else, and it does not support Menupoly.
Define the menu with Menupoly:

Create a custom module
Implement hook_menupoly(). See the example module for inspiration.
Go to Admin > Structure > Blocks, and move the newly created menupoly block to the sidebar.

E.g.:
/**
 * Implements hook_menupoly()
 */
function MYMODULE_menupoly() {
  return array(
    'sidebar_menu' => array(
      'menu_name' => 'main-menu',
      'expand' => MENUPOLY_EXPAND_ACTIVE,
    ),
  );
}

Good luck!
Answer: The reason behind disappearing of block is still not able to find region in pages just like page.tpl.php.
Suggestions:
1) Create a custom template for views page using theme_preprocess_page in template.php.You have to create template using theme_hook_suggestions under the condition of views page url.
2)Assign or create region in new views page template.
3)Assign your menu block in above region.
Note: You don't need to edit or create any views template like views.tpl.php.It should be custom just like page.tpl.php.
Also block visibility settings should be available to views page url

Breadcrumb/block settings


Using a proxy server with fopen

Question: I'm trying to use fopen to read a remote file from another website. I want to use a proxy to do this, and as far as I know I can do:
$context = stream_context_create(array(
    'http' => array(
        'proxy' => 'tcp://192.168.10.10:80' // The proxy server address and port
    ),
));

$file = fopen($url, 'r', false, $context)

but is there a way to authenticate using a username and password for that proxy? Or am I limited to having to use public proxies?
Also, the proxy definition is tcp://192.168.10.10:80. If I wanted to use a HTTP proxy, am I free to just change it to http://192.168.10.10:80?
Thanks.
Answer: You can use the Proxy-Authorization in the $context if the proxy requires authentication.Example from PHP.Net:
$opts= array(
                 'http' => array(
                 'proxy' => 'tcp://proxyip:8080',
                 'header' => array(
                                     "Proxy-Authorization: Basic $auth"
                                  )
                )
);
$context = stream_context_create($opts);

Also,I think you cannot change tcp to http in tcp://192.168.10.10:80 since what the proxy does is establishing a TCP connection to another server on behalf of a client then route all the traffic back and forth between the client and the server.Obviously it concerns with TCP(sometimes UDP) instead of HTTP.Http proxies just "understand" the traffic delivered by HTTP protocol.
Comment: Thanks, didn't think about sending a header with the request.

Using a proxy server with fopen


Is there any API in Liferay that can be used to create the Journal Article XML Content?

Question: We have a custom Journal Article web content structure and currently using the hard-coded XML content to populate the structure with the values. Is there any API in Liferay that we can make use in order to create the XML content for Journal Article.
Comment: We are creating the journals programmatically. Right now we are hard-coding the XML template based on the DDM structure and dynamically populating it with the values each time with the help of SAXReaderUtil  So far so good. Now we want to get rid of the hard-coded XML template with some API's that helps to generate the XML content for the respective DDM structure.
Comment: There is a general purpose version of this api here: https://www.e-systems.tech/web/guest/truenth-knowledge-base/-/knowledge_base/truenth-cms/api-quick-reference

But I guess it is just for subscribers.
Do you have any special case?
Comment: Sorry, @Victor . This is not what we are looking for.
Comment: hum, I have just noticed, you were looking for a structure and populating it from XML.
This sounds like a native functionality, as web content is stored as XML with in the database. just to get your case straight: XML is holding your content and you wanna access this content? or you want to get your XML and use its values to generate a second piece of content which is based on the first XML, but with a structure as base?
Comment: I am just asking for your steps, as I know there are native functions for either way. if your XML is already on your database and you have the journalarticle, you can simple do Document document = SAXReaderUtil.read( article.getContent() );
Comment: To make it more clear.for ex: Just imagine if we want to parse a Java Object to  XML, we can either hard code the XML for that respective java class or we can use any Java XML parsing library right. We are looking for the second situation in order to create an XML content using it's DDM Structure and values
Comment: so, I guess you are looking for this guy: com.liferay.dynamic.data.mapping.util.FieldsToDDMFormValuesConverter
Answer: I guess you are looking for this guy: com.liferay.dynamic.data.mapping.util.FieldsToDDMFormValuesConverter
<code>DDMFormValues ddmFormValues = DDMUtil.getDDMFormValues(ddmStructure.getStructureId(), ...);
Fields fields = DDMUtil.getFields(ddmStructure.getStructureId(), ddmFormValues);
String content = _journalConverter.getContent(ddmStructure, fields)
</code>


jquery should I use bind or live or is there another way to do this

Question: in my form I have my button like this
<button id="mybutton" type="submit"></button>

I am using query submit to submit the form
 $('#mybutton').click(function()
    {
        $('form#myform').submit();
}

It works for most besides when I hit enter it still submits the form totally by passing the click catch.
I changed button type to button
<button id="mybutton" type="button"></button>

but then it doesn't do anything when I hit enter.
I heard I could use bind or on but not sure how would that help me in this case. Any help will be appreciated
EDIT
If I change the button type from submit TO button, then it does not do anything when I press enter. then I have to manually click the button. If I leave the type to submit it submits my forms on enter by passing jquery net.
Comment: I said if I change the button type from submit TO button, then it does not do anything when I press enter. then I have to manually click the button. If I leave the type to submit it submits my forms on enter by passing jquery net.
Answer: You should bind to the submit event of the form if you want it to be triggered when the form submits by either submit button or pressing enter on the last input.
the form:
<form id="myform">

... input fields here ...

<button type="submit">Submit</button>

</form>

js:
$("#myform").submit(function(){
    alert("the form submit event happened!");
    // here you can either prevent the form
    // from submitting and do an ajax request,
    // or do nothing and let it submit naturally.
});

Comment: What does didn't work mean? What did you try? The code I gave isn't a complete working sample.
Answer: It won't do anything because it's an button type.
But you can try this to "simulate" it and do submit when pressing enter.
$(document).keypress(function(e) {
   if(e.which == 13) {
       $('form#myform').submit();
   }
});

Just to add something, some people claims that you will write 2 times the code like this:
$(document).ready(function(){

   $(this).keypress(function(e) {
     if(e.which == 13) {
       $('form#myform').submit();
     }
   });

   $('#mybutton').click(function() {
     $('form#myform').submit();
   });

});

Isn't much but I will try to do a short way :-)
Comment: word removed if you mean that.
Comment: problem using that is that if I would have to duplicate everything for enter that I have for click. since I want .click and .keypress (enter key only) to behave same way
Comment: I meant that I would have to duplicate all the code I have for click to use with your keypress code...is there a way I can check it with one call??
Comment: I know but question was just to "simulate" the enter not to short the code. But yeah, as you said @Autolycus will be good to have a short way. I'll try something :-)
Comment: fair enough. I will accept your answer. Here is the other question
Comment: http://stackoverflow.com/questions/11620436/how-to-make-this-code-short-for-both-events
Answer: try it as an input tag rather than button? Worth a try
are you trying to make this so if they hit enter it doesn't do anything? only if they actually click it?
to stop a default click:
.click(function(e){
    e.preventDefault();
});

Comment: no I ma trying so if they hit enter or click, they go through my jquery submit!
Answer: To stop the form from submitting inside the click() event, use return false; at the end of the callback.
Answer: I don't think the issue is live vs bind. It probably has more to do with the fact that you are only creating a handler for the click event.


VBA Conditional Formatting of specific Borders

Question: Hej,
So I am trying to use VBA to add conditonal formatting to compensate for some other coding, which changes the ranges from time to time. My problem is, that I only the conditional formatting to apply to xlEdgeRight and xlEdgeLeft. However, VBA always tells me that it cannot set the border style. Any ideas?
Dim rngMark As Range
Dim DateCond As FormatCondition
Dim BordNum As Long

Call wsDef
Set rngMark = wksS.Range("E11:CPB25")

rngMark.FormatConditions.Delete
Set DateCond = rngMark.FormatConditions.Add(Type:=xlExpression, Formula1:="=AND(TODAY()>=E$7,TODAY()<F$7)")
DateCond.SetFirstPriority
With DateCond
    .StopIfTrue = False
    .Font.ThemeColor = xlThemeColorAccent2
    .Font.Bold = True
    .Borders.LineStyle = xlNone
    .Borders.LineStyle = xlNone
End With
For BordNum = 7 To 8
    With DateCond.Borders(BordNum)
        .LineStyle = xlContinuous
        .TintAndShade = 0
        .Color = -16776961
        .Weight = xlThin
    End With
Next BordNum

Answer: Programming formatconditions - especially borders - is a bit special.
You have to use xlLeft = -4131 and xlRight = -4152 in this case:
Dim BordNum As Long
Dim arrBordNum(1) As Long
arrBordNum(0) = -4131   'xlleft
arrBordNum(1) = -4152   'xlright
For BordNum = 0 To UBound(arrBordNum)
    With DateCond.Borders(arrBordNum(BordNum))
        .LineStyle = xlContinuous
        .TintAndShade = 0
        .Color = -16776961
        .Weight = xlThin
    End With
Next BordNum


Updating label Control immediately

Question: My program is receiving data by serial port and I want to show it(the data) by label control.receiving datas are updating consecutive.
How can I refresh value of label immediately?
Comment: Can you please be more specific ? As you receive the value you would have to set it on the label control and refresh the label control.
Comment: http://mattgemmell.com/2008/12/08/what-have-you-tried/
Comment: Most likely your application and the serial port communications are on the same thread, so the class that is listening and reading the data received via the serial port is blocking the UI.  You should probably push the serial port communications to a background thread.  Take a look at the `BackgroundWorker` class.
Answer: Here is what you must do:
first: call your function in new thread :
Thread t = new Thread(new ThreadStart(yourfunction));
t.Start();

second:  you must invoke the Label from your form :
void yourfunction()
{
    while (..) // I think you have a loop in your function
    {
        if (this.label1.InvokeRequired)
        {
            this.Invoke(
            new changeLabelDelegateMethod(changeLabelText), label1, "your text");
        }
        else
            label1.Text = "your text";
    }
}
delegate void changeLabelDelegateMethod(Label l, string text);
void changeLabelText(Label l, string text)
{
        l.Text = text;
}

Updating label Control immediately


Align two divs side by side centered without wrapper

Question: I'm a little rusty with CSS, but I'm hoping someone can help me out. What I really want is to have 2 identical sized/celled tables sitting side by side centered in my page. Here's why I'd like to keep them as 2 individual tables... When the screen is resized more narrow (like on mobile devices), I want the Right table to then sit perfectly centered below the Left table. If I try to do this with tables only, the 2 tables can't sit side-by-side (even if there is enough space). I've read many Q&A's here that lead me towards doing it using a Div wrapper (parent) with the 2 tables inside 2 'child' divs. Problem is, if everything's in the wrapper div, it treats the 2 tables as one big piece and won't send the 2nd table down to the next row when the screen gets more narrow. Short of designing a separate mobile site, any solution for this?
Answer: Run the code snippet below in full screen mode and try to resize the browser. If the result is what you want, customize it to suit your needs.
Edit: You can also use media queries to change your display for screens with a specific size range, as the edited code shows.

#center {
  width:80%;
  margin:auto;
}
.table {
  width:45%;
  min-width:300px;
  height:150px;
  float:left;
  border:1px solid;
  margin:auto;
}
.table table {
  width:100%;
}
td {
  border:1px solid #990000;
}

@media screen and (max-width: 900px) {
.table {
    width:80%;
    float:none;
    margin:auto;
}
}

Comment: That worked great. There are a few brief points when the tables go vertical as I'm scaling the browser window more narrow where they are not centered, but eventually they snap center. I think that has to do with the Bandcamp players doing some auto-truncating of their own. I could try setting them to absolute widths to stop that, but I don't think I'd be happy with a 'one size fits' all with them. It looks good on desktop and mobile, so I'm very happy. Thanks again for the help!
Comment: Pleasure. don't forget to up vote or validate the response :)
Comment: I would vote it all up, but site says I'm too new to have that permission. Thanks again. Just about to make it public!


Overcoming maximum file path length restrictions in Windows

Question: One of our customers habitually use very long path names (several nested folders, with long names) and we routinely encounter "user education issues" in order to shorten the path to less than 260 characters.
Is there a technical solution available, can we flick some sort of switch in Windows 7 and Windows 2008 R2 to say "yeah just ignore these historical problems, and make +260 character path name work".
P.S.  I have read and been totally unedified by Naming Files, Paths, and Namespaces
Comment: Here we are in 2018 and the problem still exists in ROBOCOPY.  255 limit.  Those exceeding it simply beep but don't copy.
Comment: @SDsolar: are you using an old version of robocopy?
Comment: Yes, was going to say the same - one has to use robocopy specifically because it can handle long paths...
Answer: Just mentioning a trick I do not see mentioned here yet.
Take this file for example:
C:\Folder1\Really Long Path\Such Recursion\So Deep\Wow\Still Going\I will run out of ideas soon\I have organizational problems\Obsessive compulsive subdirectory disorder\Here is a guid for no good reason\936DA01F-9ABD-4d9d-80C7-02AF85C822A8\Almost there\Tax Returns\2013\2013_tax_return.pdf
This full file path is 290 characters long. The shell (Windows Explorer) and most command line utilities probably won't let you touch it.
Use the subst command like so:
subst X: "C:\Folder1\Really Long Path\Such Recursion\So Deep\Wow"

Now you can access (and delete, move, etc.) the file thusly:
X:\Still Going\I will run out of ideas soon\I have organizational problems\Obsessive compulsive subdirectory disorder\Here is a guid for no good reason\936DA01F-9ABD-4d9d-80C7-02AF85C822A8\Almost there\Tax Returns\2013\2013_tax_return.pdf
And now that file name is only ~235 characters or so, so you will not encounter the "Filename is too long" problems any more.
In the Windows API, there is an infamous constant known as MAX_PATH. MAX_PATH is 260 characters. The NTFS file system actually supports file paths of up to 32,767 characters. And you can still use 32,767 character long path names by accessing the Unicode (or "wide") versions of the Windows API functions, and also by prefixing the path with \\?\.
MAX_PATH was set in stone a very long time ago in the Windows world. I think it has something to do with ANSI standards at the time... but it's one of those things that's very difficult for Microsoft to change now, as now we have thousands of programs and applications, including some written by Microsoft themselves, that use MAX_PATH and would fail in strange new ways if the constant were suddenly changed. (Buffer overflows, heap corruption, etc.)
Comment: I've been taking an approach similar to `subst` by using directory junctions, which may be more convenient to cleanup if you're just looking to make a few quick changes. I use [Link Shell Extension](http://schinagl.priv.at/nt/hardlinkshellext/linkshellextension.html), but you can just use the `mklink` command like so: `mklink /J C:\Wow "C:\Folder1\Really Long Path\Such Recursion\So Deep\Wow"`.
Answer: You can get around this limitation by using the \\?\C: notation.  It's ugly, but it supports file lengths up to 2^15.
http://msdn.microsoft.com/en-us/library/aa365247(v=vs.85).aspx#maxpath
Comment: Yeah I read that, as I said (see my link).  But how do I benefit from it exactly?  Can I map a drive to \\?\something for example.  I don't understand.  The article is intended for programmers using windows APIs.  Whilst I do code in .NET as the need arises I don't use C++ etc. and can't see how this is relevant for my customers staff who are using windows explorer and the common file dialog etc.
Comment: 7-zip will happily browse and copy in \\?\C: notation, for what it's worth.
Comment: Ultimately, there is none.  :-/  Sadly.
Comment: @ChristopherEdwards you could do a link `c:\usr-data` to `c:\Users\VeryLongUserName\LongFolderName\` and tell him to use the former, but if he regularly names folders in 40-something characters then this won't help...
Comment: @HubertKario Yes, but how would that help me?
Comment: @ChristopherEdwards You can create junctions to points lower in folder hierarchy.
Comment: This also works in standard command line commands like DIR and COPY.
Answer: The methods are there, but until Microsoft re-codes the file-browser widget we're pretty much stuck with that old problem. It's sub-optimal, but that's just how it works.
Comment: Bug in MS software that has been unfixed for few OS releases, that's a new one...
Comment: Windows 10 1607 finally fixed the file-browser problem and has some wizardry to fool Win32 applications in to working in this strange new world of huge paths: https://www.howtogeek.com/266621/how-to-make-windows-10-accept-file-paths-over-260-characters/
Answer: Microsoft now has an available fix for this beginning with Windows 10, which is explained in the Naming Files, Paths, and Namespaces MSDN article.
darthcoder already answered with details on the \\?\C: notation work-around, but there is now a registry key at HKLM\SYSTEM\CurrentControlSet\Control\FileSystem LongPathsEnabled (Type: REG_DWORD) which can be used to remove MAX_PATH limitations for a single system. The article also mentions support for Group Policy control at Computer Configuration > Administrative Templates > System > Filesystem > Enable NTFS long paths for organization or group-wide implementation if needed.
Comment: This doesn't work in File Explorer because although the system and NTFS can handle long paths, Explorer cannot until it is itself re-coded.
Comment: Good info! I will probably just stick to Robocopy in that case.
Comment: I've not had time for thorough testing, but I've seen mixed results with this solution so far, and can't confirm that this solves the problem for Windows [file] Explorer.
Comment: PS, you will need to use one of the copy programs in [this SO link](https://superuser.com/questions/262981/do-fast-copy-programs-work) on top of Explorer to actually make it work.
Comment: where is darthcoder's posting? did he delete it?
Comment: Apparently it's been deleted... strange. There's some good info on it here though: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file   - essentially, the notation allows you to reference file paths that are more than 255 characters long. Works for file share paths too, via \\?\UNC\server\share\.
Answer: #If you are accessing files locally
get-childItem -LiteralPath \\?\e:\TopFolders\

#If you are accessing files through network Share
get-childItem -LiteralPath \\?\UNC\MyFileServerHostName\Share\

source link


Is it possible that the first arrival time of a poisson process is infinite?

Question: Given is a Poisson process $(N_t)_{t \geq 0}$ with intensity $\lambda(t)$. I am interested in finding the distribution of the first arrival time $T$. I can use the fact that for any $t \geq 0$ it holds $T > t$ iff $N_t = 0$. By the definition of the process $N_t \sim Poi(\mu(t))$, where $\mu(t) = \int_0^t \lambda(z) dz$. I get
$$
\mathbb{P}[T > t] = \mathbb{P}[N_t = 0] = \exp(-\int_0^t \lambda(z)dz),
$$
and therefore the distribution is given by $\mathbb{P}[T \leq t] = 1 - \exp(-\int_0^t \lambda(z)dz)$.
If I consider the intensity $\lambda(z) = \frac1{1+z^2}$, I can calculate
$$
\lim_{t \to \infty} \mathbb{P}[T \leq t] = 1 - \exp(-\int_0^\infty \lambda(z)dz) = 1 - \exp(-\frac\pi2) \neq 1,
$$
so $\mathbb{P}[T < \infty] < 1$. Have I done something wrong or is it simply possible that $T$ attains infinity with positive probability, so the process never jumps?
Answer: A homogeneous Poisson process with intensity $\lambda > 0$ almost surely has a finite first arrival time, since $$\lim_{t \to \infty} \Pr[T \le t] = \lim_{t \to \infty} 1 - e^{-\lambda t} = 1.$$
However, as you have observed, this is not the case for an inhomogeneous process, since the cumulative intensity (aka cumulative hazard) need not be an unbounded function of time.  That is to say, if $$\Lambda(t) = \int_{z = 0}^t \lambda(z) \, dz$$ obeys $$\lim_{t \to \infty} \Lambda(t) < \infty,$$ then the first arrival time may not be finite.
Comment: Does this mean that we need to accept (in this case) that $T$ has an unnormalized CDF/PDF? Or we artificially normalize it anyway by adding $\infty$ to the value set of $T$ and define the point mass $\text{Pr}[T=\infty]$ with the missing weight?


Eigenvalues of block matrix of order $m+1$

Question: How to find eigenvalues of following matrix?
$\begin{bmatrix}
mkI-A & -A & -A & \cdots & -A\\
-A & kI-A & O & \cdots & O\\
-A & O & kI-A & \cdots & O\\
\vdots & \vdots & \vdots & \ddots & \vdots\\
-A & O & O & \cdots & kI-A\\
\end{bmatrix}_{m+1}$
Where,
$A$ is any square matrix of order $n$,
$O$ is zero matrix of order $n$
$I$ is identity matrix of order $n$,
$k \in \mathbb{N}$
As well as one eigenvalue of above matrix is zero.
I think if we can convert above matrix in terms of either Kronecker product or Kronecker sum of two matrices then we can find eigenvalues of above matrix by taking multiplication or addition of two matrices respectively.
The other way is might be if we can convert above matrix in block diagonal matrix then we can find eigenvalues easily.
Comment: If you subtract $kI$ from any matrix, it will subtract $k$ from all of the eigenvalues, so your problem reduces to $\left[\matrix{(m-1)kI-A & -A & -A &\cdots&-A\cr -A&-A&0&\cdots&0\cr -A&0&-A&\cdots&0\cr \vdots&\vdots&\vdots&\ddots&\vdots\cr -A&0&0&\cdots&-A\cr}\right]$.
Comment: ya ok then what I have to do solve it further
Answer: At first, to summarize this problem, let replace diagonal factor matrices as:
$$
\begin{bmatrix}
X \\
Y
\end{bmatrix}
=
\begin{bmatrix}
\lambda-mk & 1 \\
\lambda-k & 1
\end{bmatrix}
\begin{bmatrix}
I \\
A
\end{bmatrix}
$$
where $\lambda$ is eigenvalue. Therefore, we can suppose the following determinant:
$$
\begin{aligned}
\det
\begin{bmatrix}
X & A & A & \cdots & A & A \\
A & Y & O & \cdots & O & O\\
A & O & Y & \cdots & O & O \\
\vdots & \vdots & \vdots & \ddots & \vdots & \vdots \\
A & O & O & \cdots & Y & O \\
A & O & O & \cdots & O & Y
\end{bmatrix}
\end{aligned}
$$
Calculation determinant has an important property that each rows can be added or reduced from another row. Thus, top row can be subtracted from bottom row to extract the diagonal factor as $\det(Y)$. Then the block matrix becomes smaller from $(m+1)n$ square to $mn$ square:
$$
\begin{aligned}
\det
\begin{bmatrix}
X-AY^{-1}A & A & A & \cdots & A & O \\
A & Y & O & \cdots & O & O\\
A & O & Y & \cdots & O & O \\
\vdots & \vdots & \vdots & \ddots & \vdots & \vdots \\
A & O & O & \cdots & Y & O \\
A & O & O & \cdots & O & Y
\end{bmatrix}
=&
\det
\begin{bmatrix}
X-AY^{-1}A & A & A & \cdots & A \\
A & Y & O & \cdots & O \\
A & O & Y & \cdots & O \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
A & O & O & \cdots & Y
\end{bmatrix}
\det(Y)
\end{aligned}
$$
Likewise, we repeat this operation until the block matrix becomes $n$ orders matrix. Eventually, the below determinant is obtained:
$$
\det(Y)^m\det(X-mAY^{-1}A)
$$
Now, we attempt to factorize the second determinant $\det(X-mAY^{-1}A)$ using this consideration. Then the whole result is shown below:
$$
\det(\lambda I-(kI+A))^{m-1}
\det\biggl(\lambda I-\cfrac{B+\sqrt{C}}{2}\biggr)
\det\biggl(\lambda I-\cfrac{B-\sqrt{C}}{2}\biggr)
$$
where:
$$
\begin{cases}
B=-2A+k(m+1)I \\
\\
C=4mA^2-5k(m+1)A+k^2(1+m)^3I
\end{cases}
$$
In conclusion, this $n(m+1)$ square matrix has $3n$ kinds eigenvalues. However, $C=O$ case is $2n$ kinds exceptionally because of multiple solution.


Showing that $\cos (\sqrt x)=e^x-2$ has solution in $(0,1)$

Question: I rephrased this problem as finding a solution of $f(x)=e^x-2-\cos(\sqrt x)$ in $(0,1)$. I apply the intermediate value theorem:
$f(0)=e^0-2-\cos0=-2$. The goal is to show $f(1)>0$ (which is true) or to find some other number $c\in (0,1)$ for which it is obvious that $f(c)>0$.
However, $f(1)=e-2-\cos 1$. Without using power series expansions of $e^x,\cos x$ (e.g., explaining this problem to a student in differential calculus) how can I show $f(1)>0$? I tried reasoning using the unit circle to estimate $\cos 1,$ however it is not obvious that $(e-2)>\cos 1$.
Can someone suggest a nicer way to go about this problem (e.g., find a value to plug in that works better than 1 or explain why $(e-2)>\cos 1$ is clear?
Comment: The problem wasn't a good one since it's basically requiring them to memorize decimals. The reason for knowing the decimals is that it allows us to find an approximate to $f(1)$.
Comment: So, what values you which values you want to find without series or computer: e, cos(1), sqrt(2), etc, and may I ask why? What tools are allowed?
Answer: Hint: Cosine is decreasing on $[0,\pi/2]$, and $\pi/4<1$, so
$$
\frac{\sqrt{2}}{2}=\cos\pi/4>\cos 1.
$$
Can you take it from here?
Edit
Note that
$$
\frac{\sqrt{2}}{2}\approx 0.707
$$
while
$$
e\approx 2.718.
$$
I assumed these (rather classical) approximate values were known.
Comment: Without a calculator I cannot. It's not clear to me that $e-2$ is larger than that radical.
Comment: @TheSubstitute: $\sqrt2=\sqrt{\dfrac{100}{50}}\simeq\sqrt{\dfrac{100}{49}}=\dfrac{10}7$
Comment: It is wrong that $\cos (\pi/4)> \cos 1$. Sorry, it is correct, $1$ is not degree, radian.
Comment: $\cos(\pi/4)\approx 0.707>0.540\approx \cos 1$, so the inequality is correct.
Comment: $(e-2)^2 \gt (\frac1{2!}+\frac1{3!}+\frac1{4!})^2 = (\frac{17}{24})^2 = \frac{287}{576} \gt \frac12 = \cos^2(\frac{\pi}{4}) \gt  \cos^2(1) $
Answer: For lack of a better idea, use $\dfrac12=\cos\dfrac\pi3\simeq\cos\bigg[\dfrac13\bigg(3+\dfrac17\bigg)\bigg]=\cos\bigg(1+\dfrac1{21}\bigg)$, along with
$\cos(a+b)=\cos a\cos b-\sin a\sin b$, and $\lim\limits_{t\to0}\dfrac{\sin t}t=1$, implying that $\sin t\simeq t$ for very small
values of t $\bigg($such as $t=\dfrac1{21}$, for instance$\bigg)$. Together with $\sin^2x+\cos^2x=1$, we have obtain
the stunningly beautiful and mesmerizingly elegant expression $\cos1\simeq\dfrac{441+\sqrt{1327}}{884}$ . Now,
just like $\pi\simeq\dfrac{22}7$, we also have $e\simeq\dfrac{19}7$, which is very easy to remember, considering that it's my
birthday in the old Roman calendar, which started in March. If, however, the last statement might seem either too egocentric, or too European-centric, just remember that the Jewish calendar also has a Metonic cycle of $19$ years, $7$ of which are leap years. If even this might sound a tad eccentric, or perhaps just a little too exotic, recall that Leonhard Euler, who discovered the constant, passed away on September $18$, or $18/7$, if once again we are to take into consideration the etymological interpretation of the names of the months of the Roman calendar. So you are basically left with proving that $\bigg(\dfrac57\cdot884-441\bigg)^2>1327$, which is equivalent to showing that $(5\cdot884-7\cdot441)^2$ $>49\cdot1327$, which is trivial.


Why is this segment of "E.T. The Extra-Terrestrial" in B minor and not D major?

Question: This is taken from the "E.T. The extra-terrestrial" score:

There is an analysis of here:

and this screenshot is from 00:40
I do not understand the annotation:
The first bar is written as "B minor", but is there a reason to say it is B minor and not a D major for example? (the same applies for the other bars).
Answer: Analysis is always an interpretive act, meaning there's not always a definitive answer, but rather an answer that, based on the evidence, is the best fit.
As I hear the piece and watch the analysis, there's one main feature that suggests it begins in B minor and not D major: because B minor returns several times elsewhere in the piece. See 2:20, 3:10 (in B major), 4:08, 6:13, etc. In fact, almost the entire second half is based in B minor.
Throughout much of music history, tonal composers have had a preference for monotonality, which basically means beginning and ending in the same key. Since m. 8 here is the beginning of this section, the analyst is probably choosing B minor instead of D major to show that monotonal relationship. And since B minor is present for over half of the piece, it's pretty clear that B minor is the overall tonality.
Comment: Even just jumping into that bar, I think it sounds like B minor rather than D major; the B on the fourth beat seems to be a hint and I suspect there's something in the timbre that suggests minor.
Comment: Thanks for clarifying, since B minor is common through the piece, if really makes sense, but this makes me wonder about the next bar: F minor is not present much through that piece, so is the author deciding bar 2 is in F solely on the bass note and minor because of the presence of Ab?
Comment: @Thomas It seems so. The analyst is taking what's called a *pitch inventory* and labeling the most sensible chord. The A minor label is a bit of a stretch, but honestly the labels aren't that important: more important is the claim of shifting tonal centers.


estimates for Abel's theorem

Question: Suppose $a_1,a_2,\dots$ is a sequence of real numbers with $\displaystyle\sum_{n=1}^\infty a_n =s<\infty$. For $0<z<1$, define $f(z):=\displaystyle\sum_{n=1}^\infty z^n a_n$. By Abel's theorem, we know that $\displaystyle\lim_{z\uparrow 1}f(z)=s$. Is it possible to bound $f(z)$ in terms of $z$ and $s$ without knowing anything about $f$?
Answer: Looks doubtful. Consider $f_n(z) = nz - z^{n+1} - z^{n+2} -\cdots- z^{2n}.$ Then $s=0$ for each $f_n.$ But at the fixed point $z=1/2,$ we have $f_n(1/2) \ge n/2 - n/2^{n+1} \to \infty.$

estimates for Abel's theorem


Invalidate and DrawRectangle don't work together

Question: Imagine a simple .Net 2.0 Windows-Form with a MultilineTextbox that fills the whole form.
I want to (re-)draw a rectangle everytime a key is pressed. In the real application there is fare more logic about the position and stuff of the rectangle - but keep it simple.
I thought: "Lets first invalidate the TextBox and then draw the rectangle." But this doesnt work. The screen flickers shortly - thats it. If I remove the line "invaliate" a
rectangle is drawn - but the old ones keep their position..
Whats wrong? And how do I repaint from scratch?
Thank you in advance for your answers!
private void OnKeyDown(object sender, KeyEventArgs e)
{
        textBox1.Invalidate();

        using (Graphics g = this.textBox1.CreateGraphics())
        {
            int startX = 100;
            int startY = 300;
            int height = 200;

            Brush brush = new SolidBrush(Color.FromArgb(60, 255, 0, 0));

            Pen myPen = new Pen(Color.Black, 2);
            myPen.DashStyle = DashStyle.Dash;

            g.DrawRectangle(myPen, startX, startY, this.textBox1.Width, height);

            g.FillRectangle(brush, startX, startY, this.textBox1.Width, height);
        }
}

Answer: Call this.Invalidate(); on keypress, and move your drawing code to the OnPaint event where it is supposed to go. If you want to completely avoid flicker, you need to draw according to the following guide: C#, double buffer in WinForms?.
You should also keep a List<> of all you rects and draw each one OnPaint as your key press is not the only thing that can invalidate the form and cause a redraw.
Comment: And how is that supposed to help? I don't see it.
Answer: Your approach is flawed. Invalidate() only requests a repaint but it is delayed and happens after you draw the rectangle. So it disappears again immediately.
A short (but wrong) fix would be to replace  Invalidate() with Update(), but don't do that.
You'll have to move the drawing logic to the textBox1.Paint event. And your form needs a (boolean) property to decide whether to draw the Rectangle or not.
Your KeyDown should look like:
private void OnKeyDown(object sender, KeyEventArgs e)
{
    this.DrawRect = true;
    textBox1.Invalidate();
}

Comment: Very inefficient, and you'll lose the Rect when something else Invalidates the Form.
Comment: I like the short (wrong) fix because it seems to work - what's wrong about it?
Comment: If i press a key nothing happens. If i press the key and move the mouse over the area or out of the area- the rectangle is drawn - strange ...
Answer: I was told to use "textBox1.Refresh()" instead of "textBox1.Invalidate();" and it works!
private void OnKeyDown(object sender, KeyEventArgs e)
{
    //textBox1.Invalidate(); - Dont do that
    textBox1.Refresh(); //Dominik Schelenz, my internet Hero for today!

    using (Graphics g = this.textBox1.CreateGraphics())
    {
        int startX = 100;
        int startY = 300;
        int height = 200;

        Brush brush = new SolidBrush(Color.FromArgb(60, 255, 0, 0));

        Pen myPen = new Pen(Color.Black, 2);
        myPen.DashStyle = DashStyle.Dash;

        g.DrawRectangle(myPen, startX, startY, this.textBox1.Width, height);

        g.FillRectangle(brush, startX, startY, this.textBox1.Width, height);
    }
}

Comment: [Refresh() is the same as Update()](http://stackoverflow.com/a/952964/60761). Meaning this is not an efficient way to do this.
Comment: Yes I know - http://blogs.msdn.com/b/subhagpo/archive/2005/02/22/378098.aspx - but Refresh Works and other solutions didnt - so I stick with it.
Comment: Did you test it with Invalidate caused by other events?


Envio De form com Asp net mvc5

Question: Bom dia, estou com um form para enviar onde o botão está fora do form, este formulário possui 50 campos distintos, fiz em html e preciso receber estes dados via post em um controller c#, porém não faço ideia de como receber estes dados, alguém pode me dar uma luz? não estranhem os inputs estarem contidos em uma tabela.
@for (int i = 1; i < 51; i++)
{
    if (i < 10)
    {

                             @i

                    <input type="text" name="inputN_@i" class="form-control form-control-lg" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-sm">

                    <input type="text" name="inputN2_@i" class="form-control form-control-lg" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-sm">

    }
    else
    {

                           @i

                    <input type="text" name="inputN_@i" class="form-control form-control-lg" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-sm">

                    <input type="text" name="inputN2_@i" class="form-control form-control-lg" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-sm">

    }
}

Comment: Se você está utilizando MVC, seria interessante você utilizar um submit (botão) para ele postar o formulário.
Comment: infelizmente o cliente quer que o botão fique em outra parte da da tela totalmente fora  do formulário, para revolver isto pretendo enviar via javascript
Comment: Se o cliente pede... A solução porca e menos ruim na minha visão vai ser chamar um ajax que vai pegar seus campos na tela (serializando o seu formulário).
Answer: Basta você disparar o submit() do form via javascript...

let enviar = function(){
  document.getElementById("formulario").submit();
};
<form id="formulario">
  <input type="text" name="teste" value="teste" />

</form>

<input type="button" value="Submeter" onclick="enviar()"/>

Envio De form com Asp net mvc5


Write propositions strictly using quantifiers

Question: Write the following propositions strictly using quantifiers and give also strictly the negation of the propositions.

All the students of Calculus are athletes.
Each fish has gills.
Some dogs have spots.

Firstly, taking the first proposition into consideration, I have thought that it is equivalent to saying that if $x$ is a student of Calculus, then $x$ is an athlete.
But how do we use the quantifiers?
I have thought of the following:
$\forall x$:$x$ is a student of Calculus, $x$ is an athlete.
But is this enough? Or do we have to build a proposition with more quantifiers ?
Could you give a hint so that I tell you also my efforts for the other two propositions?
Answer: As an example for the first question
Define predicates such that
$C(x):x$ is a student of Calculus.
$A(x):x$ is an athlete.

All the students of Calculus are athletes.

$$\forall x(C(x)\to A(x))$$
Try fill the blanks
$F(x):x$ is a fish
$G(x):x$ has gills

Each fish has gills.

$$\forall x(?~\to~?)$$
$D(x):x$ is a dog.
$S(x):x$ has spots.

Some dogs have spots.

$$\exists x(?~\land~?)$$
Comment: As for the first proposition, the negation is $\exists x (C(x) \land \lnot A(x))$, right?

$$$$

The equivalent expression with quantifiers to the second proposution is $\forall x (F(x) \to G(x))$, and the negation $\exists x (F(x) \land \lnot G(x))$.

$$$$

As for the third proposition, the equivalent expression with quantifiers is $\exists x  (D(x) \to S(x))$, and the negation is $\forall x(D(x) \land \lnot S(x))$.

$$$$

Am I right? Or is something of the above wrong?
Comment: @pingu For the third proposition, the equivalent expression with quantifiers should be $\exists x(D(x)\land S(x))$, everything else is correct.
Comment: Also your translation $∃x(D(x)→S(x))$ is equivalent to $∀x(D(x))→∃x(S(x))$, which says: 'If everything is a dog, then something has spots.' that is not what we want to say.
Comment: Could you explain to me why $\exists x (D(x) \to S(x))$ is equivalent to $\forall x (D(x)) \to \exists x (S(x))$ ?
$$$$

Also the negation of $\exists x (D(x) \land S(x))$ is $\forall x (\lnot D(x) \lor \lnot S(x))$, right?
Comment: @pingu This is one of quantifier distributive law, basicly it wroks because of $\exists$ is distributive over $\lor$, that $\color{red}{∃x(¬D(x)∨S(x))}\equiv\color{blue}{(∃x¬D(x)∨∃xS(x))}$  (also note $\color{red}{∃x(¬D(x)∨S(x))}\equiv∃x(D(x)→S(x))$ and $\color{blue}{(∃x¬D(x)∨∃xS(x))}\equiv\forall
 xD(x)\to∃xS(x)$ by conditional equivalence.) And yes, your negation is correct!
Comment: Nice, thanks a lot!
Answer: Let us speak the set Theory language.
We denote the sets of students of calculus  and athletes by S and A.
then, we will say
$$(\forall x\in S) \;\; x\in A$$
or if we call E, the set of all students, we could write
$$(\forall x\in E)\;\; (x\in S \implies x\in A)$$
Comment: Thank you! @hamam_Abdallah


Does this example of "reverse induction" work?

Question: Say we've shown that some statement $P(1)$ is true. Suppose that we can show $P(m) \iff P(m-1)$. Then, we will have shown $P(m) \iff P(1)$, so $P(m)$ is true. This makes sense, right?
So, with more context, let's say that we would like to show a graph that depends on $n$ with certain properties exists. Then, if we show that it exists for $n = 1$ and then we show that if a graph exists for arbitrary $n$ then we may get the $n-1$ case through edge/vertex deletions, can we say it holds for all $n \in \mathbb{N}$? To be more precise, is this general vertex/edge deletion a "reversible process"?
Answer: False theorem. For all $n$, there is a simple graph with $n$ vertices and $n^2-1$ edges.
Proof. This exists for $n=1$: take the graph with $1$ vertex and no edges.
Suppose it exists for $n$ vertices. Then by deleting a vertex of some degree $k$, and then deleting $(2n-1)-k$ more edges arbitrarily, we get a simple graph with $n-1$ vertices and $(n-1)^2-1$ edges.

This is an instance of the problem. In general, deleting things is not reversible, since you may end up getting from an impossible graph to a possible graph by deleting the places where it's impossible. Even in cases where it is reversible, your proof would be cleaner if you constructed the graphs "forward" rather than "backward".
Comment: Awesome, thanks a bunch for a nice example. The notion of deleting impossible edges/vertices is what I was worried about.
Answer: In your first paragraph, you stated showing implication in both directions and the statement makes sense. In fact, the forward implication is the standard case in normal induction
However, in your second paragraph, you showed only an implication for the reverse direction. You can only claim that if you proved the case for some fixed $k$, and then if $P(k)\implies P(k-1)$, the statement holds true for all $n\leq k$. This is known as backwards induction. You can't say anything about $n>k$.
(Correct me if my interpretation of what you meant is wrong. Because if what you want to show is the existence of a graph and you have shown a graph exist for some arbitrary $k$, you don't need induction?)
Another common induction technique in graphs is Forward-Backward Induction.
Comment: I guess what I'm getting at is: let's say you want to show for every $n$ there exists a graph that satisfies some property. If you assume a graph $G_{m}$ satisfies the property and through edge/vertex deletion you obtain another graph $G_{m-1}$ that satisfies the property, then since edge/vertex deletion is reversible (by just unioning the deleted edges/vertices to their respective sets), you've shown "$P(m) \iff P(m-1)$." Now, what I'd like to say is that if I've shown the property holds for a base case $G_{1}$, then I've shown it for all $n$. I think I'm assuming the conclusion in some way.
Comment: I assume some choice of edge/vertex deletion is needed in your deletion? I don't think it's usually reversible as you claimed. Else, why can't you show it through the normal induction?
Comment: I could show it through regular induction, I agree, but I'm curious to know if this is equivalent. But yeah I think that your point about the choice of edge/vertex deletion is what kills this idea... I guess I am assuming that I may add edges/vertices that build up my base case to higher cases.
Comment: What you've said is actually stronger. Actually I suppose it can be stretched to say it's equivalent (well-ordering principle and stuff), but I will need to think about it.

If you've shown $P(k)\Leftrightarrow P(k-1)$, showing that $P(k)$ is true for any $n\in\mathbb{N}$ is sufficient to prove the whole thing yes.


Roman Numeral Chords with Slash

Question: This chart has a listing for a chord V/1 and I'm having trouble interpreting this chord, specifically the "/1" part.  I think the "/1" part might have one of the following meanings...

"the base note of the chord (in this case, the fifth note in the scale) as the lowest note"
"the first note of the scale as the lowest note"
"the first inversion of the chord"

What is the proper way to interpret V/1?
Comment: Look at part 5, where the same map is shown with actual chords. Much easier to understand !
Comment: Exactly what is the chart purporting to show?
Answer: Check out this page where the image is given. Here you can select a key and click a chord in order to show the actual pitches of that chord.
For instance, "I/5" in C major is listed as G C E G. Since G is both scale-degree 5 and the chordal fifth, it's still unclear what 5 means. But when we see that "V/2" is listed as D G B D, we realize that these integers refer to scale degrees.
As a friendly PSA, beware of some of the pitches on this chart; their algorithm privileges flats over sharps, so chords are sometimes spelled a little strangely (e.g., they list E major as E A♭ B).
Comment: Have to say, the minute I see inaccuracies like Ab quoted in Emaj., I tend to dismiss the rest of the site as written by inexperts.

Roman Numeral Chords with Slash


Transferring ownership of raw pointer to unique_ptr

Question: I have allocated a pointer with new operator and assigned the ownership of the memory to a new unique_ptr . Do I have to delete the pointer allocated using new? Is there a memory leak here?
#include <iostream>
#include <memory>

using namespace std;

int main()
{
    int *a = new int;

    *a = 5;
    std::unique_ptr<int> auptr;

    auptr.reset(a);
    int *b = auptr.get();
    cout << *b << endl;

    cout << *a << endl;

    return 0;
}

Comment: No. As you said, the ownership has been transferred to the `unique_ptr`.
Comment: The object pointed at is the resource being owned. If you deallocate it, there is nothing *to own* anymore.
Answer: No. unique_ptr has the ownership now and its gets deallocated when it goes out of scope.
Answer: When your code reaches return, you have three pointers (a, auptr and b) pointing at the same object, which was allocated by new. After return auptr will go out of scope and it's destructor will deallocate the object, so you don't have to do it manually and there are no memory leaks.
Just note that your code looks as misuse of unique_ptr. You make a raw pointer initially, and get another raw pointer from an intermediate smart pointer. Consider using std::make_unique and get rid of raw pointers.
Answer: The ownership has been transferred to the unique_ptr auptr and deallocation is now the responsibility of the unique_ptr.
You can test whether the memory that is allocated is also being de-allocated with some modifications to your program.
#include <iostream>
#include <memory>

struct Int {
    Int() { std::cout << "Int...\n"; }
    ~Int() { std::cout << "~Int...\n"; }
};

struct D {
    void operator() (Int* p) {
        std::cout << "Calling delete for Int object... \n";
        std::cout << "Deleting at " << p << '\n';
        delete p;
    }
};

int main()
{
    std::cout << "Creating new Int...\n";
    Int* i = new Int();
    std::cout << "Created at " << i << '\n';
    std::unique_ptr<Int, D> UPInt;
    UPInt.reset(i);
}

Output:
Creating new Int...
Int...
Created at 0x234ec30
Calling delete for Int object...
Deleting at 0x234ec30
~Int...

You can see that the object created at a certain location is also being deleted.
See DEMO


Extract a particular value from categorical column using Python

Question: Following is the sample table which consists of transaction data of bank customers. I need to create a separate column as annual salary of customer taking the data from txn_description column.
Customer_ID txn_description Amount Type
01           POS            345    Dr
02           SALARY         2000   Cr
03           INTER BANK     148    Dr
04           SALARY         1500   Cr
05           NEFT           289    Dr
06           SALARY         1800   Cr
01           NEFT           40     Dr
02           SALARY         2000   Cr
04           POS            69     Dr
04           SALARY         1500   Cr
06           SALARY         1800   Cr

Note: The transaction data is of three months. So the salary is credited to a particular customer's account thrice in this table for three months.
(Dr = Debit transaction and Cr = Credit transaction)
Comment: what is the logic behind `taking annual salary of customer` from three months of data? what do you mean by this `Since the transaction data is of three months the customer ID will not be unique.`?
Comment: A customer is getting some amount credited to his account as salary. We need to calculate his annual salary based on that data....
Comment: Great. How about when we have salary data of 3 months and not one month...Check edits...
Comment: In that case, you have to filter by month and customer. i.e., the whole filtered dataframe whould have only one entry out of three months. What I suggest is, do this, `df.sort(["Customer_ID", "Date"])` and `df.drop_duplicates(subset=["Customer_ID", "Date"], keep='first')`. This will have the above mentioned condition.
Comment: After sorting shall I proceed with  df[df["txn_description"]=="SALARY"]
df["Annual"] = df["Amount"]*12
Comment: yes ofcourse you have to do, but I suggest you to do this after removing duplicate, just for improving performance. drop duplicate reduces number of rows, so, if you apply `df["Annual"] = df["Amount"]*12` on reduced rows, it will improve the running time. If you feel my answer is helpful, click on grey tick mark.
Answer: you could try this,
df= df[df["txn_description"]=="SALARY"]
df["Annual"] = df["Amount"]*12

O/P:
   Customer_ID txn_description  Amount  Annual
1            2          SALARY    2000   24000
3            4          SALARY    1500   18000
5            6          SALARY    1800   21600

Furthermore, If you want to apply it on original frame find this,
dic = df.set_index("Customer_ID")["Annual"].to_dict()

and apply it to actual dtaframe using df.map(dic)
Explanation:

First remove unwanted records, get only 'cr' or Salary records.
Now Dataframe has salary credited record of a month data of each customer. i.e., customer id and amount is one to one map.
multiply amount with 12 to get annual value.
convert customer to annual value in dic and replace into actual frame.


Problema ao iniciar aplicação em JavaFX

Question: Olá,
Estou tentando criar uma aplicação simples em JavaFX, tudo estava funcionando até que do nada começou a dar problema ao tentar iniciar o programa.
Está dando a seguinte exceção:
Exception in Application start method
java.lang.reflect.InvocationTargetException
Poderiam me ajudar a identificar o problema?
Obrigado!
public class Principal extends Application {

  public static void main(String[] args) {
    launch(args);
  }

  @Override
  public void start(Stage primaryStage) throws Exception {
   primaryStage.setTitle("Trabalho PC");

   Label lbDados = new Label("Dados:");
   lbDados.setTranslateX(25);
   lbDados.setTranslateY(65);

   Label lbCod = new Label("Codificação: ");
   lbCod.setTranslateX(25);
   lbCod.setTranslateY(90);

   ToggleGroup groupDados = new ToggleGroup();
   RadioButton rbTexto = new RadioButton("Texto");
   rbTexto.setToggleGroup(groupDados);
   rbTexto.setSelected(true);
   rbTexto.setTranslateX(80);
   rbTexto.setTranslateY(65);

   RadioButton rbBinario = new RadioButton("Binário");
   rbBinario.setToggleGroup(groupDados);
   rbBinario.setTranslateX(155);
   rbBinario.setTranslateY(65);

   ToggleGroup groupCod = new ToggleGroup();
   RadioButton rbCBinaria = new RadioButton("Binária");
   rbCBinaria.setToggleGroup(groupCod);
   rbCBinaria.setSelected(true);
   rbCBinaria.setTranslateX(115);
   rbCBinaria.setTranslateY(90);

   RadioButton rbCManchester = new RadioButton("Manchester");
   rbCManchester.setToggleGroup(groupCod);
   rbCManchester.setTranslateX(200);
   rbCManchester.setTranslateY(90);

   RadioButton rbCManchesterDif = new RadioButton("Manchester Diferencial");
   rbCManchesterDif.setToggleGroup(groupCod);
   rbCManchesterDif.setTranslateX(315);
   rbCManchesterDif.setTranslateY(90);

   Button btnIniciar = new Button();
   btnIniciar.setText("Iniciar");
   btnIniciar.setPrefSize(75, 25);
   btnIniciar.setTranslateX(400);
   btnIniciar.setTranslateY(25);

   TextField tfTexto = new TextField();
   tfTexto.setPrefSize(350, 10);
   tfTexto.setTranslateX(25);
   tfTexto.setTranslateY(25);
   tfTexto.setText("Digite o texto ou binário");

   Slider sldVelocidade = new Slider();
   sldVelocidade.setMin(0);
   sldVelocidade.setMax(20);
   sldVelocidade.setValue(10);
   sldVelocidade.setShowTickMarks(true);
   sldVelocidade.setMajorTickUnit(5);
   sldVelocidade.setMinorTickCount(1);
   sldVelocidade.setBlockIncrement(10);
   sldVelocidade.setTranslateX(190);
   sldVelocidade.setTranslateY(125);

   Label lbSlow = new Label("Slow");
   lbSlow.setTranslateX(195);
   lbSlow.setTranslateY(150);

   Label lbFast = new Label("Fast");
   lbFast.setTranslateX(298);
   lbFast.setTranslateY(150);

   Image image = new Image(getClass().getResourceAsStream("Fundo.png"));

   ImageView imvFundo = new ImageView();
   imvFundo.setFitHeight(315);
   imvFundo.setFitWidth(507);
   imvFundo.setX(15);
   imvFundo.setY(220);
   imvFundo.setImage(image);

   Image image2 = new Image(getClass().getResourceAsStream("Teste.png"));

   ImageView[] imvCod = new ImageView[9];
   for(int x = 0; x < imvCod.length; x++){
       imvCod[x] = new ImageView();
       imvCod[x].setFitHeight(53);
       imvCod[x].setFitWidth(52);
   }

   imvCod[0].setX(459);
   imvCod[0].setY(232);

   imvCod[1].setX(404);
   imvCod[1].setY(232);

   imvCod[2].setX(350);
   imvCod[2].setY(232);

   imvCod[3].setX(296);
   imvCod[3].setY(232);

   imvCod[4].setX(241);
   imvCod[4].setY(232);

   imvCod[5].setX(187);
   imvCod[5].setY(232);

   imvCod[6].setX(133);
   imvCod[6].setY(232);

   imvCod[7].setX(78);
   imvCod[7].setY(232);

   imvCod[8].setX(24);
   imvCod[8].setY(232);

   Pane pnpPrincipal = new Pane();
   pnpPrincipal.setPrefSize(550, 580);
   pnpPrincipal.getChildren().addAll(tfTexto, btnIniciar, rbTexto, rbBinario, lbDados, lbCod, rbCBinaria, rbCManchester, rbCManchesterDif, sldVelocidade, lbSlow, lbFast, imvFundo);
   for(int x = 0; x < imvCod.length; x++){
        pnpPrincipal.getChildren().add(imvCod[x]);
   }
   Scene scene = new Scene(pnpPrincipal, 550, 580);

   primaryStage.setScene(scene);
   primaryStage.show();
   btnIniciar.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent e) {
            String dados = tfTexto.getText();
            tfTexto.setEditable(false);
            rbTexto.setDisable(true);
            rbBinario.setDisable(true);
            rbCBinaria.setDisable(true);
            rbCManchester.setDisable(true);
            rbCManchesterDif.setDisable(true);
            btnIniciar.setDisable(true);
            if(groupCod.getSelectedToggle() == rbCBinaria){
                if(groupDados.getSelectedToggle() == rbTexto){
                    System.out.println("Binária / Texto");
                    Binaria bin = new Binaria(tfTexto.getText(), sldVelocidade, imvCod, 't');
                    bin.start();
                } else {
                    System.out.println("Binária / Binário");
                    Binaria bin = new Binaria(tfTexto.getText(), sldVelocidade, imvCod, 'b');
                    bin.start();
                }
            } else if (groupCod.getSelectedToggle() == rbCManchester){
                if(groupDados.getSelectedToggle() == rbTexto){
                    System.out.println("Manchester / Texto");
                } else {
                    System.out.println("Manchester / Binário");
                }
            } else {
                if(groupDados.getSelectedToggle() == rbTexto){
                    System.out.println("Manchester Diferencial / Texto");
                } else {
                    System.out.println("Manchester Diferencial / Binário");
                }
            }
        }
    });
  }
}

public class Binaria extends Codificacao {
  Slider sldVelocidade;
  ImageView[] imvCod;
  char op;
  String texto;

  public Binaria(String texto, Slider sldVelocidade, ImageView[] imvCod, char op){
    this.sldVelocidade = sldVelocidade;
    this.imvCod = imvCod;
    this.op = op;
    this.texto = texto;
  }

  public void run() {
    Image vazio = new Image(getClass().getResourceAsStream("B1.png"));
    if(this.op == 't'){
        this.trasnformaString(texto);
    } else if(this.op == 'b'){
        this.separaBinario(texto);
    }
    while(this.fila.vazia() == false){
        imvCod[8].setImage(imvCod[7].getImage());
        imvCod[7].setImage(imvCod[6].getImage());
        imvCod[6].setImage(imvCod[5].getImage());
        imvCod[5].setImage(imvCod[4].getImage());
        imvCod[4].setImage(imvCod[3].getImage());
        imvCod[3].setImage(imvCod[2].getImage());
        imvCod[2].setImage(imvCod[1].getImage());
        imvCod[1].setImage(imvCod[0].getImage());
        imvCod[0].setImage(vazio);

        if(imvCod[0].getImage().equals(vazio)){
            String bin = this.fila.remove();
            System.out.println(bin);
            Image image = new Image(getClass().getResourceAsStream("B"+bin+".png"));
            imvCod[0].setImage(image);
        }
        try {
            Thread.sleep(500);
        } catch (InterruptedException ex) {
            Logger.getLogger(Binaria.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
  }
}

public abstract class Codificacao extends Thread {
  Fila fila = new Fila();
  public void trasnformaString(String texto){
    for (char c: texto.toCharArray()) {
        String bin = Integer.toBinaryString(c);
        int i=0;
        int qtd = bin.length();
        for(i=0;i<qtd;i++){
            this.fila.insere(""+bin.charAt(i));
        }
    }
  }

  public void separaBinario(String binario){
    int i=0;
    int qtd = binario.length();
    for(i=0;i<qtd;i++){
       this.fila.insere(""+binario.charAt(i));
    }
  }
}

public class Fila {
  private List<String> alunos = new LinkedList<String>();

  public void insere(String bit) {
    this.alunos.add(bit);
  }

  public String remove() {
    return this.alunos.remove(0);
  }

  public boolean vazia() {
    return this.alunos.size() == 0;
  }
}

Answer: Nos testes que realizei em meu computador os problemas aconteceram nessas duas linhas:
Image image = new Image(getClass().getResourceAsStream("Fundo.png"));
// ...
Image image2 = new Image(getClass().getResourceAsStream("Teste.png"));

Porque os arquivos "Fundo.png" e "Teste.png" não estavam sendo encontrados.
Não vi seu stacktrace completo mas se ele for igual ao que aconteceu no meu teste você encontraria o problema real mais abaixo:

java.lang.reflect.InvocationTargetException
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:498)
      at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
      at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:498)
      at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
  Caused by: java.lang.RuntimeException: Exception in Application start method
      at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
      at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$154(LauncherImpl.java:182)
      at java.lang.Thread.run(Thread.java:748)
  Caused by: java.lang.NullPointerException: Input stream must not be null
      at javafx.scene.image.Image.validateInputStream(Image.java:1128)
      at javafx.scene.image.Image.(Image.java:706)
      at principal.Principal.start(Principal.java:105)

Portanto se você moveu ou deletou os arquivos deve atualizar seu path.

Problema ao iniciar aplicação em JavaFX


Disable select option

Question: I have a select list in my registration form here. The user can select 3 options to register for the event. For now the user has the ability to choose an early bird registration. After the periode they shouldn't be able to select that option. Is there a way to disable that option?
I have the following options:

EARLY BIRD REGISTRATION (now - Nov 1)
REGULAR REGISTRATION (Nov 1 - Mar 1)
LATE REGISTRATION Mar (1 - to conference)
SPEAKERS REGISTRATION ( now to Apr 2)
STUDENT REGISTRATION (breaks only)

After the 1nov I should be able to disable the early bird registration in the select list.
Answer: Disabling single options from select lists is currently not that easy in Drupal. There are some open issues regarding the topic and a couple of suggested patches, but so far neither made it into core:

Allow FAPI select, radios, and checkboxes to specify some options as disabled
Introduce proper Form API #types for 'option' and 'optgroup', and make #options consistent
Using form_alter to disable ONE option of a select field

That said, there is a tutorial on Exove which works around the issue, by implementing the THEME_select() hook to enable theming of individual select options using a #options_attributes key: Drupal 7 Form API select element option attributes
Using the code for your theme's template.php from the tutorial, you can disable options in your form using hook_form_FORM_ID_alter().
function hook_form_FORM_ID_alter() {
  $today = date("Y-m-d H:i:s");
  $date = "2016-11-01 00:00:00";

  if ($date > $today) {
    //replace 0 with the actual index for Early Bird
    $form['your_select_field']['#option_attributes'][0] = array('disabled' => 'true');

    //set the other fields based on dates here
  }
}

There is also a module which seems to offer the same functionality as the theme code from the tutorial, but I have not yet tested it: Form Options Attributes. It seems to work in a similar fashion however and might be even a little easier to set up (since you don't need to write that theme function).

Disable select option


The distribution of $Y|aY+b$

Question: What is the distribution of $Y|aY+b$?  I'm assuming that $a\neq 0$.  A related question here discusses the distribution of $X|X$, which is degenerate.  My guess is that the distribution of $Y|aY+b$ will also be degenerate but I'm not entirely sure how to work that out rigorously.  My thought was to try working with the definition
$$
f_{Y|aY+b}=\frac{f_{Y,aY+b}}{f_{aY+b}},
$$
but the joint distribution in the numerator doesn't make sense (I'm guessing it's degenerate).
Context:
I am working a problem where I have two random variables $Y$ and $X=a Y+b+\epsilon$, where $\epsilon\sim\mathcal N(0,\sigma^2)$.  I would like to compute the Fisher information matrix for $X$, which is too complicated; however, the fisher information matrix for $(X,Y)$ is easy to compute.  Furthermore, we have the relation
$$
I_X(\theta)=I_{X,Y}(\theta)-I_{Y|X}(\theta).
$$
If $\sigma$ is small it seems that (through Monte Carlo simulation)
$$
I_X(\theta)\sim I_{X,Y}(\theta).
$$
If I could show that $I_{Y|X}(\theta)\to\mathbf 0$ as $\sigma\to 0$ then this would explain by the approximation makes sense. My thought was to show that $I_{Y|aY+b}(\theta)=\mathbf 0$ but this requires (I think) the distribution of $Y|aY+b$, which I am not sure how to derive.
Comment: Intuitively, given $aY + b$, the value of $Y$ is completely determined, there is no more randomness about $Y$, so the distribution is degenerted!
Comment: @Zhanxiong That's kind of what I was expecting. Does that mean $I_{Y|aY+b}=\mathbf 0$? I suspect a degenerate variable doesn't carry information.
Answer: In general, if $X, Z$ are random variables defined on the probability space $(\Omega, \mathscr{F}, P)$, the conditional distribution of $X$ given $Z$ is a function $\mu(H, \omega)$ defined on $\mathscr{R}^1 \times \Omega$, with the following two properties (cf. Theorem 33.3 in Probability and Measure by Patrick Billingsley):

For each $\omega \in \Omega$, $\mu(\cdot, \omega)$ is a probability measure on $\mathscr{R}^1$.
For each $H \in \mathscr{R}^1$, $\mu(H, \cdot)$ is a version of $P[X \in H | \sigma(Z)]$.

By the above definition, it is easy to verify that the conditional distribution of $Y$ given $aY + b$ is
\begin{align}
\mu(H, \omega) = I_{aH + b}(aY(\omega) + b), \tag{1}
\end{align}
where the set $aH + b := \{ax + b: x \in H\}$.
In more elementary notations, suppose $a > 0$, $(1)$ can be rewritten as
\begin{align}
P[Y \leq y | aY + b = z] =
\begin{cases}
1 & \text{ if } a^{-1}(z - b) \leq y, \\
0 & \text{ otherwise.}
\end{cases}
\end{align}
The intuitive meaning has been noted in the comment:  once you observe the value of $aY + b$, then for any Borel set $H$, whether $Y$ belongs to $H$ is certain, which implies that the conditional probability of $[Y \in H]$ is either $1$ or $0$.
Answer: @Zhanxiong's answer got me thinking about this more, which led to a less rigorous but intuitive solution to the problem.  What caused the issue was the fact that in this question $Y$ is conditioned on a function of itself. However, note that the random variable $Y|aY+b=z$ can, after defining $Z=aY+b$, be written as $Y|aY+b=z\overset{d}{=}(Z-b)/a|Z=z$.  In this form it becomes obvious that this random variable is degenerate since
$$
\mathsf E(Y|aY+b=z)=\mathsf E((Z-b)/a|Z=z)=(z-b)/a
$$
and
$$
\mathsf{Var}(Y|aY+b=z)=\mathsf{Var}((Z-b)/a|Z=z)=0.
$$
So,
$$
Y|aY+b=z\sim\delta(y-(z-b)/a),
$$
which agrees with @Zhanxiong's answer.

The distribution of $Y|aY+b$


R: Finding relationships between 2 variables to determine any patterns in data

Question: I am working on finding relationships/patterns between 2 variables (Type_A, Type_B).
Loc_ID <- c("45", "46", "47", "48", "49", "50", "51")
Type_A <- c(22.96,23.36,23.70,23.55,23.52,23.42,23.61)
Type_B <- c(9.26,9.28,9.35,9.44,9.42,9.43,9.46)

df1 <- data.frame(Loc_ID,Type_A,Type_B)

df1:
+--------+--------+--------+
| Loc_ID | Type_A | Type_B |
+--------+--------+--------+
|     45 | 22.96  | 9.26   |
|     46 | 23.36  | 9.28   |
|     47 | 23.70  | 9.35   |
|     48 | 23.55  | 9.44   |
|     49 | 23.52  | 9.42   |
|     50 | 23.42  | 9.43   |
|     51 | 23.61  | 9.46   |
+--------+--------+--------+

Loc_ID is the location ID. Type_A & Type_B are 2 different measurement types.
Some Background:
This data was gathered from an experiment studying different hard discs. There are some hard discs that failed and some that passed. I determine this metric based on just looking at some contour profile plots of the discs using the measurement types I mentioned above. This is not an efficient process and I want to apply some data mining or machine learning techniques to automate my tasks. I did some extensive feature selection and I am sure that these measurement types tell me something about the potential causes in the process. I want to know how data mining could help determine the failure at the early stage and eliminate it.
Note: I have reported a fraction of the data for one of the failed disc here in the example.
I have tried the following so far

Generated simple stats and plots for initial visualization
Calculate key features of the data by performing dimensionality reduction
Found correlations in the dataset to determine if any relationships.

I would like to know any other methods to efficiently carry out this relationship analysis of these 2 measurement types. For example: profile comparisons with respect to locations, predict both the measurement types for building better models. I am just not able to think of best practices in machine learning to handle this problem. Kindly let me know any other techniques and how I could tackle this? I would like to automate my analysis so that I could use it on all the bad and good discs.
Answer: Although you gave some data it is still hard to tell what would be the best method to use for your challenge. Still I give it a shot.
In general it is always a good idea to do the steps you did already: summary statistics, visualization, correlation, linear regression.
In case the functional form doesn't seem to be linear you could try to find some other functional form. A good package is the following:
rgp: R genetic programming framework

RGP is a simple modular Genetic Programming (GP) system build in pure
  R. In addition to general GP tasks, the system supports Symbolic
  Regression by GP through the familiar R model formula interface. GP
  individuals are represented as R expressions, an (optional) type
  system enables domain-specific function sets containing functions of
  diverse domain- and range types. A basic set of genetic operators for
  variation (mutation and crossover) and selection is provided.

The vignette can be found here
To give you a code example based on your data:
library(rgp)

Loc_ID <- c("45", "46", "47", "48", "49", "50", "51")
Type_A <- c(22.96,23.36,23.70,23.55,23.52,23.42,23.61)
Type_B <- c(9.26,9.28,9.35,9.44,9.42,9.43,9.46)

df1 <- data.frame(Loc_ID,Type_A,Type_B)

iter <- 1000
set.seed(123)
newFuncSet <- functionSet("+","*","-","/","sin","cos")

result1 <- symbolicRegression(Type_B ~ Type_A, data=df1, functionSet=newFuncSet, stopCondition=makeStepsStopCondition(iter))
#result1 <- symbolicRegression(Type_B ~ Type_A, data=df1, functionSet=newFuncSet, stopCondition=makeFitnessStopCondition(0.1))

plot(df1$Type_B, col=1, type="l"); points(predict(result1, newdata = df1), col=2, type="l")
    #The best and worst individual can be shown using these commands:
    bf <- result1$population[[which.min(sapply(result1$population, result1$fitnessFunction))]]
bf

The results are not very meaningful for this very small dataset but you should give it a try with the real dataset. You should fiddle a little with the function set and with the number of iterations (iter) to see if you get better fitting results.
I would be interested if you get any interesting results. This is only one possibility how to proceed but I hope it helps to get you started.
Comment: Thanks @vonjd for your response. I ran your code but I am getting this error in point(predict()) function. Error in eval(expr, envir, enclos) : object 'Type_A' not found . How do I get rid of this?
Comment: @Sharath: This is strange, I removed all objects and ran it again: No error! Did you just copy and paste it, installed the rgp package and ran the code? Please run it first with my code above before you test it on your bigger data-frame. Perhaps there is some error in this data-frame. Otherwise I have no idea...
Comment: @vonjid, I just pasted your code and ran it. When I run result1 line, It now says "Error in is.empty(conset$all) : object 'numericConstantSet' not found"
Comment: @Sharath: I tried the above code on a different computer - and it worked alright! So there must be a problem with your R installation.
Comment: Works now!! Thanks. But when I use the points function, I don't see it on the plot. How does the points function work?. What are you getting in your computer? Also, Could you please explain me what  the "bf" line does? I get an output "function (Type_A) 9.38031238503754" but I am not able to interpret what it means. Please help on this.
Comment: @Sharath: As I said, the result is not very meaningful because there are not enough data. You get a constant as the resulting function (basically something like a weighted average). Did you try it with more data?
Comment: I tried it on more data. I get a constant as the output and it is something like "Type_A * 0.420695958687057"


How can 10th (or any other sufficiently low) percentile be equal to the mean number?

Question: For example, a 3rd percentile equal to n means that values of no more than 3% of observations in a group of observations are strictly less than n and that values of no less than 3% of observations are less than or equal to n.
However, if n is also the mean value, than the sum of all observations divided by their number has to equal n - and this does not appear possible since the value of any observation in the top 93% has to be more than n. I might be missing something very obvious, but it looks like having a certain (low) percentile function as a mean is basically impossible.
Comment: Data set: $\{1,1,1,1,1,1,1,1,1,1,1\}$. All percentiles are identical to the mean.
Comment: An example with no repeated values: {-34, 2, 3, 4, 5, 6, 7, 8, 9, 10}.
Comment: You can say that the mean and median cannot be more than one standard deviation apart, so if you make the standard deviation large while clumping a lot of values at one end of the distribution then you have a lot of flexibility
Answer: You're very used to thinking of nice normal distributions when it comes to statistics - in the case of a normal distribution, the median (the 50th percentile) is equal to the mean, and obviously, the 50th percentile is greater than the 3rd percentile for a normal distribution.
But all you need is a something deviating from a normal distribution to show an example of what you have described.
As an example, suppose we have a data set consisting of one $1$, ninety-eight $2$s, and one $3$. The mean is $2$, and the third percentile is $2$.
Comment: Just to make it explicit, if you add enough 2s then any sufficiently low percentile will be 2.
Answer: The mean isn't about the ordering, it's about the values. The values don't have to be similar to the ordinal position. For example, the ten values might be
$$ 1, 2, 3, 4, 5, 5, 6, 7, 8, 9999999999$$
While the median is 5, the mean is nowhere near that value.


LWUIT and kXML Parser

Question: Uncaught exception: java.lang.Error: Static initializer: java.lang.NullPointerException,   0
 - java.lang.Class.throwError(), bci=57
 - java.lang.Class.initialize(), bci=221
 - com.sun.lwuit.Component.<init>(), bci=5
 - com.sun.lwuit.Container.<init>(), bci=1
 - com.sun.lwuit.Form.<init>(), bci=8
 - com.sun.lwuit.Form.<init>(), bci=1
 - com.midlet.RSSMidlet.<init>(), bci=11
 - java.lang.Class.newInstance(), bci=0
 - com.sun.midp.main.CldcMIDletLoader.newInstance(), bci=46
 - com.sun.midp.midlet.MIDletStateHandler.createMIDlet(), bci=66
 - com.sun.midp.midlet.MIDletStateHandler.createAndRegisterMIDlet(), bci=17
 - com.sun.midp.midlet.MIDletStateHandler.startMIDlet(), bci=9
 - com.sun.midp.midlet.MIDletStateHandler.startMIDlet(), bci=4
 - com.sun.midp.appmanager.SelectorBase.run(), bci=33
 - java.lang.Thread.run(), bci=11

Coding:
package com.midlet;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import org.kxml2.io.KXmlParser;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import com.sun.lwuit.Command;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.List;
import com.sun.lwuit.animations.Transition3D;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
//import com.sun.lwuit.list.ListModel;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.plaf.UIManager;
import com.sun.lwuit.util.Resources;

public class RSSMidlet extends MIDlet implements ActionListener{

    public Vector feedVector;
    public String rssFeed;
    private Command cmdSelect;
    private Command cmdExit;

    private Form form1 = new Form("Feeds List");
//  private Form form2 = new Form("Feed Description");

//  private Vector feed_Title;
    private List resultList;
//  private List feedTitle;
    public RSSModel model = new RSSModel();

    class ReadXML extends Thread{

        public void run(){
            try{
                rssFeed = "http://www.rottentomatoes.com/syndication/rss/top_news.xml";
                HttpConnection httpConnection = (HttpConnection) Connector.open(rssFeed);
                KXmlParser parser = new KXmlParser();
                parser.setInput(new InputStreamReader(httpConnection.openInputStream()));

                parser.nextTag();
                parser.require(XmlPullParser.START_TAG, null, null);
                while(parser.nextTag() != XmlPullParser.END_TAG){
                    parser.nextTag();
                    parser.require(XmlPullParser.START_TAG, null, "channel");
                    readXMLData(parser);
                    parser.require(XmlPullParser.END_TAG, null, "channel");
                }
                parser.require(XmlPullParser.END_TAG, null, "rss");
                parser.next();
                parser.require(XmlPullParser.END_DOCUMENT, null, null);
            }catch(Exception e){

            }
        }
    }

    public RSSMidlet() {
        // TODO Auto-generated constructor stub
        Display.init(this);
        Resources r;
        try{
            r = Resources.open("/LWUITtheme.res");
            UIManager.getInstance().setThemeProps(r.getTheme("LWUITDefault"));
        }catch(IOException e){
            //e.printStackTrace();
        }

        resultList = new List();
        for(int i=0; i<feedVector.size();i++){
            model = (RSSModel) feedVector.elementAt(i);
            resultList.addItem(model.getTitle().toString());
        }

        form1.addComponent(BorderLayout.CENTER,resultList);
        form1.addCommand(cmdExit);
        form1.addCommand(cmdSelect);
        form1.setScrollable(true);
        //form1.addCommandListener((ActionListener) this);
        form1.setTransitionInAnimator(Transition3D.createRotation(250, true));
        form1.show();
    }

    protected void destroyApp(boolean unconditional)
            throws MIDletStateChangeException {
        // TODO Auto-generated method stub

    }

    protected void pauseApp() {
        // TODO Auto-generated method stub

    }

    protected void startApp() throws MIDletStateChangeException {
        // TODO Auto-generated method stub

        new ReadXML().start();
    }

    public void readXMLData(KXmlParser parser) throws IOException, XmlPullParserException{

        while(!"item".equals(parser.getName()) ){
            /** Check if document doesn't include any item tags */
            if( parser.next() == XmlPullParser.END_DOCUMENT )
                throw new IOException("No items in RSS feed!");
        }

        parser.require(XmlPullParser.START_TAG, null, "item");

        while(parser.nextTag() != XmlPullParser.END_TAG){

            parser.require(XmlPullParser.START_TAG, null, null);
            String name = parser.getName();
            String text = parser.nextText();
            //System.out.println ("<"+name+">"+text);

            if(name.equals("pubDate")){
                model.setPubDate(text);
            }else if(name.equals("title")){
                model.setTitle(text);
            }else if(name.equals("link")){
                model.setLink(text);
            }else if(name.equals("description")){
                model.setDescription(text);
            }
            parser.require(XmlPullParser.END_TAG, null, name);
        }
        feedVector.addElement(model);
        parser.require(XmlPullParser.END_TAG, null, "item");
    }

    public void actionPerformed(ActionEvent evt) {
        // TODO Auto-generated method stub
        if(evt.getCommand() == cmdExit){
            notifyDestroyed();
        }else if(evt.getCommand() == cmdSelect){

        }
    }
}

This is my codes. I can't seem to get LWUIT running with kXML. There is a forum post that says that I need to initialize graphics objects after the Display.init(this) line. But where that line should lie? Please assist me...
Answer: The Display.init(your_midlet) is responsible for initializing the Display for LWUIT, no need to do it yourself. Only restriction is, you have to initialize the Display BEFORE you use any Form.
Move the line
form1 = new Form("Feeds List")

after the line
Display.init(this);

so you initialize the Form in the Constructor after initializing the Display!

LWUIT and kXML Parser


Is this a tautological argument?

Question: Assume $A$ is true, and that $A$ implies $B$. If I then can prove that if $A$ implies $B$, then $B$ implies $A$, have I then proved that $A$ is true (without the need to assume that $A$ is true in the first place)?
Comment: If I understand your vague description correctly, you've assumed that A is true, and then used it in order to eventually prove that A is true. In that case, no, you haven't proved that A is true without assuming it in the first place.
Comment: Wait, what? What statements do you have and what do you want to prove, exactly? All statements except $A$ are true when $A$ and $B$ are both false.
Comment: The underlying problem that I am trying approach is: "If the non-trivial Riemann zeta zeros have real part $1/2$ then their imaginary parts must be of this form. And if the imaginary parts of the Riemann zeta zeros are of this form then their real part must be $1/2$.

But I am still missing the effective lower bound for gaps between the Riemann zeta zeros, and there is trouble with non-fitting values of the complex argument of a complex number.
Answer: From
$$A \implies B \\
(A \implies B) \implies (B \implies A)$$
the only possible conclusion is that
$$ A \iff B$$
So, $A$ and $B$ are either both true or both false.

Is this a tautological argument?


Base64 encoding an image alerts correct, response is nil

Question: I'm trying to encode an image in Base64 from a URL.
function getBase64Image(url) {
  var img = new Image(),
      response = '';

  img.setAttribute('crossOrigin', 'anonymous');
  img.onload = function() {
    var canvas = document.createElement('canvas');
    canvas.width = this.width;
    canvas.height = this.height;

    var ctx = canvas.getContext('2d');
    ctx.drawImage(this, 0, 0);

    var dataURL = canvas.toDataURL('image/png');
    response = dataURL;
    alert(response);
  };

  img.src = url;
  return response;
}

The alert() works fine but the response is nil:

You can see in the console in the screenshot if I log the response like so (it's done twice in the screenshot) it returns nothing:
console.log(getBase64Image('<%= asset_path "test.jpg" %>'));

Obviously we can read the image because the alert has the encoding. What am I missing?
Update
Relevant JSFiddle: https://jsfiddle.net/guxzxq20/3/
Answer: I believe you are returning the empty response object that you have created, because the response object inside the onLoad() function is not accessing the outside response.
Try changing your code to calling a callback once the onload() function reaches its end, and using that callback to alert.
Something like:
function getBase(url, callback) {
    // ... code

    img.onload = function () {
        // ... code

        callback(response);
    }
}

This was a very raw example.
Comment: That definitely helped _slightly_, I've only got `data:,` returning though.
Comment: Can you upload your code into a jsfiddle? I can help you then.
Comment: https://jsfiddle.net/guxzxq20/4/ try that and tell me if that code works. I can't test it on jsfiddle because of Cross Origin stuff.
Answer: Approach: Canvas
Load the image into an Image-Object, paint it to a non-tainted canvas and convert the canvas back to a dataURL.
function convertImgToDataURLviaCanvas(url, callback, outputFormat) {
  var img = new Image();
  img.crossOrigin = 'Anonymous';
  img.onload = function() {
    var canvas = document.createElement('CANVAS');
    var ctx = canvas.getContext('2d');
    var dataURL;
    canvas.height = this.height;
    canvas.width = this.width;
    ctx.drawImage(this, 0, 0);
    dataURL = canvas.toDataURL(outputFormat);
    callback(dataURL);
    canvas = null;
  };
  img.src = url;
}

call method
convertImgToDataURLviaCanvas('http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png',function(response){
 alert(response)
});