text:
Q: Remote EJB not found I have an EJB deployed in an EAR:
@Stateless
@Remote(ActorProvider.class)
public class ActorServiceClient implements Serializable, ActorProvider { ... }

Here is the remote interface:
@Remote
public interface ActorProvider { ... }

Now, I have a separate WAR being deployed with the following class:
@Singleton
@Startup
public class ShiroStartup implements IShiroStartup {
    @EJB
    ActorProvider actorProvider;
...
}

The idea being that I deploy my actor service in an EAR, and I separately deploy a client project that gets the ActorProvider which Shiro uses for authorization (this is ancillary, but what I'm using it for).
I get an error starting the ShiroStartup (after I have deployed the EAR with the provider in it):

No EJB found with interface of type 'consumers.ActorProvider' for binding realm.ShiroStartup/actorProvider

Why can't I do this?  If I put the Provider in the war with the ShiroStartup it works fine, but it will not inject across deployments.  Why is that?  This is Wildfly 9 using JavaEE 7.

A: 1., The EJB and WAR modules should take place in the same EAR
or
2., Include the EJB jar into the classpath of the WAR
or :)
3., with portable JNDI names (for remote interfaces):
https://docs.oracle.com/cd/E19798-01/821-1841/girgn/index.html
In particular: java:app[/module name]/enterprise bean name[/interface name]


text:
Q: Applying Stone -Weierstrass theorem Prove or disprove that vector space generated by $\{1\}$ and $\{x^{an+b}: n \in \mathbb{N}\}$ where $a,b$ are fixed positive integers is dense in $C([0,1])$

A: The beautiful result of Muntz-Szasz says that if $0<p_1<p_2 < \dots,$ then the linear span of $ \{1, t^{p_1}, t^{p_2}, \dots \}$ is dense in $C([0,1])$ iff
$$\sum_{n=1}^{\infty}\frac{1}{p_n}=\infty.$$
The answer to this specific problem is then yes. But there may be a more elementary way.

A: Here is an elementary proof of the statement. If $a\mid b$ then the element
$$x^{an+b}x^{am+b} = x^{a\left(n+m+\frac{b}{a}\right)+a}$$
is an element of the vectorspace for all $n,m\in\mathbb{N}$ making it a subalgebra of $C([0,1])$. Since the vectorspace separate points and contains a non-zero constant function the desired result follows from the Stone-Weierstrass theorem. This can in fact also be proven using the weaker Weierstrass approximation theorem (WA) and for the case $a\not\mid b$ proven below this is all we will need.
If $f(x)\in C([0,1])$ then $f(x^{1/a})\in C([0,1])$ so the problem is equivalent to proving that the vector space $$A_c=\text{span}\{1,x^{1+c},x^{2+c},x^{3+c},\ldots\}$$ where $c = \frac{b}{a}$ is dense in $C([0,1])$. We can without loss of generality assume $0<c<1$.
Fix $\epsilon>0$. By WA there exists a polynomial $P_\epsilon(x)$ that approximate $f(x^{1/a})$ to (uniform) accuracy $\frac{\epsilon}{2}$ on $[0,1]$. Next we have that the function $\frac{P_\epsilon(x)-P_\epsilon(0)}{x^c} \in C([0,1])$ since $c < 1$ so again by WA there exists a polynomial $Q_\epsilon(x)$ that approximate it to (uniform) accuracy $\frac{\epsilon}{2}$ on $[0,1]$.
We now have that the function $$R_\epsilon(x) \equiv P_\epsilon(0) + x^c Q_\epsilon(x)$$
is an element of $A_c$ which satisfy
$$|f(x^{1/a})-R_\epsilon(x)| \leq |f(x^{1/a})-P_\epsilon(x)| + |P_\epsilon(x) - P_\epsilon(0) - x^cQ_\epsilon(x)|\\ \leq \frac{\epsilon}{2} + \left|x^c\right|\left|\frac{P_\epsilon(x)-P_\epsilon(0)}{x^c} - Q_\epsilon\right| \leq \frac{\epsilon}{2} + \frac{\epsilon}{2} = \epsilon$$
where $|\cdot|$ is the uniform norm. Since $f$ and $\epsilon$ was abitrary it follows that $A_c$ is dense in $C([0,1])$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pycharm stucks with Launching skeleton generator proccess I use Ubuntu 20.04, Pycharm 2020.3.3, Docker version 20.10.4, docker-compose version 1.28.2,
I have configured Python remote interpreter via docker-compose. When I open Pycharm I see a process Launching skeleton generator... running. It runs very long time, more than 30 minutes. While that code completion is broken and error highlighting doesn't work. Eventually finishes with error:

Couldn't refresh skeletons for remote interpreter
failed to run generator3/main.py for docker-compose://[/home/belek/Work/project/docker-compose.yml]:app-name/pyhon:timed out.

What I tried to do in order to resolve problem:

*

*docker system prune -a

*Recreated python remote interpreter

*Invalidate caches and Restart Pycharm

Today morning I got latest updates of docker and compose, and probably this problem starts to occure.
Any suggestions on how to fix it?
Upd:
As a temporary solution downgraded Docker to 20.10.3
sudo apt-get install docker-ce=5:20.10.3~3-0~ubuntu-focal docker-ce-cli=5:20.10.3~3-0~ubuntu-focal containerd.io

Also found an issue in YT.


text:
Q: How to add cursor to parent element and apply that to child elements too using css? i want to apply cursor: not-allowed to parent element and this should apply to the child elements as well.
What i am trying to do?
i have the parent div element with class "card" and cursor pointer and child elements with cursor pointer. now when the parent div element is with classes "card" and "disabled" now i want the parent div element and child elements to have the cursor:not-allowed.
Below is my html code,

        <button class="icon">
            <svg />
        </button>

text

         <button>
             <svg/>
         </button>

                 <button></button>

Below is the css,
.card {
     .icon {
         cursor: pointer;
     }
     .image {
         cursor: pointer;
     }
     .footer {
         svg {
             cursor: pointer;
         }
     }
 }

Now i have applied some style like below to make the cursor: not-allowed when parent div has classes card and disabled
.card.disabled {
    cursor: not-allowed;
}

This doesnt work. could someone help me with this. thanks.

A: Try this :
.card,
.card * {
     cursor: pointer;
}

.card.disabled,
.card.disabled * {
    cursor: not-allowed;
}

A: Thy this css code:

.card.disabled,
.card.disabled * {
    cursor: not-allowed;
}

Also, you can't really change the cursor for links, so, I'd suggest to use this code also:

.card.disabled a {
    pointer-events:none;
}


text:
Q: UIkit crashes also not able to reproduce Thread 0: Crashed: com.apple.main-thread
0  libobjc.A.dylib                0x3a6285b0 objc_msgSend + 15
1  UIKit                          0x348285f5 -[UINavigationController _startTransition:fromViewController:toViewController:] + 92
2  UIKit                          0x348284c1 -[UINavigationController _startDeferredTransitionIfNeeded:] + 324
3  UIKit                          0x347f94e9 -[UILayoutContainerView layoutSubviews] + 180
4  UIKit                          0x347b8803 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 258
5  QuartzCore                     0x34562d8b -[CALayer layoutSublayers] + 214
6  QuartzCore                     0x34562929 CA::Layer::layout_if_needed(CA::Transaction*) + 460
7  QuartzCore                     0x3456385d CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 16
8  QuartzCore                     0x34563243 CA::Context::commit_transaction(CA::Transaction*) + 238
9  QuartzCore                     0x34563051 CA::Transaction::commit() + 316
10 UIKit                          0x34988369 -[UIApplication _sendOrderedOutContextsAndInvalidate:] + 112
11 UIKit                          0x3483863f orderOutContextObserverCallout + 34
12 CoreFoundation                 0x329826cd __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 20
13 CoreFoundation                 0x329809c1 __CFRunLoopDoObservers + 276
14 CoreFoundation                 0x32980c91 __CFRunLoopRun + 608
15 CoreFoundation                 0x328f3ebd CFRunLoopRunSpecific + 356
16 CoreFoundation                 0x328f3d49 CFRunLoopRunInMode + 104
17 GraphicsServices               0x364a62eb GSEventRunModal + 74
18 UIKit                          0x34809301 UIApplicationMain + 1120
19 test                           0x000f610f main (main.m:16)

I get this error in my crashlytics but not able to reproduce this error. Can any one help me to solve this how can i get rid of this crash.


text:
Q: Lambdas in Salesforce Apex Does Apex support the concept of lambdas?
Ultimately, I am trying to DRY up some really repetitive code in my tests, so I'd love to be able to pass functions around, something like this (C#-esq)
public static TestMethod void some_test_method(){
  Arrange( ()=>
    // some setup stuff
  );
  Act( ()=>
    // test action
  );
  System.assertEquals(...);
}

A: Apex doesn't have lambdas. In fact, it doesn't even have anonymous classes. (That would have been your next question.) You're going to have to stick with declared classes. Apex does support Java-ish interfaces and abstract classes.

