text:
Q: How to prove that a function for freeing a linked list is badly written? A question regarding the linked lists in C. Suppose, we have the following structures, that define the nodes in a linked list and a badly written free_list function, that (in my opinion) should cause an error:
typedef struct node *nodeT;

typedef struct node
{
    int* elem;
    nodeT next;
} *nodeT;

void free_list(nodeT list)
{
    nodeT node;

    for (node = list; node; node = node->next)
    {
        free(node->elem);
        free(node);
    }
}

As you see above, we have defined node as nodeT and a function to free the list free_list. For me, the obvious error is that inside free_list function inside for we do not have a temporary pointer to store the node value.
However, when I compile the code (on Linux), in which I create a linked list with few elements, the program doesn't crash, it seems that everything works fine.
My question is: Is there a simple way to prove that this function (free_list) is badly written? By simple I mean setting up some compiler flags (-Wall doesn't show any errors) or using such tools as Valgrind (used it with memcheck, that didn't help much)?
Update: Test case as requested:
int main()
{
    nodeT myType;
    nodeT tmpPtr;

    myType = malloc(sizeof(nodeT));
    myType->item = malloc(sizeof(int));
    *(myType->item) = 0;
    myType->next = malloc(sizeof(nodeT));
    tmpPtr = myType->next;

    tmpPtr->item = malloc(sizeof(int));
    *(tmpPtr->item) = 1;
    tmpPtr->next = malloc(sizeof(nodeT));
    tmpPtr = tmpPtr->next;

    tmpPtr->item = malloc(sizeof(int));
    *(tmpPtr->item) = 2;
    tmpPtr->next = malloc(sizeof(nodeT));
    tmpPtr = tmpPtr->next;

    tmpPtr->item = malloc(sizeof(int));
    *(tmpPtr->item) = 3;
    tmpPtr->next = NULL;

    free_list(myType);

    return 0;
}

and here is the Valgrind output:
valgrind --tool=memcheck ./a.out
...
==4318== Invalid read of size 8
==4318==    at 0x400579: free_list (in /home/melon/a.out)
==4318==    by 0x40069E: main (in /home/melon/a.out)
==4318==  Address 0x51f1048 is 0 bytes after a block of size 8 free'd
==4318==    at 0x4C2A82E: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4318==    by 0x400574: free_list (in /home/melon/a.out)
==4318==    by 0x40069E: main (in /home/melon/a.out)
...

A: I'm not sure how you did the test with valgrind, but with default parameters it detects this issue just fine:
==4464== Invalid read of size 8
==4464==    at 0x400571: free_list (list.c:15)
==4464==    by 0x4005DF: main (list.c:30)
==4464==  Address 0x51e0048 is 8 bytes inside a block of size 16 free'd
==4464==    at 0x4C2AD3C: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4464==    by 0x40056C: free_list (list.c:18)
==4464==    by 0x4005DF: main (list.c:30)

I just added this to the program to make it testable:
int main() {
    nodeT head = malloc(sizeof(struct node));
    nodeT node1 = malloc(sizeof(struct node));
    head->next = node1;
    head->elem = NULL;
    node1->next = NULL;
    node1->elem = NULL;

    free_list(head);

    return 0;
}

A: You can memset the node to zero before freeing the memory. Then it'll crash for sure.

A: You don't need any proof other than fact that the code dereferences a pointer to memory that was freed. That's undefined behavior. Invoking undefined behavior is bad.
So there's your proof.


text:
Q: Rellenar DropDownListFor con modelo diferente al de la vista Quiero rellenar un dropdownlist con un modelo diferente al que estoy usando en la vista. En la vista uso la entidad Noticia, y el dropdownlist se debería rellenar con la entidad Categoría. Trate de mandarlo con ViewBag pero me da error NullReferenceException. Les muestro un poco del código que tengo:
Noticia:
public int Id { get; set; }
public int IdCategoria { get; set; }
public string Titulo { get; set; }
public string Contenido { get; set; }
public Categoria Categoria { get; set; }

Categoria:
public int Id { get; set; }
public string Nombre { get; set; }
public string Descripcion { get; set; }
public bool Activo { get; set; }

Controlador de noticia:
public ActionResult RegistrarNoticia()
{
    ViewBag.DropDown = CategoriaLN.ListCategoria();
    return View();
}

Vista de noticia:
@using (Html.BeginForm("RegistrarNoticia", "Noticia", FormMethod.Post))
{
    <div class="form-group">
        @Html.LabelFor(model => model.IdCategoria, htmlAttributes: new { @class = "control-label" })
        @Html.DropDownListFor(model => model.IdCategoria, new SelectList(ViewBag.DropDown, "Id", "Nombre", Model.Categoria))
    </div>
}

Bueno si alguno tienen una sugerencia se lo agradecería mucho. Gracias.

A: Creo que este es tu problema:
@Html.DropDownListFor(model => model.IdCategoria, new SelectList(ViewBag.DropDown, "Id", "Nombre", Model.Categoria))

El ultimo parametro te dice que valor es el que estas seleccionando, cambialo por null o por tu variable Model.IdCategoria
@Html.DropDownListFor(model => model.IdCategoria, new SelectList(ViewBag.DropDown, "Id", "Nombre", Model.IdCategoria))

redpajama_set_name: RedPajamaStackExchange


text:
Q: Windows Sever 2000 machine with striped scsi disk to VHD Currently have a lot of servers running legacy applications that only work with W2k running on very old hardware that needs to be replaced.
The plan is to convert each current machine into a VHD and then import the VHD into W2k8 server using Hyper-V
I have managed to p2v w2k offline using the sysinternals Disk2VHD tool with servers that weren't using raid or scsi disks they only had standard hard drives with sata connections.
I disconnected hard drive from the server and used a sata to usb cable along & sata power to ac power adapter and then plugged the usb into a different machine running windows 7 started Disk2VHD tool selected the partitions of the server running w2k and created and did an offline conversion. - That was pretty seamless and really easy.
The real issue
 I am having is with some HP servers that are RAIDED striped across two scsi disks into one logical drive I cannot seem to actually convert them to VHD successfully, I have previously used VMware converter and got a .VMDK of one of the servers and tried it on ESXi but it would BSOD - Inaccessible_boot_device 0x0000007B.
If I can get it running in Hyper-V First time I would prefer to do that also If I could use the VMware Converter and then convert between VMDK and VHD that would be a good.
Any help would be greatly appreciated, thanks in advance!

A: Use vmware converter and after import the image in hyperv.
Vmware converter do a great job for the p2v by adding the scsi driver, and hyperv do a good job to import such image.


text:
Q: What is the usage of ApplicationName property in ClientContext ClientContext object has ApplicationName property.
Is this property logged anywhere on server in ULS or any other location?
Can this property be used to track different applications connecting to SharePoint?
Can this property be used to restrict access to certain applications?
I have read its documentation on MSDN but I am looking for more information.

A: Gets or sets the name of the runtime where the current client application is located.
SP.ClientContext.set_applicationName(value)

Returns String value -- The name of the runtime where the current client application is located. When setting this property, the value must be between 1 and 128 characters.


text:
Q: jQuery vs. Yahoo UI API design I am baffled by the difference in design between jQuery and Yahoo UI APIs. Disclaimer: I have a strong dislike of the jQuery api, but I am also a huge ignorant in web programming and javascript in general, so I could be dead wrong and come back here begging for redemption. so long...
The point of my question is the following. The two designs are different. jQuery puts the DOM at the center, and adorns the DOM by executing a "trigger" enhancer method on it. example
$("#flexigrid").flexigrid()

A requirement of jQuery is that you must, in some cases, follow a very specific conventional structure for your html beforehand. Example:

First header

First content

Second header

Second content

and then
$("#accordion").accordion();

Moreover, the returned entity in general does not provide any mechanism to hide the DOM through a convenient programmatic method. To manipulate your jQuery entity you have to access the DOM via selectors, access that in some case is not guaranteed to be easy to know, like in the case of internally generated ids. Suppose that you want to swap the accordion programmatically, what you do is
$('#accordion').accordion('option', 'active', 2);

and not a more intuitive
myAccordion.setActiveTab(2);

On the other hand, yahoo ui focuses on javascript objects, you create them passing the DOM node selector (e.g. myDataTable = new YAHOO.widget.DataTable("container_id"))  and then perform all manipulations through the object methods. Want to add a new row ? call myDataTable.addRow(). The DOM is hidden. You are not concerned with what's going on behind the scenes.
Now, my experience with Trolltech QT maps nicely to Yahoo UI. Clear, defined API of the widget objects, eventual freedom to reimplement part of them via inheritance, opaque rendering unless you want to open the box and get your hands dirty. QT is a winning API, works well, it's easy to use, and Yahoo UI is kind of similar in the design style. On the other hand, jQuery works in a counterintuitive (to me), very open box way, with reduced API on its objects.
Enough ranting. The point is that I assume I can be dead wrong on this, but I'd like to know why. What are the design advantages of having a jQuery-like interface (where the DOM is clearly exposed and you potentially have to hunt for stuff that jQuery plugins create automagically, so you can finally $(select) them and attach events or modify their content) instead of hiding everything behind an objects and commodity methods like YUI does ?
I'm not talking about speed, or code size, or amount of typing. I'm talking about design concepts like encapsulation, focus on interfaces, and ease of access. What design is better, in what situations, and why?

A: I don't think your argument is directed at jQuery, but more the APIs provided by plugin authors.
Unfortunately, no two plugin authors will create a plugin with the same API. The level of programmatic access is not limited by jQuery itself, but rather by the author/s of the plugin.
Also, as you said, jQuery is all about the DOM -- I see this as a benefit because it means jQuery doesn't get all mixed up in the "logic" (eh, "business logic") of the application... It's quite fine on it's own level of abstraction -- it deals with the DOM, and that's all!
You can create an unlimited amount of data structures and additional APIs for your application. jQuery doesn't hinder you in this respect.

You've added more details to your question -- this 'edit' is in response to those details.
I think what you're experiencing is common when you reach a certain stage with jQuery... The API becomes insufficient. You don't want the DOM... You want a nice clean API for your module, whether it's an accordion or a data-grid.
Personally, I don't think that some things should be bundled into a "jQuery plugin" -- doing so normally means sacrificing the API -- or having to resort to jQuery's mechanisms such as psuedo-event triggering through "trigger":
var someModule = $('#contain').someCoolModule();
someModule.trigger('initiate');

I get what you're saying, and I think I agree, but I also think it's important to have jQuery on an entirely separate level -- forget about it -- only utilise it when you need to attack the DOM.

