Should a stopbar tailpiece be level?

Question: I have a Gibson ES-137 Classic with a tune-o-matic bridge and a stopbar tailpiece (the ES-137 has a mahogany centre block so the tailpiece attaches to that and doesn't require a trapeze tailpiece like a semi-acoustic without a centre block, like an ES-175).
I've only just noticed while cleaning it at the weekend (and by cleaning I just mean wiping off fingerprints etc after playing for a couple of hours - no string changes or anything else like that) that the tailpiece is not level when compared to the body - the low E string end is considerably higher (e.g. further away) from the body than the high E string end is.
I haven't done anything to the setup on this guitar since buying it new - is there a reason why a stopbar tailpiece would not be level, or is this an example of a poor setup from the factory?
The tune-o-matic bridge is set up very nicely and there is no fret buzz and the action is lovely, but I'm wondering whether I should correct the setup of the tailpiece.
Edit: I'd also be interested whether a poorly aligned stopbar tailpiece could cause any damage to the guitar, maybe if the tension on the posts that attach the tailpiece to the instrument is uneven it may cause the holes to wear more on one side or similarly.
Edit 2: As promised, here are some images of the bridge.
Comment: Wear only occurs when there is friction. The two posts holding the tailpiece onto the body don't move, so no wear can happen. It does look like the bass side can be screwed down, though.
Answer: The stop-bar might be set up like that as the low strings might have been hitting the rear of the tune-o-matic bridge, depending on how the saddles were set for intonation purposes? In some cases a string can pivot over a saddle and contact the rear of the tune-o-matic which can introduce rattles and other undesirable elements to your tone.
However, knowing current standards of Quality Control at Gibson it is hard to say with certainty that the bridge was setup like that on purpose.
Answer: This setup will not cause any damage or problems.
The stop bar just needs to be low enough to ensure the string has sufficient tension over the bridge that it doesn't slip or move. It is a little weird seeing it that high at the low end, so you could lower it if you want (do it with the strings removed in order to avoid friction or potential issues) but if it isn't causing you any obvious problems I'd just leave it where it is.
Unless it is at a very shallow angle, I guarantee you will not notice it feeling any different (no matter what that oddly worded page that Areel linked to says!)
Comment: I've accepted this answer as while the other ones provide some interesting information, this one does answer my question. I think I will level the tailpiece, at a height where the strings do not touch the tailpiece. Thanks!
Answer: Perhaps the setter-upperer (technical term) was looking for a sweet spot between attack on the lower strings and bending on the higher strings:
http://www.frudua.com/guitar_strings_tension.htm
Answer: I also have a 339 by Epiphone. It has the same situation that you show. When I purchased it the stop bar was screwed down to the body both ends. That gave a very steep angle over the bridge. I adjusted to achieve a shallower angle at the bridge and the result is just like yours. The angle of all strings is about the same over the bridge. I put spacing washers under the bolts of the stopbar and bolted down tight to achieve the same position as your stopbar. This relieves any bending effect on the bolts, and possibly helps sustain

Should a stopbar tailpiece be level?


VueRouter - localStorage gets cleared when no trailing slash is added in URL

Question: I use localStorage to store a JWT-token.
When I go to https://www.example.com/my-web-app/, I can see the JWT token in the Developer Tools --> Application.
When I go to https://www.example.com/my-web-app, no data in the localStorage is visible.
This means that user of the application has to log in over and over again if he doesn't add a trailing slash to the URL.
Anyone have an idea where the cause might be?
Dependencies
{
   "vue": "^2.6.11",
   "vue-router": "^3.1.5"
}

VueRouter config:
{
    path: '/',
    name: 'home',
    component: Home,
    meta: {
        requiresAuth: true
    }
},
{
    path: '/:catchAll(.*)',
    name: 'NotFound',
    component: NotFound
}

htaccess config (located in /my-web-app)
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /my-web-app/
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /my-web-app/index.html [L]
</IfModule>

Answer: You can create a utility function that auto add the trailing slash on every route when is not :
util.js
export function trailingSlash (str) {
  return str.endsWith('/') ? str : str + '/'
}

in the router file,
router/index.js
    import { trailingSlash } from 'util.js'
    ...
    ...
    router.beforeEach((to, from, next) => {
        return to.path.endsWith('/') ? next() : next(trailingSlash(to.path))
    })

A trailing slash is going to be added a the end of the url.
Comment: This gives this error:
`Error: Redirected when going from "/page2/" to "/page1" via a navigation guard.`
Comment: Besides, I guess the problem is already happening even before the user enters the Vue application. Could we force this at the htaccess level?
Comment: yeah i guess is better
Comment: # Force Trailing Slash
Comment: RewriteCond %{REQUEST_FILENAME} !-f
Comment: RewriteRule ^[^/]+$ %{REQUEST_URI}/ [L,R=301]
Comment: The problem doesn't occur in [hash mode](https://beluxvacc.org/adids-staging/#/acc). Only in history mode. Thanks for the htaccess snippet. Can you give me the complete snippet? I guess it needs to be mixed with the original of VueRouter: https://router.vuejs.org/guide/essentials/history-mode.html#apache
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/232269/discussion-between-edouard-yonga-and-studio-pj).
Comment: For the followers of this question; The issue is not solved yet.


Stop displaying errors in production server in Drupal 7

Question: How to stop Drupal from showing unnecessary errors?
I'm deploying my Drupal 7 site to production server, and I want to stop displaying general purpose errors.
EDIT:
I found something about showing errors in this link:
<?php
    error_reporting(-1);
    $conf['error_level'] = 2;
    ini_set('display_errors', TRUE);
    ini_set('display_startup_errors', TRUE);
?>

Can someone explain what will be the appropriate value for $conf['error_level'] to stop displaying errors?
Answer: Did you try this way : admin/config/development/logging ?
(Where you can choose to display every messages, or just errors, or no message at all)


SDL2 Load embedded binary

Question: Hi I'm trying to load an embedded png with SDL2. I only managed to create the file before but didn't load it directly. I tried to put the
_binary_flower_png_ in the IMG_LoadTexture but it didnt work .Here is how far I come(It works fine, but I dont wont to create a file)
 #include <stdlib.h>

#include <stdio.h>

#include <SDL2/SDL.h>

#include <SDL2/SDL_image.h>

extern const char _binary_flower_png_start[];

extern const char _binary_flower_png_end[];

extern const int _binary_flower_png_size;

int main()
{

SDL_Event event;
    SDL_Renderer *renderer = NULL;
    SDL_Texture *texture = NULL;
    SDL_Window *window = NULL;
        SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO);
    SDL_CreateWindowAndRenderer(
        500, 500,
        0, &window, &renderer
    );

    //File create

FILE *f = fopen("flower.png", "wb");
    fwrite(_binary_flower_png_start, &_binary_flower_png_end,
    &_binary_flower_png_start, f);
    fclose(f);
    printf("File created");

    //Load here

    IMG_Init(IMG_INIT_PNG);
    texture = IMG_LoadTexture(renderer, "flower.png");

//Render

    while (1) {
        SDL_RenderCopy(renderer, texture, NULL, NULL);
        SDL_RenderPresent(renderer);
        if (SDL_PollEvent(&event) && event.type == SDL_QUIT)
            break;
    }
    SDL_DestroyTexture(texture);
    IMG_Quit();
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return EXIT_SUCCESS;

}

Comment: You need `IMG_LoadTexture_RW` along with `SDL_RWFromConstMem`.
Answer: The way you load any resource in SDL 2.0 (whether it is from SDL_image, SDL_mixer, SDL_ttf, et. al.) is by using an SDL_RWops pointer to that memory.
To load a .png file from a memory buffer:
extern uint8_t *buffer; // presumably, this holds the bytes of a .png file
extern int cbBuffer; // the size of the .png data buffer

SDL_Surface *loadPng(void) {
  SDL_Surface *result = NULL;
  SDL_RWops *stream = SDL_RWFromConstMem(buffer, cbBuffer);
  if (stream == NULL) {
    // error handling for failure - call SDL_GetError()
  }
  else {
    result = IMG_LoadPNG_RW(stream); // does not free the source stream
    SDL_RWclose(stream);
  }
  return result; // may be NULL - caller should check
}

Alternatively, you could use the SDL_RWFromFile() function to load the .png file, if it isn't already loaded into an external buffer:
SDL_Surface *loadPng(const char *path) {
  SDL_Surface *result = NULL;
  SDL_RWops *stream = SDL_RWFromFile(path, "rb");
  if (stream == NULL) {
    // error handling for failure - call SDL_GetError()
  }
  else {
    result = IMG_LoadPNG_RW(stream); // does not free the source stream
    SDL_RWclose(stream);
  }
  return result; // may be NULL - caller should check
}

SDL2 Load embedded binary


Multiplication in $\mathbb{Z}$ corresponds to multiplication in rings?

Question: So I was trying to prove that the characteristic of an integral domain is either $0$ or prime. I got stuck, so I searched for a proof and I came across the following proof online

Now I almost want to accept this proof, except for the following (possibly silly and pedantic) issue. In the above proof we know that $n_0 \in \mathbb{N} \subseteq \mathbb{Z}$, so since $n$ is not prime, we factorize $n = m \cdot k$ (where $\cdot$ represents multiplication on the integers in the ring $(\mathbb{Z}, +, \cdot)$). Now in the above proof the following is asserted $$n(1_D) = \underbrace{1_D + \dots + 1_D}_{n \text{ times}} =0_D \implies m\cdot k(1_D) = \underbrace{\left(1_D + \dots + 1_D\right)}_{m \text{ times}} \ \bullet  \underbrace{\left(1_D + \dots + 1_D\right)}_{k \text{ times}}$$
Now seemingly it seems that multiplication of $m$ and $k$ in $\mathbb{Z}$ is inducing (ring) multiplication of elements in $D$ (when I thought we'd only end up with addition of the $1_D$'s $mk$ times).
Is there a reason why this happens?
Comment: For any commutative ring $R$, the map $\;\begin{aligned}[t]\mathbf Z&\to R\\n&\mapsto n\cdot 1_R\end{aligned}$ is a ring homomorphism.
Answer: This happens simply because by induction and definition of $k\cdot 1_D$, one may prove $(n\cdot 1_D)\times (m\cdot 1_D) = nm\cdot 1_D$.
The proof by induction on, say, $m$ is easy  : $(n\cdot 1_D)((m+1)\cdot 1_D) = (n\cdot 1_D)(m\cdot 1_D + 1_D) =...$
Comment: The key property being the distributive law.
Answer: As @Bernard pointed out in the comment above, for any commutative ring $R$ the map $\varphi : \mathbb{Z} \to R$ defined by $$\varphi(n) = n\cdot 1_R = \underbrace{1_R + \dots + 1_R}_{n \text{ times}}$$
is a ring homomorphism. Thus in my problem above where we have as our ring the integral domain $(D, +, \bullet)$ since we can factorize $n = m\cdot k$ in the ring $(\mathbb{Z}, +, \cdot)$ then we have
\begin{align*}
mn \cdot 1_R &= \varphi(m \cdot n) \\
&= \varphi(m) \bullet \varphi(n) \\
&= (m\cdot 1_R) \bullet (n\cdot 1_R) \\
&= \underbrace{\left(1_D + \dots + 1_D\right)}_{m \text{ times}} \ \bullet  \underbrace{\left(1_D + \dots + 1_D\right)}_{k \text{ times}}
\end{align*}