A: You can try R.apex(https://github.com/Click-to-Cloud/R.apex) for a functional stylish programming, although you still have to use declared classes.


text:
Q: adding a variable into a function with colours? Hello i have a granit php function but would like to print my own text into it which is stored in side a variable and my own colours which are also stored in side variable
This is how the code looks be for i enter the variable
 gradient('FF0000', '0000FF', 'my test goes here');

Which works fine but now i want to put the variable
gradient($colour1,$colour2,$profile);
which is prining of the letter w  even thos if i just print of profile and the other 2 variable there all set... and none of them are just w
Here is were i get the colours...
    <?php

    $sql1 = "SELECT * FROM profile_colurs WHERE username='{$profile}' ";
$result1 = mysql_query($sql1) or die(mysql_error());
$values1 = mysql_fetch_array($result1);

$co1= mysql_real_escape_string($values1['colour1']);
$colour1 = strip_tags($co1);
$co2= mysql_real_escape_string($values1['colour2']);
$colour2 = strip_tags($co2);
$co3= mysql_real_escape_string($values1['colour3']);
$colour3 = strip_tags($co3);

        include_once('functions/granit.php');

        gradient($colour1,$colour2,$profile);

         ?>

All variable  print of perfect but has soon has i put it into the function im just getting "w"
What am i doing wrong ??

A: First suggestion, don't use the MySQL_* function set. It is deprecated and its use is discouraged.

Use of this extension is discouraged. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

Secondly, change your mysql_fetch_array to mysql_fetch_assoc if you only want the associative results (meaning column name as array index).
Lastly, do a var_dump( get_defined_vars () ); and validate the data from the database to what you would expect. In your snippet of code, where is $profile set and what is it's value?


text:
Q: How to get a MSAL access token for SharePoint Online in a federated environment the non-interactive way in a non-interactive .Net console app? The task as simple as to have a scheduled .NET console app which will download a file from SharePoint Online on a regular basis using AD domain user account.
If I use recommended way
var token = publicApplication.AcquireTokenByIntegratedWindowsAuth(scopes).ExecuteAsync().Result;

I'm getting

UriFormatException: Invalid URI: The hostname could not be parsed.

What does it mean? Which URI, hostname? Should I override something somewhere or add some special parameter?
I've googled thru this stuff a lot, and I have no idea where to look further, any advice will be appreciated.
P.S. I have no permissions to do anything on SharePoint side, I'm not a SP admin. I just have access to specific folder on the site from which I'm downloading the file. And also I have a code which works interactively:
        WebRequest.DefaultWebProxy = WebRequest.GetSystemWebProxy();
        WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials;
        var scopes = new string[] { "https://tenant.sharepoint.com/.default" };
        var options = new PublicClientApplicationOptions()
        {
            TenantId = "tenant.com",
            ClientId = "{872cd9fa-d31f-45e0-9eab-6e460a02d1f1}",//known Visual Studio Id
        };
        var publicApplication = PublicClientApplicationBuilder.CreateWithApplicationOptions(options).Build();
        var token = publicApplication.AcquireTokenInteractive(scopes).WithLoginHint("name.surname@tenant.com").ExecuteAsync().Result;

But it shows a browser window
No questions asked, pop-up disappear, and I get the token which is used further to download a file from SPOnline using /_api/web/GetFileByServerRelativeUrl(' stuff.
So just run the app, see the popup, get the file downloaded. No interaction needed.
But this approach doesn't work if I put this routine really non-interactive:

Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation. Specify the ServiceNotification or DefaultDesktopOnly style to display a notification from a service application.

A: Turns out the non-interactive way is only possible using tenant-side registered application. Implemented using certificate authentication.
But surprisingly the token obtained by ConfidentialClientApplicationBuilder doesn't work the way I wanted/expected (scopes/user impersonation issues). So now we use Graph client approach.
This is the only way which works for me (.NetFramework 4.7.2):
using Azure.Identity;
using Microsoft.Graph;
//...
        static async Task GetFile(GraphServiceClient graphClient, string fileName2get)
        {
            var fileitem = graphClient
                .Sites["SiteGuidYouMayGetBy /sites/[your site name]/_api/site/id"]
                .Drives["CrazyLongDriveIdYouMayGetByEnumeratingDrivesHere"]
                .Root
                .ItemWithPath($"/Path To The File starting from Drive Root/{fileName2get}")
                .Content
                .Request().GetResponseAsync();
            var stream = fileitem.GetAwaiter().GetResult();
            using (var fileStream = System.IO.File.Create($"C:/Temp/{fileName2get}"))
            {
                await stream.Content.CopyToAsync(fileStream);
            }
        }


text:
Q: Does Excel as something similar to SQL "Except"? I am able to perform Union of two tables in MS Query of excel but its throwing error for "Except".
Can someone please let me know is there anyway to use "Except" of two tables in Excel.
SELECT * FROM [Book1query] tbl2
EXCEPT
SELECT * FROM [Merge1] tbl1

A: EXCEPT returns only rows, which are not available in the second SELECT statement. In other words, a join type of left anti.
In Power Query you can do that with a Merge of two tables, using the Join Kind option for Left Anti.
For a detailed description of all the Join Kind options, visit https://radacad.com/choose-the-right-merge-join-type-in-power-bi


text:
Q: How can I reset my sudo password with a separate monitor? My laptop screen has been damaged, so I have a separate monitor connected, but when I'm in recovery mode the separate monitor doesn't get the signal from the laptop so I can't see what the screen says while I enter commands.
Is there a way to change the password without recovery mode and through the terminal?

A:
TL;DR: You should be able to boot to a live environment, chroot in, and reset the password.

The challenge you've described is that when you run the system normally, your external display is used, but in recovery mode, it isn't. If you can boot into a live environment, such as from an Ubuntu live USB or live DVD, your external display will probably work there. If it does, you can change passwords from the live environment (see below).
Simply inserting the live medium and rebooting may be sufficient to boot from it. This depends on the boot order that is set in your computer's firmware (i.e., BIOS or UEFI). Although it's possible to configure Ubuntu's boot loader to boot a different device on the next boot, and even sometimes to change your firmware's boot settings from within Ubuntu, both these actions would require that you be able to run commands as root within the Ubuntu system, which you cannot currently do.
Even though recovery mode doesn't use the external display, I would not assume that your computer's firmware setup won't. You should try it, if the machine doesn't just boot from a live USB or live CD/DVD when you reboot with it inserted (see below). Which key or keys to hold down to bring this up vary by manufacturer. Some machines also have a separate key or key combination to hold down to bring up a menu on which you select which device to boot from just one time. You can look these both up based on the model of your computer.
If you can't boot the system into a live environment, perhaps someone else will come up with an alternative solution. If ultimately you cannot find a software-based approach, you can take the hard disk out and put it in an enclosure, where you can then freely modify its contents from another machine. You might even be able to do it from the same machine, since without the internal drive it should fall back to booting from a USB flash drive or DVD that is inserted, and you can attach the enclosure after the live system is booted.
The instructions below are for the case where you can boot into a live environment and your external display works in it. They are adapted and shortened from the "If You Can Use the Installed Ubuntu System, Even As a Non-Administrative User" section of my answer to How do I reset a lost password (using recovery mode requires me to type the password)?
One of the ways I shortened them is to cover only the case of changing passwords, and not that of making a user an administrator. Note that the numbering of steps is not the same. For more details, I recommend looking at my original answer. Some answers to How do I reset a lost administrative password? also cover chroot-based techniques.

*

*If you don't still have the USB flash drive or CD/DVD you used to install Ubuntu, make a new one. Note that if you do have it but you upgraded so it's for an older version of Ubuntu, that's fine. If you have a live CD/DVD or live USB for a different GNU/Linux operating system, that's likely to work, too.

*Unless you know the device name of the partition that contains your Ubuntu system, don't boot into the live environment yet. In the installed system, open a terminal window (Ctrl+Alt+T) and run this command, including the spaces before on and after /:
mount | grep ' on / '

You should see something like:
/dev/sda1 on / type ext4 (rw,errors=remount-ro,commit=0)

The text before on, in this case /dev/sda1, is the device name of the partition that contains your Ubuntu system's root filesystem. Remember it, or write it down.

*Boot your computer from the live USB or live CD/DVD. Select Try Ubuntu without installing.

*Once the desktop has come up, open a terminal window (Ctrl+Alt+T).

*Run
sudo mount /dev/sda1 /mnt
but replace /dev/sda1 with the device name of the partition containing the root filesystem, if different.
If you get an error about how a device or partition does not exist or about an "unknown filesystem type," your root filesystem is probably not on the device you specified.

*Run:
sudo chroot /mnt

Some chrooting procedures involve setting up additional mounts in the chroot, such as as /proc. That's not needed for what we're doing here.
If the partition you mounted in step 5 exists but is the wrong one, you may see this error message:
chroot: failed to run command '/bin/bash': No such file or directory

If you do, run sudo umount /mnt to unmount the partition, then mount the correct one.
All subsequent steps must be run in the terminal where you ran chroot, unless stated otherwise.

*You likely know your username, but if you don't, run:
ls /home

Or, if you prefer, you can run ls /mnt/home outside the chroot. In either case, this is usually an effective way to list the human users on the installed system. You should be able to find your username that way. If you never made any other user accounts, it should even be the only output of that command.

*Reset the password by running
passwd username
but write your actual username instead of username.
If there are no error messages, it worked.

*Leave the chroot and unmount the installed system's root filesystem by running these commands, the last of which closes the terminal window:
exit
sudo umount /mnt
exit

*Use the menus in the live environment's desktop to reboot (check the upper right if the user interface differs from the one you're used to). Or it would even be okay to run sudo reboot in a terminal.
You may need to remove the live USB or live CD/DVD to boot into your installed system.
In the installed system, you should again be able to run commands with sudo and pkexec and perform other actions that require you to enter a correct password.


text:
Q: match columns on different lines and sum I have a csv with about 160,000 lines, it looks like this:
chr1,160,161,3,0.333333333333333,+
chr1,161,162,4,0.5,-
chr1,309,310,14,0.0714285714285714,+
chr1,311,312,2,0.5,-
chr1,499,500,39,0.717948717948718,+
chr2,500,501,8,0.375,-
chr2,510,511,18,0.5,+
chr2,511,512,6,0.333333333333333,-

I would like to pair lines where column 1 is the same, column 3 matches column 2 and where column 6 is a '+' while on the other line it is a '-'. If this is true I would like to sum column 4 and column 5.
My desired out put would be
chr1,160,161,7,0.833333333333333,+
chr1,309,310,14,0.0714285714285714,+
chr1,311,312,2,0.5,-
chr1,499,500,39,0.717948717948718,+
chr2,500,501,8,0.375,-
chr2,510,511,24,0.833333333333333,-

the best solution I can think of is to duplicate the file and then match columns between the file and it's duplicate with perl:
#!/usr/bin/perl
use strict;
use warnings;
open my $firstfile, '<', $ARGV[0] or die "$!";
open my $secondfile, '<', $ARGV[1] or die "$!";
my ($chr_a, $chr_b,$start,$end,$begin,$finish, $sum_a, $sum_b, $total_a,
    $total_b,$sign_a,$sign_b);

while (<$firstfile>) {
    my @col = split /,/;
    $chr_a  = $col[0];
    $start  = $col[1];
    $end    = $col[2];
    $sum_a  = $col[3];
    $total_a = $col[4];
    $sign_a = $col[5];

    seek($secondfile,0,0);
    while (<$secondfile>) {
       my @seccol = split /,/;
       $chr_b     = $seccol[0];
       $begin     = $seccol[1];
       $finish    = $seccol[2];
       $sum_b     = $seccol[3];
       $total_b   = $seccol[4];
       $sign_b    = $seccol[5];

       print join ("\t", $col[0], $col[1], $col[2], $col[3]+=$seccol[3],
                         $col[4]+=$seccol[4], $col[5]),
           "\n" if ($chr_a eq $chr_b and $end==$begin and $sign_a ne $sign_b);
    }

}
And that works fine, but ideally I'd like to be able to do this within the file itself without having to duplicate it, because I have many files and so I would like to run a script over all of them that is less time-consuming.
Thanks.

A: In the absence of a response to my comment, this program will do as you ask with the data you provide.
use strict;
use warnings;

my @last;

while (<DATA>) {
  s/\s+\z//;
  my @line = split /,/;

  if (@last
      and $last[0] eq $line[0]
      and $last[2] eq $line[1]
      and $last[5] eq '+' and $line[5] eq '-') {

    $last[3] += $line[3];
    $last[4] += $line[4];
    print join(',', @last), "\n";
    @last = ()
  }
  else {
    print join(',', @last), "\n" if @last;
    @last = @line;
  }
}

print join(',', @last), "\n" if @last;

__DATA__
chr1,160,161,3,0.333333333333333,+
chr1,161,162,4,0.5,-
chr1,309,310,14,0.0714285714285714,+
chr1,311,312,2,0.5,-
chr1,499,500,39,0.717948717948718,+
chr2,500,501,8,0.375,-
chr2,510,511,18,0.5,+
chr2,511,512,6,0.333333333333333,-

output
chr1,160,161,7,0.833333333333333,+
chr1,309,310,14,0.0714285714285714,+
chr1,311,312,2,0.5,-
chr1,499,500,39,0.717948717948718,+
chr2,500,501,8,0.375,-
chr2,510,511,24,0.833333333333333,+


text:
Q: Weierstrass factorization/proving existence of entire function Let $a_n$ be a sequence of complex numbers without an accumulation point. Let $c_n$ be an arbitrary sequence of complex numbers. Prove that, there is an entire function f, such that $f(a_n)=c_n$.
So the Weierstrass factorization ensures the existence of a holomorphic function, such that $f(a_n)=0$, so $c_n=0$, $\forall n$, we would be finished. But how can I proceed when $c_n \neq 0 \forall n$?

A: Wlog assume that $|a_n|$ is increasing. The $a_n$ are distinct. Set $f_1(z)=c_1$ and
$$f_k(z)= f_{k-1}(z)+ (c_k-f_{k-1}(a_k))(z/a_k)^{e_k} \prod_{n=1}^{k-1}\frac{z-a_n}{a_k-a_n}$$
To ensure that $\lim_{k\to \infty}f_k$ converges locally uniformly, take $e_k$ large enough so that $$\sup_{|z|<|a_k|-1}|(c_k-f_{k-1}(a_k))(z/a_k)^{e_k} \prod_{n=1}^{k-1}\frac{z-a_n}{a_k-a_n}|<2^{-k}$$


text:
Q: How to catch tab change events on a GWT TabLayoutPanel I am developing a GWT application which uses the standart GWT TabLayoutPanel.
Just realized that this component doesn't have an event to notify you when a tabs gets changed.
It has a getSelectedIndex() method, but I need an event so that other parts of the UI can react to changes.
My initial idea was to put a component that will always be bound and will fire an event when it gets loaded. It seams like a hack and I haven't figured out how yet.
Does anyone know what a good way to catch the tab change event would be?

A: I've never worked with this widget, but isn't addSelectionHandler what you need?


text:
Q: Display files and folders in Google Apps Script web app I'm developing a web app with Google apps script where the user will be able to search for and open files from their drive. Right now I display the files with this loop:
var files = DriveApp.searchFiles('title contains "banana"');
var fileCount = 0;

while (files.hasNext()) {
  var file = files.next();
  app.getElementById('displayFilesPanel').add(app.createAnchor(file.getName() + ' - ' + file.getOwner().getEmail(), file.getUrl()));
  fileCount++;
}

The problem here is that the getOwner() method takes quite some time (about 0.1 seconds) which adds up quite fast. The other thing is that it doesn't look very nice with these links representing files.
Is there any way to do these searches with DriveApp.searchFiles() and display the results with something else than anchors/links?
Edit:
As both Zig Mandel and Serge insas mentioned HTML-Service should be considered to make it look better.
I found that the DriveApp.searchFiles-function was not very useful because when i use it with parameters like 'title contains "banana"' it will not finish within the 5 min timeout limit. The thing is that it found about 40 matches but then went on and probably checked all the other (>120000) files in my drive.
In my case I went with the getAllFilesForPaging(number, token)-function and checked every file if the title contained "banana" with the .indexOf('banana') != -1-method.

A: You cant get arround the speed issue with DriveApp. Its apparently doing another  roundtrip to get the owner's email.
To make it look better use htmlService instead of uiApp. In both you can add file icons to make it look better.

A: Concerning the way it looks, even if Zig is right when he recommends HTML service , it is still possible to get interesting results using UiApp.
See that link for example where an animated gif represents the link
That said, I have to admit it is not the simplest thing on earth :-) but it still works !
Here is the code I used to get the example above (full app code, look at the 2 widgets I use):
function doGet(){
  var app = UiApp.createApplication().setStyleAttribute("background", "#CCCCFF").setTitle('Anchor Test')
  var top = '100PX';// define dimensions and position
  var left = '100PX';
  var width = '80PX';
  var height = '80PX';
  var mainPanel = app.createVerticalPanel();

  var customAnchor = app.createHorizontalPanel().setId('usethisId')
  addStyle(customAnchor,top,left,width,height,'1','1')

  var image = app.createImage("https://dl.dropbox.com/u/211279/Time-change-clock_animated_TR80.gif")
  addStyle(image,top,left,width,height,'1','1')

  var realAnchor = app.createAnchor('This is the Anchor', 'https://sites.google.com/site/appsscriptexperiments/home')
  addStyle(realAnchor,top,left,width,height,'2','0')

  customAnchor.add(realAnchor);
  customAnchor.add(image)
  mainPanel.add(customAnchor);
  app.add(mainPanel);
  return app;
}