A: jQuery doesn't require any kind of special markup - you can write a selector for any object. You can also use an existing DOM reference, and turn it into a jQuery object like so: $(domObject). Actually simpler and more capable than Yahoo UIs.
It's not required to know your dom selectors if you already have a DOM reference... That might be the source of your misunderstanding.
Having worked with both Yahoo UI and jQuery, let me tell you they are both great libraries. They're for different roles, but both have great approaches.
jQuery is kind of a wrapper, simplifying everything that has to do with the DOM, Ajax, selecting objects, doing graphics. It has a very concise and brilliantly simple API that abstracts all the browser compat nonsense away.
jQuery uses radically different design concepts than most newbie programmers are used to. It is really the poster child for how Javascript should be used. A few years back, there was a lot of ignorance about the power of Javascript. Mostly, because most of the javascript on the internet was terrible. Now, I think most people have realized that Javascript is one of the most capabable languages. It supports several paradigms: functional, imperative, object-oriented (prototype, not class-based), data literals....
jQuery uses Javascript to its full ability, using each aspect of its design to solve each problem in the most effective way.
I tell all people learning javascript to read the jQuery source over and over until they understand it.... It will be hard, but they will finish by being much better programmers, with a much larger assortment of tools in their toolbox.
It's kind of perpendicular to the Java/.NET brainwashing, which is to give every developer a screwdriver (OOP), and tell them it is the perfect soltion to every problem in programming and life.
Which, it's not. Every problem needs a different tool. OOP is good, but often a bad idea for some problems.
jQuery's mixin-style plugin architecture is really good. Different, but highly effective, fast, and easy to use.
jQuery is #1 for a reason - it's simple to use, and incredibly powerful.
Yahoo UI is a different approach, for a different problem. It's a UI toolkit that has very heavy abstraction from the DOM (vs. jQuery's lightweight approach).
You'll find yourself speding a lot of time modifying it if you intend to something outside the norm. (That's the downside of the heavyweight approach).
It's not a framework for developing apps. It's a bunch of GUI widgets.
I've used both together. There's no reason you can't use both jQuery and Yahoo UI on the same page, they're two different tools for different problems.
I suggest including jQuery site/app-wide, then including jQuery UI plugins as needed. If you need heavyweight stuff, add Yahoo UI. But stick to jQuery for your plumbing code...
Learn from jQuery. Understand the power of array programming, callbacks, data literals, treating code as data, and keeping things concise. And that using the right tool for each problem means much shorter, simpler code.

A: In my opinion, YUI is weaker in DOM manipulation, but is way ahead in design.
JQuery is designed for those with little or no JavaScript (or general coding) experience.  Its very easy to get an application up and running.
YUI is more readable, and any programmer can pick it up and go very quickly because of the wide use of best-practice methodologies.

A: jQuery is a great library for DOM manipulations, and centering it's API around selectors is one of the reasons why it's so popular today. The thing is, jQuery wouldn't be needed if the browsers DOM APIs were more consistent and easier to use. And I agree with Robert Harvey (commented above) that as an abstract layer over the DOM jQuery does a very capable job.
But as I understand, you dislike jQuery plugin system and the jQuery UI, not the core library itself. Personally, I prefer a YUI style API for components and widgets, because at the higher abstraction level DOM elements become less important. I think the reason why jQuery UI authors chose this design is to make API more consistent with their main product, jQuery library. But I don't agree that this was a good decision.

A: *