how to fetch array value from json in mule 4

Question: A quick question, in HTTP POST body I am passing a table details with columns. Here columns element is an array. I want to fetch the entire array.
I am using mule 4
Eg:
<code>  {
  "TableName": "Customer",
  "Columns": ["ID","Name"]
}
</code>
Expected Output: In a variable both columns: (ID, Name)
How can this be achieved?
Thanks in advance
Answer: To get value you just mention it in the Transformation. Like this
<code>%dw 2.0
var x={
  "TableName": "Customer",
  "Columns": ["ID","Name"]
}
output application/json
---
{
    array:x.Columns
}
</code>
result:
<code>{
  "array": [
    "ID",
    "Name"
  ]
}
</code>

If you want to grab value from your POST payload then it should be like this:
<code>        <ee:transform doc:name="Transform Message" >
            <ee:message>
            </ee:message>
            <ee:variables >
                <ee:set-variable variableName="myArray" ><![CDATA[%dw 2.0
output application/java
---
payload.Columns]]></ee:set-variable>
            </ee:variables>
        </ee:transform>
</code>


Set default to empty result with views exposed filters

Question: I am using Views (7.x-3.0-beta3) and I have created a exposed text filter to a view, which work fine.
The problem is the default result value: when the field is empty, is displaying all possible results. But I want to display the empty result by default. If you have a solution please shear it.
Answer: You can use a views preprocessor to achieve this. The 'empty' element behaves similarly to the "No Results Behavior" option in the Views UI. Place this code in template.php and clear the cache:
<code>function mytheme_preprocess_views_view(&$vars) {
  if ($vars['view']->name == 'my_view_name') {
    if (empty($vars['view']->exposed_input)) {
      $vars['rows'] = array();
      $vars['empty'] = '';
    }
  }
}
</code>
Tested using Views 7.x-3.0-rc1.
Comment: I am having similar requirement. Where exactly should this code be added? can I add it in views.php?


How to remove the half image card and make it full in html,css

Question: I am creating a website for my college, but this image card thing messed up things, how can i make the background image of the card full rather than shown in the image.Please see through it