function addStyle(widget,top,left,width,height,z,visibility){
widget.setStyleAttributes(
    {'position': 'fixed',
     'top' : top,
     'left' : left,
     'width' : width,
     'height':height,
     'opacity' : visibility,
     'zIndex' : z});
   }

About speed : no comment, it is indeed very slow and if you have lots of files it happens that you just can't reach the end of the list because of the 5 minutes limit... no solution that I know :-/


text:
Q: Converting a stored mysql DateTime from UTC to local offset in PHP I'm walking into a project where a database is already set up.  Up until now, the client has been working with using NOW() in PHP to store a DateTime in mysql.  The problem is that now they want people from all over the world to be able to return data and have it display in their current time.  So I changed all the functions from NOW() to UTC_TIMESTAMP() so the database is using UTC for all stored DateTime stamps.  Looking at the table it's stored as YYYY-MM-DD HH:MM:SS.  So how can I can I convert, using PHP, that timestamp from a UTC time to what it would be in their timezone?
So if I'm in GMT-6, and there is a timestamp of "2015-12-08 15:17:20" it'll display as "2015-12-08 09:17:20" on the page?
I've been looking at all sorts of PHP options, I can't really change anything in SQL, nor the database structure, all I can do is take the data being stored and manipulate it with PHP.


text:
Q: Proof completion: Determine a simple expression for $\tau(G)$ in terms of the vertex degrees of $G$. (details inside) I need some help completing a proof I wrote (or seeing a simpler solution to the same problem).

For a list of paths $P_1, \ldots , P_m$, let $L(P_1, \ldots, P_m)$ be the number of paths in $P_1, \ldots, P_m$ which are not closed. Let $\tau(G)$ be the smallest value of $L(P_1, \ldots, P_m)$ over all the lists pf paths $P_1,\ldots, P_m$ such that their edge sets partition $E(G)$ (i.e. each edge of $G$ appears in exactly one path). For example, if $G$ is a cycle with an extra edge, then $\tau(G) = 1$. Determine a simple expression for $\tau(G)$ in terms of the vertex degrees of $G$.