*jQuery is designed to work with the DOM (i.e. it's a language highly optimised around web pages).

*
you potentially have to hunt for stuff that jQuery plugins create automagically

Presumably if it's appropriate, a plugin returns a jQuery object that you can manipulate, unless it's badly written. In which case that's obviously the plugin's fault.

*If you're using a method that autogenerates IDs then jQuery may not be for you. However for example I've used jQuery with Google Maps without too much trouble.

*If you wanted to add a row to a table automatically, I'm sure there's a plugin out there. If not, it wouldn't take much to write one.

A: I agree with Computer Linguist. OOP is not a perfect fit for every possible for problem.
In case of web development one first has to decide upon the kind of solution that one has to design. Is the solution essentially a web page with interactive widgets embedded at places that enhance the interactivity or is it a full fledged RIA. JQuery,I believe is fit for the first case and it is basically targeted towards ease of handling of the DOM.
In case of RIA applications, toolkits working at a higher level of abstraction are prefered because the developer in this case is dealing with widgets and layouts rather than the HTML and css that lies underneath. In such case using Object Oriented Toolkits like YUI, Dojo or ExtJS are more convenient as they bring the desktop application development approach (with its associated advantages) to the web domain.


text:
Q: Convenient way to include equations in pstricks? For example, I want something of the form
$\circle =\frac{[2][3]}{[6]}$,

but where the "circle is actually \pscircle(x,y){r}.
I have seen the minipage environment solution, but the trouble is that, I need a pretty long list of such picture=numerical value types of equations, preferably where some appear side by side, which the minipage environment solution doesn't seem optimal for. Is there an easy way to insert equations in the pstricks picture environment?

A: Please provide complete  examples and not only fragments.
\begin{pspicture}(6,6)
\pscircle(2,4){1}\rput[l](3,4){ $=\frac{[2][3]}{[6]}$}
\end{pspicture}


text:
Q: Does any version of Windows support uncompressing splitted archives natively? I mean, are multi-volume .zip archives, or maybe any other kind of archive format, natively supported without any third-party application like 7Zip or WinRAR?

A: Not out of the box.  You have to go with 3rd party software to get the kind of functionality you're talking about.
I'm trying to find a MS reference for this, but so far no luck. Oh well, that's MS documentation for you.


text:
Q: Git Privately Setup Server with GUI which includes feature of GitHub I am working on one govt project, so i need to setup a git server privately and want to achieve all the functionality what GitHub provide mainly Sending Pull Request and merge with other repo.
Is there any way so that i can achieve all the github ui features in privately setup git on VM. I dont want to publish repository remotely it will keep it in local server only.
Note: I need all this features offline with open source or free tools.

A: I think what you are looking for is the GitHub Enterprise product:
https://help.github.com/en/articles/githubs-products#github-enterprise
If you self-host it on your network it gives all the functionality of GitHub on the private network.

A: GitBucket seems to offer all the functionality you need:
https://github.com/gitbucket/gitbucket
It is hosted on GitHub :-/


text:
Q: How to use this BLDC and know more about it? I have this BLDC I removed from a CD Drive.
I want to use it. Just for playful reasons. But I don't know what to make of it. Where to get started with on the Internet. Any help will be appreciated.

A: These are fun to play with and a good introduction to BLDC technology.
Technically it is a 3 phase BLDC motor with 9 stator arms and 12 magnet poles, probably 'Star' wound, with analog Hall sensors. If it came from a standard size (5.25") CDROM drive then it is probably rated for 12V (but will run on less) and draws less than 1A in normal operation.
To drive it properly you need a BLDC controller. You can try to make one with a dedicated sensored controller chip like I did, but getting the wiring right is tricky (25 different different ways it could be connected, and only 2 are correct!). Alternatively just use a standard 'RC hobby' brushless ESC, and solder the ESC's phase leads directly to the windings (no need to connect the Hall sensors).
For even more fun you can try rewinding it and replacing the Ferrite 'ring' magnet with Neodym magnets for more power.
If you do an Internet search for 'brushless CDROM motor' you should find many examples of driving them with an Arduino etc.

A: That's not a brushless DC motor in itself – that's just the stepper motor-alike part of a BLDC motor.
The other half is the motor controller that sits on the PCB at the other end of the flat cable, which converts the DC to appropriately timed waveforms for the different coil circuits, based on desired speed/torque, position and other constraints. It typically has a closed loop control mechanism that incorporates the currents flowing through the coils and/or e.g. a hall effect sensor to observe the rotational state.
That means the project you're up for is designing an ESC – not a starter's project in itself, but luckily there's plenty of literature on motor control, and you'll certainly find something there on how to design ESCs for BLDC motors.


text:
Q: Horizontal scrolling between dynamic number of pages with tabs in Polymer Is there a Polymer WebComponent that allows horizontal scrolling between dynamic number of pages with tabs?
To those familiar with Android im looking for something like PagerTabStrip

A: The swipe-pages custom element allows horizontal scrolling with tabs. You can check the demo here: http://theseamau5.github.io/swipe-pages/components/swipe-pages/demo.html.
But this has not been updated for a long time.


text:
Q: How do I assign the working directory for rmarkdown/knitr interactive doc on shinyApps.io? I have a fully functional interactive shiny doc using knitr/r markdwon.
However, when I try to publish (deploy) it to shinyApps.io, I get an error saying the .PNG file I try to incorporate into the doc (using readPNG from the png package) is unable to open.
I know the problem is related to working directories.
In my original code I assigned a working directory to my folder (i.e., "C:/Users/NAME/documents/...." that contains both my .rmd file and my .png file. However, obviously my folder doesn't exist on the shinyapps.io.
So how exactly do I set my working directory to open the .png file via my doc on shinyapps.io?
I can't find anywhere that explicitly walks through this process. Please help explain this simply/basically for me.
Example:
Assume I have a folder in "C:/Users/NAME/documents/Shiny" that contains 2 files: "shiny.rmd" and "pic.png". I want "pic.png" to be rendered in my shiny.rmd doc.
Currently I have:
---
title: "TroubleShoot"
output:  html_document
runtime: shiny
---

```{r ,echo=FALSE,eval=TRUE}
library(png)
library(grid)
direct <- "C:/Users/NAME/documents/Shiny/"
img <- readPNG(paste0(direct,"pic.PNG"))
grid.raster(img)
```

How do I rewrite my code so it works on shinyApps.io?
Do I need to create and name folders in specific ways to place my 2 files into before deploying?

A: When you paste the c drive to direct, and read the direct into img, you are sending the app/markdown to your local drive. You need to use a relative path to the project. I would suggest something like:
direct <- "./"

Which uses the relative path, not the absolute path.
That said you might be able to skip that step entirely if the .png is in the same folder as the shiny object. just call the file name and format and leave it as that.
Also, check you use of ". Your syntax highlighting indicates your code won't run properly as it thinks some of your functions and variables are character strings because you've misplaced your quotes around read.png(). That's probably just a copy and paste typo though.
In summary, call the image via grid.raster("./pic.PNG"), and brush up on how working directories and relative paths work.
In the absence of knowing exactly how you're 'setting' your working directory:
In rStudio to correct and easiest approach is to make a 'New Project' for every New Project. You can do this as the first step in your project, or you can add a project file to an existing directory.
When you do this it automatically sets your working directory correctly. The way you seem to be doing it is not correct, you are merely supplying a 'path'. If you were to not want to use a project for some reason (I can't think of a case where that would be right), then you can always use setwd(), however, I believe this needs to be used in every session. A true project doesn't have that requirement.
This will then allow you to deploy your app properly as it will update the working directory to the one on the host machine at shinyapps.io when it is initialised there.
Finally, using the correct relative syntax "./path/to/my.file" to reference all your assets, images, data etc, should correct your issue as stated in the question.


text:
Q: Какие есть варианты, чтобы не использовать "@" (массивы, for)? error_reporting(E_ALL); // - Обязательно

Есть числовой массив c чётным кол-вом ключей (а сколько их вообще - не известно заранее):
$arr = ['0'=>'value1', '1'=>'value2', '2'=>'value3', '3'=>'value4'];

Стоит задача получить:
Array ( [value1] => value2 [value3] => value4 )

Делаю так:
$count = count($arr);
for ($i = 0; $i < $count; $i++) {
   $res[$arr[$i]] = $arr[++$i];
}

И всё вроде ок, но когда массив с нечётным кол-вом ключей:
$arr = ['0'=>'value1', '1'=>'value2', '2'=>'value3'];

Задача состоит в том, чтобы получить массив вида:
Array ( [value1] => value2 [value3] => )

И здесь в 'value3'=>'' — не пропущенна 2, а именно должен быть null
Делаю аналогично, только добавляю костыль в виде @:
$count = count($arr);
for ($i = 0; $i < $count; $i++) {
   @$res[$arr[$i]] = $arr[++$i];
}

А без @ будет выведена ошибка:

Notice: Undefined offset...

Результат получаю тот, что и нужно:
Array ( [value1] => value2 [value3] => )

Вот только использование @ — меня сильно смущает. Как можно этого избежать?

A: if( count($arr) % 2) array_push( $arr, null);

И у вас гарантированно чётное число элементов в массиве – бейте на пары.
Если число элементов массива нечётное, остаток от деления на 2 не ноль, в конец массива дописываем null, который достанется последнему ключу, как вы и хотели.
if(( $count = count($arr)) % 2) array_push( $arr, null);
for ($i = 0; $i < $count; $i+=2) {
   $res[$arr[$i]] = $arr[$i+1];
}

Ideone.


text:
Q: Ghost handlebars.js {{#has tag="Top"}} doesn't work In my loop.hbs template I'm trying to get Ghost to pin posts that have the tag "Top" to the top.  I'm using the {{#has}} helper combined with a {{#foreach posts}}.
See code below.  The behaviour I'm getting though is that only the {{^has tag="Top"}} (i.e. the second foreach loop) is working.
Any clues as to what I might be doing wrong?
{{#foreach posts}}
    {{#has tag="Top"}}

{{{title}}}

{{excerpt words="26"}} »

                {{#if author.image}}{{/if}}
                {{author}}
                {{tags prefix=" on "}}
                <time class="post-date" datetime="{{date format='YYYY-MM-DD'}}">{{date format="DD MMMM YYYY"}}</time>

    {{/has}}
{{/foreach}}

{{! All the code above doesn't seem to be working.  Only the below code outputs posts to the blog homepage }}
{{#foreach posts}}
     {{^has tag="Top"}}

{{{title}}}

{{excerpt words="26"}} »

                {{#if author.image}}{{/if}}
                {{author}}
                {{tags prefix=" on "}}
                <time class="post-date" datetime="{{date format='YYYY-MM-DD'}}">{{date format="DD MMMM YYYY"}}</time>

    {{/has}}
{{/foreach}}

A: Solution was to wrap the first block of code in {{#get}} wrappers, i.e.
{{#get "posts" include="tags,author" filter="featured:true" limit="all" as |featured|}}{{/get}}

The below gist pins posts with "top" tag to the top of the Ghost blog (on page 1 only) and formats posts marked as featured (but with no "top" tag) and includes them with other posts in default chronological order.
https://gist.github.com/anonymous/386c7eb445cc97a45a1ea0ff56898ec6


text:
Q: Is there any way to hide a portion of a line drawn by \columnseprule in multicol? I have a three-column multicol layout throughout my document, with some special text (like a title) at the very start of the document, like this:

The use of three columns is due to space constraints on the document that I'm writing.  The above document was generated with this code:
\documentclass[a4paper,landscape]{article}

\usepackage{multicol}
\usepackage[margin=0.7cm,bottom=1.3cm,footskip=0.7cm]{geometry}
\usepackage{lipsum}
\setlength{\columnseprule}{0.4pt}

\begin{document}
\begin{multicols*}{3}
\raggedright
{\huge \textbf{Long Long Very Long Title Abcdefg}}
\section*{Limits}
\lipsum\lipsum
\end{multicols*}
\end{document}

The title wraps into two lines and that's ugly.
I know I'm asking for something strange, but is there a way to force the title into one line, and hence "eat" into the adjacent column (thereby removing the column separator between the first and second columns, and pushing text on the second column downward)?
(Note: The third column should not be pushed downward.)
Pushing text downward in the second column is a secondary concern, because I can do that manually by adding some vspace in the text at the correct location, but I have no workaround to remove the bit of column separator that overlaps the title.
I have tried using mbox, i.e.:
\mbox{\huge \textbf{Long Long Very Long Title Abcdefg}}

but this will (as expected) not get rid of the column separator:

It isn't very obvious with the word "Title", but the column separator is actually there.  Ideally, the separator should start from about 1cm below the bottom of the title, at the same height as the "Limits" subsection name.
I've also tried setting the background color of the mbox, but the column separator is drawn over the mbox, so I can't hide the column separator with this method.
Any suggestions on how I might achieve this?

A: Changing the size of multicol's columns individually isn't possible without a major rewrite of its internal column balancing routines. Manually shrinking a column separator is possible with the very latest version of multicolrule (1.2), which I released earlier today and should be hitting your CTAN mirror within the next day or so. (If you're impatient, it's is available immediately at github.)
These two commands are the core of the solution:
\DeclareMCRulePattern{shrink-me}{extend-top=-\reservespace-\baselineskip}
\SetMCRule{width=thin,line-style=solid,patterns=shrink-me,pattern-for=1}

It works by declaring a pattern for the column separator, and then applying that pattern to the first separator only.
MWE:
\documentclass[a4paper,landscape]{article}
\usepackage[margin=0.7cm,bottom=1.3cm,footskip=0.7cm]{geometry}
\usepackage{lipsum}
\usepackage{multicolrule}

\newsavebox{\mytitle}
\newlength{\reservespace}
\savebox{\mytitle}{\textbf{\huge Long Long Very Long Title Abcdefg}}
\setlength{\reservespace}{\ht\mytitle}
\addtolength{\reservespace}{\dp\mytitle}
\addtolength{\reservespace}{\baselineskip}
\addtolength{\reservespace}{-\topskip}
\DeclareMCRulePattern{shrink-me}{extend-top=-\reservespace-\baselineskip}
\SetMCRule{width=thin,line-style=solid,patterns=shrink-me,pattern-for=1}
\raggedright

\begin{document}
\begin{multicols*}{3}
\usebox{\mytitle}
\section*{Limits}
\lipsum[1-3]

\columnbreak\vspace*{\reservespace}

\lipsum[4-7]
\lipsum
\end{multicols*}
\end{document}

The result:


text:
Q: JAXB and CData without control over generated sources I have a project using a 3rd party lib, including generated JAXB Java objects (Which I haven no source control over)
I found that one of the elements in this model, expects a <![CDATA blob. Is there any way to make Jaxb marshaller aware of this, and not escape the output in that particular field?
The XML model is as follows:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(
    name = "MyComplexType",
    propOrder = {"val1", "cdataval"}
)
public class MyComplexType {
    @XmlElement(
        name = "val1",
        required = true
    )
    protected String val1;

    protected String cdataval;

    public MyComplexType() {
    }

    ... getter and setters...
}

So, as I mentioned earlier, adding CData to the cdataval makes JaxB marshaller escape the content leading to invalid CData content.
How could I make the marshaller NOT escape the content, without modifying the generated sources? It would be so easy to just add a special XmlAdapter on that field, but nope, can't do that.
Regards


text:
Q: I am using the Android Template Navigation Drawer Activity but if I change the title and add Fragments, if I click it doesn''t take me to the fragment I open a new Activity using Android template for Navigation Drawer Activity.
When I click on the default Navigation drawer it shows the different fragment.
I have changed the title of the options in Navigation Drawer.
But if I click on then, it doesn't take me to the Fragment.
I cannot find any itemSelected or onClick methods in the Main Activity of the template where I can change the code to show new Fragments.
Please help how can I adjust the code to get my own fragments.
'''
public class MainActivity extends AppCompatActivity {

    private AppBarConfiguration mAppBarConfiguration;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action",
        Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        DrawerLayout drawer = findViewById(R.id.drawer_layout);

        NavigationView navigationView = findViewById(R.id.nav_view);

        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home, R.id.nav_order, R.id.nav_status)
                .setDrawerLayout(drawer)
                .build();
        NavController navController = Navigation.findNavController(this,
        R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController,
        mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is
       present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this,
     R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }
}

'''

A: //First set Navigation Item Selected listener

navigationView.setNavigationItemSelectedListener(this);

//then override the onNavigationItemSelected method like this..
 @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        // Handle navigation view item clicks here.
        switch (item.getItemId()) {

            case R.id.home:
               //do something...
                break;
            case R.id.about:
                 //do something...
                break;

        }


text:
Q: Sharepoint Casecade lookup is not working with Office 365 sharepoint Trying to figure out cascade lookup with 2 different lists as detailed below.

*

*List Name-1:  Facilities, Field name:  Title (Facility)

*List Name-2:  Deparatments, Field Names:  Facility (Lookup from
Facilities), Title (Department)

Trying to add jquery and javascript and is not working.  Find below are the codes added to seattle master page and formnew pages.
Please advise how I can get this resolved.
https://rubiconoffshore.sharepoint.com/sites/DEV/SiteAssets/jquery.SPServices-2014.02.min.js
https://rubiconoffshore.sharepoint.com/sites/DEV/SiteAssets/jquery-3.2.1.js

<script type="text/javascript">
$(document).ready(function(){
    $().SPServices.SPcascadeDropDowns({
            relationshipList: "Departments",
                relationshipListParentColumn: "Facility",
                relationshipListChildColumn: "Title",
                parentColumn: "Facility",
                childColumn: "Title",
                debug: true
    })
})
</script>

A: JQuery reference file has to be above the SPServices file.


text:
Q: Why a simple for loop without OpenMP is faster than it with OpenMP Here is my test code for OpenMP
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <time.h>

int main(int argc, char const *argv[]){

    double x[10000];
    clock_t start, end;
    double cpu_time_used;
    start = clock();

    #pragma omp parallel
    #pragma omp for
    for (int i = 0; i < 10000; ++i){
        x[i]    = 1;
    }

    end = clock();
    cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
    printf("%lf\n", cpu_time_used);
    return 0;
}

I compiled the code with the following two commands:
gcc test.c -o main

The output of rum main is 0.000039
Then I compiled with OpenMP
gcc test.c -o main -fopenmp

and the output is 0.008020
Could anyone help me understand why it happens. Thanks beforehand.

A: As High Performance Mark so eloquently described in his comment, there is a cost (overhead) with creating threads and distributing work. For such a tiny piece of work (39 us), the overhead outweighs any possible gains.
That said, your measurement is also misleading. clock measures CPU time and is most likely not what you wanted (wall clock). For more details, see this question.
Another misconception that you might have: As soon as x is large enough, the simple loop will become memory-bound. And you will likely not see the speedup you expect. For example on a typical desktop system with four cores you might see a speedup of 1.5 x instead of 4 x.


text:
Q: How to do - SQL Update scenario using Join condition on multiple columns and exclude column in join condition if null I have 2 tables A & B, need to update UCode of Table A with UCode of Table B using c1, c2, c3, c4 as join conditions. tricky part is I should ignore not null columns from Table b on the join condition
for example shown below, table B join condition should consider 4 columns for 1st row , only 3 columns for 2nd row, only 2 columns for 3rd row and so on
Table A
 ID   UCode    c1    c2    c3   c4
 100           abc   xy    pq   rs
 200           ab    bc    cd   ef
 300           aa    bb    cc
 400           uu    pp    kk   mn

Table B
 c1    c2    c3  c4    UCode
 abc   xy    pq   rs   UC11
 ab    bc    cd        UC22    --Ignore c4 on join condition
 aa    bb              UC44    --Ignore c3,c4 on join condition
 uu                    UC55    --Ignore c2, c3, c4 on join condition

Any help is appreciated.

A: Not sure I understand your desired outcome, but i think that you can put some checks on Table B columns in the join condition:
declare @tableA table (ID int,  UCode varchar(10), c1 varchar(10), c2 varchar(10),c3 varchar(10),c4 varchar(10))
declare @tableB table (c1 varchar(10), c2 varchar(10), c3 varchar(10),c4 varchar(10), UCode varchar(10))

insert into @tableA
values
  (100, null, 'abc', 'xy','pq',   'rs' )
 ,(200, null, 'ab' , 'bc','cd',   'ef' )
 ,(300, null, 'aa' , 'bb','cc',   null )
 ,(400, null, 'uu' , 'pp','kk',   'mn' )

 insert into @tableB
values
 ('abc',   'xy',     'pq'   ,'rs' ,'UC11')
,('ab' ,   'bc',     'cd'   ,null ,'UC22')
,('aa' ,   'bb',     null   ,null ,'UC44')
,('uu' ,   null,     null   ,null ,'UC55')

update
    @tableA
set UCode= b.UCode
from
    @tableA as a
        inner join
    @tableB as b
        on
        a.c1=b.c1
    and (b.c2 is null or a.c2=b.c2)
    and (b.c2 is null or a.c2=b.c2)
    and (b.c3 is null or a.c3=b.c3)
    and (b.c4 is null or a.c4=b.c4)

After the update statement Table A looks like this:


text:
Q: How to left join with or operator and determined only one column that match I've search the internet for days and found no solution to my problem.
I've two simple tables here:
TB1
tb1_id  tb1_name
1       Red
2       Blue
3       Yellow

TB2
tb2_id  tb2_id1 tb2_id2 tb2_type    tb2_value
1       3       1       A           2

Suppose table 1 is list of users. The guy called Red want to have relationship with a guy called Yellow. So he send a request. When Yellow accepted the request I update tb2_value to 2.
Several days later, Yellow logged in and see who he has relationship with.
How to do a query for this where both guys can see each other too.
Here's my attempt so far and it's not working:
SELECT
    tb2_id1, tb2_id2, tb2_type, tb2_value, tb1_id, tb1_name
FROM
    TB2
LEFT JOIN
    TB1
    ON
        tb2_id1 = tb1_id OR tb2_id2 = tb1_id
WHERE
    (tb2_id1 = :user_id AND tb2_id2 != :user_id) OR (tb2_id1 != :user_id AND tb2_id2 = :user_id) AND tb2_type = :tb2_type AND tb2_value = :tb2_value AND RAND()<(SELECT ((15/COUNT(*))*10) FROM TB2)
ORDER BY
    RAND()
LIMIT
    15

Or do I do it wrong?
Thank you,

A: Try this:
SELECT
    TB2.tb2_id1, TB2.tb2_id2, TB2.tb2_type, TB2.tb2_value,
    IF(TB2.tb2_id1 = :user_id, t2.tb1_id, t1.tb1_id) AS tb1_id, -- :user_id = 1
    IF(TB2.tb2_id1 = :user_id, t2.tb1_name, t1.tb1_name) AS tb1_name -- :user_id = 1
FROM TB2
LEFT JOIN TB1 t1
ON TB2.tb2_id1 = t1.tb1_id
LEFT JOIN TB1 t2
ON TB2.tb2_id2 = t2.tb1_id
WHERE (TB2.tb2_id1 = :user_id OR TB2.tb2_id2 = :user_id) -- :user_id = 1
AND TB2.tb2_type = :tb2_type -- :tb2_type = 'A'
AND TB2.tb2_value = :tb2_value -- :tb2_value = '2'
-- RAND()<(SELECT ((15/COUNT(*))*10) FROM TB2)
ORDER BY RAND()
LIMIT 15

SQLFiddle Demo


text:
Q: Can $f*g = f+g$ for $f$ and $g$ compactly supported? Let $f$ and $g$ be  continuous, compactly-supported functions $\mathbb{R} \to \mathbb{C}$. Can it happen that $f*g  = f+g$? Here, $f*g$ denotes the convolution
$$(f*g)(s) = \int_\mathbb{R} f(t) g(s-t) \ dt.$$
Edit: Discount the solution $f=g=0$.

My thoughts: My feeling is that the answer is "no". We are asking for a certain identity to hold in the dense subalgebra $C_c(\mathbb{R})$ of the Banach algebra $L^1(\mathbb{R})$. If there is a pair such that this happens, then without loss of generality, $\|f\|_1 < 1$. But then, the series
$$h = f + f*f + f*f*f + \ldots$$
converges in $L^1(\mathbb{R})$. It is not hard to see that $g = -h$ has $f*g = f+g$. I think there can only be one $g$ satisfying $f+g = f*g$, so this is the one. But, my sense is that the interated convolutions in the sum are making the support spread out. Could somebody please clarify this for me?

A: For a continuous function $f$, write $M(f)=\max \operatorname{supp}f$ and $m(f)=\min \operatorname{supp}f$. Suppose $f*g=f+g$. On one hand,
$$M(f+g)\le \max(M(f),M(g)),\quad m(f+g)\ge \min(m(f),m(g)) \tag{1}$$
On the other hand, the  Titchmarsh convolution theorem says that $$M(f*g)=M(f)+M(g),\quad m(f*g)=m(f)+m(g)\tag{2}$$
Since $a+b=\max(a,b)+\min(a,b)$ for any reals $a,b$, it follows that
$$\min(M(f),M(g))\le 0,\quad \max(m(f),m(g))\ge 0 \tag{3}$$
So, the supports have disjoint interiors. Since the support of $f+g$ is the union of supports, equality holds in both places in (1), and consequently in (3).
Without loss of generality, $M(f)=0$ and $m(g)=0$. Fix $\epsilon>0$ such that $m(f)+\epsilon<0$ and $\int_{0}^{\epsilon} |g(t)|\,dt\le 1/2$. Let $\mu = \max_{[m(f),m(f)+\epsilon]}|f|$, which is positive. Pick $x\in [m(f),m(f)+\epsilon]$ such that $|f(x)|=\mu$. We have
$$
\mu=|f(x)|=|(f+g)(x)| = |(f*g)(x)| = \left|\int_0^\epsilon  f(x-t)g(t)\,dt \right| \le
\mu  \int_{0}^{\epsilon} |g(t)|\,dt \le \frac{\mu}{2}
 $$
A contradiction.


text:
Q: Ratio distance similarity transformations: $|\varphi (a)- \varphi (b)| = k|a-b|$ I am struggling with the following group geometry question. I am given that:
A simililarity transformation is a non-constant map $\varphi : \mathbb{R^2} \to \mathbb{R^2}$ that leaves the ratios of distances invariant: for all $a,b,c,d \in \mathbb{R^2}$ with $a \neq b$ and $c \neq d$ we have $\frac{|\varphi(a)-\varphi(b)|}{|a-b|} = \frac{|\varphi (c)-\varphi(d)|}{|c-d|}$.
I have to use the isometries on $\mathbb{C}$, and prove the following:
1) The similarity transformation multiplies all distances by the same positive factor $k$, so basically $|\varphi (a)- \varphi (b)| = k|a-b|$.
2) The set of all similarity transformations $Sim(\mathbb{R}^2)$ is a subgroup of the permutation group $S(\mathbb{R}^2)$.
I am failing to understand how I can use the isometries on $\mathbb{C}$ for this, if someone can perhaps explain simply its relation to rotations, translations, etc in $\mathbb{R}^2$, that would clarify a lot I think.

A: For part 1), we start by picking any $c\neq d\in \mathbb{R}^2$. Apply $\varphi$ and set $k=\frac{|\varphi (c)-\varphi(d)|}{|c-d|}$. By definition we have $\frac{|\varphi(a)-\varphi(b)|}{|a-b|} = \frac{|\varphi (c)-\varphi(d)|}{|c-d|}$ for any $a$, $b\in \mathbb{R}^2$. This gives $$\frac{|\varphi(a)-\varphi(b)|}{|a-b|} = k$$
$$|\varphi(a)-\varphi(b)|=k|a-b|$$
For part 2), we need to show that these transformations are bijective (so that they are actually in $S(\mathbb{R})$ to begin with) and that their subgroup is closed under composition. Closure follows from 1) by writing $$\frac{|\varphi_2(\varphi_1(a))-\varphi_2(\varphi_1(b))|}{|a-b|}=\frac{k_2|\varphi_1(a)-\varphi_1(b)|}{|a-b|}=\frac{k_2k_1|a-b|}{|a-b|}=k_2k_1$$
which implies that the composition of two similarity transformations is again a similarity transformation, and the subgroup is closed.
That the transformations are injective is clear: $\varphi(x) = \varphi(y)$, $x\neq y$ implies $k=0$, but then $\varphi(a)=\varphi(x)$ for all $a\in \mathbb{R}^2$, and $\varphi$ is constant, which we don't allow.
For surjectivity, we can modify Qiaochu Yuan's answer here. I believe all that needs to be changed is the first line – we are mapping the sphere of radius $r$ to the sphere of radius $rk$, and it isn't an isometry. The rest still works. With that result, we know that the sphere of radius $r$ is mapped bijectively to the sphere of radius $rk$ centered at $\varphi(0)$. To show that a point $x$ is in the image of $\varphi$, we just take the image of the sphere of radius $r=\frac{|x-\varphi(0)|}{k}$.


text:
Q: Android emulator in VS code is transparent and only shows the frame I try to set up VS code for flutter and I am stuck with my virtual android device. When I use AndroidStudio the emulator works perfectly but in VS code I only get the frame of the virtual phone.
I already tried

*

*changing the graphics in the device manager to automatic, hardware, software

*in the advanced settings of the emulator I tried all different combinations of renderer and API level

*using different virtual devices (only on Android Pie though)

the funny thing is, if I diable the device frame in the Device manager it works perfectly fine in VS code as well. But I kinda like to see the device and not just the window.
Greatful for any help!


text:
Q: How to get user dictionary in Google translate Api I would like to make some website with remembered translations in google translate. I think that getting user saved translations is not possible but maybe anyone know some way to do this. I saw that google translate api provide not many endpoints, there is endpoints for detecting languages, translatios and providing available languages.
Does anyone know how to get saved vocabulary?

A: Unfortunately, there is no way to retrieve the saved vocabulary (aka phrasebook)
There is an existing feature request asking for some sort of access (a Phrasebook API?) to this data. I'd suggest you to star the issue and show your interest, in order to attract its developer's attention and increase the chances that'll be implemented.


text:
Q: Pass target to jQuery function I want to create a function that lays out a button - in doing so I would like to pass a custom target - is this possible?
function appendHeroButton(parent, child, text, target, x, y, w, h){

    var childDiv = $("
"+text+"
");
    $("#"+parent).append(childDiv);

    var div = document.getElementById(child);
    div.addEventListener('click', target);

}

A: If I have understood the question correctly, you want a callback to be added as a param to your appendHeroButton function, and attached to the div.
Here is an example of doing so, you can simply just reference the function by name, then you can interact with the div if needed using the passed event.

function appendHeroButton(parent, child, text, target, x, y, w, h){

    var childDiv = $("
"+text+"
");
    $("#"+parent).append(childDiv);

    var div = document.getElementById(child);
    div.addEventListener('click', target);

}

var someFunction = function (e) {
  var div = $(e.currentTarget);
  console.log(div.text());
};

var parent = "foo";
var child = "bar";
var targetFn = someFunction;

appendHeroButton(parent, child, "text", targetFn, 10, 50, 100, 100);

Click here


text:
Q: Components are exposed for all users? I want to create a centralized Release Management server, for our customers but in my tests I'm not able to secure that our components will be safe from change mistakes. For example:
My test was like that:
User 1 - Release Manager (with all permissions)
User 2 - Ordinary user (just permission for approvals)
Logged with my User 1 - Release Manager (with all permissions)
First of all I ensured that only Release Managers will have access, and be able to see that release template:

I created a new component:

Then I logged with my User 2 - Ordinary user (just permission for approvals)
Firstly I can't see the release template I set permissions above in the release template list. Then I went to the components list and I'm able to see the same component, and even change it.

The main problem is that after done that, it impacts the releases for all release templates that contains that Component.
I hope to be wrong, and that someone should clarify it to me, that we may secure somehow all components with permission and so on. Any ideas?

A: Adding security for components is on our backlog. Thanks for the feedback. vNext components do not have tool or execution command stored in them. So, they are a little safer from this issue. Nevertheless, they do have configuration, and you would want to protect that configuration. This feature will be added sometime this year.


text:
Q: How to remove the empty section header in UITableView I am having a UITableView in that I am having three title headers.problem is: when my title header value become empty means that header should not show in the table view. I have tried many method its not helped for me. can anyone help me please.
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [reverseOrder1 objectAtIndex:section];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
 return 60;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 75)];
UILabel *headerTitile =[[UILabel alloc]initWithFrame:CGRectMake(20, -5, tableView.bounds.size.width-20, 75)];
headerTitile.text = [reverseOrder1 objectAtIndex:section];

headerTitile.textColor = [UIColor whiteColor];
headerTitile.TextAlignment=NSTextAlignmentCenter;
[headerView addSubview:headerTitile];
headerTitile.font = [UIFont fontWithName:@"Arial" size:16.0f];

headerView.backgroundColor = [UIColor colorWithRed:48/255.0f green:119/255.0f blue:21/255.0f alpha:1];

return headerView;

}

A: You can use like this
    - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
     {

    if ([tableView.dataSource tableView:tableView numberOfRowsInSection:section == 0])
    {
        return 0;
    }
    else
     {
        return 60;
     }
    }

A: In addition to Ravi's answer, make sure you set the section height property of table view to 0 in storyboard.


text:
Q: need help with joining the 2 tables on closest date I am a newbie in SQL and need help with the joining of these 2 tables on the closest date. Thanks in Advance!
Table A

billing_start_date
id
status

2020-07-27
100
active

2018-12-27
101
inactive

Table B

period_end_date
id
A
B

2018-12-21
100
4
5

2018-12-28
100
2
3

2020-07-24
101
3
4

2020-07-31
101
2
3

Output

period_end_date
id
period_end_date
status
A
B

2018-12-27
100
2018-12-28
active
2
3

2020-07-27
101
2020-07-24
inactive
3
4

A: You could try this - it makes the assumption that billing_start_date, id and status will remain the same.
I've used MySQL 8 to do this - previous versions have problems with GROUP BY (Google ONLY_FULL_GROUP_BY to find out about this - it's become the default in version 8, so no risk of being tripped up by this particularly egregious bug).
All of the code below is available on the fiddle here.
First, I started by creating the tables and records as per your data (this is really your job - it eliminates duplication of effort and provides a single source of truth):
CREATE TABLE billing_start  -- your table_a - I try to give my tables meaningful names!
(
  billing_start_date DATE NOT NULL,
  id                 SMALLINT NOT NULL,
  status             VARCHAR (25) NOT NULL
);

and:
INSERT INTO billing_start VALUES
('2020-07-27', 100, 'active'),
('2018-12-27', 101, 'inactive');

and the other table:
CREATE TABLE period_end
(
  period_end_date DATE NOT NULL,
  id              SMALLINT UNSIGNED NOT NULL,
  code_a          TINYINT  UNSIGNED NOT NULL,
  code_b          TINYINT  UNSIGNED NOT NULL
);

and:
INSERT INTO period_end VALUES
('2018-12-21',  100,    4,  5),
('2018-12-28',  100,    2,  3),
('2020-07-24',  101,    3,  4),
('2020-07-31',  101,    2,  3);

Then, I pick out the date differences as follows:
SELECT
  b.billing_start_date AS bsd, b.id AS bid, b.status,
  ABS(p.period_end_date - b.billing_start_date) AS diff
FROM billing_start b
JOIN period_end    p
  ON b.id = p.id;

Result:
bsd     bid     status  diff
2020-07-27  100     active  19506
2020-07-27  100     active  19499
2018-12-27  101     inactive    19497
2018-12-27  101     inactive    19504

Note the use of the ABS() function... it's required to get the smallest gap in the dates!
Then I use the above result in a subquery to get the billing_start table records with a given id and status which match the criteria! But I hold onto the differences in date so I can JOIN back to the period_end table using these dates as the JOINing criterion.
SELECT bsd, bid, bstat, MIN(diff) AS mdiff
FROM
(
  SELECT
    b.billing_start_date AS bsd, b.id AS bid, b.status AS bstat,
    ABS(p.period_end_date - b.billing_start_date) AS diff
  FROM billing_start b
  JOIN period_end    p
    ON b.id = p.id
) AS tab1
GROUP BY bsd, bid, bstat;

Result:
bsd     bid     bstat   mdiff
2020-07-27  100     active  19499
2018-12-27  101     inactive    19497

Finally, I join back to the period_end table as explained above:
SELECT
  t.bsd, t.bid, t.bstat, p.period_end_date, p.id, mdiff,
  p.period_end_date - t.bsd, p.code_a, p.code_b
FROM
(
  SELECT bsd, bid, bstat, MIN(diff) AS mdiff
  FROM
  (
    SELECT
      b.billing_start_date AS bsd, b.id AS bid, b.status AS bstat,
      ABS(p.period_end_date - b.billing_start_date) AS diff
    FROM billing_start b
    JOIN period_end    p
      ON b.id = p.id
  ) AS tab1
  GROUP BY bsd, bid, bstat
) AS t
JOIN period_end p
  ON  t.bid = p.id
  WHERE ABS(p.period_end_date - t.bsd) = ABS(mdiff)
ORDER BY t.bid;

Result:
bsd        bid  bstat   period_end_date id  mdiff   p.period_end_date - t.bsd   code_a  code_b
2020-07-27 100  active   2018-12-28     100  19499  -19499                   2  3
2018-12-27 101  inactive 2020-07-24     101  19497   19497                   3  4

Et voilà! The desired result!
I left the date differences in (and in the fiddle) to show my line of thinking. Tricky enough question - +1! But next time, please put in your server version and please go to the trouble of constructing a fiddle - help us to help you!


text:
Q: Question regarding a domain name ending with "ubuntu" I'm building a website like OMG!Ubuntu. I know that when using domain names ending with "Ubuntu" I must get consent from Canonical.
How do I get their consent ?

A: The Intellectual Property Rights Policy as described on Ubuntu.com has the necessary information:

*

*You can use the Trademarks, in accordance with Canonical's brand guidelines, with Canonical's permission in writing. If you require a Trademark licence, please contact us (as set out below).

*You will require Canonical's permission to use: (i) any mark ending with the letters UBUNTU or BUNTU which is sufficiently similar to the Trademarks or any other confusingly similar mark, and (ii) any Trademark in a domain name or URL or for merchandising purposes.

The "Contact Us" section links to http://www.ubuntu.com/legal/terms-and-policies/contact-us, which is a form:

Please contact us using the form below if you'd like to request an Ubuntu trademark licence, or have any other trademark enquiry. A member of our trademarks team will be in touch with you shortly.

More options for contacting Canonical are given in their "About" page: http://www.canonical.com/about


text:
Q: VB.NET Split Text File In Parts Let's say a text file contains:
<-NewItems->
Alpha
Omega
Beta
<-NewItems->
Delta
Gamma
Epsilon
<-NewItems->
Something
Something

And I want to make a new text file with the items every time <-NewItems-> is found. I am thinking its more of a For-Each or Do-while method but I can't figure out how to code it. I'm new to visual basic.
Edit: Will someone tell me how or at least lead me where I can figure it out myself?
Thank you.

A: How about
Private Sub Example()
    Dim counter As Integer = 1
    Dim input As String = @"
        <-NewItems->
        Alpha
        Omega
        Beta
        <-NewItems->
        Delta
        Gamma
        Epsilon
        <-NewItems->
        Something
        Something"

    For Each content In input.Split({"<-NewItems->"}, StringSplitOptions.RemoveEmptyEntries)
        My.Computer.FileSystem.WriteAllText($"somefolder/myfile{counter}.txt", content, True)
        counter += 1
    Next
End Sub


text:
Q: Origin of "Butter wouldn't melt in his/her mouth." This phrase means that someone is being prim and proper with a cool kind of demeanour. But from what event or phenomenon or occurrence was this idiom derived from, and when?

A: The Phrase Finder has a citation from 1530, in Jehan Palsgrave's Lesclarcissement de la langue françoyse:

He maketh as thoughe butter wolde nat melte in his mouthe.

It goes on to say,

The phrase is usually used in a derogatory and critical sense and, in the past at least, was most often applied to women. Occasionally, it was used to denote a quiet meekness and sweetness of temper rather than emotional coldness. For example, this description of Mr Pecksniff in Charles Dickens' Martin Chuzzlewit:

It would be no description of Mr Pecksniff's gentleness of manner to adopt the
         common parlance, and say that he looked at this moment as if butter wouldn't melt
          in   his mouth. He rather looked as if any quantity of butter might have been made  out of him,
         by churning the milk of human kindness, as it spouted upwards from his heart.

A: Eric Partridge offers this citation in A Dictionary of Slang and Unconventional English:

butter would not melt in one's mouth, (look) as if (To seem) demure. Coll. from the 1530's; Palsgrave (O.E.D.), Latimer, Sedley, Swift, Scott, Thackeray. In reference to women, Swift and Grose add: yet, I warrant you, cheese would not choke her, the meaning of which must be left to the reader who will look at cheese.

So, onward to cheese, we find — nothing useful. Partridge is curiously silent on the subject, at least as it relates to this case directly. I wonder if his reticence might be due to one unsavory meaning of the word, use of cheese for smegma, giving the whole thing a lewd sexual connotation. But I can find nothing in the O.E.D. or elsewhere to support this contention. Still, if cheese is somehow related to butter in this context, this could well shed a whole new light on that phrase as well. But given the lack of sources, I have to conclude this is a dead end.
Still, we might also consider another meaning of butter as "fulsome flattery, unctuous praise" (Partridge). A young woman who was demure, as Partridge calls it, would be likely to receive much of this kind of butter.

demure |diˈmyoŏr|
  adjective ( -murer, -murest)
  (of a woman or her behavior) reserved, modest, and shy : a demure little wife who sits at home minding the house.

A woman who was "reserved, modest, and shy" would probably seem a little cold, and certainly resistant to the kind of buttering flattery that might come her way.

A: I would offer the suggestion that butter and cheese though both dairy products have varying melting points. Though butter may go soft at room temperature (and some cheeses) I might infer that the suggestion from this quote may be that cheese would in fact melt in her mouth and therefore butter wouldn't stand a chance. The key to this being that she 'looks' as though butter wouldn't melt although the truth is that cheese would not choke her. Perhaps therefore it has 'melted' or at least gone soft. Good old hot lips.


text:
Q: Why I cant seem to center and get my radio buttons inline with the labels? No matter what I look up online, anything I try doesn't seem to center these annoying radio buttons with the labels inline horizontally.

*

*I have the labels to the left of the form, with the radio buttons inline on the right of the labels.

*The radio buttons are a tad lower than the labels, and I am looking to center them evenly with the labels so it looks nicer and more professional.

I am very finicky with the smallest details, so getting this right is a huge thing for me!
Hoping someone can point out what I am missing or doing wrong.
P.S. I am brand new to this!
CSS code for radio buttons
What it looks like now

A: You need to wrap the label and input field in a div and use flexbox property like:
.className {
   display: flex;
   align-items:center;
   gap:10px;
 }

A: It would be helpful if you could also put in your html. I don't seem to be having the same problems. The radio buttons align with the baseline of the text as can be seen below. If you need to nudge them up a bit you can use the transform css rule as per the example below
Also see here

.nudge {
  transform: translateY(-0.1rem);
}

Would you recommend this survey to others?

Yes?<input id='radio1' type='radio' name='radios'>

No?<input id='radio2' type='radio' name='radios'>

What is your go-to weapon for hunting deer?

<input type='checkbox' id='checkbox1'>Rifle

<input type='checkbox' id='checkbox2'>Shotgun

NUDGED Would you recommend this survey to others?

Yes?<input class='nudge' id='radio3' type='radio' name='radiosx'>

No?<input class='nudge' id='radio4' type='radio' name='radiosx'>

What is your go-to weapon for hunting deer?

<input class='nudge' type='checkbox' id='checkbox3'>Rifle

<input class='nudge' type='checkbox' id='checkbox4'>Shotgun


text:
Q: How can I json_encode the output of my function? How can I json_encode the output of this function I use to get all attached images of a post?
<?php
function get_all_images($postid=0, $size='bigger', $attributes='') {
    if ($postid<1) $postid = get_the_ID();
    if ($images = get_children(array(
        'post_parent' => $postid,
        'post_type' => 'attachment',
        'numberposts' => -1,
        'orderby' => 'menu_order',
        'post_mime_type' => 'image',)))
        foreach($images as $image) {
            $attachment=wp_get_attachment_image_src($image->ID, $size);
            ?><img src="<?php echo $attachment[0]; ?>" alt="" /><?php
        }
}?>

Everything is already setup for admin-ajax.php.

A: Not sure if the get_all_images() function is the one that is added to your wp_ajax_{action} hook.  If it is you will want to output a string back to your js.  I would define a variable and concatenate the img html to it as you loop through your images.
function get_all_images() {
//your code
$response = '';
foreach($images as $image) {
        $attachment=wp_get_attachment_image_src($image->ID, $size);

        $response .= '';
    }

 die( json_encode( $response ) );

}


text:
Q: Closed parallel (1,1)-forms on compact Kähler manifolds Let $(X,\omega)$ be a compact Kähler manifold. We know one example of a closed parallel (1,1)-form, namely, $\omega$ itself. Are there obstructions for the existence of non-vanishing closed parallel (1,1)-forms? What about $(p,p)$-forms?

A: Take a compact complex torus with a Kähler structure, say, an abelian variety, for example.  Then there are lots of non-vanishing closed parallel $(1,1)$-forms, and their products will generate $(p,p)$-forms.
If $(X,\omega)$ is a Hermitian symmetric space, there will be many parallel $(p,p)$-forms (and they will all be closed).  Exactly how many depends on the symmetric space.
If $(X,\omega)$ is a product of two Kähler manifolds, there will be more $(p,p)$ forms than just the powers of $\omega$.  For example, if $X = X_1\times X_2$ and $\omega = \pi_1^*\omega_1 + \pi_2^*\omega_2$, where $(X_i,\omega_i)$ are compact Kähler manifolds, and $\pi_i:X\to X_i$ is the projection, then $\pi_i^*\omega_i$ for $i=1,2$ are parallel $(1,1)$-forms and the sub-algebra they generate consists entirely of parallel $(p,p)$-forms.
Conversely, if $(X,\omega)$ is not locally a product or locally symmetric, then the only parallel $(p,p)$-forms are the constant multiples of $\omega^p$.
This follows from the classification of holonomy groups of irreducible manifolds, since, if $(X,\omega)$ is an irreducible Kähler complex $n$-manifold and is not locally symmetric, then, by Berger's Theorem, its holonomy group is isomorphic to one of $\mathrm{U}(n)$, $\mathrm{SU}(n)$, or $\mathrm{Sp}(\tfrac12n)$.  In all of these cases, any parallel  $(p,p)$-form is a constant multiple of $\omega^p$.


text:
Q: Passing variable from fancybox to parent page when closing fancybox Hi im trying to send a variable from a child iframe fancybox to the parent. But i cant seem to grasp how to do it. Does anyone have a idea. I already tried with js. A friend suggested to do it with php but havent find a solution. I have a mess right now. I tried another questions answers similar to mine with no luck. Here is the code
this is in the fancybox:

<?php foreach($files1 as $file): ?>
                <?php if ($cont>1) { ?>

                        <a onclick="OnClickButton ('<?php echo $file;?>');" href="<?php echo $file;?>">

                <?php } ?>
              <?php $cont++; endforeach ?>

This is in the parent page
function nombre (nombre) {

        name = nombre;
        alert(nombre)

    }
    $(document).ready(function() {
        $(".fancybox").fancybox();
    });
    $(document).ready(function() {
    $(".various").fancybox({
        maxWidth    : 800,
        maxHeight   : 400,
        fitToView   : false,
        width       : '70%',
        height      : '70%',
        autoSize    : false,
        closeClick  : false,
        openEffect  : 'none',
        closeEffect : 'none',
        afterClose  :   function() {

            if (name == 'folder 1') {
                $('.fancybox-thumb').fancybox().trigger('click');
            }
            if (name == 'folder 2') {
                $('.fancybox-thumb2').fancybox().trigger('click');
            }
            if (name == 'folder 3') {
                $('.fancybox-thumb3').fancybox().trigger('click');
            }

        }
    });
    });

A: I will try two solution, i don't know if in your case can works but are pretty solid.
1) sessionstorage:
using sessionstorage with jquery you can save a parameter and use it later in any page.
sessionStorage.setItem("nameofthestorage", yourvalue);

and to take the saved info
var x = sessionStorage.getItem("nameofthestorage");

2)save a php session:
i'm a bit rusted with php but you can see this official and easy guide
http://www.w3schools.com/php/php_sessions.asp


text:
Q: Strikethrough or line-through text using sIFR I am using sIFR3-r436. I want to strikethrough or line-through some text. I have tried both <s>HTML</s> and CSS: text-decoration:line-through but it won't work.
Here's my code.
css: ['.sIFR-root { font-size:28px;
line-height:36px; font-weight:bold;
color:#130f0e; text-align:center;
leading: 0; margin:0px; padding:0;
}','strong
{text-decoration:line-through;}']

Is there any solution for this?

A: sIFR 3 is based on Flash 8, which I believe does not support line-through.


text:
Q: ReactJS: How can I update state of property using localStorage? I have a component with the following initial state:
  constructor(props) {
    super(props)
    this.state = {
      currentId: 0,
      pause: true,
      count: 0,
      storiesDone: 0
    }
    this.defaultInterval = 4000
    this.width = props.width || 360
    this.height = props.height || 640
  }

I have to start from currentId = 0 and then update the state of the component, even after a page refresh.
I want to restore currentId = 1 after persisting a value of 1.
I am getting an error that the property cannot change , when I try replacing currentId = localStorage.getItem('currentId') in the above code.
    var currentId = this.state.currentId;
      localStorage.setItem( 'currentId', 1);
      console.log(currentId);
      localStorage.getItem('currentId');

I also tried:
  _this.setState((state) => {
      return {currentId: localStorage.getItem('currentId')};
    });

A: The value type persisted to localStorage must be a string.
Consider revising the code that interacts with localStorage so that the state value currentId is first converted to a string before it is passed to localStorage.setItem().
Also note that string values are returned by localStorage.getItem() when a key is present, which means you should parse the returned value to obtain currentId as a number.
Something along the lines of this should work:
const saveCurrentId = () => {

    const { currentId } = this.state;

    /* Format string from value of currentId and persist */
    localStorage.setItem( 'currentId', `${ currentId }`);
}

const loadCurrentId = (fallbackValue) => {

    /* Load currentId value from localStorage and parse to integer */
    const currentId = Number.parseInt(localStorage.getItem('currentId'));

    /* Return currentId if valid, otherwise return fallback value */
    return Number.isNaN(currentId) ? fallbackValue : currentId;
}

With the code above, you can then update your components constructor to automatically load and apply the persisted currentId as follows:
 constructor(props) {
    super(props)
    this.state = {

      /* Use 0 as fallback if no persisted value present */
      currentId: this.loadCurrentId( 0 ),

      pause: true,
      count: 0,
      storiesDone: 0
    }
    this.defaultInterval = 4000
    this.width = props.width || 360
    this.height = props.height || 640
  }

A: Use componentDidMount. See the code below. I added checking if localStorage.currentId have value. If it have, check if the value from localStorage.currentId match state's currentId and if it don't then update the state to the value from localStorage.
state = {
  currentId: 0,
  pause: true,
  count: 0,
  storiesDone: 0
}
componentDidMount() {
  //Assign localStorage.get("currentId") to a variable
  const localCurrentId = localStorage.get("currentId");
  //Check if localCurrentId is not null or undefined
  if (localCurrentId) {
    this.setState(prevState => ({
      //Update state's currentId if the current value didn't match with localCurrentId
      currentId: prevState.currentId !== localCurrentId ? localCurrentId : prevState.currentId
    }));
  }
}


text:
Q: how to scale a web application - common patterns consider iis and mssql on one hand and apache and mysql on another. is it the same tactic when scaling iis and apache?
i got the basic scaling thing - separate web tier and db tier, and then db redundancy etc...
BUT how to scale an application running on iis?
for example, it used to run on one machine, now we want it on multiple machines?
same question for something hosted on apache? lets saw wordpress (common example) - how to make it so that requests for a blog can be processed on more than one (virtual) machine in the cloud?
hope my question is at least somewhat clear, if not ask please.
basically i'm looking for a pattern when scaling web apps. any? any links to info perhaps?
CLOUD BASED especially.
thank you

A: Generally you'd have a web farm:

*

*Browser sends request to a web site

*Web site DNS resolves to a load balancer (LB)

*LB forwards request to one of several web servers

The LB will also monitor the web servers so that a failed server is ignored.
There are some issues about session etc if not shared in a database, but generally this works well. You decouple your web site from a single machine and gain basic DR functionality

A: Well, you probably won't be deploying Wordpress this way (though django and web2py are possibilities) ... but here's a thought
Google App Engine is supposed to help developers deploy scalable apps, and one would hope that some of Google's experience in this area is crystallized into the structure of GAE. Here are the salient features  I gathered from my brief experience:

*

*independent java (or python) servlets that can be started or terminated on individual hosts in a collection of identical unspecialized hosts, on demand -- instead of bulky applications requiring several processes and special prepared environments

*on a busy app that is active across multiple servers, the web browser may not match up with the same host each time... and the servlet needs to be written to deal with that

*for a scalable app, the developers should test and ensure that most requests will take under 1 second to process (GAE permits 30 seconds; but will flag requests taking over 1 sec, and they explain that the sub-second performance goal is taken into account when deciding how your app will be treated by GAE)

*use volatile ram (memcache service) to help avoid searching disk (storage service) where possible for popular data requests [on a traditional approach this would also avoid creating read locks that tie up writers... provided serving some stale data is acceptable]

I should also note that only recently has GAE supported mySQL as part of GAE Business class ... the original DB service is somewhat different and more like a large associative array.


text:
Q: Define a customized operation in MXNetR I am creating a network using mxnetR and want to create a customized operator. I look at the mx.symbol.Custom function in the package and the description says that I should use a front end language like Python to define my operation.
I found a sample code here: https://github.com/dmlc/mxnet/issues/4205 where the programmer use the @mx.operator.register decorator followed by the definition of the operation. I wonder if I can do the same thing in R.

A: Unfortunately, current version of R package for MxNet doesn't support custom operators. You can create custom loss functions and custom metrics, but not operations for now. Stay tuned, it is probably going to change in future.


text:
Q: Mysqli db to db copy and strange charset behaviour I converted a lot to mysqli so far but cannot get it to work.
What I want is to copy row with 50+ columns from DB1 to DB2 but don't know how or where to reference FROM DB1
    $query="INSERT INTO `action_templates`(`field1` `...`)
SELECT `field1`, `...`
FROM `action_templates` WHERE `id` = '$id' ";
mysqli_query($DB2, $query) or die ("Error in query: $query");

As alternative I tried the following but 1) php side it obviously dont escape the  utf8 (& # 3 9 ;) but insert side the database get it as ' and it break the insert.
    Input $field1 = "toespits om 'n doelwit te bereik";

$query = "SELECT * FROM `action_templates` WHERE `templateid` = '$templateid' ";
$result=mysqli_query($DB1, $query);
$row = mysqli_fetch_assoc($result);
if ($row == true) {
$field1 = mysqli_real_escape_string($DB1, $row['field1']); // or whatever escaping
...
...
}

$query="INSERT INTO `action_templates` ('NULL', `field1` '...', '...')";
mysqli_query($DB2, $query) or die ("Error in query: $query");
}

Output $field1 = "toespits om 'n doelwit te bereik"; // ' seems to be inserted as '

Both database charsets are set as UTF8


text:
Q: Stylecop Suppress errors for Reference.cs file I have just asked a similar question regarding auto generated code from Service References and Xml summary errors. An answer was posted suggesting that I could add the Service Reference into its own project and then it can avoid Xml summary warnings and Stylecop errors completely.
But I realised that I was able to get around the Xml problem by setting the Service Reference to Internal and am now stuck on the StyleCop errors.
I am using FxCop version 10.0.
In the properties of my project, in the Code Analysis tab, I have checked the option for

Suppress results from generated code
  (managed only)

Also, from looking at the generated code in the Reference.cs file, I see that the code is decorated with the following attribute:
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]

..which Stylecop should then skip, right? Although this is not working, I am still getting StyleCop errors for the generated code.
Edit: The following header can also be found in the generated code:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.18033
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

So why isn't it being ignored?
I also found this question and tried using the following in my StyleCop setings:
<CollectionProperty Name="GeneratedFileFilters">
    <Value>Reference\.cs$</Value>
 </CollectionProperty>

But this doesn't work either, I have been struggling with the regex but tried to add the following values to the above example to get Stylecop to ignore my generated code.
Reference.cs
\Reference\.cs
\Reference\.cs$
Reference\.cs$

Does anyone know how to suppress all Stylecop errors for a Reference.cs file?
Edit2: The errors being displayed for the Reference.cs file:

Error 1   CA1812 : Microsoft.Performance : ... is an internal class that
  is apparently never instantiated. If so, remove the code from the
  assembly. If this class is intended to contain only static methods,
  consider adding a private constructor to prevent the compiler from
  generating a default constructor.
Error 2   CA2239 : Microsoft.Usage : Add a 'private void
  OnDeserialized(StreamingContext)' method to type ... and attribute it
  with the System.Runtime.Serialization.OnDeserializedAttribute.
Error 4   CA1811 : Microsoft.Performance : ... appears to have no
  upstream public or protected callers.

I have 27 of these 3 types of errors.
Edit 3: I have Style/Fx cop setup to run on build. I have added CODE_ANALYSIS in the Conditional compilation symbols in the build tab and
"$(ProgramFiles)\Microsoft FxCop 10.0\FxCopCmd.exe" /file:"$(TargetPath)" /ruleid:-"Microsoft.Design#CA1006" /ruleid:-"Microsoft.Design#CA1020" /console /cul:en-GB /q /assemblyCompareMode:StrongNameIgnoringVersion

... in the Post-build event command line in the Build Events tab.

A: The CAxxxx errors are from FxCop, not StyleCop.  If they are appearing for generated code, and you want to keep the generated code without changing the generator, simply add project-level exclusions (e.g.: in GlobalSuppressions.cs).
Following question edit #3:
Since you're running fxcopcmd.exe "manually", your C# project setting for ignoring generated code isn't being used at all.  You'll need to add the /ignoregeneratedcode switch to your fxcopcmd.exe command line to get this to be applied.


text:
Q: What classes in VB has default initialization? I am not even sure that default initialization is the correct word.
For example, I know that a string defaults to "". If we declare a string and we don't initialize it, it's "".
We also know that most numbers, long, integer, single, double, defaults to 0 or false.
So dim a= list (of boolean)(100) will give a list of 100 boolean whose values are false.
Are there samples? Are variables in vb.net always preinitialize?
Bonus: What about in other languages? What languages have this feature and what's not?


text:
Q: Join Query for Count in mysql statement SQL Fiddle
I have three db tables and I'd like to select the 10 most used tags from song_tag table, which I can do with the sql query below
SELECT `tag_id`,
COUNT(`tag_id`) AS `value_occurrence`
FROM `song_tag`
GROUP BY `tag_id`
ORDER BY `value_occurrence` DESC
LIMIT 10;

How would I then get the tag name value from the tags table in the same query? Is it even possible? I have set up a fiddle with some dummy data and the three tables that are needed.(link at top of post).
This will be used in a wordpress wpdb query. I don't think there is much else to add about configuration setup, languages etc.

A: You would need to join the tags table to your result. So something like:
SELECT s.tag_id, COUNT(s.tag_id) AS value_occurrence, t.name
FROM song_tag s LEFT JOIN tags t
    ON s.tag_id = t.id
GROUP BY s.tag_id
ORDER BY value_occurrence DESC
LIMIT 10;

A: Answering your comment here so that I can format.
I personally don't know a way to get all tags in a single row with the song, however, we can create a SELECT statement that associates all tags to a song in different rows. It would look something like
SELECT s.title, t.name
FROM songs s LEFT JOIN song_tag st
    ON s.id = st.song_id
LEFT JOIN tags t
    ON st.tag_id = t.id
WHERE s.id = "123";


text:
Q: Split a string based on hyphen I have a string like this
XX0099-X01

I would like to split the string into two based on the hyphen, i.e.
XX0099 and X01
I have tried as
SELECT 'XX0099-X01',
           SUBSTR('XX0099-X01',
                  1,
                  INSTR('XX0099-X01',
                        '-',
                        1
                        ) -1
                  )
    FROM   dual

Not sure how to get the second part.
We have an old legacy system which still using 8i Oracle database.

A: Using combination of substr and instr:
select
  substr(s, 1, instr(s, '-') - 1),
  substr(s, instr(s, '-') + 1)
from t;

Another way is using regexp_substr if supported:
select
  regexp_substr('XX0099-X01','[^-]+', 1, 1),
  regexp_substr('XX0099-X01','[^-]+', 1, 2)
from dual;

A: If you can't use a regex substring/replacement, here is an option which uses Oracle's base string functions:
SELECT SUBSTR(col, 1, INSTR(col, '-') - 1) AS first_part,
       SUBSTR(col, INSTR(col, '-') + 1)    AS second_part
FROM yourTable


text:
Q: Require.js, module dependencies I have few modules: "Shapes.js" which is container for Shape objects(module "Shape.js") "Mouse.js" which will calculate coordinate when user press left click on the mouse and module "Selection.js" which need to do calculations and determinate that coordinate belong to the shape or not.
// Mouse.js
define([], function() {
    function Mouse(element, e) {
        var offsetX = 0, offsetY = 0;

        if (element.offsetParent !== undefined) {
            do {
                offsetX += element.offsetLeft;
                offsetY += element.offsetTop;
            } while ((element = element.offsetParent));
        }

        this.getMouseX = function() {
            return e.pageX - offsetX;
        }
        this.getMouseY = function() {
            return e.pageY - offsetY;
        }
    }
    return Mouse;
});

// Selection.js
define(['modules/Shapes', 'modules/Mouse'], function(Shapes, Mouse) {
    var selection;
    document.getElementById('canvas').addEventListener('mousedown', function(e) {
            selection = null;

            var mouse = new Mouse(document.getElementById('canvas'), e);
            var shapes = Shapes.getShapes();

            for(var i=0; i<shapes.length; i++) {
                if ((shapes[i].getX() <= mouse.getMouseX())
                    && (shapes[i].getX() + shapes[i].getWidth() >= mouse.getMouseX())
                    && (shapes[i].getY() <= mouse.getMouseY())
                    && (shapes[i].getY() + shapes[i].getHeight() >= mouse.getMouseY())) {

                    selection = shapes[i];
                    break;
                }
            }
        });
    return selection;
});

To keep this question small i will not post "Shape" and "Shapes" module, they are not important.
So now in the "main.js" module i want always to have reference to selected element(or null) when user triger mousedown event but i can't get it. Dont even know from where to start. If i just load Selection module in the main module i will always get undefined.Thanks in advance.
(Code snippets are from Simon Sarris canvas tutorial with minor modification, just trying to do everything through Require.js)
EDIT: @Katana314, did you thought something like this?
// Selection.js(EDITED)
define(['modules/Shapes', 'modules/Mouse'], function(Shapes, Mouse) {

    var selection;

    return function(e) {
        selection = null;

        var mouse = new Mouse(document.getElementById('canvas'), e);
        var shapes = Shapes.getShapes();

        for(var i=0; i<shapes.length; i++) {
            if ((shapes[i].getX() <= mouse.getMouseX())
                && (shapes[i].getX() + shapes[i].getWidth() >= mouse.getMouseX())
                && (shapes[i].getY() <= mouse.getMouseY())
                && (shapes[i].getY() + shapes[i].getHeight() >= mouse.getMouseY())) {

                selection = shapes[i];
                break;
            }
        }

        return selection;
    }
});

// Main.js
document.getElementById('canvas').addEventListener('mousedown', function(e) {
    console.log(Selection(e)); // Shape... :D
});

A: EDIT: Misread something, skip ahead. Original reply below:
Part of the point of requirejs is that a module only be instantiated once. This is actually running counter to how your setup is at the moment, though.

*

*Run "Mouse.js"' define function, store returned result (a constructor function) as module path "Mouse"

*Run "Selection.js"' define function, store returned result (selection, which has not received a value yet) as module path "Selection"

*Anything requiring "Selection" will have 'undefined' as a result.

I think the goal you want here is to return some sort of unchanging object, or even a function, from Selection. Then, whatever is requiring it can do something like this:
require('Selection', function(getSelection) {
  var currentElement = getSelection(); // and so on...
});

Since your question was focused on RequireJS, I haven't really analyzed the other functionality of the code for other errors though.
EDIT: Actually, I may have misread a small part of your syntax. It does seem like you're already returning a function in your module, and not the selection itself. The issue at hand may be more to do with the code that checks the active selection. Just to verify, how are you including Selection in your other code, and have you tried stepping through its contents with a debugger?


text:
Q: Ad Hoc Test builds for other companies in the iOS Developer Enterprise Program My company is enrolled in Apple's Enterprise Program. We're doing demo/test builds for employees of other companies. According to Apple, we can't use the enterprise program for deploying apps to the employees of other companies. But does that include sending of Ad Hoc test builds to testers at other companies?
This question addresses a very similar, but not identical, question. We're not wanting to use Enterprise Program to get around any 100 device limit - we're not having issues with that.
It seems to be a bit of a grey area. TestFlight works with builds we send, created with the Enterprise Program, as long as the appropriate UDIDs of tester devices are in the provisioning profile. But isn't that technically still 'illegal' according to Apple, if we're sending the test build to an employee in a different company (even with UDID in the profile)?
My current take on the situation is that we should be signed up to the regular developer program too, and use the regular program to sign Ad Hoc builds that go to testers at other companies. Correct?
Update
I'm pretty certain Jonathan's answer is correct.

A: My understanding is that the Enterprise Program allows for both internal distribution as well as a 100 device Ad-Hoc for testing. I think the crucial thing here is that you don't distribute an application signed for internal use to external "testers" because this will violate the agreement rather make sure you use the ad-hoc method.
Best Jon


text:
Q: How to check whether app is compatible in all devices or not? I have developed app and tested it in the all the possible devices i have(i.e. on physical devices,genymotion).But i got reviews from client that in some devices it works and in some devices it won't.
I have added the minSdkVersion and targetSdkVersion in my AndroidManifest.xml file.
So,I want to know that is there any tool/software available online to find out that app(which i have developed) is compatible in this list of devices with respective information.
Please suggest me other ways to get the info for same.
Thanks in Advance.

A: There is a tool which lets you test your app with multiple virtual and real devices. The link is :
https://testobject.com


text:
Q: Draw arc with increasing radius? I am drawing an arc which increases gradually and turns in to a circle.On completion of animation(arc turning in to a circle) i want to draw another circle with increased radius with the previous circle persisting and the second animation continuing.
Arc to circle fiddle
After the circle is drawn,it gets washed out which is something that I dont want and continue the second animation.
Some unnecessary animation appears after the completion.
What should I do?
MyCode:
    setInterval(function(){
        context.save();
        context.clearRect(0,0,500,400);
        context.beginPath();
        increase_end_angle=increase_end_angle+11/500;
        dynamic_end_angle=end_angle+increase_end_angle;
        context.arc(x,y,radius,start_angle,dynamic_end_angle,false);
        context.lineWidth=6;
        context.lineCap = "round";
        context.stroke();
        context.restore();
           if(dynamic_end_angle>3.5*Math.PI){  //condition for if circle completion
                draw(radius+10);//draw from same origin and increasd radius
           }
    },66);

window.onload=draw(30);

UPDATE:when should i clear the interval to save some cpu cycles and why does the animation slows down on third circle ??

A: This snippet from your code has some flaw.
if(dynamic_end_angle>3.5*Math.PI){  //condition for if circle completion
    draw(radius+10);//draw from same origin and increased radius
}

The recursive call to draw() will continue to run after the first circle was drawn completely. This is why the performance will be slow down immediately. You need to somehow block it.
I did a simple fix, you can polish it if you like. FIDDLE DEMO
My fix is to remove context.clearRect(0, 0, 500, 400); and change the new circle drawing logic to:
if (dynamic_end_angle > 3.5 * Math.PI) { //condition for if circle completion
    increase_end_angle = 0; // this will prevent the draw() from triggering multiple times.
    draw(radius + 10); //draw from same origin.
}

In this stackoverflow thread, it mentions how to make it more smooth. You'd better use some drawing framework since the optimization needs a lot of work.

A: First of all, about the flicker: you are using setInterval and not clearing it for the next draw(). So there's that.
But I'd use a completely different approach; just check the time elapsed since the start, and draw an appropriate number of circles using a loop.
var start = new Date().getTime();

var timePerCircle = 2;
var x = 190, y = 140;

function draw() {
    requestAnimationFrame(draw);
    g.clearRect(0, 0, canvas.width, canvas.height);

    var t = (new Date().getTime() - start) / 1000;
    var circles = t / timePerCircle;
    var r = 30;

    do {
        g.beginPath();
        g.arc(x, y, r, 0, Math.PI * 2 * Math.min(circles, 1));
        g.stroke();
        r += 10;
        circles--;
    } while(circles > 0);
}

draw();

A:
When should I clear the interval to save some cpu cycles?

Better yet not use an interval at all for a couple of reasons:

*

*Intervals are unable to sync to monitor's VBLANK gap so you will get jerks from time to time.

*If you use setInterval you risk stacking calls (not high risk in this case though).

A much better approach is as you probably already know to use requestAnimationFrame. It's less CPU hungry, is able to sync to monitor and uses less resources in general even less if current tab/window is not active.

Why does the animation slows down on third circle ??

Your drawing calls are accumulating which slows everything down (setInterval is not cleared).
Here is a different approach to this. It's a simplified way and uses differential painting.
ONLINE DEMO
The main draw function here takes two arguments, circle index and current angle for that circle. The circles radius are stored in an array:
...,
sa = 0,                   // start angle
ea = 359,                 // end angle
angle = sa,               // current angle
oldAngle = sa,            // old angle
steps = 2,                // number of degrees per step
current = 0,              // current circle index
circles = [70, 80, 90],   // the circle radius
numOfCircles = circles.length, ...

The function stores the old angle and only draws a new segment between old angle and new angle with 0.5 added to compensate for glitches due to anti-alias, rounding errors etc.
function drawCircle(circle, angle) {

    angle *= deg2rad; // here: convert to radians

    /// draw arc from old angle to new angle
    ctx.beginPath();
    ctx.arc(0, 0, circles[circle], oldAngle, angle + 0.5);
    ctx.stroke();

    /// store angle as old angle for next round
    oldAngle = angle;
}

The loop increases the angle, if above or equal to end angle it will reset the angle and increase the current circle counter. When current counter has reach last circle the loop ends:
function loop() {

    angle += steps;

    /// check angle and reset, move to next circle
    if (angle >= ea - steps) {
        current++;
        angle = sa;
        oldAngle = angle;
    }

    drawCircle(current, angle);

    if (current < numOfCircles)
        requestAnimationFrame(loop);
}


text:
Q: HTMLElement.blur method not working in componentWillReceiveProps It seems as though using the HTMLElement.blur does not work as expected when called from componentWillReceiveProps, although HTMLElement.focus actually does work.
Simple repro case (es2015 using babel):
class App extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      index: 0
    };
  }

  componentWillMount() {
    document.addEventListener("keydown", e => this.handleKeyDown(e));
  }

  handleKeyDown(e) {
    let index = this.state.index;
    switch (e.which) {
      case 40: // up arrow
        index = Math.max(0, index - 1);
        break;
      case 38: // down arrow
        index++;
        break;
    }

    this.setState({index});
  }

  render() {
    return (

        <SearchBox index={this.state.index} />

Index: {this.state.index}

    );
  }
}

class SearchBox extends React.Component {

  componentWillReceiveProps(nextProps) {
    if (nextProps.index === 0) {
      console.log('focusing');
      this.textbox.focus(); // this works
    } else {
      console.log('blurring');
      this.textbox.blur(); // this doesn't
    }
  }

  render() {
    return (
      <input type="text" ref={n => this.textbox = n} />
    );
  }
};

I have created a JSBin here that displays the unexpected behavior.
Does anybody have an explanation for this? Is there something about the react lifecycle that I have misunderstood?

A: It seems as though that was indeed the wrong life-cycle hook to use.
Found this nugget when I re-read the docs:

Updating: componentDidUpdate
void componentDidUpdate(object prevProps, object prevState)
Invoked immediately after the component's updates are flushed to the DOM. This method is not called for the initial render.
Use this as an opportunity to operate on the DOM when the component has been updated.

From here
I moved the relevant code to componentDidUpdate and now all works as expected.