element.style {
}
.item_service_card {
    position: relative;
    overflow: hidden;
}
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
}
*, ::after, ::before {
    box-sizing: border-box;
}
user agent stylesheet
div {
    display: block;
}
.owl-carousel.owl-drag .owl-item {
    -ms-touch-action: pan-y;
    touch-action: pan-y;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
.owl-carousel, .owl-carousel .owl-item {
    -webkit-tap-highlight-color: transparent;
    position: relative;
}
body {
    font-family: 'Open Sans', sans-serif;
    font-size: 14px;
    line-height: 1.48;
    font-weight: 400;
    color: #000;
}
body {
    line-height: 1;
}
body {
    margin: 0;
    font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol";
    font-size: 1rem;
    font-weight: 400;
    line-height: 1.5;
    color: #212529;
    text-align: left;
    background-color: #fff;
}
:root {
    --blue: #007bff;
    --indigo: #6610f2;
    --purple: #6f42c1;
    --pink: #e83e8c;
    --red: #dc3545;
    --orange: #fd7e14;
    --yellow: #ffc107;
    --green: #28a745;
    --teal: #20c997;
    --cyan: #17a2b8;
    --white: #fff;
    --gray: #6c757d;
    --gray-dark: #343a40;
    --primary: #007bff;
    --secondary: #6c757d;
    --success: #28a745;
    --info: #17a2b8;
    --warning: #ffc107;
    --danger: #dc3545;
    --light: #f8f9fa;
    --dark: #343a40;
    --breakpoint-xs: 0;
    --breakpoint-sm: 576px;
    --breakpoint-md: 768px;
    --breakpoint-lg: 992px;
    --breakpoint-xl: 1200px;
    --font-family-sans-serif: -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol";
    --font-family-monospace: SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;
}

html {
    font-family: sans-serif;
    line-height: 1.15;
    -webkit-text-size-adjust: 100%;
    -ms-text-size-adjust: 100%;
    -ms-overflow-style: scrollbar;
    -webkit-tap-highlight-color: transparent;
}
user agent stylesheet
html {
    color: -internal-root-color;
}
*, ::after, ::before {
    box-sizing: border-box;
}
*, ::after, ::before {
    box-sizing: border-box;
}
the following code is my html code for the card

       SYCon

Lorem ipsum dolor sit amet, consectetur
      adipiscing elit. In risus magna, porta sit amet
      orci ultrices, condimentum facilisis.

       SYCon

Guide:

Jak Rooney

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
      In risus magna, porta sit amet orci ultrices.
      Praesent sed eros et sapien laoreet vehicula ac at arcu. Suspendisse et nulla sem.
      Vestibulum condimentum risus vitae quam fringilla,
      vitae congue sem mattis. Nulla accumsan nisl ac massa sodales gravida.

The details

I want to remove the half background in the image and make it full in the image area
Comment: Try to add width of 100% to image or set image url to the `.image-service` class div and make background-size to cover this will work exactly as you want.
Answer: You can do this by placing image as background-image
Add this to your css
.image_service{
background:url(https://www.w3schools.com/bootstrap/la.jpg)center no-repeat;
background-size:cover;
height:-webkit-fill-available;
}

*,
 ::after,
 ::before {
   box-sizing: border-box;
}

.item_service_card {
   position: relative;
   overflow: hidden;
}

.owl-carousel.owl-drag .owl-item {
   -ms-touch-action: pan-y;
   touch-action: pan-y;
   -webkit-user-select: none;
   -moz-user-select: none;
   -ms-user-select: none;
   user-select: none;
}

.owl-carousel,
.owl-carousel .owl-item {
   -webkit-tap-highlight-color: transparent;
   position: relative;
}

.image_service {
   background: url(https://www.w3schools.com/bootstrap/la.jpg)center no-repeat;
   background-size: cover;
   height: -webkit-fill-available;
}

              SYCon

Lorem ipsum dolor sit amet, consectetur adipiscing elit. In risus magna, porta sit amet orci ultrices, condimentum facilisis.

              SYCon

Guide:

Jak Rooney

Lorem ipsum dolor sit amet, consectetur adipiscing elit. In risus magna, porta sit amet orci ultrices. Praesent sed eros et sapien laoreet vehicula ac at arcu. Suspendisse et nulla sem. Vestibulum condimentum risus vitae quam fringilla, vitae
              congue sem mattis. Nulla accumsan nisl ac massa sodales gravida.

Note: If you are trying to make a carousel, then you can do that with Bootstrap itself, Check this codeply: Multi slider carousel with cards which was beautifully explained by skelly here .You can adjust col and transform:translateX(*%) as per your requirement. For col-sm-4 it would be transform:translateX(-33.3%) and for col-sm-3 it would be transform:translateX(-25%).
Comment: I have 10 cards like that, how can i change the .image servicfe for everyone
Comment: you can mention separate class for all the cards like `card1` `card2` etc for all the image holder `div` and then add the images in the background. By the way, are you trying to make a carousel with cards?
Comment: check the above answer, updated. If you feel that was helpful, please accept my answer


How to run a .jar file after every boot on Debian (Raspbian)

Question: I want to run a .jar file always after I booted up my Raspberry Pi. I know how to run the file in the console:
java -jar pi/test.jar

But how can I save this command in a executable file and where is the place to save it, that the file starts after boot up? This is not a duplicate because it's different on a Raspberry Pi than on other linux systems.
Comment: cron "@reboot" maybe
Comment: Use cron's `@reboot`.
Comment: Possible duplicate of [Linux run at start](http://stackoverflow.com/questions/24174134/linux-run-at-start)
Answer: you can use my setup :
save this in /etc/init.d/raspberryUtils (change as appropriate)
#!/bin/bash
# MyApp
#
# description:raspberryUtils util service

case $1 in
    start)
        /bin/bash /home/developer/raspberryUtils/bootstartup/startServer.sh
    ;;
    stop)
        /home/developer/raspberryUtils/bootstartup/stopServer.sh
    ;;
    restart)
        /home/developer/raspberryUtils/bootstartup/stopServer.sh
        /home/developer/raspberryUtils/bootstartup/startServer.sh
    ;;
esac
exit 0

startServer.sh:
#!/bin/bash

java -cp /home/developer/raspberryUtils/dist/RaspberryUtils.jar service.StartServices  &

stopServer.sh
#!/bin/bash
# Grabs and kill a process from the pidlist that has the word myapp

pid=`ps aux | grep RaspberryUtils | awk '{print $2}'`
kill -9 $pid

this way you can stop,start without restarting the pi too
NOTE:
as mentioned by @Cosu its better using jps so stopServer.sh is :
#!/bin/bash
# Grabs and kill a process from the pidlist that has the word StartService

pid=`jps | grep StartService | awk '{print $1}'`
kill -9 $pid

Comment: Instead of using ps aux to get the procss list you can use `jps`. It might not be an issue in this case but it's a good habit.
Comment: @PascalAckermann yes mate, just use  `java -cp yourjarFile yourclasswithMain`
Comment: @PascalAckermann also bear in mind that I just copied and paste my code, please change the location accordingly
Comment: so RaspberryUtils.jar would be my jar-file?
Answer: You can user crontab for executing jar file every time you reboot. In terminal type crontab -e. at last of that code add line "@reboot command(For jar)".
If crontab -e is not working properly that execute export EDITOR=nano and then crontab -e.


How to mount Solaris Hard Drive?

Question: I have received a HDD. It has single partition with id 42 SFS covering the whole partition. But I am reliably told that it came from Sun Fire XXXX (where XXXX is 15 hundred or thousand or something like that).
Please help me to mount it.
I'm sure that it is not SFS.
Running strings against the device shows loads of files/text etc.
I've tried mounting it as UFS/ZFS/newfs, doesn't work. Tried to run fsck to find the correct magic number, still doesn't work.
I'm thinking that the drive was part of Solaris Volume Manager or Hardware Raid. Any tips on how to verify this and mount the harddrive under solaris?
Comment: On what OS do you try to mount the disk?
Comment: @SvenW I'm on Solaris 11 VM. the harddisk is connected to the VM and has a device file in /dev/dsk/
Answer: The Sun-Blade-1500 is a SPARC machine. A Solaris 11 VM (assuming on x86) won't mount a SPARC disk, unless perhaps if it is an EFI disk with ZFS.
Your disk is more likely ufs or vxfs. There is no fdisk partition table on SPARC disks, as they aren't using BIOS. The ID 42 partition is probably just an artifact.
Should you want to try mounting it and assuming you didn't break it with fsck or newfs, you first need to find SPARC hardware, at least if you use Solaris. Linux might be able to read a sun label and mount its big endian ufs although I'm skeptical about it.
Comment: This makes the most sense! doing a whole disk partition 42 is a way to protect disk from erasing data, just because OS cannot read the formatting properly. Thanks.
Answer: You tried... what? newfs? I would expect it to overwrite your disk, and you don't seem to want that.
42 is more commonly used for "Windows 2000 dynamic extended partition marker" than for Secure Filesystem (SFS). So it can be a dummy partition that really contains Windows "dynamic" disk, with proprietary LDM (or DDM) structure. It may contain Windows volumes, or parts of volumes. I would simply try it on Windows (XP is compatible with these, not sure about Vista/7).
Comment: Why would a Windows dynamic disk have: SUNW, Sun-Blade-1500, /opt/SUN /usr/bin/ksh and etc. And no references to WINDOWS or anything like that.
Answer: The problem you are facing is that SPARC is Big Endian, while x86 is Little Endian. Back in the days that meant, that Little- and BiG Endian systems save stuff in opposite byte order to disk. With modern filesystems like ZFS that doesn't matter anymore, but what you got is probably UFS (just out of my head). So basically you need another SPARC machine to read that.
Comment: Put in procurement request for a sparc machine now....
Comment: So this is probably solved, then..
Comment: The big/little endian mismatch is just a part of the issue and it isn't always a show stopper. For example FAT is little endian and can be mounted on SPARC anyway. The bigger issue is that x86 machines expect disks to have a partition table with up to four primary partitions and a valid checksum there. SPARC machines use a differently written "slice table" with up to 8 (or 16) partitions.
Comment: Sure, but FAT has its endianness clearly defined, whereas UFS in UFA it is not. So basically when mounting FAT on SPARC there is a wrapper in between that needs to take care of byte order, since FAT always is little endian.
The vtoc of course, also is a problem. Modern SPARC machines with ZFS use EFI labels, but with UFS volumes EFI isn't well supported.

How to mount Solaris Hard Drive?


Lista Encadeada (inserção no fim)

Question: Estou tentando fazer uma lista encadeada com inserção no fim dela, mas na hora de escrever da erro e não sei qual o problema.
#include <stdio.h>
#include <stdlib.h>

struct cel
{
    int v;
    struct cel *prox;
};
typedef struct cel celula;

int main()
{
    celula *inicio;
    inicio = NULL;
    inserefim(&inicio);
    escreve(inicio);
    return 0;
}

void inserefim(celula **ini)
{
    celula *aux;
    celula **fim;
    int x;
    do{
        scanf("%d",&x);
        if(x)
        {
            if(*ini == NULL){
                aux =(celula*) malloc(sizeof(celula));
                aux->v = x;
                aux->prox = NULL;
                *ini = aux;
                *fim = aux;
            }else{
                aux = (celula*)malloc(sizeof(celula));
                aux->v = x;
                (*fim)->prox = aux;
                aux->prox = NULL;
            }

        }
    }while(x);
}

void escreve(celula *ini)
{
    while(ini =! NULL)
    {
        printf("\nNUM:%d",ini->v);
        ini= ini->prox;
    }
}

Comment: E qual é a mensagem de erro?
Answer: Na função inserefim tem alguns acertos a fazer:

celula **fim; o ponteiro para o fim não precisa de ser duplo, um ponteiro simples é suficiente o que simplifica o código
Faltou no else voltar apontar o ponteiro fim para aux:
if(*ini == NULL){
    ...
}else{
    ...
    //aqui
}

Repare também que o código que tem no if e no else é grande parte repetido. Quando é esse o caso deve tentar colocar o que é igual antes ou depois do if ... else de forma a não se repetir e tornar o código mais simples.

Escreva então a sua função inserefim assim:
void inserefim(celula **ini)
{
    celula *aux;
    celula *fim; //ponteiro simples
    int x = 1;
    do{
        scanf("%d",&x);
        if(x)
        {
            aux =(celula*) malloc(sizeof(celula)); //era igual no if else
            aux->v = x; //era igual no if else
            aux->prox = NULL; //era igual no if else

            if(*ini == NULL){
                *ini = aux;
            }else{
                fim->prox = aux;
            }

            fim = aux; //agora executa tanto no if como no else
        }
    }while(x);
}

No função escreve também se enganou no operador diferente !=:
while(ini =! NULL)
// -------^ está =! quando devia estar !=

Este tipo de distrações são muito fáceis de apanhar no compilador. Ora veja o warning que ele dá neste caso com o operador diferente escrito ao contrário:

||=== Build: Debug in Test (compiler: GNU GCC Compiler) ===|
...main.c||In function 'escreve':|
...main.c|13|warning: assignment
  makes pointer from integer without a cast [enabled by default]|
...main.c|13|warning: suggest parentheses around assignment used as
  truth value [-Wparentheses]|
||=== Build finished: 0 error(s), 2 warning(s) (0 minute(s), 1 second(s)) ===|

Isto reforça a ideia de que é muito importante olhar para os avisos dados. Quando está a começar ou quando ainda não tem muita experiencia você quer considerar todos os avisos como erros mesmo, pois na verdade a maior parte deles são coisas que não está a fazer corretamente, e que terão implicações mais tarde.
Veja o código com as alterações indicadas no Ideone

Lista Encadeada (inserção no fim)


Switch default bootstrap styles with different ones

Question: I have this site that's using a subtheme of Drupal Boostrap theme. The contents are mainly made with views. I want to change the look of the table on the link with the style of the condensed table on this boostrap template
How can I achieve this? Do I define the css to use in views? Should I change the style.css in my subtheme to override the default css with the new one? Should I copy the css files of the new theme?
I'm really lost on how to apply the styles to the subtheme. Can someone guide me on how to do it or if there's some kind of tutorial for this particular case: Bootstrap Template do Drupal Theme.
Thanks.
Answer: I think you could approach this issue with any of the solutions you just mentioned. If it's just a table you are theming, I don't know that I would necessarily go through the trouble of creating an entirely new theme or sub-theme for just that component. Can you use the bootstrap styles and simply integrate them into your site with different class names?
Comment: Hi Maria, thanks for your answer. I already have a bootstrap subtheme so I will try to change the table style.


Empty rewrite.log on Windows, RewriteLogLevel is in httpd.conf

Question: I am using mod_rewrite on Apache 2.2, Windows 7, and it is working ... except I don't see any logging information.
I added these lines to the end of my httpd.conf:
RewriteLog "c:\wamp\logs\rewrite.log"
RewriteLogLevel 9

The log file is created when Apache starts (so it's not a permission problem), but it remains empty. I thought there might be a conflicting RewriteLogLevel statement somewhere, but I checked and there isn't.
What else could cause this?
Could this be caused by Apache not flushing the log file? (I closed it by hitting CTRL-C on the httpd.exe command ... this caused the access logs to be flushed to disk, but still nothing in rewrite.log)
My (partial) httpd-vhosts.conf:
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName my.domain.com
    DocumentRoot c:\wamp\www\folder

    <Directory c:\wamp\www\folder>
        Options -Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
        allow from all

        <IfModule mod_rewrite.c>
            RewriteEngine On
            RewriteBase /

            RewriteRule . everything-redirects-to-this.php [L]
        </IfModule>
    </Directory>
</VirtualHost>

Comment: Not having any rewrites, forgetting `RewriteEngine on` and not making any requests that hit rewrites *could* all cause it.  Where are your rewrites defined?
Comment: @Ladadadada - I have `RewriteEngine On` and the actual rewrites inside a Virtual Host, inside a Directory (in httpd-vhosts.conf). I have made requests that hit rewrite.
Comment: "Inside a ``" sound suspicious.  Could you add that part of your config to the question?
Comment: @Ladadadada - Added.
Comment: I'm starting to run out of ideas.  Might be time to see what Apache has to say about it.  What's in your error log?
Comment: @Ladadadada - sadly, nothing relevant.
Comment: how about, switch to linux ?
Answer: How about adding your error log in your vhost like i do for each vhost, ie something like:
<VirtualHost *>

    ServerAdmin firstname.lastname@example.com
    DocumentRoot "/web/htdocs/olivier/xxx/prod/website"

    ServerName xxx.fr
    ServerAlias *.xxx.fr
    ErrorLog "/web/logs/xxx.error.log"
    ...
    ...
    ...

</VirtualHost>

Comment: Nothing interesting there: http://pastebin.com/iUrT73hm
Answer: I think this is a WAMP bug, based on this thread.
Comment: Welcome to Server Fault! Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.
Answer: I'm far from an apache guru, but I did notice you had:
AllowOverride None

under
My understanding is that this needs to be:
AllowOverride All

Comment: The `AllowOverride` directive has [nothing to do with this problem](http://httpd.apache.org/docs/2.2/mod/core.html#allowoverride).


Handling missing data points with mean

Question: I have seen a lot of datasets where missing values are replaced with the mean. What if data was not normally distributed, does it still make sense to replace missing values with mean if one would choose to do so?
Answer: In general, replacing missing values with the mean (on fact,  I believe the median is more popular) of the variable that is missing across other observations is not a good approach, even if the variable is normally distributed. It's more of an initial try one can implement without much effort,  results in a value that is usually not totally absurd and if the variable does not matter too much may not affect modelling results all that much.
There are substantially better other methods that can make use of other information (e.g. multiple imputation, knn imputation etc.). E.g. let's say you want to predict what income people have, but for some records age is missing. Yet,  you know whether they are "in school", "receiving other education/training" "employed", "unemployed" or "retired". Would you put the mean age of all people for a record with missing age that says the person is still in school?

Handling missing data points with mean


ARIMA model forecast does't seem right

Question: I am doing a SARIMA forecasting for my monthly data in STATA, and below is my forecast. I use a SARIMA (1,1,1)(0,1,1,12) model, but the forecast seem to only capture the previous month pattern, which cause the forecast very repetitive (eg. the trend is going upward, which seems logical that we expect a greater number of ship arrivals to port). Looking at the historical pattern, there were up and downs like a random noise shape. My forecast, however does not capture the random noise shape. I am curious what went wrong? Is it because of the ARIMA I used is incorrect? Or what other reasons? I would really be grateful if someone could tell me where I did wrong, and the corrections that I could make to make the forecast seem more realistic. Thank you!
Here is the command code I used in STATA:
<code>*tsset month1, monthly
tsappend, last(2030m1) tsfmt(tm)
arima con_arrivals, arima(1,0,1) sarima(0,1,1,12)
predict con_arrivals_f, y dynamic(m(2019m1))
tsline con_arrivals con_arrivals_f if month1 > m(1995m1)*
</code>
Comment: You can only predict the regularities in data; whatever is truly random is unpredictable.
Comment: What do you expect the forecast to look like?
Comment: Hi, looking at the historical patterns, I would expect the forecast to be not just repetitive, but have some up and downs.
Comment: Hi thank you for the advice. Just one question: in the previous historical pattern, there are sometimes a peak and then a downturn to trough. However, the forecast does not capture that, in other words, the forecast is just keep going up. This cant possibly be right?
Answer: As Firebug notes, time series forecasting algorithms can only predict signal or patterns. Patterns that are unpredictable in timing can, by definition, not be predicted. And so they will not be.
Let's turn the question around: you expect the forecast to contain large peaks and troughs just like the past observations do. When do you expect them? Why do you expect them at some specific point in time, rather than, say, half a year earlier or two years later? If you can answer these questions, then you can start looking for a prediction algorithm that incorporates this kind of information.
ARIMA, incidentally, won't. It only looks back a short number of periods. It does include the possibility of large peaks and troughs by having large prediction intervals (not shown on your plot) - larger ones than if your series did not have these strong fluctuations.
You mention that your series is one of ships arriving in ports, and I notice that the big drop is apparently in 2008. This looks like it was driven by the Great Recession. If you can predict the next similarly strong downturn with any kind of accuracy, then you should not be forecasting ship arrivals, but earning tons of money by shorting stocks. (This is shorthand for: many extremely smart people are trying to predict exactly this kind of pattern, and unsuccessfully so, so it's not realistic to expect a dumb algorithm to manage it.)
Related: How to know that your machine learning problem is hopeless?

ARIMA model forecast does't seem right


Why should or shouldn't we prefer a macro that accepts arguments over a function that does the same job?

Question: Following are two programs that give the area of the circle when the radius is passed as argument. But in the first program, macro.c, I am using a macro for the job, while in the second, function.c I am using a function for the job.
I am familiar with the use of functions,and the nuances it takes. But what about the case of macros that accept arguments? When should we prefer them over functions? And when should we avoid them? Which one gives better performance? I know the macro approach will lead to bulky code if the macro is used many times in the program, while for the case of the function, the same function is invoked many times for the job. But beyond this trivial difference, what are the other issues we need to look out for?
//macro.c

#include<stdio.h>
#define AREA(x) (3.14*x*x)

int main(void)
{
    float r1=6.25,r2=2.5,a;

    a=AREA(r1);
    printf("\nArea of circle=%f",a);
    a=AREA(r2);
    printf("\nArea of circle=%f",a);
}

//function.c

#include<stdio.h>
float area(float);

int main(void)
{
    float r1=6.25,r2=2.5;
    printf("\nArea of circle=%f",area(r1));
    printf("\nArea of circle=%f",area(r2));
}

float area(float radius)
{
    return 3.14*radius*radius;
}

Comment: While your question seems reasonable from a "let's learn something" standpoint, it's unfortunately not really answerable and therefore off topic for Stack Overflow.  There are reasons to use both, and these days most compilers support inline functions, too.
Comment: This has been asked many times before: http://stackoverflow.com/questions/9104568/macro-vs-function-in-c and http://stackoverflow.com/questions/1616802/when-to-use-function-like-macros-in-c to name a few
Comment: `area(++r1);area(r1+r2);`
Comment: @BLUEPIXY What on earth is that supposed to mean?
Comment: A specific example of the result of this case is different.
Comment: @BLUEPIXY Thanks to you too.I've noticed that many times you point to something very useful & relevant,but struggle with your English!!
Answer: A number of flip sides of macro:

With macro you lose all the type safety. The arguments being passed are not typed checked as in case of inline functions.
Since macros are pure textual replacement they may produce Side effects.
An macro might be evaluated more than once and result in errors.

So it is better to just avoid them, Use inline functions instead.
inline functions do have their own share of flip sides:

They are not guaranteed to be inlined per see.

But given the comparison, inline definitely scores over macros.
Comment: @Rüppell'sVulture Multiple evaluation is `AREA(++foo)` expanding to `3.14 * ++foo * ++foo` (which, by the way, will not produce the correct answer).
Comment: And multiple evaluation fail, and worse possibilities for intelligent inlining, etc..,
Comment: @H2CO3 What exactly is multiple evaluation here?
Comment: @AlokSave Are inline functions in C a post C99 thing?Wikipedia says `Compilers are not obligated to respect this request.`
Comment: @Rüppell'sVulture: It is a suggestion in terms of actual code inlining but it is most appropriate way to wriggle out of one definition rule and define functions in header files.
Comment: @michaelb958 It'll be very nice of you if you can give me link on SO where this issue is discussed in a separate question.
Comment: @michaelb958 And I would never use something complicated like `AREA(++foo)` for macros, I'll prefer functions instead.
Comment: @Rüppell'sVulture That isn't SO question fodder; that's basic Googleable preprocessor weirdness. (And what about `AREA(rand() % 16)`? Or `AREA(complicated_calculation(foo, num_of_bars, baz))`? All legitimate use cases that work fine in an `inline` function and fall flat in a macro.)
Comment: @michaelb958 Thank you.Your comment supplemented the answers to this question well.
Answer: One reason to prefer functions, particularly external functions in library code, is so you can fix bugs without recompiling everything that uses them. For instance, fixing your bad definition of pi... :-)
The only time I can think to prefer macros is when you're doing generic programming, i.e. you want the same code to work on various different types, or where you want to use arguments to the macro in ways other than as expressions (for instance, having an operator as an input to the macro, or stringifying an argument, etc.).
Answer: Adding some more :)
->In C, macro invocations do not perform type checking, or even check that arguments are well-formed, whereas function calls usually do.
->a macro cannot return anything which is not the result of the last expression invoked inside it.
->Since C macros use mere textual substitution, this may result in unintended side-effects and inefficiency due to re-evaluation of arguments and order of operations.
->Compiler errors within macros are often difficult to understand, because they refer to the expanded code, rather than the code the programmer typed.
->Many constructs are awkward or impossible to express using macros, or use a significantly different syntax.
Answer: Macro will give you better performance but only for small code whereas if you want your funciton to do many things for you then it is beter to use function.
The explanation on this link is clear enough
http://www.c4learn.com/difference-between-macro-and-function-in-c-programming.html

If you stil have any doubts i ll try to answer
Comment: Macros *should not* perform better than static inline functions.
Comment: @R.. The following paragraph from Wikipedia's `inline function` entry seems to suggest that using inline functions in C seem to carry no guarantee `In various versions of the C and C++ programming languages, an inline function is a function upon which the compiler has been requested to perform inline expansion. In other words, the programmer has requested that the compiler insert the complete body of the function in every place that the function is called, rather than generating code to call the function in the one place it is defined. Compilers are not obligated to respect this request.`
Comment: Using macros also carries no guarantee. The compiler is free to factor the common code from multiple macro expansions out into a function and generate call instructions to call it.
Comment: There is not guarantee that the function would be inlined, but the question is if you should care about it. Maybe you should let your optimizer do what it wants, even if it decides not to inline. Your question is still interesting of course, I understand that it can be frustrating. I have been working with an optimizer that wouldn't inline a `static inline` function that was called only once, and I could not see any reason why.
Answer: The #define directive specifies a macro identifier and a replacement list.
Redefining a macro previously defined is not legal, unless the new definition is precisely the same as the old.
Eg syntax:
#define identifier replacement-list
#define AREA(x) (3.14*x*x)
AREA(x) is identifier anf (3.14*x*x) is the replacement list
The replacements are done while pre-processing By the end of pre-processig phase, the replacements are complete.
Prior to pre-processing phase:
int main{
      float r1=6.25,r2=2.5,a;
      a=AREA(r1);
      printf("\nArea of circle=%f",a);
      a=AREA(r2);
      printf("\nArea of circle=%f",a);
      return 0;

}
After pre-processing:
int main{
      float r1=6.25, r2=2.5,a;
      a=(3.14*r1*r1);
      printf("\nArea of circle=%f",a);
      a=AREA(3.14*r2*r2);
      printf("\nArea of circle=%f",a);
      return 0;

}
Advantages of MACROS
-> When the code in the replacement-list is less in size, we can use MACROS. Because the replacements are done during pre-processing time, the program doesn't have to shift the controls between functions during run time. And the program execution speed is great.
-> The Function over head is reduced.
Dis-advantages of MACROS
-> The ultimate goal of a programmer is to write programs of lesser size. When the code in the replacement list is more, what happens!! Redundancy of code occurs, which is very bad in the perspective of a good programmers. This is where the functions come in to play.
-> The arguments in the replacement-list aren't type checked.
->
 It is not a good programming practice to specify macro arguments that use the increment (++), decrement (- -), and assignment operators (such as +=)
For example, do not pass the following argument to the _toupper macro:
_toupper(p++)
When the argument p++ is substituted in the macro definition, the effect within the program stream is as follows:
((p++) >= 'a' && (p++) <= 'z' ? (p++) & 0X5F : (p++))
Because p is being incremented, it does not have the same value for each occurrence in this macro replacement.
Even if you are aware of possible side effects, the replacement lists within macro definitions can be changed, which changes the side effects without warning.
So, everything has its advantaged and dis-advantages :)
Comment: Macros are resolved **prior** to compiling the code, that is during pre-processing.


Fundamental Theorem of Calculus: Derivative of integral with respect to parameter in integration limits

Question: I have the following function:
$$F(t) = \int_{a-t}^{b+t} f(x) dx$$
In my notes when this is differentiated with respect to $t$ we get:
$$\frac{d F}{d t} = f(b + t) + f(a - t)$$
How can we obtain this result?
My approach
The approach that I was thinking about was about splitting the integral into two based on the integration limits, for instance, something like:
$$F_1(t) = \int_{a-t}^c f(x) dx \quad \quad F_2(t) = \int_{c}^{b+t} f(x)dx$$
So that $F(t) = F_1(t) + F_2(t)$, however I don't know how else to proceed.
Answer: You're on the right track. You can proceed by using the chain rule.
Observe that (with your notation)
$$ F_1(t) = G(H(t)), $$
where
$$ H(t) = a-t, \quad \text{and} \quad G(t) = \int_t^c f(x) \, \mathrm dx = -\int_c^t f(x) \, \mathrm dx. $$
Now
$$ H'(t) = -1, \quad \text{and} \quad G'(t) = -f(t), $$
where we invoked FTC when differentiating $G$.
Hence, the chain rule gives
$$ F_1'(t) = G'(H(t))H'(t) = -G'(a-t)f(t) = f(a-t). $$
Can you deal with $F_2$ on your own?
P.S. You could also directly refer to the more general Leibniz integral rule.
Comment: Thanks for directing me to Leibniz integral rule, seems super handy!
Comment: @Euler_Salter Indeed!
Answer: If we have a function defined by $$Q'(x)=f(x)$$
Then we have that $$F(t)=Q(b+t)-Q(a-t)$$
Taking $\frac{\mathrm d}{\mathrm dt}(\cdot)$ on both sides:
$$F'(t)=\frac{\mathrm d}{\mathrm dt}Q(b+t)-\frac{\mathrm d}{\mathrm dt}Q(a-t)$$
$$F'(t)=Q'(b+t)\frac{\mathrm d}{\mathrm dt}(b+t)-Q'(a-t)\frac{\mathrm d}{\mathrm dt}(a-t)$$
$$F'(t)=Q'(b+t)+Q'(a-t)$$
$$F'(t)=f(b+t)+f(a-t)$$
QED
Comment: @Euler_Salter Thank you very much. I have often found that many seemingly complex problems in calculus have amazingly simple results.
Comment: This is amazingly simple!
Comment: True! I think in this case I was just subconsciously deceived by the usual notation F on the LHS of the Fundamental Theorem of Calculus
Answer: $$\frac{dF}{dt}=\frac{d(b+t)}{dt}\frac{d}{d(b+t)}\int_c^{b+t}f(x)dx-\frac{d(a-t)}{dt}\frac{d}{d(a-t)}\int_c^{a-t}f(x)dx\\=1\cdot f(b+t)-(-1)\cdot f(a-t)=f(b+t)+f(a-t).$$We use the chain rule at the first $=$, then the FTC at the second $=$.
Comment: @Euler_Salter See edit.
Comment: can you please state which results you're using?
Comment: Thank you for explaining it more!


Editing existing Group Policy using PowerShell

Question: I have been created on my DC Group Policy which creates Schedule Task.
My question - How can I edit the command action inside the Schedule Task using PowerShell?
Answer:
Do this via New-ScheduledTaskAction and Set-ScheduledTask
<code>$action = New-ScheduledTaskAction -Execute 'PowerShell.exe' -Argument '-Command Example-Command'
Set-ScheduledTask -TaskName 'ExistingTaskName' -Action $action
</code>
Comment: Thanks for your answer but it isn't editing Group Policy it's edit a local schedule task


I have a date/time stamp field, where I need to pull records just by date

Question: I have a date/time stamp field, where I need to pull records just by date.
Example: All data were records are >= '01/01/2016'.
The data in the field is store in the following format '9/5/2012 7:34:59 AM'
I have tried the following but either I get an error or bad results:

where to_char(start_time) > '01/01/2016'  (still gives 2012 records)
where trunc(start_time) > '01/01/2016'   (Error: Not a valid month)
Comment: See: http://stackoverflow.com/questions/267721/mysql-strip-time-component-from-datetime
Comment: to_char and trunc are from Oracle...you sure you're using MySQL?
Comment: Is your date/time stamp field of `DATE` or `TIMESTAMP` data type, or is it `VARCHAR2` or `NUMBER`? The best way to know is to run the `DESCRIBE` command: `DESCRIBE `. This will give you the names AND DATA TYPES of all the columns in your table.
Answer: In  mysql you should use
this is in string canonical format
select * from my_table
where start_time > '2016/01/01'

or
or converting by str_to_date using proper format
select * from my_table
where start_time > str_to_date('01/01/2016', '%d/%m/%Y')

Answer: Use to_date to convert the string to date and then do the comparison.
Try this:
where start_time >= to_date('01/01/2016', 'dd/mm/yyyy');

Comment: Thanks! this worked.  I able to get the data I need.
Answer: In Oracle (and perhaps other database products) you can use the ANSI date literal, as shown below. You could also use to_date(), but the benefit of the ANSI date literal is that it doesn't require a function call. (Function calls are overhead which consumes time and resources, although calling to_date() just once is not a concern.)
... where start_time >= date '2016-01-01'

Note that in the ANSI standard date literal, the date must be in the exact format YYYY-MM-DD (with dashes and not with slashes or any other separators), since the ANSI date literal does not take a format model.


Custom view default style not wokring without style tag

Question: I have researched a lot and find many sources to this problem but no solutions working for me I don't know  what's going wrong.

Some resources i have look into

Custom view style, android's attributes are ignored
https://androidpedia.net/en/tutorial/1446/creating-custom-views
https://infinum.com/the-capsized-eight/how-to-support-themes-in-custom-views-for-android-apps

This is repo for this problem

https://github.com/burhankhanzada199888/CustomView-Style-StackOverflow-Question/tree/master/app
I have 2 custom view in my activity first without style tag and second with style tag but cardView style only apply when using in xml

custom_view.xml

<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:parentTag="com.google.android.material.card.MaterialCardView"
    tools:style="@style/CustomCardView">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="4dp"
        android:background="?colorSurface"
        android:gravity="center"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:padding="8dp"
            android:src="@mipmap/ic_launcher"
            app:srcCompat="@mipmap/ic_launcher" />

        <TextView
            android:id="@+id/textView"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="?colorAccent"
            android:gravity="center"
            android:text="Lorem ipsum"
            android:textColor="@android:color/white"
            android:textSize="25sp" />

    </LinearLayout>

</merge>

activity_main.xml

 <com.myapp.CustomCardView
     android:layout_width="match_parent"
     android:layout_height="0dp"
     android:layout_weight="1" />

 <com.myapp.CustomCardView
     style="@style/CustomCardView"
     android:layout_width="match_parent"
     android:layout_height="0dp"
     android:layout_weight="1" />

CustomCardView.java

public class CustomCardView extends MaterialCardView {

public CustomCardView(Context context) {
    this(context, null);
}

public CustomCardView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public CustomCardView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomCardView, defStyleAttr, R.style.CustomCardView);

    float imageSize = a.getDimension(R.styleable.CustomCardView_imageSize, 0);
    float textSize = a.getDimension(R.styleable.CustomCardView_textSize, 0);

    a.recycle();

    inflate(context, R.layout.custom_view, this);

    ImageView imageView = findViewById(R.id.imageView);
    imageView.getLayoutParams().height = (int) imageSize;
    imageView.getLayoutParams().width = (int) imageSize;

    TextView textView = findViewById(R.id.textView);
    textView.setTextSize(textSize);

}

}