Let $A = \{v \in V(G): \operatorname{deg}(v)$ is odd $\}$. We first prove that $\tau(G) \leq \frac{|A|}{2}$.
Let $v \in A$. Start a path from $v$ and continue adding edges till it is not possible to add more edges to the path. Each time the path passes through a vertex $x$, it reduces the degree of $x$ by $2$. The path cannot terminate at a vertex of even degree, by the preceding fact. So, the path terminates at some $v' \in A$. Since $v$ has an odd degree, $v' \neq v$.
Now, consider the graph $G^{(1)} - \{e \in E(G): e$ is an edge in the preceding path $\}$. Let $A^{(1)}$ be the set of all vertices in $G^{(1)}$ with odd degree. It can easily be seen that $A^{(1)}=A-\{v, v'\}$. Continue the procedure till $A^{(n)} = \varnothing$. Then, the only vertices remaining are those with even degree, and the remaining edges can be partitioned into closed paths. Here, $L(P_1, \ldots, P_m) = \frac{|A|}{2}$.
Now, it remains to prove that it cannot be the case that $\tau(G) < \frac{|A|}{2}$.

A: You've actually done the "hard" direction already.  To see that $\tau(G) \ge |A|/2$, first convince yourself that it's sufficient to show the following:

In any graph formed by the edge-disjoint union of a finite set of paths $P_1, \ldots, P_m$ (of which exactly $k$ are unclosed), there are at most $2k$ vertices of odd degree.

This is a pretty straightforward induction on $k$.


text:
Q: Identifying pairs in two columns in R I have a data frame with bilateral relations between countries:
C1 C2
US FR
FR US
US DE
DE US
US RU
US FI
RU FI
FI RU

The links are directional and some of them are missing (e.g. I have US>RU but not RU>US). I would like to identify all unique pairs; to have something like this:
C1 C2 PairID
US FR 1
FR US 1
US DE 2
DE US 2
US RU -
US FI -
RU FI 3
FI RU 3

Any suggestions?

A: Here is one option assuming you also want to count relations that are not bidirectional like US>RU:
library(dplyr)
df %>%
        mutate(relation = paste(pmin(C1, C2), pmax(C1, C2), sep = "-"), #define the relation no matter the direction
               PairID = cumsum(c(1, head(relation, -1) != tail(relation, -1)))) %>%
        select(-relation)
# output
  C1 C2 PairID
1 US FR      1
2 FR US      1
3 US DE      2
4 DE US      2
5 US RU      3
6 US FI      4
7 RU FI      5
8 FI RU      5

# Data: df
structure(list(C1 = c("US", "FR", "US", "DE", "US", "US", "RU",
"FI"), C2 = c("FR", "US", "DE", "US", "RU", "FI", "FI", "RU")), .Names = c("C1",
"C2"), class = "data.frame", row.names = c(NA, -8L))

A: We can create a string identifier that captures a given pair of countries independent of their ordering:
library( tidyverse )

# Original data
X <- data_frame(C1 = c("US", "FR", "US", "DE", "US", "US", "RU", "FI"),
            C2 = c("FR", "US", "DE", "US", "RU", "FI", "FI", "RU"))

# Creates an order-independent string ID for each entry
Y <- X %>% mutate( S = map2_chr( C1, C2, ~str_flatten(sort(c(.x,.y))) ) )
# # A tibble: 8 x 3
#   C1    C2    S
#   <chr> <chr> <chr>
# 1 US    FR    FRUS
# 2 FR    US    FRUS
# 3 US    DE    DEUS
# 4 DE    US    DEUS
# 5 US    RU    RUUS
# ...

We can then use these string identifiers to find pairs of countries that occur in both directions (e.g., US > FR and FR > US). These pairs will have two matching string IDs.
# Identify string IDs with both orderings and assign an integer ID to each
Z <- Y %>% group_by(S) %>% filter( n() == 2 ) %>% ungroup %>%   # Keep groups of size 2
  select(S) %>% distinct %>% mutate( PairID = 1:n() )           # Annotate unique values
# # A tibble: 3 x 2
#   S     PairID
#   <chr>  <int>
# 1 FRUS       1
# 2 DEUS       2
# 3 FIRU       3

All that's left to do is join the new string ID -> integer ID map against the original data, and replace NAs with "-":
left_join( Y, Z ) %>% select(-S) %>% mutate_at( "PairID", replace_na, "-")
# # A tibble: 8 x 3
#   C1    C2    PairID
#   <chr> <chr> <chr>
# 1 US    FR    1
# 2 FR    US    1
# 3 US    DE    2
# 4 DE    US    2
# 5 US    RU    -
# 6 US    FI    -
# 7 RU    FI    3
# 8 FI    RU    3


text:
Q: Вызвов функции или процедуры Задача. Просмотреть таблицу/вьюху (например V$session) и если в ней в определенном столбце (например action) есть заданное значение - вывести EST, если нет - No result.
В таблице v$session есть значение KTSJ Slave в столбце Action.
Есть анонимный блок, он корректно работает:
   begin
    DECLARE
    v_action varchar2(100);
      CURSOR session_cursor IS
        SELECT action, osuser, machine from v$session where action='KTSJ Slave';
         v_session v$session%rowtype;
    BEGIN
      OPEN session_cursor;
    FETCH session_cursor into v_session.action, v_session.osuser,v_session.machine;
         if session_cursor%found=FALSE then
           v_action:='no result';
          DBMS_OUTPUT.PUT_LINE (v_action);
           else
           v_action:='EST`!`';
            DBMS_OUTPUT.PUT_LINE (v_action);
      end if;
      CLOSE session_cursor;
    END;
    end;

Вывод : EST
Если подставить v_action='BLABLA' вывод будет No result.
А дальше я тупой.
Хочу запихать этот код в функцию или процедуру, чтобы при ее вызове у меня возвращалась или EST или No result и в зависимости от результата выполнять разные действия.
create or replace function q (v_action in varchar2) return varchar2  is

begin

begin
DECLARE
v_action varchar2(100);
  CURSOR session_cursor IS
    SELECT action, osuser, machine from v$session where action=to_char(v_action); /*'KTSJ Slave';*/
     v_session v$session%rowtype;
BEGIN
  OPEN session_cursor;
FETCH session_cursor into v_session.action, v_session.osuser,v_session.machine;
     if session_cursor%found=TRUE then
       v_action:='Nelz9 zapuskat`';
            return v_action;
       else
                v_action:='no result';
       return v_action;
  end if;
  CLOSE session_cursor;
END;
end;

end q;

Например так. Но как бы я ее не вызывал, с какими бы параметрами, результат всегда No result.
begin
dbms_output.put_line (q('KTSJ SLAVE'));
end;

Пожалуйста, помогите тупому, как РАБОТАЮЩИЙ анонимный блок запихать в функцию и процедуру и КАК ее вызвать, чтобы результат был таким же, как и при выполнении анонимного блока. Спасибо.

A: Такие ошибки, в данном случае - маскирование переменной другой переменной с тем же именем, легко находятся, сделав минимальный воспроизводимый пример:
create or replace function q (v_action in varchar2) return varchar2  is
begin
    declare
        v_action varchar2(100);
    begin
        return v_action;
    end;
end q;
/
select q('blah blah') ret from dual;

RET
--------
null

Возможное решение - использовать квалифицированные имена переменных:
create or replace function q (action in varchar2) return varchar2  is
begin
    <<my>> declare
        action varchar2(100);
    begin
        if 1=0 then return my.action; end if;
    end;
    return q.action;
end q;
/
select q ('blah blah') ret from dual;

RET
----------
blah blah


text:
Q: Sending email messages using nodemailer I am using nodemailer to send email messages from my server (Node.js) and currently, i'm using this generic function:
// Generic Inner Function - Send Email
exports.sendEmail = function(email, message, emailType){
    if((email)&&(message)&&(emailType)){
        var subject;
        if(emailType == "signUp")
            subject = "Welcome to my site - ";
        if(emailType == "forgotPass")
            subject = "Recovery Password from my site - ";
        if(emailType == "newResult")
            subject = "We have Found New Results for you - ";
        if(emailType == "arrivedPrice")
            subject = "Product Arrived - ";
        if(emailType == "tonePrice")
            subject = "Product Arrived tone - ";

        console.log("Send Email to: "+email+" / Email Type: "+emailType);
        'use strict';
        const nodemailer = require('nodemailer');

        // create reusable transporter object using the default SMTP transport
        let transporter = nodemailer.createTransport({
            service: 'gmail',
            auth: {
                user: 'tester@gmail.com',
                pass: 'test'
            }
        });

        // setup email data with unicode symbols
        let mailOptions = {
            from: '"tom " <tester@gmail.com>', // sender address
            to: email, // list of receivers
            subject: subject, // Subject line
            text: message, // plain text body
            html: ''+message+'' // html body
        };

        // send mail with defined transport object
        transporter.sendMail(mailOptions, (error, info) => {
            if (error) {
                return console.log(error);
            }
            console.log('Message %s sent: %s', info.messageId, info.response);
        });
    }
};

Now, I was creating a new HTML messages that I want to send according to the action the user is doing and I am struggling with how to do it.
I want to use Nodemailer to do this operation and I didn't find information over the web.
Sample of the HTML message:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>A Simple Responsive HTML Email</title>

                      Tester

                      Chasing For You

                Welcome to Cricket !

              We're so happy you have joined our family!!!

              We founded Tester because we wanted to create a trustworthy app

                        Tester offers a Chrome extension that lets you set a.

                            GET THE EXTENSION

                         Tester is also offers an Android App that lets you.

                            GET THE APP

                ® Copyright © 2017 - Designed & Developed by Cricket Team

                Unsubscribe
                from Test newsletter


text:
Q: Rust Lifetime mismatch in trait method I'm working through the Rust book, and trying to implement logic to allow text to only be added to a blog Post if its in the Draft state, as can be found here (one of the suggested exercises).
The idea is to implement the state pattern in Rust using structs and traits.  I simply want to pass a string slice to a default implementation of add_text which returns an empty string slice if not in the Draft state.  Then I'll override the default implementation for the Draft state and return the string slice that was passed in for the text in the Draft state.
pub struct Post {
    state: Option<Box<dyn State>>,
    content: String,
}

impl Post {
    pub fn new() -> Post {
        Post {
            state: Some(Box::new(Draft {})),
            content: String::new(),
        }
    }

    pub fn add_text(&mut self, text: &str) {
        let text = self.state.as_ref().unwrap().add_text(text);
        // self.state.as_ref().unwrap().add_content(text)
        self.content.push_str(text);
    }

    //snip

trait State {
    fn request_review(self: Box<Self>) -> Box<dyn State>;
    fn approve(self: Box<Self>) -> Box<dyn State>;
    fn content<'a>(&self, post: &'a Post) -> &'a str {
        ""
    }
    fn reject(self: Box<Self>) -> Box<dyn State>;
    fn add_text(&self, text: &str) -> &str {
        ""
    }
}

struct Draft {}

impl State for Draft {
    fn request_review(self: Box<Self>) -> Box<dyn State> {
        Box::new(PendingReview {})
    }
    fn approve(self: Box<Self>) -> Box<dyn State> {
        self // don't want to approve a draft before review!
    }
    fn reject(self: Box<Self>) -> Box<dyn State> {
        self // reject doesn't do anything on a draft!
    }
    fn add_text(&self, text: &str) -> &str {
        text
    }
}

I'm getting a lifetime mismatch on the very last method above add_text inside impl State for Draft.  The message reads:
lifetime mismatch

...but data from `text` is returned hererustc(E0623)
lib.rs(67, 30): this parameter and the return type are declared with different lifetimes...
lib.rs(67, 39):
lib.rs(68, 9): ...but data from `text` is returned here

I'm new to Rust and can't get the lifetime annotations right in this case.  I tried explicit lifetime annotations but it didn't help.  Also, I know that since one of the references is &self all lifetime parameters should have the same lifetime as &self automatically (I think?).
Can someone enlighten me on getting this code to compile? It also may be useful to those using the book in the future.

A: You were tripped over by lifetime elision rules:

Each elided lifetime in input position becomes a distinct lifetime parameter.
If there is exactly one input lifetime position (elided or not), that lifetime is assigned to all elided output lifetimes.
If there are multiple input lifetime positions, but one of them is &self or &mut self, the lifetime of self is assigned to all elided output lifetimes.
Otherwise, it is an error to elide an output lifetime.

In your code fn add_text(&self, text: &str) -> &str, the returned &str picks up the elided lifetime from &self, but then it is actually the second parameter. A mismatch as if it were:
fn add_text<'a, 'b>(&'a self, text: &'b str) -> &'a str {
    text
}

The trick is to make lifetime explicit here:
trait State {
    fn add_text<'a>(&'a self, text: &'a str) -> &'a str;
}

impl State for Draft {
    fn add_text<'a>(&'a self, text: &'a str) -> &'a str {
        text
    }
}

If you want a slightly more general version:
trait State {
    fn add_text<'a, 'b: 'a>(&'a self, text: &'b str) -> &'a str;
}

impl State for Draft {
    fn add_text<'a, 'b: 'a>(&'a self, text: &'b str) -> &'a str {
        text
    }
}

Here it says as long as text outlives &self all is good. You decide if the extra generic lifetime is worth the trouble.


text:
Q: How to type this complex object idea? I have this literal object:
const objectIdea = {
  form: {
    div: {
      attributes: {
        cssClasses: ["Container", "flex"],
      },
      h1: {
        attributes: {
          text: "Hello world 2!",
        },
      },
    },

    div: {
      h1: {
        text: "And so on."
      },
    },

    main: {
      h1: {
        attributes: {
          text: "Hello world!"
        }
      },
    },
  },
};