styles.xml

attrs.xml

<declare-styleable name="CustomCardView">
    <attr name="imageSize" format="dimension|reference" />
    <attr name="textSize" format="dimension|reference" />
</declare-styleable>

Answer: You can add in the attrs.xml:
<attr format="reference" name="customCardViewStyle"/>

Change the constructor:
public CustomCardView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

to
public CustomCardView(Context context, AttributeSet attrs) {
    this(context, attrs, R.attr.customCardViewStyle);
}

Then in your app theme add:
<item name="customCardViewStyle">@style/CustomCardView</item>

Just pay attention to <item name="android:layout_margin">...</item>. The LayoutParams are specific to the parent view type and you can't apply it with a theme.You can set the layout attributes in a style on in the layout.
Answer: It happens because you've removed super calls in public CustomCardView(Context context) and public CustomCardView(Context context, AttributeSet attrs) constructors. Indeed your constructors must be like these:
public CustomCardView(Context context) {
    super(context)
    this(context, null);
}

and
public CustomCardView(Context context, AttributeSet attrs) {
    super(context, attrs)
    this(context, attrs, 0);
}

Comment: IIRC, there's no actual need for calling _both_ the superclass' constructor and the custom class' constructor.


Como resolver java.lang.NullPointerException?

Question: Criei a classe Server! Contudo é lançada uma exception do tipo java.lang.NullPointerException! Será que alguém me podia ajudar neste problema?
A classe é a seguinte:
public class Server {

    public static final int SERVERPORT = 8888;
    public static void main(String[] args) throws IOException {

        System.out.println("Starting echo server...");
        ServerSocket ss = new ServerSocket(SERVERPORT);

        boolean condition = true;

        while (condition)
        {
            Socket s = ss.accept();

            try
            {
                InputStream is = s.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);

                String msg = br.readLine();

                boolean condition1 = true;
                while (condition1) {

                    System.out.println(msg);
                    msg = br.readLine();

                    if(msg.equals("quit")){
                        condition1=false;
                    }
                }

                if(msg.equals("quit")){
                    condition=false;
                }

            }
            catch (IOException ioe)
            {
                System.err.println("I/O error: " + ioe.getMessage());
            }
            finally
            {
                try
                {
                    s.close();
                }
                catch (IOException ioe)
                {
                    assert false;
                }
            }
        }
    }
}

Comment: Onde dá o erro?
Comment: @MarcoAF Se o conteúdo da stream acabar antes da mensagem `quit` chegar, o `br.readLine()` vai retornar `null`. Não há muita saída a não ser testar por isso... (ou garantir seja lá como que nunca vai faltar o `quit` no final) P.S. Você lê a mensagem, imprime na tela, depois lê de novo - como saber se a primeira mensagem recebida já não foi o quit?
Comment: Não vou conseguir te ajudar mas já que eu modifiquei o código para eu entender melhor fica a dica de uma lógica sem *flags*. http://ideone.com/aiXooY
Comment: @bigown -> http://meta.pt.stackoverflow.com/questions/2333/por-que-muitas-pessoas-respondem-nos-coment%C3%A1rios-em-vez-de-criar-uma-resposta - fica a dica :)
Comment: O erro aponta para a seguinte instrução:     if(msg.equals("quit"))
Comment: @Victor não acredito que isto responde a pergunta de fato. Não tenho o Java aqui para testar corretamente.
Answer: O seu erro ocorre aqui:
if(msg.equals("quit")){

Na verdade, há duas linhas assim. Uma forma simples de resolver isso é:
if("quit".equals(msg)) {

E não haverá mais NullPointerException.
Ainda há o problema de um dos sockets para o cliente terminar sem nunca enviar um quit, e com isso ele ficaria preso no laço interno porque br.readLine() sempre retornaria null. A solução é testar o null no segundo if:
if(msg == null || "quit".equals(msg)) {

Há outras coisas que dá para melhorar no seu código. É possível eliminar a variáveis condition ao usar um break ou return ao invés de condition = false. O mesmo pode se aplicar ao condition1, em que é possível transformar o seu while interno em um for. Além disso você pode evitar ter que usar aquele finally horrível com try-with-resources. Seu código fica assim:
public class Server {

    public static final int SERVERPORT = 8888;
    public static void main(String[] args) throws IOException {

        System.out.println("Starting echo server...");
        ServerSocket ss = new ServerSocket(SERVERPORT);

        loop: while (true) {
            Socket s = ss.accept();

            try (InputStream is = s.getInputStream()) {
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);

                for (String msg = br.readLine(); msg != null; msg = br.readLine()) {
                    System.out.println(msg);
                    if ("quit".equals(msg)) break loop;
                }
            } catch (IOException ioe) {
                System.err.println("I/O error: " + ioe.getMessage());
            }
        }
    }
}

E se você achar esse for muito complicado, pode usar um do-while:
                String msg;
                do {
                    msg = br.readLine();
                    System.out.println(msg);
                    if ("quit".equals(msg)) break loop;
                } while (msg != null);


How to get an generic image icon for image field type (like Generic File formatter for file field)

Question: I have media field on a paragraph entity.
This field can hold media types, files, image etc.
Looking at admin/structure/media/manage/file/display there is a generic file formatter. However, for image - admin/structure/media/manage/image/display there is not.
So when the data is rendered, I get generic icon for word documents, but not images.
How can I get all my media items to render as generic icons?
Comment: I'm voting to close this question as it's too broad. Well if the image field's don't have that such feature then the only way is for you to programmatically add said feature. Have a look at [Create a custom field formatter](https://www.drupal.org/docs/8/creating-custom-modules/creating-custom-field-types-widgets-and-formatters/create-a-custom-0). You could also look into how Core is doing that for files. Good luck. If you get stuck when you have some code to show us, then maybe we can help you.
Answer: It seems this issue is being worked on at : #2568289: Not possible to reuse field formatters between entity_reference, file, and image fields
For now I've used the following code - included in the mytheme.theme file. (view mode custom_generic_file)
<code>use Drupal\file\Plugin\Field\FieldType\FileItem;

/**
 * Implements hook_preprocess_field().
 */
  function mytheme_preprocess_field(&$variables, $hook) {
    __mytheme_preprocess_field__generic_download_icons_view_mode($variables, $hook);
  }

/**
 * Ensure generic icon view mode for image media entities.
 *
 * Image field type doesn't have a generic file formatter.
 *
 * Called by hook_preprocess_field().
 *
 * @see Drupal\file\Plugin\Field\FieldFormatter\GenericFileFormatter::viewElements()
 * @see https://www.drupal.org/project/drupal/issues/2568289
 */
   function __mytheme_preprocess_field__generic_download_icons_view_mode(&$variables, $hook) {
  if (isset($variables['entity_type'])
    && ($variables['entity_type'] == 'media')
    && isset($variables['field_type'])
    && ($variables['field_type'] == 'image')
    && isset($variables['element']['#view_mode'])
    && ($variables['element']['#view_mode'] == 'custom_generic_file')) {

    foreach ($variables['items'] as $key => $item) {
      /* @var Drupal\image\Plugin\Field\FieldType\ImageItem */
      if (isset($item['content']['#item']) && $item['content']['#item'] instanceof FileItem) {
        /** @var \Drupal\Core\Entity\Plugin\DataType\EntityReference $entityReference */
        $entityReference = $item['content']['#item']->get('entity');
        /** @var \Drupal\Core\Entity\Plugin\DataType\EntityAdapter $entityAdapter */
        $entityAdapter = $entityReference->getTarget();
        /** @var \Drupal\Core\Entity\EntityInterface $file */
        /** @var \Drupal\file\Entity\File $file */
        $file = $entityAdapter->getValue();
        $item['content'] = [
          '#theme' => 'file_link',
          '#file' => $file,
          '#description' => NULL,
          '#cache' => [
            'tags' => $file->getCacheTags(),
          ],
        ];
        // Replace for real.
        $variables['items'][$key]['content'] = $item['content'];
      }
    }
  }
}
</code>


Cannot group by Year, Month and Date C#

Question: I would like to know how I can group dates by year, month and date respectively.
So far I managed to group by month and date, however I am getting some trouble understanding to group b a year
So, I created several classes that represent Day, Month and Year:
public class Day
{
    public DateTime Date { get; set; }
}

public class Month
{
    public int MonthNumber { get; set; }
    public List<Day> Days { get; set; }
}

public class Year
{
    public int YearNumber { get; set; }
    public List<Month> Months { get; set; }
}

So first I got a range of dates overall and add them to list of days.
var startDate = DateTime.Parse("12/08/2019");
var endDate = DateTime.Parse("01/03/2020");
var days = new List<Day>();
var months = new List<Month>();
var years = new List<Year>();
if (endDate >= startDate)
{
    for (var date = startDate; date <= endDate; date=date.AddDays(1))
    {
        var dayModel = new Day();
        dayModel.Date = date;
        days.Add(dayModel);
    }
}

Then I tried to group days by months and add them to list of Months:
var grouppedMonths = days.GroupBy(y => y.Date.Month).ToList();

foreach (var month in grouppedMonths)
{
    var monthModel = new Month();
    monthModel.Days = month.Select(d => d).ToList();
    months.Add(monthModel);
}

After groupping by months I want to group actual result by the year.
I tried something like this:
var grouppedYears = months.GroupBy(x => x.Days.Select(y => y.Date.Year));

but it did not work for me.
Overall I want to get

list of years

that contain list of months

that contain list of days.
Comment: You are loosing the Date.  So if grouping my months I use following : days.GroupBy(y => new DateTime(y.year, y.month, 1));
Answer: I guess you want this:
var results = days
    .GroupBy(d => d.Date.Year)
    .Select(y => new Year
    {
        YearNumber = y.Key,
        Months = y
            .GroupBy(d => d.Date.Month)
            .Select(m => new Month
            {
                MonthNumber = m.Key,
                Days = m.ToList()
            })
            .ToList()
    })
    .ToList();

Cannot group by Year, Month and Date C#


Drupal 7 - Cors

Question: I'm trying to get a hang of the CORS requests.
I'm logged in at the website, this is done manually from the website.
Now I'm trying to fetch my own user data from another website.
I have the "fetch token" request up and running just fine.
But when I try to fetch the user data I always get the anonymous user data.
Here is my Drupal Code:
<code> if (isset($_SERVER['HTTP_ORIGIN'])) {
  drupal_add_http_header("Access-Control-Allow-Origin", $_SERVER['HTTP_ORIGIN'], TRUE);
  drupal_add_http_header("Access-Control-Allow-Credentials", "true", TRUE);
}

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

  if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
    drupal_add_http_header("Access-Control-Allow-Methods", "POST, OPTIONS", TRUE);

  if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
    drupal_add_http_header(
      "Access-Control-Allow-Headers",
      $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'],
      TRUE
    );
  }
  drupal_exit();
  exit;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

  global $user;
  netpunkt_provider_remove_user_data($user);

  $return = new stdClass();
  $return->sessid = session_id();
  $return->session_name = session_name();
  $return->user = $user;

  drupal_json_output($return);
  drupal_exit();
  exit;
}
</code>
Here is my javascript code from the other website:
<code> var createCORSRequest = function(method, url) {
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr) {
      // Most browsers.
      xhr.open(method, url, true);
    } else if (typeof XDomainRequest !== "undefined") {
      // IE8 & IE9
      xhr = new XDomainRequest();
      xhr.open(method, url);
    } else {
      // CORS not supported.
      xhr = null;
    }
    xhr.withCredentials = true;
    return xhr;
  };

  function tokenButton() {

    var token = "";

    var url = 'http://******/cors_token';
    var method = 'POST';
    var xhr = createCORSRequest(method, url);

    xhr.setRequestHeader('Accept', 'application/json');
    xhr.setRequestHeader('Content-type', 'application/json');

    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4 && xhr.status === 200) {
        token = JSON.parse(xhr.responseText).token;
        document.getElementById("userButton").setAttribute("token", token);
        document.getElementById("tokenSpan").innerHTML = token;
      }
    };

    xhr.onerror = function(data) {
      alert('FEJL');
      console.log(data);
    };

    xhr.send();
  }

  function userButton() {

    var url = 'http://******/cors_check';
    var method = 'POST';
    var xhr = createCORSRequest(method, url);

    xhr.setRequestHeader('Accept', 'application/json');
    xhr.setRequestHeader('Content-type', 'application/json');
    xhr.setRequestHeader(
        "X-CSRF-Token",
        document.getElementById("userButton").getAttribute("token")
    );

    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4 && xhr.status === 200) {
        console.log(xhr.responseText);
      }
    };

    xhr.onerror = function(data) {
      console.log(data);
    };

    xhr.send();
  }

  document.getElementById("tokenButton").addEventListener(
    "click", tokenButton
  );

  document.getElementById("userButton").addEventListener(
    "click", userButton
  );