The idea es that the key represents and HTMLTag and it's value is another object which accepts an attributes key and another HTMLTag . The point of this ( i'm experimenting) is to automatically generate HTML Components from that object meaning that first Form it's the parent and continues with 3 childs div. The first div has an h1 tag and so on.  Object could be any length and any nested length but always should be:
 HTMLTag: {
        attributes: HTMLTagAttributes,  // should infer this from it's parent
        HTMLTag:  {      //is the child
                    attributes: HTMLTagAttributes,     // should infejr this from it's parent
                    HTMLTag:  // I think you get the idea
}

I tried some stuff but nothing usefull to this problem.
interface IComponentObject<T extends keyof HTMLElementTagNameMap = keyof HTMLElementTagNameMap> {
  T:{
    attributes: T

  }
}

A: I think it should be possible to create a structure, like yours.
There are two thinks you need to add:

*

*unique HTML Tags

*Recursive structure

Here is my code for this. Maybe this help.
type HTMLTag = "div" | "form" | "p" // add more when needed

type UniqueHTMLTag = `${HTMLTag}#${string}` // make html tags unique, because same keys are not allowed

type HTMLDOM = {
    [key in UniqueHTMLTag]: {
        attributes: {
            "name": string
        }
        children: HTMLDOM
        // add more thinks
    }
}


text:
Q: Hibernate Criteria uniqueResult My sql query is somethin like below
SELECT count(1),tran_nbr FROM AAA WHERE P_D IN (3,4) AND
 DTE_OF_ISS BETWEEN to_date('01/01/2014','mm/dd/yyyy') and to_date('01/31/2015' ,'mm/dd/yyyy')

And i have written a hibernate query like this.
Criteria criteria = session.createCriteria(AAA.class).setProjection(Projections.rowCount());

   criteria.add(Restrictions.sqlRestriction("(P_D IN ('4'))"));

   if (reportsForm.getFromDate() != null && reportsForm.getToDate() != null) {
        criteria.add(Restrictions.sqlRestriction("DTE_OF_ISS = to_date('"+ utils.convertDateToString(reportsForm.getFromDate()) + "', 'MM/dd/yyyy')"));
        criteria.add(Restrictions.sqlRestriction("DTE_OF_ISS <= to_date('"+ utils.convertDateToString(reportsForm.getToDate()) + "', 'MM/dd/yyyy')"));
    }

  criteria.setFetchSize(100);
criteria.setMaxResults(500);
    listResult = criteria.list();

   listResult = criteria.list();
    int count = ((Long) criteria.uniqueResult()).intValue();

when i see the "show_sql" the query looks like this.
select * from ( select count(*) as y0_ from Schema.AAA this_ where (P_D IN ('4')) and DTE_OF_ISS = to_date('01/01/2014', 'MM/dd/yyyy') and DTE_OF_ISS <= to_date('01/31/2015', 'MM/dd/yyyy') ) where rownum <= ?

No idea from where the addition select coming and rownum? Please help me out..


text:
Q: Search comparing and searching for strings in a varient table, trouble with correct construct for varient type So I am following the example in the documentation here as I am trying to compare the json strings that I have uploaded from the tutorial, but am having troubles searching the variant type I uploaded my json file into.
So for the basic understanding I tried:

USE DATABASE MYDB;
USE WAREHOUSE MYWH;

create table demonstration1 (
    id integer,
    array1 array,
    variant1 variant,
    object1 object
    );

insert into demonstration1 (id, array1, variant1, object1)
  select
    1,
    array_construct(1, 2, 3),
    parse_json(' { "key1": "value1", "key2": "value2" } '),
    parse_json(' { "outer_key1": { "inner_key1A": "1a", "inner_key1B": "1b" }, '
              ||
               '   "outer_key2": { "inner_key2": 2 } } ')
    ;

insert into demonstration1 (id, array1, variant1, object1)
  select
    1,
    array_construct(1, 2, 3, null),
    parse_json(' { "key1": "value1", "key2": NULL } '),
    parse_json(' { "outer_key1": { "inner_key1A": "1a", "inner_key1B": NULL }, '
              ||
               '   "outer_key2": { "inner_key2": 2 } '
              ||
               ' } ')
  ;

  select variant1  from demonstration1
  where variant1 contains('value');

error was that it did not recognize contains:
SQL compilation error: syntax error line 2 at position 17 unexpected 'contains'.
This did not work either when I tried to use Array_contains:
ARRAY_CONTAINS('value'::variant, array_construct(variant1)) from demonstration1;

What should I be trying?

A: The syntax for contains is a bit different. Try this instead:
select variant1 from demonstration1 where contains(variant1, 'value2');


text:
Q: Javascript code not available when called
Possible Duplicate:
jQuery AJAX: return value on success

Im having this weird reference issue when im trying to get a JSON file through query:
    var themeData;
    $.getJSON("json/sample.js", function(data) {
                themeData = data.theme;
                        console.log(themeData.sample[0].description);
            });
   console.log(themeData.sample[0].description);

The first console.log works, the second doesnt. Why is this happening?

A: It's the second one (chronologically in your code) that doesn't get hit.  That's because it hasn't been set yet.  The callback inside getJSON gets invoked asynchronously after returning from the server.
var themeData;

// FIRST -- themeData currently null
$.getJSON("json/sample.js", function(data) {

    // THIRD -- now themeData has a value, and gets logged
    themeData = data.theme;
    console.log(themeData.sample[0].description);
});

// SECOND -- themeData still null
console.log(themeData.sample[0].description);

If you really need to call a method "after" getJSON, then embrace the idea of callbacks.  Use something like this.
var themeData;
function myCallback(data) {
    console.log(data.sample[0].description);
}
$.getJSON("json/sample.js", function(data) {
    themeData = data.theme;
    console.log(themeData.sample[0].description);
    myCallback(themeData);
});

Edit
You could also force a synchronous call instead using async: false of the JQuery ajax function.
$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback,
  async: false
});

A: No, $.getJSON is a async method, when the second console.log is called, there's no themeData at that time.


text:
Q: How to Append queries in Power BI / Power Query with Union instead of Union All When I try to combine two datasets (coming from same table with exactly the same structure), I'm using
Table.Combine({table1, table2})

Unfortunately this results in the following native SQL:
SELECT *
FROM table1
UNION ALL
SELECT *
FROM table2

I'd prefer to use a normal UNION instead... is there a way to achieve this in M?

A: The equivalent would be to add a Table.Distinct ( "Remove Duplicates" ) step, following the Table.Combine.


text:
Q: Postgres 10 TDS_FDW extension undefined symbol: Float4GetDatum I'm trying to add the tds fdw extension to a new installation of Postgres 10 on CentOS.
I've run make/install for the tds_fdw, but when attempting to
CREATE EXTENSION tds_fdw;

from PG Admin it fails with the message:
ERROR: could not load library "/usr/pgsql-10/lib/tds_fdw.so": /usr/pgsql-10/lib/tds_fdw.so: undefined symbol: Float4GetDatum
SQL state: XX000

I'm new to CentOS and building anything postgres related. Thanks in advance.

A: This sounds like the PostgreSQL for which you built the extension is configured in a different way than the one where you try to run it.
The obvious cause would be if the one for which you built tds_fdw was configured with --disable-float4-byval.


text:
Q: @selector implementation in C++ I need to implement similar mechanism like @selector(Objecitive-C) in C++. By googling i have found. It does not help me...
template <class AnyClass>
class ClassCallback
{
    // pointer to member function
    void (AnyClass::*function)(void);

    // pointer to object
    AnyClass object;
public:

    ClassCallback()     {  }
    ~ClassCallback()    {  }

    ClassCallback(AnyClass _object, void(AnyClass::*_function)(void))
    : object( _object ), function( _function ) { };

    virtual void call(){
         (object->*function)();
    };

};

Is there any different approach to implement which is similar to objective-C like
typedef struct objc_selector    *MY_SEL;

Need to implement objc_selector It is abstract class in objective-C. How to implement objc_selector any idea...

A: Just a few precisions on the Objective-C messaging system, with the selectors.
A selector (SEL) is an opaque type, but it's only something like a char *, containing only the name of the method (so many classes can share the same selector).
An Obj-C method is a struct containing:

*

*A SEL field

*A char * containing infos about the return type and arguments.

*An IMP field

Something like:
struct objc_method
{
    SEL    method_name;
    char * method_types;
    IMP    method_imp;
};
typedef objc_method Method;

An IMP is just a C function pointer.

A: Objective-C and C++ are very different languages, and as far as I know C++ doesn't have anything equivalent or even similar to Objective-C's selectors. If you explain the problem you're trying to solve, I'm sure someone here will be happy to discuss the way that problem might be dealt with from a C++ perspective.

A: If you're happy with using a custom preprocessor before compiling C++ files, you can use Qt's signal and slot mechanism, which is an implementation of message-passing system in a slightly-extended C++. See here.

A: You might want to do something like this :
// We use something to define what "identifies" a
class selector {
private:
   std::string name;
public:
    selector(std::string const& n) : name(n) {}
    selector(const char* n) : name(n) {}
};
typedef const selector* SEL;

Use it like this :
typedef void* (*method) (object&, ...);
struct object {
private:
   std::hash<SEL,method>* methods;
public:
   object(std::map<SEL,method>* m)  : methods(m) {};
};

selector cloneSelector = selector("clone");
typedef void* cloneImplementation(object&, ...) {
  ....
};

Use it like this :
std::map<SEL,method> fooMethods;
fooMethods[cloneSelector]=&cloneImplementation;

class foo : public object {
public:
  foo()  : object(&fooMethods) {};
};

There are several problems however (typing, function signature …). You probably do not want to do this.
Ohterwise, look at the code. Gobjc is open source, it is quite simple to see how it is done. Looking at objc/deprecated/struct_objc_selector.h of (GNU) gobjc I find:
struct objc_selector
{
  void *sel_id;
  const char *sel_types;
};

AFAIK sel_id is a pointer to a string made of the method name and the (encoded) argument types.
You might want to group methods in interfaces and have a slightly more "COM-ish" way of doing it :
 struct interface_id {};

 class object {
 protected:
    virtual void* getVtable_(interface_id const&) = 0;
 public:
    template<class X> X* getVtable() {
        return getVtable(X::interface_id);
    }
    virtual ~object();
 };

 // Exemple interface

 struct FooInterface {
 public:
   class vtable {
     void (*fooMethod2)(void* self, int n);
     std::vector<int> (*fooMethod2)(void* self, double x);
   };
   static interface_id ID;
   static std::string NAME; // = "FooInterface"
 private:
    void* self;
    FooVtable* vtable;
 public:
    void fooMethod1(int n) {
      return vtable->fooMethod1(self,n);
    };
    void fooMethod2(double x) {
      return vtable->fooMethod2(self,double x);
    };
 };

// Exemple object

class foo_object : public bar_object {
private:
   static std::map<interface_id, void*> INTERFACES;
public:
   virtual void* getVtable_(interface_id const& id) {
     void* res = INTERFACES[&id];
     if(res!=null)
        return res;
     else
        return bar_object::getVtable(id);
   };
};

It gives an an idea of how to enforce function signatures. You should be able to use the same kind of thing for the selector-based approach (using some boring template-meta-programming code …).

A: I had a similar problem when using Cocos2d-x, and in my case I used callfunc_selector to get the selector:
Suppose a class Foo and a method Bar() inside it, just call callfunc_selector(Foo::Bar); and it will return a CCObject* to the method.


text:
Q: Problems labeling an arrow Having this in the preamble:
\usepackage{tikz}
\usetikzlibrary{chains,shapes.multipart}
\usetikzlibrary{scopes}
\usetikzlibrary{decorations.markings}
\usetikzlibrary{shapes,calc}
\usetikzlibrary{automata,positioning}

I have the following figure:
\begin{figure}
       \centering
       \begin{tikzpicture}[start chain=going right,>=latex,node distance=0pt]
         \node[draw,rectangle,on chain,minimum size=1.5cm] (rr) {$I$};
         \node[draw,rectangle,on chain,draw=white,minimum size=0.8cm]{};
         % the rectangular shape with vertical lines
        \node[rectangle split, rectangle split parts=5,
        draw, rectangle split horizontal,text height=1cm,text depth=0.5cm,on chain,inner ysep=0pt] (wa) {};
         \fill[white] ([xshift=-\pgflinewidth,yshift=-\pgflinewidth]wa.north west) rectangle ([xshift=-15pt,yshift=\pgflinewidth]wa.south);
        \node at (wa.east) (A){};
        \draw [-latex] (A) --+(30:1.5) coordinate (B1);
        \draw [-latex] (A) --+(-30:1.5) coordinate (B2);
         % the circle
         \node [draw,circle,on chain,minimum size=1cm] at (B1) (se1) {$U_1$};
         \draw [-latex] (se1) --+(0:1.3) coordinate (BB1);
         \node [draw,circle,on chain,minimum size=1cm] at (B2) (se2) {$U_2$};
         \draw [-latex] (se2) --+(0:1.3) coordinate (BB2);
         \node [draw,diamond,on chain,minimum size=0.2cm] at (BB1) (C3){};
         \draw [-latex] (C3)--+(0:1)node[midway,above] {$\mu$};
         % the arrows and labels
         \draw[<-] (wa.west) -- +(-20pt,0) node[midway,below] {$\lambda$};
         \draw[->] (C3.north) to[out=120, in=145] ([shift=(up:.3)] wa.west);
       \end{tikzpicture}
          \caption{The model represented as a queuing system.}
             \label{fig:queue}
       \end{figure}

How to put labels on arrows where there are none (the picture below shows the edges where i want to put labels)?

A: Converting my comment into an answer:
On a curved path, the node specification must follow to. So the relevant line in your example should be:
\draw[->] (C3.north) to[out=120, in=145] node[below] {<label text>} ([shift=(up:.3)] wa.west);

Also note that many of the libraries you've loaded are not required for this particular example; just chains and shapes (which includes shapes.multipart) are required.
Code
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{chains,shapes}

\begin{document}
\begin{figure}
       \centering
       \begin{tikzpicture}[start chain=going right,>=latex,node distance=0pt]
         \node[draw,rectangle,on chain,minimum size=1.5cm] (rr) {$I$};
         \node[draw,rectangle,on chain,draw=white,minimum size=0.8cm]{};
         % the rectangular shape with vertical lines
        \node[rectangle split, rectangle split parts=5,
        draw, rectangle split horizontal,text height=1cm,text depth=0.5cm,on chain,inner ysep=0pt] (wa) {};
         \fill[white] ([xshift=-\pgflinewidth,yshift=-\pgflinewidth]wa.north west) rectangle ([xshift=-15pt,yshift=\pgflinewidth]wa.south);
        \node at (wa.east) (A){};
        \draw [-latex] (A) --+(30:1.5) coordinate (B1);
        \draw [-latex] (A) --+(-30:1.5) coordinate (B2);
         % the circle
         \node [draw,circle,on chain,minimum size=1cm] at (B1) (se1) {$U_1$};
         \draw [-latex] (se1) --+(0:1.3) coordinate (BB1);
         \node [draw,circle,on chain,minimum size=1cm] at (B2) (se2) {$U_2$};
         \draw [-latex] (se2) --+(0:1.3) coordinate (BB2);
         \node [draw,diamond,on chain,minimum size=0.2cm] at (BB1) (C3){};
         \draw [-latex] (C3)--+(0:1)node[midway,above] {$\mu$};
         % the arrows and labels
         \draw[<-] (wa.west) -- +(-20pt,0) node[midway,below] {$\lambda$};
         \draw[->] (C3.north) to[out=120, in=145] node[below] {$X$} ([shift=(up:.3)] wa.west); % <<< additions here
       \end{tikzpicture}
          \caption{The model represented as a queuing system.}
             \label{fig:queue}
       \end{figure}
\end{document}

Output


text:
Q: EF 4.3 CF does not update relationships when saving changes I've got a ClubItem object with a relationship collection ICollection ClubUsers. I load a ClubItem from the context and add a couple of new users to the CluItem. When saving the ClubItem in a disconnected state the context does not see the new ClubUsers as new entities. How to tell the context that something changed? I allready use this to change entitystate of the ClubItem:
    public virtual void Update(IEntity entityToUpdate)
    {
        DbSet.Attach(entityToUpdate);
        Context.Entry(entityToUpdate).State = EntityState.Modified;

        SaveChanges();
    }

A: In your specific case you can probably just remove the Attach line. Attach puts the detached entity including other detached entities in the object graph into state Unchanged. When you change the state to Modified it affects only the parent entity, the children are still in state Unchanged. If you call SaveChanges the children won't be saved because their state is Unchanged.
If you don't call Attach the children stay detached until SaveChanges is called where EF will assume that they are new entities (because they are not attached to the context) and set their state to Added. Then they will be inserted into the database.
However, if you remove the Attach line you cannot use the method anymore to update the relationship between existing parent and existing children.
Generally, when the detached entity contains a child collection of entities that are changed, added of where entities have been removed from you normally have to reload the original object graph from the database and merge the changes into it. Such an Update of a complex detached object graph does not work in a generic way and will require entity type specific code. An example is here: https://stackoverflow.com/a/5540956/270591


text:
Q: How Can I Get Started with PhoneGap in Eclipse? Trying to create my first PhoneGap project in eclipse. I have followed the Getting Started tutorial but that only seems to help in a best case scenario. My guess is that if they make the tutorials vague enough people will pay them for adequate help.
Following this tutorial: Getting Started with Android
When I run the create command I get the following error (see below). My guess that my environment is not ready. I have installed the Android SDK, I have the Java SDK installed and in my path. The only part that I am not clear on is the Apache Ant. I thought that was installed along with Eclipse?
Missing one of the following:
JDK: http://java.oracle.com
Android SDK: http://developer.android.com
Apache ant: http://ant.apache.org

What do I need to do to fix this problem and successfully create a PhoneGap project in Eclipse?

A: I'm assuming you're on Windows because I just finished resolving the same error.
What I did:

*

*Install the latest JDK [1]

*Install Apache Ant binary [2]

*Install Android SDK [3]

After all of those were installed I appended the below paths to my Path system variable which can be found at:
Control Panel > System > Advanced System Settings > Advanced tab > Environment Variables button > System variables
C:\Program Files\Java\jdk1.7.0_09\bin;C:\Users\Rob\Documents\apache-ant-1.8.4\bin;C:\Program Files (x86)\Android\android-sdk\tools
Be aware that my username is in those paths so yours will be different. Don't forget the semi-colon between the existing path and what you will be adding.
Depending on your usage of the above tools, it may be cleaner to add the path to the create.bat script.

*

*http://www.oracle.com/technetwork/java/javase/downloads/index.html

*http://ant.apache.org/bindownload.cgi

*http://developer.android.com/sdk/index.html


text:
Q: Crash on Production Firebase Database RejectedExecution Exception and HardAssert Exception Android App getting crashed on production many times by two exceptions.

Non-fatal Exception: java.lang.RuntimeException: Uncaught exception in Firebase Database runloop (20.0.0).

further caused by:

Caused by java.lang.AssertionError: hardAssert failed: Expected connection state disconnected, but was GettingToken
at com.google.firebase.database.connection.ConnectionUtils.hardAssert(ConnectionUtils.java:67)

and

Non-fatal Exception: java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask@ea8d495 rejected from com.google.firebase.database.v.i0.c$a@ee619aa[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 430]

I had tried the latest version of Firebase Libraries, tried older version libraries as well but no luck.
This is only happening on production live build, so it is hard to track the cause.
Someone help is highly appreciated. Please help me out.
Thanks


text:
Q: How to Make SO questions more Google-Friendly Glancing at the SO homepage I found that a lot of questions are asked in such a way that it's not easy for Google to find them. Any idea how to fix this?
P/S: I know that this is entirely up to the users to ask good question. But maybe we can do something to "improve their odds" of asking good questions?

A: Just clean up the grammar, wording, and clarity. It you build it, Google will come :)

A: The biggest point about finding questions with Google is the same for finding content of any sort through Google: it's all about the title.
So pick a good title that succinctly gives people an idea of what the question is about. Sometimes it can be hard thinking of a good title. I've sometimes spent some serious time thinking of a good title for things (blog posts and so on).
Compare and contrast:

*

*"I'm confused";

*"This doesn't work"; and

*"What do I do?"

vs

*

*"I don't understand why Java isn't cleaning up my thread pool";

*"Why is this code giving me a NullPointerException?"; and

*"My Ruby page takes 10 seconds to load. How do I find out why?"

Also think about likely search terms if you were looking for this question. You will get a higher ranking for something which is an exact phrase match than with something than isn't (generally speaking).


text:
Q: Scripting in Bash I have a function in bash say parse which takes one argument and function name is f. My file to be processed is somewhat like
a@b@c@
a@d@e@g@
m@n@
t@

I want to give the output as
a@f(b)@f(c)@
a@f(d)@f(e)@f(g)@
m@f(n)@
t@

That is apply function f to all except the first. Any clues so how can I do this?

A: This should do it:
sed 's/@\([^@]*\)/@f(\1)/g'

If all the fields are single characters, you can simplify it a bit (say, using . rather than \([^@]*\)).

A: You could use sed:
sed -e 's/@\(.\)/@f(\1)/g'

A: awk 'BEGIN {OFS=FS="@"} {for (i=2; i<=NF-1; i++) $i="f("$i")"; print}'

A: maybe this is what you want?
e.g. you have a script called sqr.sh:
kent$  cat sqr.sh
#!/bin/bash
echo $(($1*$1))

now you want to apply the function above on your input:
kent$  echo "foo@2@3@4@
0@10@20@
x@"|awk -F'@' -v OFS=@ '{for(i=2;i<=NF;i++) if($i) "./sqr.sh "$i|getline $i; print}'

foo@4@9@16@
0@100@400@
x@


text:
Q: Django CSRF Cookie Not Setting I have been trying to set up CSRF protection on my POST forms on my django 1.4.3 site and have been getting the 403 CSRF cookie not set error.
I believe I have followed the doc in detail, followed advice on many forums but all to no avail. I have stripped back the code as much as possible and the cookie just does not set. The csrfmiddlewaretoken is present, so that's not the source of the problem. I'm at my wit's end. No doubt the answer is stupidly simple, I just need a fresh set of eyes to point it out to me...
So here's some code:
#urls.py
...
url(r'^csrf/$', csrf_test, name='csrf_test'),
...

#views.py
...
from django.views.decorators.csrf import csrf_protect

@csrf_protect
def csrf_test(request):
    c = {}
    c.update(csrf(request))
    return render_to_response('csrf.html', c)
...

<!-- csrf.html -->
<html>
<body>
<form action="" method="post">
{% csrf_token %}
<input name="Submit" value="Submit" type="submit"/>
</form>
</body>
</html>

#settings.py
...
MIDDLEWARE_CLASSES = (
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    #for db transactions. Check middleware order if faulty
    'django.middleware.transaction.TransactionMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'debug_toolbar.middleware.DebugToolbarMiddleware',
)
...
TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + (
    'django.core.context_processors.csrf',
    'django.core.context_processors.request',
)
...