</code>
What am I missing here?
Answer: The answer is in _drupal_session_read().
<code>if (empty($sid) || !isset($_COOKIE[session_name()]) && !isset($_COOKIE[$insecure_session_name])) {
$user = drupal_anonymous_user();
return '';
</code>
Since the cors request runs on it's own request, there's no session info, hence you get the anonymous users data.
Comment: Hi Krisztián, I'm not sure I'm following you. I have "allow credential" in the request - so it should be allowed to read cookies (Or am I missing something in your answer?)
Comment: You are running a request from an other host. The cookies are stored in your browser. If a session is being started for that request, it will have it's on session data. If you would like to get a list of logged in users, run a query against the session table and grab the uids.
Comment: It is my own user data I want from another site. I logon to site A, go on to site B. Site B now needs to verify that I'm logged in at site A. Thank you for your time / help btw :-)
Answer: I figured out what the problem is...
My Firefox had "Accept third party cookies" set to "Never".
I changed this to "Always" - and Voila - the script now works.

Drupal 7 - Cors


Erro Repository Spring de Entidade com Relacionamentos

Question: Estou com um projeto usando Spring Boot para servir JSON em um WebService.
Um erro ocorreu quando adiciono a classe de Repository. Se removê-la o programa inicia normalmente (sem erros no console, não falo de funcionalidades).
O erro é: http://www.cjoint.com/c/FGir7xhZgvR (coloquei no Cjoint por ser muito grande).
As classes são:
@RepositoryRestResource
public interface Sells extends PagingAndSortingRepository<Long, Sell> {

}

@Entity
public class Sell implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private Date sellDate;
    @OneToMany(mappedBy = "sell", targetEntity = SellItem.class,
        fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private List<SellItem> sellItems;
    private Double total;
    // Getters e setter omitidos
}

@Entity
public class SellItem implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @ManyToOne
    private Product product;
    private Integer quantity;
    @ManyToOne
    @JoinColumn(name = "sell_id")
    private Sell sell;
    //Getters e setter omitidos
}

Caso necessário, peça mais informações nos comentários.
Answer: Olá, não sei se você já identificou o seu problema. Dei uma olhada no erro e vi que você declarou o seu repository da seguinte maneira:
public interface Sells extends PagingAndSortingRepository<Long, Sell> {
}

Sendo que a maneira correta é:
public interface Sells extends PagingAndSortingRepository<Sell, Long> {
}

Pelo que me parece você só inverteu a ordem dos argumentos genéricos da interface PagingAndSortingRepository.


IPv6 tunnel with openvpn "tun" and subnetting

Question: I have a vps with a /64 IPv6 prefix and I'm trying to use it to bring IPv6 connectivity to a host using openvpn.
I first used the layer-2 "tap" method, I created a permanent tap tunnel and configured radvd on that interface.
The client could obtain an ipv6 address, and packets arrived at the server, but I didn't configure routing or something else correctly I think, so on the server's eth0 interface I would see
2a01:7f00::f03c:91ff:fedb:6541 > ff02::1:ff86:a71: ICMP6, neighbor solicitation, who has 2a01:7f00::2daa:ad77:2286:a71, length 32

I decided to try with tun.
This is my conf (with a minor edit to the ipv6 prefix)
dev tun0
tun-ipv6
server-ipv6 2a01:7f00::/112
server 10.0.0.0 255.255.255.0
push "route-ipv6 2a01:7f00::/64"
comp-lzo
status openvpn-status.log
log-append /var/log/openvpn.log
verb 3
tls-server
ca /etc/openvpn/keys/ca.crt
cert /etc/openvpn/keys/server.crt
key /etc/openvpn/keys/server.key
dh /etc/openvpn/keys/dh2048.pem

the client obtains an IPv6 address, but you can see that something is wrong:
2a01:7f00::1000/64

it obtains a /64 address when I wanted a /112 subnet. And when I try "ping6 google.com" I obtain "Network is unreachable"
I'm new to IPv6, what I'm doing wrong?
All of the examples I see are with a server having a /48 prefix, and delegating a /64 prefix to the client.
Answer: Part of IPv6 is that you aren't supposed to subnet with prefixes any larger than 64 bits.  This is in part because mechanisms like SLAAC and privacy extensions generate the lower 64 bits of the address.
According to RFC 4862 section 5.5.3, autoconfiguration should have failed, so you may have hit a bug (unsurprisingly, as you're doing stuff that you oughtn't).  However, either way, this is not a configuration which would reasonably be expected to work.
The common interpretation of RFC 2373 section 2.4 is that prefix lengths longer than 64 bits are basically forbidden for non-multicast addresses, though it says this in a complex way.
Comment: Thanks. So, the bottom line is that with a /64 prefix I'm not going anywhere. I really need to find a server with a /48 prefix, right?
Comment: It would really depend on what you're trying to do.  Hurricane (tunnelbroker.net) is still offering /48s free of charge in a similar schema to what you are using.  That's if you need to subnet at all; you may not need to.  But, if you want to, you do indeed need a shorter prefix.
Comment: My problem is that I don't know the public ip addresses of the network my host will be part of, nor I do know if the tunneling mechanism used by tunnelbroker will be allowed in the network. SixXs rejected me because they think my home address is invalid. Are there any other tunnel brokers/hosting providers that assign a /48 prefix?
Comment: I don't know of any besides HE, though as long as your address isn't an RFC1918 one, it should be accepted by them.  If it is, you don't have many options besides perhaps teredo.


Remove library from page based on node field value

Question: We have a content type, Basic Page, where we may want to include 3rd party CSS such as Bootstrap. However, this 3rd party CSS may conflict with our custom theme, mytheme. On the Basic Page, we added a custom field of type Boolean, field_include_css, that a content editor can set to true if they want to use the Bootstrap CSS instead of mytheme.
How would we remove all the libraries added to the page that come from mytheme?
Here is what we tried, but did not work.
function mytheme_preprocess_page(&$variables) {
  $node = $variables['node']'
  // Basic page's machine name is page.
  if(is_object($node) && $node->getType() == 'page' && $node->field_include_css->value == '1') {
    unset($variables['page']['#attached']['library']);

    // above line didn't work so we also tried these, but they failed too.
    $variables['page']['#attached']['library'] = '';
    $variables['#attached']['library'] = '';
    unset($variables['#attached']['library']);
  }
}

Answer: Drupal has dedicated theme hook, hook_page_attachments_alter, for this scenario. Your theme can hook into it, check the rendered route (for your node type), and take action on the $page['#attached']['library'] render array accordingly:
function MYTHEME_page_attachments_alter(array &$page) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if (!is_null($node) && $node->getType() == 'page') {
    //@TODO: remove the appropriate library items from $page['#attached']['library']
  }
}

Comment: using `\Drupal::routeMatch()->getParameter('node')` got me the node i needed and then i was able to do the validation similar to your `if` statement.
Comment: Please be aware that `\Drupal::routeMatch()->getParameter('node')` doesn't always return an object. If it is not an object you'll have to load the node first, before calling methods on it.


Port blocked from network

Question: Situation:
Windows Server 2003 R2 running HP Data Protector Client
Port 5555 is blocked. Telnet to Server:5555 from the network fails but works from the machine itself. Firewall is disabled. AV is disabled/uninstalled. Disabled the Data Protector client. Installed SSH server with port 5555 and 5556. Port 5556 works as expected. 5555 is blocked. Performed Winsock reset. Connected second NIC and tried with that. This machine was infected and problem occurred a few weeks after cleaning up that unknown virus.
I'll take any ideas at this point. Sacrifice 2 chickens and a gerbil?
Comment: `This machine was infected...` means that a rebuild is in order.
Comment: And what exactly is the question?
Answer: I dont know nothing about HP Data Protector but you could check if service listening on port 5555 is binded to the right network interface (and not loopback only).

Port blocked from network


Proving that $(H_0^1)^\perp = H^\infty$

Question: The question is clear.
Note that $H_0^1 =\{ g \in H^1 : g(0)=0\}$, and $f \in H^1$ if $\sup \frac{1}{2\pi} \int \lvert f(re^{i \theta}) d \theta < \infty$, and $H^\infty$ contains all bounded analytic functions.
What I found that might work for this is the following:
If $Y=H_0^1$, by the definition, $Y^\perp = \{ f \in L^\infty : \langle g, f\rangle =0, \forall g \in H_0^1\}$. Note that $z^n=e^{i n \theta}$ belongs to $H_0^1$  when $n>0$. So integrating against it, it follows that any function in the dual must have all coefficients $a_m=0$, for $m<0$. However, a function in $L^{\infty}$ with that property is analytic so it is in $H^{\infty}$, and if $f \in H^\infty$, with the same reasoning it lies in $Y^\perp$ and hence, $Y^\perp =H^\infty$.
However, it doesn't seem to be clear to myself and I still don't see the part where we conclude the functions are analytic and hence lie in $H_0^1$.
Comment: The definition of the spaces should be written more precisely. What is $H^1$? On which set are defined the function considered? The open unit ball? The sup is over all $r<1$?
Comment: Just for clarity: Is the scalar product $<\cdot,\cdot>_{L^1}$?
Comment: @Max yes! that's right
Answer: As @Christophe Leuridan said it, some notations are confusing so I assumed that,
$$
H^1 = \left\{g : \mathbb{D} \rightarrow \mathbb{C} \textrm{ analytic}\ \middle|\ \sup_{r < 1}\int_0^{2\pi} |g(re^{i\theta})| \, d\theta\right\},
$$
where $\mathbb{D}$ is the open unit disk in $\mathbb{C}$. And the pairing $\left<\cdot,\cdot\right>$ is the natural pairing $\displaystyle \left<g,f\right> = \int_{\mathbb{D}} f(z)g(z) \, dz$ where $g \in L^1$ and $f \in L^\infty$. As $H^1_0 \subset L^1$, the question makes sens. I also assume that the $a_m$ you talk about are the coefficients of the Fourrier series of some $f \in L^\infty \subset L^2$.
However the functions you consider are not defined on the circle $\partial\mathbb{D}$ but on all the disk, thus it is non sens to talk about Fourrier series which makes all the rest of the proof collapses.
If I haven't misinterpret the problem (and I may have, notations are unclear), only one half of the result is true. Indeed, if $f \in H^\infty$ and $g \in H_0^1$, then $f \in L^\infty$ and $fg$ is analytic thus harmonic. It follows the mean value formula that for all $r$,
$$
\int_{r\mathbb{D}} f(z)g(z) \, dz = \pi r^2f(0)g(0) = 0.
$$
When $r \rightarrow 1$, the bounds on $f$ and $g$ imply that the integral converges toward $\left<g,f\right>$ and toward $0$. We deduce that $\left<g,f\right> = 0$ so $H^\infty \subset (H_0^1)^\bot$.
Reciprocally, however, we can find a lot of $f \in (H_0^1)^\bot\backslash H^\infty$. For example, for any $r < 1$, $f = \mathbf{1}_{r\mathbb{D}}$ is not continuous (thus not analytic) and belongs to $H_0^1$ by the same argument as previously (when $g \in H_0^1$, $fg$ is harmonic on $r\mathbb{D}$). Similarly, any function of the form $\displaystyle f = \sum_{i = 1}^m f_i\mathbf{1}_{r_i\mathbb{D}}$ where the $f_i$ are analytic and $0 < r_i \leqslant 1$ belongs to $(H_0^1)^\bot$.
If you want a continuous (and even smooth) counterexample, $f(z) = |z|$ the module function also verifies $f \in (H_0^1)\backslash H^\infty$. Indeed, $f$ has image in $\mathbb{R}$ and it is not constant thus it is not analytic and for all $r < 1$, by the mean value formula (or the Cauchy integral formula) applied to $g$,
$$
\int_{r\mathbb{D}} f(z)g(z) \, dz = \int_0^{2\pi}\int_0^r |te^{i\theta}|g(te^{i\theta}) \, tdtd\theta = \int_0^r t\int_0^{2\pi} g(te^{i\theta}) \, d\theta dt = 0.
$$
By a simlar argument as previously, $\left<g,f\right> = 0$. We deduce that $f \in (H_0^1)^\bot$. In fact, we can generalize both of the previous counterexample to say that for any bounded function $b : [0,1[ \rightarrow \mathbb{C}$, $f : z \mapsto b(|z|)$ belongs to $(H_0^1)^\bot$.

Proving that $(H_0^1)^\perp = H^\infty$


Condition plugins: two on the same form?

Question: I'm working on porting the CAS module to Drupal 8. On the main configuration form, users can list paths that will activate a feature of the module.
I read about using the new condition API recently, which has a condition for matching request paths, and decided to try and incorporate it into the module settings since it seems perfect for what I'm doing.
On the form submit handler, I have code like:
$this->myPathCondition->submitConfigurationForm($form, $form_state);

And the actual submitConfigurationForm code from the RequestPath class looks like this:
public function submitConfigurationForm(array &$form, array &$form_state) {
  $this->configuration['pages'] = $form_state['values']['pages'];
  parent::submitConfigurationForm($form, $form_state);
}

Couple problems though:

I have two instances of the condition plugin, so they would trip over each other in the form submission
For that reason, I would typically "namespace" each to a section, like: $form_state['values']['forced_login']['paths']

But since the condition plugin looks at a specific array structure for the value, this won't work. This appears to be a limitation of the plugin, but perhaps there's a reason for this, or a method around it?
I understand D8 isn't even in beta yet, but I didn't want to comment on the closed issue where this was implemented: https://www.drupal.org/node/1921544
Answer: You are responsible for only passing a sub-key of the form to each plugin configuration method.
Have a look at BlockBase::buildConfigurationForm() and the corresponding validate and submit methods. Note that this itself is already a partial form of BlockForm::form().
For a more flexible approach, have a look at https://drupal.org/project/page_manager, which has an UI that allows to add conditions and configure them in separate forms, but those forms also pass only a part of the form to those methods.
The main advantage of the page_manager approach is that BlockBase only works in a useful way with condition plugins that have a no-op mode, meaning, that you can configure them so they don't do anything (and that is the default configuration) because all condition configurations are saved and all plugins are invoked.
Yes, this is sometimes limiting and inconsistent, but that's how it works and I don't really have an idea to improve it...
Comment: Thanks. It didn't dawn on my that I could just create my own form_state to pass to the validate and submit handlers for the condition.


Index num campo ENUM pode trazer alguma vantagem?

Question: Estava lendo numa resposta do SOen, que os campos de uma tabela que possuem INDEX podem otimizar uma consulta. Claro, desde que essa consulta seja conhecida, como uma pesquisa de usuários pelo campo de email, por exemplo.
Tenho aqui no sistema uma tabela Pessoa que possui um campo ENUM('M', 'F') chamado sexo.
Essa tabela está bem "gordinha" e eu gostaria de saber se, se eu colocar um INDEX nesse campo, pode haver melhoria na consulta (Pois temos relatórios que fazem uma consulta específica para esses valores).
É vantajoso utilizar index para campos do tipo enum ou boolean  (tinyint(1))?
Comment: @bigown não tem sentido com o que eu estou perguntando essa pergunta aí. Eu quero saber se posso ou não usar `INDEX` num campo `ENUM` para melhoria de performance. Na verdade, quero saber se tem alguma vantagem em relação a valores com `INDEX` como o `VARCHAR` por exemplo.
Comment: Relacionado: http://pt.stackoverflow.com/q/81801/101
Answer: Não sei dizer no MySQL especificamente (nem acho que importe, espero que não :P). Provavelmente não há vantagem, se for um índice com coluna única e/ou enumeração tão simples, mas não afirmo com tanta certeza.
Se for um cadastro de engenheiros pode ser que tenha algum ganho quando for buscar por mulheres. Pra que ficar procurando no banco de dados inteiro para pegar 1% das linhas? Não garanto que os resultados serão tão melhores para esse 1%, mas certamente não serão para os 99%.
Então depende do caso e tem que fazer testes com a base de dados real.
Certamente ficaria mais interessante se a coluna da enumeração/booleano fosse parte do índice composto.
Seria mais interessante se esta coluna fosse calculada a partir de outras e fosse uma auxiliar justamente para filtrar uma determinada condição complexa e facilitar certas buscas.
Alguns bancos de dados até tem índice especial para isso mapeando os bits e criando um índice compacto. Este índice pode ser usado em uma condição específica, em geral não é usado em uma coluna booleana. O índice é criado baseado em uma expressão where e o resultado é que é indexado, assim ele já consegue selecionar rapidamente as linhas que satisfazem essa condição. Isto é feito internamente e o desenvolvedor não pode criar previamente este tipo de índice.
Pergunta com um caso que mostra que nem sempre o índice ajuda como as pessoas pensam.
Comment: "Engenheiros" me lembrou aquela propaganda que fala das mulheres terem que conquistar o direito na política :D


Sharepoint Online web api returns 401 after logged In using angular

Question: Am using Angular 4 application with Adal angular4 for connecting sharepoint online web api. I can able to view the user info which means I can able to login to the sharepoint online application. But after I could not able to get the list using the api.
const url = 'https://sitename/sites/applicationName/_api/lists/getbytitle(\'tenets\')/items';
const myHeaders = new HttpHeaders({
  'Authorization': 'Bearer ' + this.adalService.getCachedToken(environment.config.clientId),
  'content-type': 'application/json;odata=verbose'
});
return this.http.get(url, { headers: myHeaders }).subscribe(
  data => console.log(data),
  err => console.log(err),
  () => console.log('in complete')
);

Answer: SharePoint Online is used to store the data and it can be used as a web api. We are integrating this web api to Angular application. Below steps are helps to integrate adal-angular4 with Angular7
Install latest version of Adal-angular using below the command,
npm install adal-angular4 –save

Add AdalService and AdalGurad in provider @app.module.ts
providers: [ AdalService, AdalGuard],

Set up the SharePoint configuration in src/environment/environment.ts file
Ex:
export const environment = {
  production: false,
  config: {
    tenant: 'tenant-id,
    clientId: 'client-id',
    redirectUri: 'http://localhost:4200/'
  }
};

Create a service and import the AdalService and create a private variable for AdalService inside the constructor. Initialize your SharePoint Online configuration in constructor()
Ex: Web.service.ts
import { AdalService } from 'adal-angular4';
constructor(private adalService: AdalService) {
    this.adalService.init(environment.config);
  }

Write below mentioned method inside the service
Ex:
 handleWindowCallback() {
    this.adalService.handleWindowCallback();
  }
  login() {
    this.adalService.login();
  }
  logout() {
    this.adalService.logOut();
  }
  get authenticate() {
    return this.adalService.userInfo.authenticated;
  }

Once defined the above method, setup your login process in your login component. In general, after successful login, SharePoint will redirect to login component only, so we are validating the login and redirecting to a specific page.
Ex:
import { WebService } from '../web.service';
constructor(private webService: WebService) { }
ngOnInit() {
    this.webService.handleWindowCallback(); // this is to store the token to adal storage
    if (this.webService.authenticate) {
      this.router.navigate(['/', 'dashboard']);
    }
  }
login() {
    this.webService.login();
}

Add the below code inside auth.guard.ts to check whether the user is authenticated before every routing with the help of authenticate() method which is present inside the service,
constructor(private webService: WebService) { }
canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> |boolean{
      if (this.webService.authenticate) {
        return true;
      } else {
        this.router.navigate(['/']);
        return false;
      }
    }
  }

Add the below mentioned codes inside the login component to call the service on every login and logout request,
login() {
     this.webService.login();
}
logout() {
     this.webService.logout();
}

Write the below method inside the service to make a request to the SharePoint using URL and to get the corresponding response by passing the title,
import 'rxjs/add/operator/mergeMap';

getdata(listname): Observable<any> {
    const url = 'https://sitename.sharepoint.com/sites/application_name/_api/web/lists/
                 getByTitle(\'' + listname + '\')/items';
    return this.adalService.acquireToken('tenantid/tenant name')
           .flatMap(token => {
                    const headersParam = new HttpHeaders({
                        'Content-Type': 'application/json;odata=verbose',
                        'Authorization': 'Bearer ' + token.toString()
                    });
                return this.http.get(url, { headers: headersParam });
            });
  }

Add the below mentioned method inside the component where you want to fetch and process the data.
getdata() {
    const listname = 'tenets';
    this.webService.getdata(listname).subscribe(data => {
      console.log(data);
    });
}

This method prints the value and title of the tenets list,


SQLite funções nativas X SugarRecord

Question: Quais a vantagens e desvantagem no uso do SugarRecord quando comparado com as funções nativas  SQLite,
Exemplo na criação de uma tabela com o SQLite Funções Nativas
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {

    // Logcat tag
    private static final String LOG = "DatabaseHelper";

    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "contactsManager";

    // Table Names
    private static final String TABLE_TODO = "todos";
    private static final String TABLE_TAG = "tags";
    private static final String TABLE_TODO_TAG = "todo_tags";

    // Common column names
    private static final String KEY_ID = "id";
    private static final String KEY_CREATED_AT = "created_at";

    // NOTES Table - column nmaes
    private static final String KEY_TODO = "todo";
    private static final String KEY_STATUS = "status";

    // TAGS Table - column names
    private static final String KEY_TAG_NAME = "tag_name";

    // NOTE_TAGS Table - column names
    private static final String KEY_TODO_ID = "todo_id";
    private static final String KEY_TAG_ID = "tag_id";

    // Table Create Statements
    // Todo table create statement
    private static final String CREATE_TABLE_TODO = "CREATE TABLE "
            + TABLE_TODO + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_TODO
            + " TEXT," + KEY_STATUS + " INTEGER," + KEY_CREATED_AT
            + " DATETIME" + ")";

    // Tag table create statement
    private static final String CREATE_TABLE_TAG = "CREATE TABLE " + TABLE_TAG
            + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_TAG_NAME + " TEXT,"
            + KEY_CREATED_AT + " DATETIME" + ")";

    // todo_tag table create statement
    private static final String CREATE_TABLE_TODO_TAG = "CREATE TABLE "
            + TABLE_TODO_TAG + "(" + KEY_ID + " INTEGER PRIMARY KEY,"
            + KEY_TODO_ID + " INTEGER," + KEY_TAG_ID + " INTEGER,"
            + KEY_CREATED_AT + " DATETIME" + ")";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        // creating required tables
        db.execSQL(CREATE_TABLE_TODO);
        db.execSQL(CREATE_TABLE_TAG);
        db.execSQL(CREATE_TABLE_TODO_TAG);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // on upgrade drop older tables
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_TODO);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_TAG);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_TODO_TAG);

        // create new tables
        onCreate(db);
    }