I am running the django development server on 127.0.0.1:8000.
I have cookies enabled on my browsers and have confirmed cookies are being set from other websites.
I have checked the csrfmiddlewaretoken is being passed as a POST variable.
I always get the error, this is not intermittent.
I have no problem with POST forms when I have disabled the middleware/used @csrf_exempt.
As I say, I'm at my wit's end. What on earth have I missed?
Thanks
Nathan
EDIT:
It now works, but I have no idea what has changed. For anyone reading this in the future I created a new project and app, it created the cookie straight away. Thinking it must have been a settings issue I changed the order of my MIDDLEWARE_CLASSES entries by moving 'django.middleware.csrf.CsrfViewMiddleware' down below 'django.contrib.sessions.middleware.SessionMiddleware'. I ran the original app and it worked. However to test whether the settings change was responsible I reversed the change. It still worked. Go figure.
I hope this helps someone in the future FWIW.
Nathan

A: if you're using render_to_response then you should probably use a RequestContext
This will handle the csrf protection for you -
def csrf_test(request):
    render_to_response('csrf.html', context_instance=RequestContext(request))

You don't need to include the csrf_protect decorator, since you've got the csrf middleware.

A: def csrf_test(request):
    .....
    return render(request, 'csrf.html', { ..... })


text:
Q: Get first json object from response rest service by Beanshell in jmeter I get this JSON response from my web service:
[
    {
        "type": "022",
        "sendDate": "2020-11-09 12:43:07",
        "message": "test1",
        "id": 8035,
    },
    {
        "notificationType": "023",
        "sendDate": "2020-11-09 11:40:02",
        "message": "test2 ",
        "id": 8034,
    },...
]

Now by Beanshell in JMeter I want to pass first id into new request so in JSR223 PostProcessor i write a simple print like this:
import com.eclipsesource.json.*;
String jsonString = prev.getResponseDataAsString();
log.info("value=" + jsonString);
JsonArray inbox =  Json.parse(jsonString).asArray();
//String id_BSH = ((JSONObject) storeArray.get(0)).getAsString("id");
//vars.put("id_BSH", pickup);

but i got this error :
2020-11-10 17:59:55,245 ERROR o.a.j.e.JSR223PostProcessor: Problem in JSR223 script, JSR223 PostProcessor
javax.script.ScriptException: Sourced file: inline evaluation of: ``import com.eclipsesource.json.*; String jsonString = prev.getResponseDataAsStrin . . . '' : Typed variable declaration : Class: JsonArray not found in namespace : at Line: 4 : in file: inline evaluation of: ``import com.eclipsesource.json.*; String jsonString = prev.getResponseDataAsStrin . . . '' : JsonArray
 in inline evaluation of: ``import com.eclipsesource.json.*; String jsonString = prev.getResponseDataAsStrin . . . '' at line number 4
    at bsh.engine.BshScriptEngine.evalSource(BshScriptEngine.java:93) ~[bsh-2.0b6.jar:2.0b6 2016-02-05 05:16:19]
    at bsh.engine.BshScriptEngine.eval(BshScriptEngine.java:46) ~[bsh-2.0b6.jar:2.0b6 2016-02-05 05:16:19]
    at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:233) ~[?:1.8.0_202]
    at org.apache.jmeter.util.JSR223TestElement.processFileOrScript(JSR223TestElement.java:224) ~[ApacheJMeter_core.jar:5.3]
    at org.apache.jmeter.extractor.JSR223PostProcessor.process(JSR223PostProcessor.java:45) [ApacheJMeter_components.jar:5.3]
    at org.apache.jmeter.threads.JMeterThread.runPostProcessors(JMeterThread.java:940) [ApacheJMeter_core.jar:5.3]
    at org.apache.jmeter.threads.JMeterThread.executeSamplePackage(JMeterThread.java:572) [ApacheJMeter_core.jar:5.3]
    at org.apache.jmeter.threads.JMeterThread.processSampler(JMeterThread.java:489) [ApacheJMeter_core.jar:5.3]
    at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:256) [ApacheJMeter_core.jar:5.3]
    at java.lang.Thread.run(Thread.java:748) [?:1.8.0_202]

A: I've heard Groovy "is the new black", moreover you should not be using Beanshell since JMeter 3.1 so you can go for Groovy's JsonSlurper class and store the first ID into a variable with this one-liner:
vars.put("id_BSH", new groovy.json.JsonSlurper().parse(prev.getResponseData()).get(0).id as String)

More information: Apache Groovy - Parsing and Producing JSON


text:
Q: A HTML validator in Java I want validate HTML code in Java.
Like this:
HTMLValidator.validateHTML("aaa<b>bbb<b>");
// Returns false, because tag <b> is not closed

What Java libraries exist to do this?

A: You can try JTidy.
JTidy is a Java port of HTML Tidy, a HTML syntax checker and pretty printer.
http://jtidy.sourceforge.net/


text:
Q: How to get make asyc get with CognitoIdentityCredentials After declaring the cred object with new AWS.CognitoIdentityCredentials I go ahead and use .get method to get the credentials and store them in IdentityId variable. When I run this function, the IdentityId variable is show to be undefined. It seems the
console.log("...IdentityId:", IdentityId); is evaluated before the credenitals are queried.
Is there a way I could use await to get the the credentials first and then move to the console.log command ?
async function GetCredentials(email, password, callback) {

  let response = await signIn(email, password);
  console.log("...response:", response);

  let idToken = response.response.token.idToken;

  let logins = {};
  logins[
    "cognito-idp." + AWS_REGION + ".amazonaws.com/" + AWS_COGNITO_USER_POOL_ID
  ] = idToken;
  console.log("...logins:", logins);

  let creds = new AWS.CognitoIdentityCredentials({
    IdentityPoolId: AWS_COGNITO_IDENTITY_POOL_ID,
    Logins: logins
  });
  console.log("...creds:", creds);

  let IdentityId;
  creds.get(function(err) {
    console.log("--------------------------")
    console.log('creds.data:', creds.data);
    IdentityId = creds.data.IdentityId;
    console.log("--------------------------")
  });

}

A: You could try
const promise = new Promise((resolve) => {
  creds.get(function(err) {
    console.log("--------------------------")
    console.log('creds.data:', creds.data);
    const IdentityId = creds.data.IdentityId;
    resolve(IdentityId)
    console.log("--------------------------")
  });
})
const returned = await promise

But I'm not sure where exactly you're using IdentityId because your statement

It seems the console.log("...IdentityId:", IdentityId); is evaluated before the credenitals are queried.

doesn't exist in your code


text:
Q: CollectionView removing from DOM when setting contentBinding I have a simple google maps view which is a CollectionView and has a contentBinding to an array controller. Every time I set the content to a new set of objects by setting it to a new array the CollectionView which has the maps on is removed from the DOM. However, If I push objects to content it will work fine. I need to reset the content with a new array of data though as it will be coming from an API. Can someone please tell me why this is happening I've been trying to solve this for a good day now.
Here is a jsbin. You can uncomment the code within the 'refresh' method that I've described above to see it working / failing.

A: Finally, I've found a solution. I created a ember component which applies the goole maps view to its self and then within the components view template add the collection view for the markers. Now I can refresh the data without it removing the google maps view. Please see this jsbin to see it working


text:
Q: Cronjob not echoing? I have a script to check if mysql is running.
#!/bin/sh
SERVICE='mysql'

if ps ax | grep -v grep | grep $SERVICE > /dev/null
then
    echo "$SERVICE service running, everything is fine"
else
    echo "$SERVICE is not running"
    echo "$SERVICE is not running!" | mail -s "$SERVICE down" root
fi

I set up cron to run it every minute.
1 * * * * /cronscripts/mysqlcheck

The script works fine when I run it manually, but it does not echo to the screen once a minute. The file is executable.

A: And why do you think cron manager will echo to the screen? Which exactly screen? No screen there, the file is launched from a daemon.
Check your e-mail, all this echoes should be reported as mails to root, cron or some user like this.
Edit: If you want a screen echo then try to use the screen , e.g. echo "bla bla bla" > /dev/tty1

A: The ! usually do some trouble in scripts when inside double quotes


text:
Q: Checkbox and Icons of MFC application are not displayed on Win11 machine I see a weird issue with my MFC application where check boxes and icons are disappeared when running it in Windows 11.
But the same is working well when running in windows 10.
Does any one have idea on this?
Appreciate your help.


text:
Q: VideoJS's live UI -- any way to manually manipulate seek behavior? I would like to both
1) Programmatically navigate the user to a specific point on the seekbar.
2) Prevent the user from clicking anything but a few spots on the seekbar.
As far as I can tell this is totally impossible. Does anyone have ideas?

A: You can manually move to any spot on the seekbar with Player.currentTime(seconds).
You can have custom behavior for what isn't seekable by listening for the seeked and seeking events, e.g. https://codepen.io/rosswaycaster/pen/gpzLao
 myPlayer.on("seeking", function(event) {
      if (currentTime < myPlayer.currentTime()) {
        myPlayer.currentTime(currentTime);
      }
    });

    myPlayer.on("seeked", function(event) {
      if (currentTime < myPlayer.currentTime()) {
        myPlayer.currentTime(currentTime);
      }
    });

    setInterval(function() {
      if (!myPlayer.paused()) {
        currentTime = myPlayer.currentTime();
      }
    }, 1000);


text:
Q: Correct way to submit a phonegap/jQM form. very new at this. Could someone tell me what is the best method of submitting a form when using phonegap and JMQ?  What I want to be able to do is passing the form data to a php file and then having the results passed back into app so that the user isnt directly accessing the php file at any point.
I found the following page link which basically does what I want but I keep getting "Origin null is not allowed by Access-Control-Allow-Origin" when testing out the code. So I'm guessing this will only work if the app is located on a server also?
Any happy would be great. thank <3

A: To test your solution on the computer you need to launch chrome from the terminal with the argument --disable-web-security. See this answer: Disable same origin policy in Chrome
In your Phonegap application you add a line of code to your config.xml in the www-folder: <access origin="*.yourdomain.com" />. Build, and you are now allowed to request all domains and subdomains from yourdomain.com. For more details on whitelisting see http://docs.phonegap.com/en/3.0.0/guide_appdev_whitelist_index.md.html#Domain%20Whitelist%20Guide

A: You are not able to make post through the local files, so Yes, you need to have it running in a Web Server.
But if you deploy your application, it should work either in a emulator or in your device.


text:
Q: Private inheritance and swap I'm using private inheritance in the implementation of two very related classes.  The using Base::X; is very useful and elegant.  However, I can't seem to find an elegant solution for reusing the base class's swap function.
class A
{
public:
   iterator       begin();
   const_iterator begin() const;
   const_iterator cbegin() const;

   A clone();

   void swap( A& other );
};

class Const_A : private A
{
public:
   // I think using A::A; will be valid in C++0x
   Const_A( const A& copy) : A(copy) { }

   // very elegant, concise, meaningful
   using A::cbegin;

   // I'd love to write using A::begin;, but I only want the const overload
   // this is just forwarding to the const overload, still elegant
   const_iterator begin() const
   { return A::begin(); }

   // A little more work than just forwarding the function but still uber simple
   Const_A clone()
   { return Const_A(A::clone()); }

   // What should I do here?
   void swap( Const_A& other )
   { /* ??? */ }
};

So far the only thing I can come up with is copy-pasting A::swap's definition into Const_A::swap's definition, YUCK!
Is there an elegant solution to to reuse the private base class's swap?
Is there a cleaner way to implement what I'm trying to do here (a const wrapper for a class)?

A: Well, can't you just call the base's version of swap?
void swap( Const_A& other )
{
    A::swap(other); // swaps the `A` portion of `this`.
    // …
}

In place of …, you'd normally swap the members pertaining only to Const_A, not A but since there aren't any in your particular case, this is all that you should need.

A: You can do as with the rest of the methods:
void Const_A::swap( Const_A& other ) {
   A::swap(other);
   // here any specifics
}


text:
Q: Can TFS use both Git and TFVC on the same repo I'm working on a big Web solution that uses TFS 2015 as source code management along with TFVC.
There is one scientific project, will generate a bunch of JavaScript files, needs to be accessed by another team that uses Git.
Can TFS have a single repository managed by both Git and TFVC so both teams can work on it simultaneously?

A: No, that's not possible.
You could use a tool like git-tfs as a bridge.
That's still better than TFVC for most of the actions but don't solve every problems...

A: This is impossible for now.
However as a workaround, you could use Git and TFVC repos in the same team project.

In Team Foundation Server 2015 Update 1 and above, a project
  administrator can add a Git repo to a team project created with Team
  Foundation Version Control (TFVC).
This allows you to adopt a new version control system while preserving
  all the data in your team project.

More details please refer this tutorial: TFVC and Git repositories in the same team project
Or you could also use  a two-way bridge between TFS (Team Foundation Server) and git, similar to git-svn. It fetches TFS commits into a git repository, and lets you push your updates back to TFS. Such as git-tfs.


text:
Q: How do I prevent anacron from running certain scripts? I am running RHEL5 and software RAID (mdadm). Currently I allow the 99-raid-check weekly cron script to run at the normal time (early Sunday morning). However, if the system is off during that time it will run when the system boots with a delay. Looking at the man page for anacrontab and /etc/anacrontab, I can see the current config is set to run every 7 days with a delay of 70 minutes for the cron.weekly scripts. I need to be able to predict when there will be high disk IO, so I want it to run early Sunday morning if it's on, or not at all. My question is, how can I prevent 99-raid-check just to wait until the following week to run and not utilize anacron?

A: The simplest option would be to modify your script to check for I/O load and only run if it is below a threshold. Use something like iostat and add a check in your script that will only run if I/O is below X. You can then leave the cron as is since the script itself will deal with checking the load.


text:
Q: Hyper-V extensible virtual switch disables network I just installed the Hyper-V role on my Windows Server 2012. It comes with something called a "Hyper-V extensible virtual switch". I assigned it to the only network card in my server. By doing so, the network card became useless/disabled/inactive/.. because the virtual switch disabled all features (IPv4, IPv6, Client for Microsoft Networks, ...) on the network adapter.
Can the extensible virtual switch be used in a single NIC configuration?  If so, how do I configure the host network after enabling the virtual switch?

A: In Windows Server 2008 R2 Hyper-V when using a single NIC and creating a Virtual Switch on that NIC, Hyper-V will create a virtual NIC that all of the networking components bind to and the physical NIC gets bound with the Microsoft Virtual Network Switch Protocol (which is the virtual switch driver). That shouldn't stop you from having normal network connectivity through the physical NIC.
In your case, the Hyper-V host and the Hyper-V guests will share the physical NIC. Make sure to check the check box on the Microsoft Virtual Switch that reads "Allow management operating system to share this network adapter".
That being said, at the very least you should have 2 network cards in the server: 1 dedicated for the host server and a second dedicated for the VM's.
I'm assuming all of the above is applicable in W2K12 and Hyper-V 2K12, or that it's very nearly applicable.
http://technet.microsoft.com/en-us/library/cc816585(v=ws.10).aspx

A: The problem was that I had VirtualBox installed (but not running). After uninstalling VirtualBox, it now works as it should.
Note: All features (IPv4, ...) are still disabled on my physical NIC. Instead, the virtual switch takes over the features and settings (like static IP address) from the physical NIC and is now used for network traffic. The physical adapter is no longer used (directly).


text:
Q: Prove inequality $(1+\frac{1}{2n})^n<2$ How can I prove inequality
$$
(1+\frac{1}{2n})^n<2
$$
for $n\in\mathbb{N}$ by using induction proof method?
I have tried to write that:
for $n=1$ it's true. So let's suppose that $(1+\frac{1}{2n})^n<2$. and now I don't know what do nect because I know that $(1+\frac{1}{2(n+1)})^{n+1} > (1+\frac{1}{2n})^n$ but I don't know how to show that $(1+\frac{1}{2(n+1)})^{n+1} < 2$.
In this task I cannot use the definition of $e$ number.

A: You can prove by induction that
$$(1-x_1)(1-x_2)\cdots (1-x_n)\geq 1-x_1-x_2-\ldots -x_n$$
for all real numbers $x_1,x_2,\ldots,x_n\in[0,1]$ (the equality holds, by the way, iff at least $n-1$ of $x_1,x_2,\ldots,x_n$ are $0$).  Using that inequality, we have
$$\frac{1}{\left(1+\frac1{2n}\right)^n}=\left(1-\frac{1}{2n+1}\right)^n\geq 1-\frac{n}{2n+1}>\frac{1}{2}.$$

A: We can use the binomial theorem as in the proof for
$$\left(1+\frac1n\right)^n<e$$
refer to:

*

*proof 2<lim (1+1/n)^n<3 (2<e<3)
or as an alternative
$$\left(1+\frac{1}{2n}\right)^n<2\iff n\log \left(1+\frac{1}{2n}\right)<\frac12<\log 2$$

A: Hint: Use Bernoulli's inequality (one from here for instance http://lkozma.net/inequalities_cheat_sheet/ineq.pdf)

A: It is enough to show that $\log(2)\geq \frac{1}{2}$, since
$$ 2^{1/n} = e^{\frac{\log 2}{n}} > 1+\frac{\log 2}{n} \stackrel{\color{red}{?}}{\geq} 1+\frac{1}{2n}.$$
is granted by the convexity of $e^x$. On the other hand $\log(2)>\frac{1}{2}$ is equivalent to $e<4$, and
$$ e = \sum_{k\geq 0}\frac{1}{k!}=\frac{8}{3}+\sum_{k\geq 4}\frac{1}{k!}<\frac{8}{3}+\frac{1}{6}\sum_{k\geq 4}\frac{1}{4^{k-3}}=\frac{49}{18}. $$
As an alternative,
$$ 0 < \int_{0}^{1}x^3(1-x^3)e^{-x}\,dx = \frac{1158}{e}-426 $$
directly gives $e<\frac{193}{71}$. Or, more elementary:
$$ \log(2)-\frac{1}{2}=\int_{0}^{1}\frac{dx}{1+x}-\int_{0}^{1}\frac{dx}{1+1}=\frac{1}{2}\int_{0}^{1}\frac{1-x}{1+x}\,dx > 0.$$

Yet another approach: for any $n\geq 1$, $2^{1/n}$ is the geometric mean of $\frac{n+1}{n},\frac{n+2}{n+1},\ldots,\frac{2n}{2n-1}$. By the AM-GM inequality it follows that
$$\begin{eqnarray*} 2^{1/n} < \frac{1}{n}\sum_{k=0}^{n-1}\left(1+\frac{1}{n+k}\right)&=&1+\frac{1}{n^2}+\frac{1}{n}\sum_{k=1}^{n-1}\frac{1}{k+n}\\&<&1+\frac{1}{n^2}+\frac{1}{n}\sum_{k=1}^{n-1}\frac{1}{\sqrt{k+n}\sqrt{k+n-1}}\end{eqnarray*} $$
and by the Cauchy-Schwarz inequality (see also page 8 of my notes) we have
$$ \sum_{k=1}^{n-1}\frac{1}{\sqrt{k+n}\sqrt{k+n-1}}\leq \sqrt{\sum_{k=1}^{n-1}1\sum_{k=1}^{n-1}\left(\frac{1}{k+n-1}-\frac{1}{k+n}\right)}=\frac{n-1}{\sqrt{n(2n-1)}},$$
so $2^{1/n}< 1+ \frac{1}{n\sqrt{2}}+\frac{1}{n^2}$ and actually $2^x< 1+\frac{x}{\sqrt{2}}+x^2$ for any $x$ in a pointed neighbourhood of the origin. By replacing $x$ with $-x$ and reciprocating we get
$$ 2^x > \frac{1}{1-\frac{x}{\sqrt{2}}+x^2} $$
and
$$ 2^{1/n} > \frac{1}{1-\frac{1}{n\sqrt{2}}+\frac{1}{n^2}} $$
still is stronger than needed.


text:
Q: Android - Circular array display I have a array of cities -

String[] cities = { "Riyadh", "Jubail", "Jeddah", "Madinah",
        "Tabuk","Bangalore","Chennai","Pune" };

I am displaying them in a list that has three textview(fixed) . This means we are  going to display three cities at a time. Here is the method to display the cities.

void setUpCityList(int iCity) {
    tvOneCity.setText(cities[iCity]);
    tvTwoCity.setText(cities[iCity + 1]);
    tvThreeCity.setText(cities[iCity + 2]);
}

When the user swipes up ,i am incrementing the index and the user swipes down i am decrementing the index.
void swipeUp()
{
    iCity++;
    setUpCityList(iCity);
}

void swipeDown()
{
    iCity--;
    setUpCityList(iCity);
}

I want to give this list a endless scroll functionality .
That means if the user swipes up - and list reaches the last three elements , it should again start from first element.
Example - 1. Current display - Last three elements - "Bangalore","Chennai","Pune"
 2. Swipe up -- Display should be - Chennai , Pune , Riyadh
How can i achieve this functionality .
This is more of a programming question .
Any Help will be highly appreciated.

A: You just need to change the indexing in your method:
void setUpCityList(int iCity) {
    int length = cities.length;

    tvOneCity.setText(cities[iCity % length]);
    tvTwoCity.setText(cities[(iCity + 1) % length]);
    tvThreeCity.setText(cities[(iCity + 2) % length]);
}

Once the iCity or iCity + 1, etc, reaches the length, actual index will automatically become 0. And for values less than length, it will behave normally, as if there was no modulus operator.
This way you can create a cycle of as much item you want. So, it's a generalized and extensible solution.

A: void swipeUp()
{   if(iCity == cities.length()){
        iCity = 0;
        setUpCityList(iCity++);

    }
    else{
        iCity++;
        setUpCityList(iCity);
    }
}

Try something like this.

A: you can try this:
void swipeUp()
{
iCity++;
if ( iCity > urMaxlength){
   iCity =0;
}
setUpCityList(iCity);
}

void swipeDown()
{
iCity--;
if ( iCity < urMinlength){
   iCity =urMaxlength;
}
setUpCityList(iCity);
}