E com o Sugar SugarRecord
public class Book extends SugarRecord<Book> {
  String title;
  String edition;

  public Book(){
  }

  public Book(String title, String edition){
    this.title = title;
    this.edition = edition;
  }
}

Comment: Esse é um tipo de pergunta cuja resposta é subjetiva. De qualquer forma, as **vantagens** você pode entrar no próprio site do SugarRecord e o **desvantagens** é simplesmente ficar dependente de uma lib de terceiros quando você poderia fazer você mesmo esse serviço.
Answer: Desenvolver aplicações com Sugar ORM pode ser útil para aqueles que precisem persistir informações em banco de dados local e desejem usufruir do modelo ORM, não necessitando utilizar SQL para criação e manuseio de tabelas.
Sugar ORM é uma biblioteca para persistência em banco de dados que disponibiliza uma maneira simples e consistente de integrar os modelos da aplicação em um banco de dados SQLite. A principal vantagem do Sugar ORM é a sua simplicidade mas que permite a realização de tarefas um pouco mais complexas como por exemplo a utilização de relacionamentos um-para-muitos.
Podemos ver essa "simplicidade" no CRUD do Sugar ORM:
Salvar:
Book book = new Book("Title here", "2nd edition")
book.save();

Carregar:
Book book = Book.findById(Book.class, 1);

Atualizar:
Book book = Book.findById(Book.class, 1);
book.title = "updated title here"; // modify the values
book.edition = "3rd edition";
book.save(); // updates the previous entry with new values.

Deletar:
Book book = Book.findById(Book.class, 1);
book.delete();

Operações em massa:
List<Book> books = Book.listAll(Book.class);

Book.deleteAll(Book.class);

Já no SQLlite:
Criação:
/*
 * Creating a todo
 */
public long createToDo(Todo todo, long[] tag_ids) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_TODO, todo.getNote());
    values.put(KEY_STATUS, todo.getStatus());
    values.put(KEY_CREATED_AT, getDateTime());

    // insert row
    long todo_id = db.insert(TABLE_TODO, null, values);

    // assigning tags to todo
    for (long tag_id : tag_ids) {
        createTodoTag(todo_id, tag_id);
    }

    return todo_id;
}

Busca:
Busca do tipo SELECT * FROM todos WHERE id = 1;
/*
 * get single todo
 */
public Todo getTodo(long todo_id) {
    SQLiteDatabase db = this.getReadableDatabase();

    String selectQuery = "SELECT  * FROM " + TABLE_TODO + " WHERE "
            + KEY_ID + " = " + todo_id;

    Log.e(LOG, selectQuery);

    Cursor c = db.rawQuery(selectQuery, null);

    if (c != null)
        c.moveToFirst();

    Todo td = new Todo();
    td.setId(c.getInt(c.getColumnIndex(KEY_ID)));
    td.setNote((c.getString(c.getColumnIndex(KEY_TODO))));
    td.setCreatedAt(c.getString(c.getColumnIndex(KEY_CREATED_AT)));

    return td;
}

Busca do tipo SELECT * FROM todos;
/*
 * getting all todos
 * */
public List<Todo> getAllToDos() {
    List<Todo> todos = new ArrayList<Todo>();
    String selectQuery = "SELECT  * FROM " + TABLE_TODO;

    Log.e(LOG, selectQuery);

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor c = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (c.moveToFirst()) {
        do {
            Todo td = new Todo();
            td.setId(c.getInt((c.getColumnIndex(KEY_ID))));
            td.setNote((c.getString(c.getColumnIndex(KEY_TODO))));
            td.setCreatedAt(c.getString(c.getColumnIndex(KEY_CREATED_AT)));

            // adding to todo list
            todos.add(td);
        } while (c.moveToNext());
    }

    return todos;
}

Atualização:
/*
 * Updating a todo
 */
public int updateToDo(Todo todo) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_TODO, todo.getNote());
    values.put(KEY_STATUS, todo.getStatus());

    // updating row
    return db.update(TABLE_TODO, values, KEY_ID + " = ?",
            new String[] { String.valueOf(todo.getId()) });
}

Deletar:
/*
 * Deleting a todo
 */
public void deleteToDo(long tado_id) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_TODO, KEY_ID + " = ?",
            new String[] { String.valueOf(tado_id) });
}

A desvantagem é que ainda está em desenvolvimento e podem ser encontrados bugs. Segundo esse site: "Se você tem um banco de dados mais complexo com mais do que apenas os campos de texto e números inteiros, ou se você tem que implementar uma migração de banco de dados, o que não pode ser feito por instruções SQL simples, você está perdido, infelizmente. Qualquer coisa além de acesso a objetos de banco de dados simples resultará em escrever código manual com instruções SQL limitados."

SQLite funções nativas X SugarRecord