text:
Q: Como mudar o switch toggle através da base de dados Estou a tentar que ao mudar na base de dados o bool para true ou false, que o switch toggle mude, consoante o true ou o false.
<script>
$(document).ready(function () {
    for (var i = 0; i < '@Model.Participantes.Count()'; i++) {
        if ($('#Participantes_' + i + '__ID').val() == "true")
            $(".botaoConfirmacao[data-rowindex='" + i + "']").prop('checked', true).change();
        else
            $(".botaoConfirmacao[data-rowindex='" + i + "']").prop('checked', false).change();
        i++;
    }

    $('.botaoConfirmacao').change(function (event) {
        event.preventDefault();
        if ($(this).prop('checked')) {
            $('#' + $(this).attr('id')).val('true');
        }
        else {
            $('#' + $(this).attr('id')).val('false');
        }
    });
 });


text:
Q: Initialized object that is in other object PL SQL I have the following object:
TYPE o_seat IS OBJECT
(
    seat_id VARCHAR2 (8 BYTE),
    seat_category_name VARCHAR2 (32 BYTE)
)

and the following objects :
 TYPE m_seats IS TABLE OF o_seat;

TYPE o_row IS OBJECT
(
    row_no NUMBER (2, 0),
    seats_array m_seats
)

I initialize object:
   v_row   o_row := o_row (NULL,NULL);

How can I initialize seats_array  in v_row?

A: Something like :
o_row (12,m_seats(o_seat('x','y'),o_seat('y','z')) )

A: DECLARE
v_row   o_row := o_row (
                        '1',
                        m_seats(
                                o_seat('Seat1','Elite'),
                                o_seat('Seat2','Premium')
                                )
                        );
BEGIN

FOR I IN 1..v_row.seats_array.COUNT LOOP
        DBMS_OUTPUT.PUT_LINE('Row :'||v_row.row_no||
                            ' Seat: '||v_row.seats_array(I).seat_id||
                            ' Category: '||v_row.seats_array(I).seat_category_name);
END LOOP;
END;
/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Authenticating Domino REST Service Requests I have installed "Domino Sample REST Service Feature" from  901v00_11.20141217-1000 version of XPages Extension Library. OpenNtfSample service (com.ibm.domino.services.sample.service.SampleService) works as it should in general and the only problem with it that it completely ignores authentication settings of the server.
I have tried both Basic and Session Authentication as described in Authenticating Domino REST Service Requests and the result I get is the following - the service returns data always and does not ask for any user name and password.
The server is configured with Session Authentication now and I get password prompt when I try to access
{my_server}/api/data
but does not get it when I open
{my_server}/api/sample
After I had added this Web Site Rule
Description: DAS service
   Type of rule: Override Session Authentication
   Incoming URL pattern: /api/
the server changed password prompt for
{my_server}/api/data
but
{my_server}/api/sample
remained open.
Has anybody experienced this kind of error? Can anybody help me password protect this sample service so that I could start developing my own once based this example?

A: The /api/sample resource is wide open on purpose.  That just returns a link to the contacts resource -- /xpagesext.nsf/api/sample/contacts.
If you really want to prevent anonymous access to the /api/sample resource, there are two possible solutions: 1) Disable anonymous access for all HTTP requests, or 2) Make a change to the RootResource class.  The first solution is a server config change.  I'm sure you can find details about that elsewhere.  Since this is StackOverflow, I'll focus on the second solution.
As you have already noticed, we don't allow anonymous access to the /api/data resource.  You can mimic that behavior in the /api/sample resource with a simple change to RootResource.getLinks().  Near the top of the method, just add these lines of code:
        boolean authenticated = false;
        Session session = ContextInfo.getUserSession();
        if ( session != null ) {
            String userName = session.getEffectiveUserName();
            if ( userName != null && !userName.equals("Anonymous")) {
                authenticated = true;
            }
        }

        if ( !authenticated ) {
            throw new NoAccessSignal("Need user context");
        }

By the way, you won't need to make the same change to the contacts resource class (ContactsListResource.java). Because the contacts resource URL includes a database name (xpagesext.nsf), the web server will attempt to open the database before forwarding the request to the REST service.  You can prevent anonymous access to the contacts resource by changing the ACL of xpagesext.nsf.  Just make sure the default access is "No access".


text:
Q: How do I make libusb work as non-root? I'm making a custom USB HID device, and a desktop app to go with it, using HIDAPI on Lubuntu 16.04.3 LTS.  We'll call it myapp for now.
Apparently, if I do $ ./myapp, libusb_open() fails with LIBUSB_ERROR_ACCESS.  (shown in my debugger as -3; it took a while to figure that out because the enum doesn't seem to be documented very well)
But if I do $ sudo ./myapp, it succeeds.
I really don't want myapp to have root permissions, so how can I talk to my USB device without them?

I was hoping for an answer here, but it seems to have been abandoned at exactly this point.  It says something about user permissions, but I can't seem to find that on my system.  I thought I might find a group called usb or libusb that I could add myself to, but no such luck.

This question on a different SE site has an answer that uses some austere text files to change the permissions either globally (probably a bad idea) or for a specific device, but:

*

*It's not the "muggle's tweak" that I was looking for.

*Most of those files have a warning against modifying directly because they're auto-generated.  So how can I be sure that a random package update isn't going to wipe out my changes and thus break myapp?

*It doesn't seem to do anything anyway.  I followed those instructions and rebooted, and myapp with user permissions still can't talk to USB.

A: For anyone else struggling with this - i needed to add GROUP="plugdev" to my udev rule under Ubuntu 18.04 to make it work.
so for my BTD-400 adapter the file /etc/udev/rules.d/51-usb-device.rules reads:
SUBSYSTEM=="usb", ATTRS{idVendor}=="0a5c", ATTRS{idProduct}=="21e8", GROUP="plugdev", TAG+="uaccess"

A: It's still not the "muggle's tweak" that I'm really looking for, but at least this works:
Apparently there are two directories for udev (I have no idea why):

*

*/etc/udev/rules.d

*/lib/udev/rules.d
I'd been messing with the /lib one and getting nowhere.  I found the /etc one here, and it does work:

Put SUBSYSTEM=="usb", ATTRS{idVendor}=="VID", ATTRS{idProduct}=="PID", MODE="0666"

*

*VID is the USB-IF-assigned Vendor ID of the device in question *

*PID is the Vendor-assigned Product ID of the device in question *

*0666 gives universal read/write access to whatever matches this line
* $ lsusb to see all attached USB devices and their ID's.
In /etc/udev/rules.d/xx-my-rule.rules (may need root/sudo permissions)

*

*xx is any number > 50 (the defaults are in 50, and higher numbers take priority)

*my-rule is whatever you want to call it

*must end in .rules
Then udevadm control --reload-rules (may also need root/sudo permissions), and it should "just work" for that specific VID/PID pair.

Another option, to tighten the permissions a little bit more, is to use TAG+="uaccess" in place of MODE="0666".  This limits access to the currently-logged-in (physical) user instead of all users.  Thanks @Lekensteyn!


text:
Q: Display facebook user images in PhoneGap (Android) I have a very simple use case. I have an xhr object  of ids of facebook users.
Now I just want to display the images of the users in the following way.
    xhr.objects.forEach(function (user) {
 $('#userimage').append( '< img src="https://graph.facebook.com/"+user.user_id+"/picture/?type=small"/>');
                                                    });

For some reason this is not working. The images are not being displayed. I have added "https://graph.facebook.com" to allow access. Also images from the local web server are being displayed properly.

A: Your string should read
picture?type=small

not
picture/?type=small

So the correct URL is:
"https://graph.facebook.com/"+user.user_id+"/picture?type=small"

See how do I get a facebook users profile image through the fb api for details.


text:
Q: Single JavaScript file. Without inserting inline scripts, how can I check if a specific page has loaded? Without inserting inline scripts, how can I check if a specific page has loaded? Usually I put an inline script that calls a function in the page's html head using window.onload, but how can this be achieved with a linked JavaScript file?
For example, suppose I have a button that opens a special page, and I need the DOM to be ready before I start any using scripts on that. Should I use two JavaScript files, linked at the bottom of each body?, then wrap everything in a function called by the onload event?

A: It's pretty common practice to place the script tags at the bottom of the page, just before the final body tag. This will mean that the DOM would have loaded by this point and it will be safe to execute your code. Also it means that your scripts won't be downloaded till the very end which makes for a better experience for visitors.
If you wanted to be particular about it, you could then add an event listener onto the body tag and have your code run after body loads. I'm not sure your exact use case so I don't know if this would serve your purpose better. Assuming you aren't doing anything out of the ordinary and your scripts are placed just before the final body tag this wouldn't make much of an extra difference as the majority of the DOM would have already loaded. If you did want to do this you'd use the following code.
var bodyElement = document.getElementsByTagName("BODY")[0];
bodyElement.onload = function () {
    // Your loading function
}

A: Let A be the page with the button you click.
Let B be the the special page that opens on A's button click
I struggle to understand what you're asking exactly, but this sounds like a case of "A comes before B".
If the button on page A is clickable after that page finishes loading, then the script that runs after page B finishes loading can safely assuming that both A and B have loaded. You can write logic in B that depends on A being loaded only if you can guarantee that A loads B. What happens if B is accessed directly bypassing A?
Possible markup for B follows:
<html>
    <head>
        <title>Special Page</title>
    </head>
    <body>

        <script src="test.js"></script>
    </body>
</html>

The test.js file linked above:
window.onload = function(){
    console.log('special page is loaded');
};

The onload event on page B may safely assume A has loaded but only if you can guarantee A always calls B.
I have no idea if you're trying to load page B into an iframe or do a page redirect from A to B or fetch B into A by way of Ajax and HTTP GET.


text:
Q: Powershell Pass "Press any key to continue" from another script I'm writing a powershell script to automate some updates.
For this purpose I need to execute another script and save the output into a variable.
Afterwards I can cut the things that I need off and save them into other variables.
These things theoreticly work but the other script which I'm executing stops the process,
beause it need any key to continue at the end.
Does somebody know how I can pass this?
The scripts stops after:
$list = .\list.cmd

Kind regards :)
Thats a part of the script:
Write-Host "Importing..."
cd "$path"
$list = .\list.cmd

Write-Host "Searching for the certificate file"
$CertificateFile = $list | where {$_ -match "Certificate File:"}
$CertificateFile = $CertificateFile.Substring(18)

Write-Host "I'm trying to find the Password File:"
$PasswordFile = $PasswordFile = $list | where {$_ -match "Password File:"}
$PasswordFile.Substring(15)

Write-Host "Searching for the password file"
$Enddate = $list | where {$_ -match "Validity NotAfter:"}
$Enddate = $Enddate.Substring(19)

A: Here is how you send a keystroke.  As for timing, it needs to occur when the paused app is in the foreground 'active' window.
add-type -AssemblyName System.Windows.Forms
[System.Windows.Forms.SendKeys]::SendWait("A")


text:
Q: Finding maximum likelihood This is a model that is used to model soccer scores, so $i$ and $j$ are, respectively, home and away teams. Random variables $(x,y)$ are the goals scored by the home and away teams, respectively. Parameter $\lambda$ is a known mean goals scored by the home team and $\mu$ is the mean goals scored by the away team. I have managed to fix all the other parameters except for $\rho$, which I have to estimate via MLE.
$$Pr(X_{i,j}=x, Y_{i,j}=y)=\tau_{\lambda, \mu}(x,y)\frac{\lambda^x \text{exp}(-\lambda)}{x!}\frac{\mu^y\text{exp}(-\mu)}{y!}$$
where
$$\lambda=\alpha_{i}\beta_{j}\gamma$$
$$\mu=\alpha_{j}\beta_{i}$$
and
$$\tau_{\lambda,\mu}(x,y)=\left\{\begin{array}{cc}
1-\lambda\mu\rho &\text{if $x=y=0$,} \\
1+\lambda\rho &\text{if $x=0,y=1$,}\\
1+\mu\rho &\text{if $x=1,y=0$,}\\
1-\rho &\text{if $x=y=1$,}\\
1 &\text{otherwise}\end{array}
\right.$$
Based on the above equations, all the parameters $(\lambda, \mu, \alpha, \beta, \gamma)$ are known constants.
So, now, the problem that I am having is that I have no clue on how to estimate $\rho$ using the maximum likelihood function since a piece-wise equation is involved.
Also, it will be great if anyone can do this using R.

A: If I understand it, your data is $\{(i_m,j_m,x_m,y_m) : m=1,\dots,n\}$, in which, for the $m$-th match, $i_m$ is the index of the home team, $j_m$ is the index of the away team ($i_m\neq j_m$), $x_m$ is the number of goals scored by the home team, and $y_m$ is the number of goals scored by the away team.
If we have $t$ teams disputing the $n$ matches, the likelihood $L(\rho,\gamma,\alpha_i,\beta_i, i=1,\dots,t)$ is proportional to
$$
  \prod_{m=1}^n \tau_{\lambda_m,\mu_m}(x_m,y_m)\,\lambda_m^{x_m} \,\mu_m^{y_m}\,e^{-(\lambda_m+\mu_m)} \, ,
$$
in which $\lambda_m = \alpha_{i_m} \beta_{j_m}\gamma$ and $\mu_m = \alpha_{i_m} \beta_{j_m}$. This likelihood is a function of $2(t+1)$ parameters. You will probably need to implement some conjugate gradient method to solve this constrained optimization problem. I wonder what happens if we put some priors on the parameters and MCMC the posterior with a random walk Metropolis. You said that you know the values of the parameters, except for $\rho$ (and I wonder how...). Hence, your first step is to write an R function that computes the product above for each value of $\rho$. Then, plot it and use the optimizer to see what happens.


text:
Q: Android banner ribbon using shape I am trying to figure out how I would stack shapes so I can create the following ribbon(Pink/White/Pink/White/Pink part). I will then be using this as a background for my textview.

A: I figured it out using a layer-list
<?xml version="1.0" encoding="utf-8"?>

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape xmlns:android="http://schemas.android.com/apk/res/android">
            <solid android:color="#FFe5887c" />
            <size android:width="2dp" android:height="2dp"/>

        </shape>
    </item>
    <item android:top="2dp">
        <shape xmlns:android="http://schemas.android.com/apk/res/android">
            <solid android:color="#FFFFFFFF" />
            <size android:width="1dp" android:height="1dp"/>

        </shape>
    </item>
    <item android:top="3dp">
        <shape xmlns:android="http://schemas.android.com/apk/res/android">
            <solid android:color="#FFe5887c" />
            <size android:width="20dp" android:height="20dp"/>

        </shape>
    </item>
    <item android:top="23dp">
        <shape xmlns:android="http://schemas.android.com/apk/res/android">
            <solid android:color="#FFFFFFFF" />
            <size android:width="1dp" android:height="1dp"/>

        </shape>
    </item>
    <item android:top="24dp">
        <shape xmlns:android="http://schemas.android.com/apk/res/android">
            <solid android:color="#FFe5887c" />
            <size android:width="2dp" android:height="2dp"/>

        </shape>
    </item>
</layer-list>


text:
Q: Java 11 stripLeading() method unavailable in Android Studio Arctic Fox In Java 11 there are some new String methods - strip(), stripLeading() etc. But it is not possible to use them in Android Studio Arctic Fox - when I try to type them, they aren't recognized:

I have Java 11 installed, in Settings the embedded JDK version 11.0.10 is specified:

In the build.gradle file, in compileOptions, I have changed to JavaVersion.VERSION_11:
compileOptions {
        sourceCompatibility JavaVersion.VERSION_11
        targetCompatibility JavaVersion.VERSION_11
    }

Why aren't the new methods available?

A:
I have Java 11 installed, in Settings the embedded JDK version 11.0.10 is specified

That is the version of Java used to run Gradle. It is unrelated to the version of Android that is used on Android devices.

In the build.gradle file, in compileOptions, I have changed to JavaVersion.VERSION_11

That does not change what is on Android devices.

Why aren't the new methods available?

Because Android supports a subset of Java 8.


text:
Q: How is Einstein-Bose condensation supposed to stabilize d*(2380)? A recent paper suggests a new dark matter candidate: Einstein-Bose condensates of the hexaquark/dibaryon d*(2380) ($uuuddd$). The nice thing about this theory is that it does not require any new physics, just that during Big Bang the densities are high enough for the hexaquarks to form condensates.
My problem with this is that free d*(2380) appears to have a lifespan of $10^{-23}$ s. So clearly joining the BEC must extend the lifespan tremendously. My question is: how?

A: Bose condensation does not really have anything to do with the (possible) stability of D* matter. The paper assumes that a miracle happens, and D* matter is so tightly bound that the binding energy per particle-pair is bigger than the mass difference between the D* and a deuteron, and as a result D* matter is absolutely stable.
The proposed state is a Bose condensate simple because it is a systems of Bosons at essentially zero temperature. The idea of Bose condensation of bosonic multi-hadrons is not in itself crazy, Bose condensates of deuterons or alpha are likely to exist (but with much smaller binding energies).
However, if D* matter is indeed bound by several hundred MeV per particle (the miracle assumed above), then the interaction would have to be quite strong, the density would have to be quite large (several times larger than ordinary nuclear matter density), and there is no obvious sense in which this is a Bose condensate of approximately point-like D* particles. This is really absolutely stable, non-strange quark matter, an idea that gets tossed around every so often (which has no experimental evidence in favor, and very little theoretical support).


text:
Q: Adding Text under each image in image gallery I tried using p tag with max-width attribute but in doesn't worked for me:
.a {
     max-width:100px;
}

With HTML:

Hello Welcome to Stackoverflow.

I want this text to be fit under image of resolution 500*500. If the text goes more than image width it should be automatically wrapped in next line.

A: Use This Code

div {
  height: auto;
  width: 500px;
}

img {
  height: 100%;
  width: 100%;
}

Hello Welcome to Stackoverflow

A: You can try this.
It works fine for me.

.resized_anchor {
  max-width: 100px;
 }
<!DOCTYPE html>

<title>question reality.</title>
<link rel="stylesheet" type="text/css" href="style.css">

   Hello Welcome to Stackoverflow. Doing a greate job here

A: I don't know is this what you need, just check this snippet

.image_wrap {
  width: 300px;
}
.image_wrap img {
  width: 100%;
}

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has


text:
Q: Combinations - at least and at most There are 20 balls - 6 red, 6 green, 8 purple
We draw five balls and at least one is red, then replace them.  We then draw five balls and at most one is green.  In how many ways can this be done if the balls are considered distinct?
My guess:
$${4+3-1 \choose 3-1} \cdot {? \choose ?}$$
I don't know how to do the second part...at most one is green?
Thanks for your help.

A: There are $14$ non-red balls, so there are $\binom{14}5$ ways to draw $5$ non-red balls. There are $\binom{20}5$ ways to draw $5$ balls regardless of color, so there are $\binom{20}5-\binom{14}5$ ways to draw $5$ balls including at least one red ball.
Now we'll calculate the number of ways to draw $5$ balls, of which at most one is green. The easiest way to calculate this is to split it into two cases: no green balls, and exactly one green ball. Since there are $6$ green balls, there are $14$ non-green balls, and the number of ways of drawing $5$ of them is $\binom{14}5$, just as when we counted the ways of drawing $5$ non-red balls. There are $\binom61=6$ ways to draw one green ball and $\binom{14}4$ ways to draw $4$ non-green balls, so there are $6\binom{14}4$ ways to draw $5$ balls, exactly one of which is green. Adding the two cases, we see that there are $\binom{14}5+6\binom{14}4$ ways to get at least one green ball amongst the $5$.
The final answer, as you realized, is the product of these two numbers,
$$\left(\binom{20}5-\binom{14}5\right)\left(\binom{14}5+6\binom{14}4\right)\;.$$
I make that $(15504-2002)(2002+6006)=108,124,016$.

A: Event A
Number of ways to choose 5 balls = $ _{}^{20}\textrm{C}_5 $
Number of ways to choose 5 balls with no red balls = $ _{}^{14}\textrm{C}_5 $
Hence the number of ways to choose 5 balls including at least one red ball =$ _{}^{20}\textrm{C}_5 - _{}^{14}\textrm{C}_5 $
Event B
Number of ways to choose 5 balls with no green balls = $ _{}^{14}\textrm{C}_5 $
Number of ways to choose 5 balls with exactly one green ball = $ _{}^{14}\textrm{C}_4 \times 6 $ (we multiply here by 6 because we have 6 choices for the green ball we choose.)
Since the above two choice processes are mutually exclusive we have that,
Hence the number of ways to choose 5 balls including at most one green ball =$ _{}^{14}\textrm{C}_5 + _{}^{14}\textrm{C}_4 \times 6 $

Events A and B are independent.
Therefore, the total number of ways of doing A and B = $ (_{}^{20}\textrm{C}_5 - _{}^{14}\textrm{C}_5) \times (_{}^{14}\textrm{C}_5 + 6_{}^{14}\textrm{C}_4  )$


text:
Q: Adding flash before erasing and writing into flash In a program to erase and write into flash, I donot understand the lines
struct kinetis_flash *kf = calloc(1, sizeof(*kf));
    struct target_flash *f = &kf->f;

from the below section of the code. And the whole program can be found at https://github.com/blacksphere/blackmagic/blob/master/src/target/kinetis.c
struct kinetis_flash {
    struct target_flash f;
    uint8_t write_len;
};

static void kl_gen_add_flash(target *t, uint32_t addr, size_t length,
                             size_t erasesize, size_t write_len)
{
    struct kinetis_flash *kf = calloc(1, sizeof(*kf));
    struct target_flash *f = &kf->f;
    f->start = addr;
    f->length = length;
    f->blocksize = erasesize;
    f->erase = kl_gen_flash_erase;
    f->write = kl_gen_flash_write;
    f->done = kl_gen_flash_done;
    f->erased = 0xff;
    kf->write_len = write_len;
    target_add_flash(t, f);
}

It would be great if someone helps me understanding above tw lines, thanks in advance.Many targets for example KL25, K22, K64 can be accordingly used what i understood from the project. Are those two lines storing target specific specifications for flash?
In general we donot need to allocate any space for flash right using calloc or malloc like we do it for RAM.

A: This line
struct kinetis_flash *kf = calloc(1, sizeof(*kf));

is a dynamic allocation of a struct kinetis_flash somewhere in RAM. It's probably used for holding information about a flash device present in the system.
This line
struct target_flash *f = &kf->f;

makes f point to the struct target_flash - named f - inside struct kinetis_flash so that you can write to it using f->some_var = ...
So the whole function is simply creating and initializing an object of type struct kinetis_flash
Though the code is correct, it's (IMO) a bit confusing to have a variable f pointing to f inside a struct. Perhaps a name like ptr_f would be more clear.
Also notice that the code is equivalent to:
static void kl_gen_add_flash(target *t, uint32_t addr, size_t length,
                             size_t erasesize, size_t write_len)
{
    struct kinetis_flash *kf = calloc(1, sizeof(*kf));
    kf->f.start = addr;
    kf->f.length = length;
    ...
}

A: The code in question extends GDB, allowing it to use various JTAG or Serial Wire interfaces to program and debug certain ARM devices. Identifying the attached devices flash device is a time consuming and disruptive (as-in can't run device code) task, so you only want to do it once, hence the local RAM allocation for storing the type and current state of the attached flash.


text:
Q: Displaying the number of valid results for a range of dates I currently have a table with a creation date and a expiry date. I currently have a sql command to get the number of valid items for a given date.
select
    count(id) ,CONVERT(date, getdate())
 from
    table
 where
    createDate < getdate() and expDate > getdate()

This returns the count and current date.
Is it possible to wrote a sql query that will return the result for a range of dates, say I if wanted to plot the number of valid items over a range of 15 days?
Thanks!

A: Check this,
DECLARE @StartDate  DATETIME,
        @EndDate    DATETIME;

SELECT   @StartDate = '20110501'
        ,@EndDate   = '20110801';

SELECT
        DATEADD(d, x.number, @StartDate) AS MonthName1
        ,
        x.number
FROM    master.dbo.spt_values x
WHERE   x.type = 'P'
AND     x.number <= DATEDIFF(MONTH, @StartDate, @EndDate);

The above query give the list of dates between 2 dates.
As per your table and question, check this also.
declare @table table(id int,frdt datetime, todt datetime)

insert into @table values (1,GETDATE()-20, GETDATE()-19)
,(2,GETDATE()-9, GETDATE()-8)
,(3,GETDATE()+20, GETDATE()+18)
,(4,GETDATE(), GETDATE()-1)
,(5,GETDATE()-20, GETDATE())
,(6,GETDATE()-10, GETDATE()+10 )

select * from @table

declare @frdt datetime = null , @todt datetime = getdate()-10

select @frdt, @todt,* from @table
where
 (@frdt is null or @frdt between frdt and todt)
and
 (@todt is null or @todt between frdt and todt)

 select @frdt = GETDATE()-15 , @todt = GETDATE()

 select @frdt, @todt,* from @table
where
 (@frdt is null or @frdt between frdt and todt)
 and
 (@todt is null or @todt between frdt and todt)

A: Try this:
create table #datelist (ValidDateCheck date, ValidResults int)

declare @startdate date = '1/1/2015'
declare @enddate date = '2/1/2015'
declare @interval int = 1 --Use 1 if you want every day between your dates, use 2 if you want every other day, etc.

declare @datecounter date = @startdate
declare @count int

while @datecounter <= @enddate
begin
set @count =
    (select count(*)
    from Table
    where CrtDt <= @datecounter and ExpDt > @datecounter)
insert into #datelist values (@datecounter, @count)
set @datecounter = dateadd(dd, @interval, @datecounter)
end

select * from #datelist order by 1

It loops through all the dates in your range, counting valid results for each one.


text:
Q: Как в C# создать отдельный класс для заполнения combobox на многих формах? Смысл в чем имеется несколько форм, на этих формах имеются одинаковые combobox к примеру выберите пол человека. Как сделать что бы считывание данных с БД в combobox происходило в отдельном классе?
Если бы это было в методе формы то код был бы
    public static class cb_Drop_down
    {
     public static void Drop_down_cb_sex()
     {
         SqlConnection sqlConnection = new
 SqlConnection(ConectionSQL_string.sql_string);
        sqlConnection.Open();
        string sql_quiry = $"SELECT Name, id FROM Sex";
        DataTable dataTable = new DataTable();
        SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sql_quiry,
sqlConnection);
        sqlDataAdapter.Fill(dataTable);
        this.cb_sex.DataSource = dataTable;
        this.cb_sex.DisplayMember = "Name";// столбец для отображения
        this.cb_sex.ValueMember = "id";//столбец с id
        this.cb_sex.SelectedIndex = -1;
    }

но в отдельном классе через this не связать:( что можно использовать в данном случае?

A: У вас есть много способов решения вашей проблемы.
Как самый простой вариант, вы можете переделать вашу функцию так, чтобы оправлять в неё комбобокс и внутри этот комбобокс готовить как вам надо. Например
public static void Drop_down_cb_sex(Combobox target) ....


text:
Q: How do we know that $\omega_1$ exists in ZF? In ZF, not all "collections of objects" are sets. For example, there is no set of all sets, and there is no set of all ordinals.
So, how do we know that there is a set of all countable ordinals? In other words, how do we know that $\omega_1$ exists? (I'm assuming you don't need Choice.)

A: Its a consequence of the axiom of replacement. The set of all binary relations on $\omega$ exists, its just $P(\omega \times \omega)$ and the subset $X$ of all well orders of $\omega$ also exists. To every well order of $\omega$ there is a well defined ordinal number, $\omega_1$ is the image of $X$ under the assignment of ordinal numbers.
Incidentally replacement is needed even to show that $\omega+\omega$ exists.


text:
Q: FFMpeg Sound Lost When Short Overlay Video Ends I am creating a video file that is 36 seconds long. It is made of three .mp4 files. One video file is the background and the other two videos are overlays. One of the overlay videos ends about 26 seconds into the video.
Problem: When the overlay ends at 26 seconds into the video, the overlay video remains on the screen paused and the audio for the other two videos is lost. There is 10 seconds of dead air.
It would be preferable if the video for the overlay was removed when it ended. However, the most important thing is it ending should not stop the audio for the other two videos.
ffmpeg -loglevel fatal \
    -itsoffset 0.401 -i 4609_segment_1_remote_0.mp4 \
    -itsoffset 0.304 -i 4609_segment_1_remote_1.mp4 \
    -i 4609_segment_1_local_0.mp4 \
    -filter_complex " \
        [1:v]scale=iw/4:-1:flags=lanczos[rem1]; \
        [2:v]scale=iw/4:-1:flags=lanczos[loc0]; \
        [0:v]transpose=1[rotate1]; \
        [rotate1][loc0]overlay=main_w-overlay_w-10:main_h-overlay_h-10[rem0]; \
        [rem0][rem1]overlay=main_w-overlay_w-180:main_h-overlay_h-10[rem1]; \
        [0:a][1:a][2:a]amerge=inputs=3[a]" \
    -map "[rem1]" -map "[a]" -ac 3 -vcodec libx264 \
    -ar 44100 -strict -2 -acodec aac 4609_segment_1.mp4

Input File [0]: 4609_segment_1_remote_0.mp4
Alias: [0:v], [rem0], rotate1]
Duration: 00:00:35.58
Dimensions: 640x480 [SAR 1:1 DAR 4:3]
Starts: 0.401 seconds
Video is Rotated 90 degrees clockwise
Background Video
Input File [1]: 4609_segment_1_remote_1.mp4
Alias: [1:v], [rem1]
Duration: 00:00:25.14
Dimensions: 640x480 [SAR 1:1 DAR 4:3]
Starts: 0.304 seconds
Overlay: 180 px from right, 10 px from bottom
Input File [2]: 4609_segment_1_local_0.mp4
Alias:  [2:v], [loc0]
Duration: 00:00:34.98
Dimensions: 640x480 [SAR 1:1 DAR 4:3]
Starts: Immediately
Overlay: 10 px from right, 10 px from bottom
The result is a video 480x640. Video lasts 36 seconds. Audio lasts 26 seconds. There are two overlayed videos in the bottom right corner of the video.

A: Use
ffmpeg -loglevel fatal \
    -itsoffset 0.401 -i 4609_segment_1_remote_0.mp4 \
    -itsoffset 0.304 -i 4609_segment_1_remote_1.mp4 \
    -i 4609_segment_1_local_0.mp4 \
    -filter_complex " \
        [1:v]scale=iw/4:-1:flags=lanczos[rem1]; \
        [2:v]scale=iw/4:-1:flags=lanczos[loc0]; \
        [0:v]transpose=1[rotate1]; \
        [rotate1][loc0]overlay=main_w-overlay_w-10:main_h-overlay_h-10[rem0]; \
        [rem0][rem1]overlay=main_w-overlay_w-180:main_h-overlay_h-10:eof_action=pass[rem1]; \
        [1:a]apad[1a];[2:a]apad[2a]; \
        [0:a][1a][2a]amerge=inputs=3[a]" \
    -map "[rem1]" -map "[a]" -ac 3 -vcodec libx264 \
    -ar 44100 -strict -2 -acodec aac 4609_segment_1.mp4

amerge terminates with the shortest input, so the remedy is to indefinitely extend all inputs except one, which decides output audio length.
eof_action=pass will clear out the overlay once the secondary stream ends.


text:
Q: Microsoft Graph API: Teams App - Problem with "List members of a channel" using "team id" I have a Teams App with a bot and am attempting to use Microsoft Graph API to retrieve all the members of a channel conversation.
According to the Microsoft Doc here, the GET URL is...
GET https://graph.microsoft.com/v1.0/teams/{team-id}/channels/{channel-id}/members

When I send a bot mention in the channel, it provides an event context dictionary which includes a "channelData" param like the below (slightly redacted with "X"):
  channelData: {
    teamsChannelId: '19:9b9d91fb85ec4146972XXXXXXXXXXXXX.tacv2',
    teamsTeamId: '19:B9zDXPWNaGn03wB8iifYw6XXXXXXXXXXXXXX@thread.tacv2',
    channel: { id: '19:9b9d91fb85ec414XXXXXXXXXXXXXXXXa@thread.tacv2' },
    team: {
      id: '19:B9zDXPWNaGn03wB8iifYw6XXXXXXXXXXXXXX@thread.tacv2'
    },
    tenant: { id: 'b06932a5-6eed-4e9a-XXXX-XXXXXXXXX' }

However, when I make a call to the GET endpoint with teams-id = team{id} or tenant{id} and channel-id = channel{id} it returns the following:
{
    "error": {
        "code": "NotFound",
        "message": "No Team found with Group id: b06932a5-6eed-4e9a-XXXX-XXXXXXXXX",
        "innerError": {
            "message": "No Team found with Group id: b06932a5-6eed-4e9a-XXXX-XXXXXXXXX",
            "code": "ItemNotFound",
            "innerError": {},
            "date": "2022-05-30T21:13:42",
            "request-id": "d8e2dfc5-0410-422b-b79d-96b73f38196b",
            "client-request-id": "d8e2dfc5-0410-422b-b79d-96b73f38196b"
        }
    }
}

I think what the API really wants is team-id = "groupID" because when I go into the Teams Desktop app and "Get link to channel" it gives me the following...
https://teams.microsoft.com/l/channel/19%3a3ca3a04e49c447XXXXXXXXXXXXXXXXXXthread.tacv2/Test%2520Channel%25201?groupId=8325270c-856a-4271-XXXXXXXXXXXXXX&tenantId=b06932a5-6eed-4e9a-XXXX-XXXXXXXX

...and then if I use the "groupId" in the same GET call, it gives the expected response where all the members of the conversation are listed.
Now, this would be totally fine except...I can't fine the "groupId" anywhere in the bot message turn context...even on the "onMembersAdded" event which occurs when the bot is first added.
I've read every article / forum listing I can find on this, but so far am completely stumped...hopefully I'm missing something simple that someone can point out!

A: Ok, finally figured this out...the link here shows how to get additional context for the bot.
You have to call the TeamsInfo.getTeamDetails(turnContext) to retrieve the aadGroupID:
export class MyBot extends TeamsActivityHandler {
    constructor() {
        super();

        // See https://aka.ms/about-bot-activity-message to learn more about the message and other activity types.
        this.onMessage(async (turnContext, next) => {
            const teamDetails = await TeamsInfo.getTeamDetails(turnContext);
            if (teamDetails) {
                await turnContext.sendActivity(`The group ID is: ${teamDetails.aadGroupId}`);
            } else {
                await turnContext.sendActivity('This message did not come from a channel in a team.');
            }

            // By calling next() you ensure that the next BotHandler is run.
            await next();
        });
    }
}


text: Q: How to enable crash reports in Chromium on Windows? Through the method of debugging and deduction I got to this file, did everything straightforwardly and simply returned the true from the right methods, but crash reports still disabled! Can you help me understand why?


text:
Q: Video Previewing in CWAC-CAMERA In the CWAC-CAMERA DOCUMENT it is written "From a UI standpoint, the CameraFragment solely handles the preview pane.".But for videos i don't see any preview is avalaible after i capture video.Do CWAC-CAMERA library has inbuilt video previewing?Below is code i am using.
 f = new CameraFragment();
        getFragmentManager().beginTransaction()
                .add(R.id.preview_view, f, TAG_CAMERA_FRAGMENT)
                .commit();
builder=new SimpleCameraHost.Builder(new DemoCameraHost(getApplicationContext()));
switchToVideoOpen.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
  if (!isVideoOpen) {

    isVideoOpen = true;

    takeVideo();
}
else{
    isVideoOpen = false;

    stopVideo();
}

    }
});
private void takeVideo() {

    CameraFragment f = (CameraFragment) getFragmentManager().findFragmentByTag(TAG_CAMERA_FRAGMENT);
    if (f != null && f.isVisible()) {
        try {
            f.record();

        } catch (Exception e) {

        }
    }
}
private void stopVideo() {

    CameraFragment f = (CameraFragment) getFragmentManager().findFragmentByTag(TAG_CAMERA_FRAGMENT);
    if (f != null && f.isVisible()) {
        try {
            f.stopRecording();

        } catch (Exception e) {

        }
    }
}

A: Previews are what the user sees while lining up the photo or video to be captured.

But for videos i don't see any preview is avalaible after i capture video

You can call that whatever you want, but I will not be calling it a "preview". CWAC-Camera does not display photos or videos after they are taken. If you want to do that, you need to do that yourself.


text:
Q: Dismiss NavigationView when Hidden SwiftUI How can I dismiss a view that I presented with a NavigationButton where the NavigationBar is hidden.
I intentionally have hidden the NavigationBar so I can put items on top of the NavigationBar in the center which is not possible by default(only trailing and leading).
My current code is this:
NavigationView {
        VStack {
                ...
                NavigationButton(destination: SignUpView(), isDetail: true) {
                    Text("Account erstellen").bold()
                        .frame(minWidth: 0, maxWidth: .infinity)
                        .frame(minHeight: 40).padding(.top, 0)
                        .background(Color.blue)
                        .foregroundColor(.white)
                        .cornerRadius(20)
                }
                ...
        }
        .navigationBarItem(title: Text(""), titleDisplayMode: .inline, hidesBackButton: true)
        .navigationBarHidden(true)
    }

On SignUp View I have an dismissBtn but without functionality which I want to add now.


text:
Q: Best way to design Domain with constant in grails I have lots of domain classes in my project. Many of them has type column. For example: User table has userType column, Book table has bookType column. I often pass these types into GSP g:select source by calling BookType.list() method. But problem is if GSP contains lots of g:select then I have to execute lots of redundant query.
And another problem is when I create a new Domain instance, I have to get these constant types from DB by following way
Book book = new Book();
book.bookType = BookType.findByName(BookTypes.COMICS);

Here I also have the same problem, I have to execute redundant query. Is there any good design to do all these stuff without executing these redundant queries?

A: If the types are not very volitile, I assume that is the case because I can see you defined an enum for type. Try using enum, totally -- I mean, don't bother with the database table at all to back that up. For example,
enum SomeType {

    TYPE1(1, "Type 1"),
    TYPE2(2, "Type 2"),
    TYPE3(3, "Type 3")

    final int id
    final String value

    private SomeType(int id, String value) {
        this.id = id
        this.value = value
    }

    // Might be needed for <g:select> tags, I'm not very sure
    int getKey() { id }

    static SomeType byId(int id) {
        values().find { it.id == id }
    }
}

Then, in your domain, do something like,
class SomeDomain {

    static constraints = {
        ...
        type nullable: false
        ...
    }

    ...
    SomeType type
}

Then, you can simply do something like this,
SomeDomain book = new SomeDomain(..., type: SomeType.TYPE1, ...);


text:
Q: Add a new column by multiple conditions I am trying to add a new column, category, by the existing category's id.
conditions = [
    (result['id'] == 1362) or (result['id'] == 7463),
    (result['id'] == 543) or (result['id'] == 3424)]
choices = ['A1', 'A2']
result['category'] = np.select(conditions, choices, default='black')

But, I got an error:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-289-7cb2bbdaab53> in <module>()
      1 conditions = [
----> 2     (result['id'] == 1362) or (result['id'] == 7463),
      3     (result['id'] == 543) or (result['id'] == 3424)]
      4 choices = ['A1', 'A2']
      5 result['category'] = np.select(conditions, choices, default='black')

/anaconda/lib/python3.6/site-packages/pandas/core/generic.py in __nonzero__(self)
    951         raise ValueError("The truth value of a {0} is ambiguous. "
    952                          "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
--> 953                          .format(self.__class__.__name__))
    954
    955     __bool__ = __nonzero__

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

How can I correct this?

A: With pandas you need to use elementwise logical or | or np.logical_or():
import numpy as np
import pandas as pd

d = {"id": [1362, 1361, 7463, 7462, 543, 542, 3424, 3333]}
result = pd.DataFrame(d)

conditions = [np.logical_or(result['id'] == 7463, result['id'] == 1362),
              np.logical_or(result['id'] == 3424, result['id'] == 543)]

#Alternate syntax
#conditions = [(result['id'] == 7463) | (result['id'] == 1362),
#              (result['id'] == 3424) | (result['id'] == 543)]

choices = ['A1', 'A2']
result['category'] = np.select(conditions, choices, default='black')

print(result)

     id category
0  1362       A1
1  1361    black
2  7463       A1
3  7462    black
4   543       A2
5   542    black
6  3424       A2
7  3333    black


text:
Q: problem loading several OBJ files in ThreeJS and setting their positions I want to load a number of OBJ files and position them at specific positions for a mechanical assembly. I can do a number of snippets like
{
  const objLoader = new OBJLoader();
  objLoader.load('obj/'+'AA2.obj', function(object) {
    object.traverse( function ( child ) {
       if ( child instanceof THREE.Mesh )
          child.material.color.setRGB (0.6,0.3,0.3);
   });
  object.position.x=-1065.4;
  object.position.y=700.0;
  object.position.z=-937.1;
  scene.add( object );
  })
}

and this works fine.
But I want to do that in a loop. I am using the array:
const parts = [
  ['AA1',-1065.4,0.0,-937.1,0.6,0.3,0.3],
  ['AA2',-1065.4,700.0,-937.1,0.6,0.3,0.3],
  ['AB1',-225.0,0.0,-937.1,0.6,0.3,0.3],
  ['AB2',225.0,0.0,-937.1,0.6,0.3,0.3],
  ...
  ];

and then I loop with:
for (var i = 0;i < parts.length; i++) {
    const objLoader = new OBJLoader();
    objLoader.load('obj/'+parts[i][0]+'.obj', function(object) {
      object.traverse( function ( child ) {
        if ( child instanceof THREE.Mesh )
          child.material.color.setRGB (parts[i][4], parts[i][5], parts[i][6]);
        });
      object.position.x=parts[i][1];
      object.position.y=parts[i][2];
      object.position.z=parts[i][3];
      scene.add( object );
    })
  }

and this fails in that all objects have the same final color, and they are all set at
position 0.
There are no error messages in the console. What am I doing wrong? Does this have
something to do with asynchronous loading?
Thanks,
Dennis

A: The problem is that while calling the callback function, the loop has already completed its work and set the last value for i. That is why you always see the same color. Below is a similar example. As one solution, just replace the var with let

for (var i = 0; i < 10; i++) {
  setTimeout(() => console.log('var: ', i), 100)
}

for (let i = 0; i < 10; i++) {
  setTimeout(() => console.log('let: ', i), 100)
}


text:
Q: Is it possible to alert returned xml data from ajax call I am trying to at least alert the data that is being returned as xml from this ajax request. Any ideas on how to accomplish? So its pulling the data from a url not an actual xml list, but it is being converted to xml. Also, is it possible for me to alert a specific node if I can get the data to alert?
function getData(){
    $.ajax({
        url: searchData.SiteUrl + "/_vti_bin/lists.asmx",
        type: "POST",
        dataType: "xml",
        data: soapEnv,
        complete: processResult,
        contentType: "text/xml; charset=\"utf-8\""
    });
}

A: function getData(){
    $.ajax({
        url: searchData.SiteUrl + "/_vti_bin/lists.asmx",
        type: "POST",
        dataType: "xml",
        data: soapEnv,
        complete: processResult,
        contentType: "text/xml; charset=\"utf-8\"",

success:function(response){
     alert (response.responseText);
},

error:function(response){
     alert (response.responseText);

},
    });
}

Try adding the success and error fields to your ajax call.
Per hina10531's suggestion, use this to alert the text held in the foo node:
alert ($(response).find ('foo').text ());

A: I figured out a solution!
    alert(xData.responseXML);
    console.log(xData.responseText);


text:
Q: .htaccess laravel remove public and redirect to https I am using shared hosting.
so I need to use .htaccess to public and i want public to be not shown.
I could do this far but i want to redirect from http to https.
Could you help me to do this?
RewriteEngine on
RewriteRule ^/?$ /public/ [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(.*) /public/$1 [L]

I want to redirect from http to https.
Thanks

A: You should do it by making a symbolic link between your public folder of the laravel project and the public_html folder in your server.
For example:
ln -s ~/nameOfProject/public public_html
You will need ofcourse SSH access to do it.

A: You can do that simply by adding new rewrite rule into your .htaccess
RewriteRule ^(.*)$ https://yourdomain.com$1 [R=301,L]

A: While creating virutal host, point your directory to /path_to_root/public. In this way, you will run site using public and "public" folder will not show in URL.
Redirecting will work as per normal htaccess rules.

A: After a lot of struggle with the exact issue (I've tried many suggestions, but they either didn't force https or caused an infinite redirect loop) I've put together this solution:
put the code in .htacces in your laravel root directory:
RewriteEngine On

# enforce https
RewriteCond %{ENV:HTTPS} !on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=302]

# use public directory as root, but don't show in url
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(.*)$ /public/$1 [L,QSA]


text:
Q: Is this router ok? I administer a small business of around 20 people. They are wanting to get some faster internet to get the youtube and the torrents. I was looking at buying a CRS-3 from cisco. Does anyone here have experience with these? They look like good value.

A: Unless your router is 15 years old, upgrading your router is unlikely to get you faster internet. If your aim is faster internet, you need to upgrade your internet connection first. For 20 people, any router that your ISP can provide should be fine.


text:
Q: Move(style) marker using attribute on referencing element Let say I have a following marker (I want to have only one marker element in dom):
<marker id="arrow" viewBox="0 -5 10 10" refX="22.5" refY="0" markerWidth="20" markerHeight="20" orient="auto"><path d="M0,-5L10,0L0,5" fill="#000000"></path></marker>

And I'm using it with line to draw arrow on it:
<line stroke="black" stroke-width="0.5" x1="1190.5337908659556" y1="814.1321248143822" x2="1183.09985813189" y2="-58.79906521075237" marker-end="url(#arrow)" display="inline"></line>
<line stroke="black" stroke-width="0.5" x1="797.4477436706952" y1="325.5996932062993" x2="877.7838866381225" y2="631.7793113188723" marker-end="url(#arrow)" display="inline"></line>

Is there a way to move arrow along the line by using some attribute on line element referencing the marker?

A: You would need to animate the end point of the line that the marker is applied to.
In the example below, I have added a second line. Then we animate the x2 and y2 attributes from the start of that line to the end.  So it starts with zero length and end up the same as the original line.

<svg viewBox="600 300 600 400">
  <defs>
    <marker id="arrow" viewBox="0 -5 10 10" refX="10" refY="0" markerWidth="20" markerHeight="20" orient="auto"><path d="M0,-5L10,0L0,5" fill="#000000"></path></marker>
  </defs>

  <!-- original path -->
  <line stroke="black" stroke-width="0.5" x1="797.4477436706952" y1="325.5996932062993" x2="877.7838866381225" y2="631.7793113188723"/>

  <!-- original path -->
  <line stroke="none" stroke-width="0.5" x1="797.44" y1="325.59" x2="797.44" y2="325.59" marker-end="url(#arrow)">

     <animate attributeName="x2" from="797.44" to="877.78" dur="2s" fill="freeze"/>
     <animate attributeName="y2" from="325.59" to="631.77" dur="2s" fill="freeze"/>
  </line>
</svg>

A: This doesn't appear to be possible with CSS. From the spec:

The 'display' property does not apply to the 'marker' element

Markers are not directly rendered, so none of the usual methods for moving an element with CSS (transform/translate, positioning, margins, etc) are applicable to them.
To animate a marker, I think you'll need to use JS to animate the refX and refY values on it directly. Something like Anime can help with that.


text:
Q: Expansion `$` come with `*` and `@` I am learning bash expansion.
There are three types of expansions binding with $

*

*Parameter Expansion

*Command Substitution

*Arithmetic Expansion.

I experiment on special symbol $.
    $ ls
    foo bar zoo
    $ echo $*
    #return nothing
    $ echo $@*
    foo bar zoo

What's going on with @ and $
Additionally,
    $ ls $
    ls: $: No such file or directory
    $ ls $*
    foo bar zoo
    $ ls $a  #or any character
    foo bar zoo

I am confused about the mutablility of $.
How to interpret its behaviors above.

A: some examples:
#!/bin/bash

a_function(){

    echo "positional parameters must be called in a script or a function"
    echo "positional parameters: $@"
    echo "positional parameters: $*"
    echo "directory's content:" *
}

a_function "one" "two" "three" "pan"

output:
positional parameters must be called in a script or a function
positional parameters: one two three pan
positional parameters: one two three pan
content of directory: <your current directory>

ps:

*

*ls $a ls variable a (empty), so simple ls

*ls $* ls positional parameters (empty), so simple ls

*echo $@* display $@ (empty) and directory"

*ls: $, error $ alone

more infos: doc bash


text:
Q: VBA having column name and value down the left of the worksheet rather than have all my column names across the top of the worksheet, I'm looking to have them down the left hand side eg in Column A. The value of that will then be in Column B.
I have used a record set which loops through and pulls the first column correctly, but I need 30 more columns to do the same with the values.
My code:
' Run the query and store the retrieved data in the recordset
Set adoRecordset = adoCommand.Execute
' Set to the first empty row
intRow = 10
' Loop through the recordset
Do While Not adoRecordset.EOF
    For rs = 0 To adoRecordset.Fields.Count - 1

        With shtData

                With .Cells(intRow, intCol + 1)

                ' Write the data to the cells
                .Cells(intRow, intCol + 1).Value = adoRecordset.Fields(intCol).Name
                .Cells(intRow, intCol + 2).Value = adoRecordset.Fields(intCol).Value

                End With

        End With
    ' Go to the next column in the record
    Next rs
    'Next intRow

    ' Go to the next row
    intRow = intRow + 1
    ' Move to the next record in the recordset
    adoRecordset.MoveNext
Loop
' Reset the recordset
Set adoRecordset = Nothing
' Reset the command
Set adoCommand = Nothing
' Closet and reset the connection
adoConnection.Close
Set adoConnection = Nothing


text:
Q: Advantages of popup over panels in Windows Phone I'm curious about Popup control in Windows Phone. For me, it's some kind of panel, that has IsOpen property. And I should used it, when i want to present some only in some defined context (e.g. button pressed).
But why not use just normal stack, or grid panel, and when use Visiblity when you want to hide, or show it?  It's seems to behave the same.

A: You can change the Horizontal and Vertical position of the popup using the HorizontalOffset /VerticalOffset properties in the Popup control. We don't have that option in the Grid and to other panels.

A: It is an overlay. It doesn't break page layout as it shows above the main content.
While StackPanel or Grid should be added to main content and when they are shown they'll move other controls down.


text:
Q: how are deleted files stored in recycle bin since we are able to recover them later I am guessing some information about the files will he stored but having entire files stored untill recycle bin is emptied seems a brute effort.
so what information of deleted files are stored and does it requires main memory?
suppose in my htc smartphone with 8gb capacity  I have deleted some 5gb data and not emptied the recycle bin next I use store some new data so will I have all the space available and if i pack my phone with about 8gb data and later wish to recover the previously deleted 5gb data, given I make space for it by deleting currently stored data.

A: When you a delete a file, it is not erased/deleted permenently from the drive unless we clean by emptying the recycle bin
Operating Systems keep track of where files are on a hard drive using "pointers." Each and every file/folder on the hard disk has a pointer that specifies where the file's data begins and ends.So when we delete a file, Operating System removes the pointer and marks the sectors containing the file's data as available in other words free memory . From the file system's point of view, the file is no longer present on your hard drive.
So untill we write new data to the sectors ,the deleted data will still remain in that sector.
A file recovery program can scan a hard drive for these deleted files and restore them.IF a portion of the entire file has been overwritten, then the file cannot be recovered completely.


text:
Q: USB hub not working at -40degC I have a TUSB8041I industrial rated USB hub which is expected to work at -40 to +85degC.
I have tried everything I could.
Power sequence, reset sequence, oscillator startup OK.
It happens on 1 out of 10 boards, and happens only at -40 to -30 side. It works at room temperature, no problem.
Any ideas?

A: I agree with @TimW, first item of suspicion is the oscillator. Especially if it works at -40°C but will not start up after soaking.
The selected crystal's ESR meets the minimum requirements, but the load capacitances are a bit on the light side. The crystal calls for 12pF load, so about 22pF would be closer.
Replacing it with a packaged oscillator or a resonator (not sure a typical resonator would be acceptable accuracy-wise) would likely improve things.

If it's not the oscillator then it's probably inside the chip and nothing  you can do except talk to the manufacturer. Typically they don't actually test the chips over the whole temperature range, of course, but depend on parameters they can measure cheaply/quickly to assure it will work over the specified range.


text:
Q: How do I find out what's linked to my Excel Worksheet? I've got an Excel 2007 worksheet that I inherited, and each time it opens, I get the dialog box asking if I would like to update values from an outside, linked worksheet. I'm trying to track down if I should be saying yes or no; as I'm not familiar with the linked spreadsheet, nor what types of data it creates, nor if it's even in use and updated regularly.
Is there a way I can get a list of worksheets, paths, and linked cells so I can trace the formulae and see which links can be severed?
d

A: These directions are for Excel 2010 (but if memory serves, Excel 2007 ribbon is the same in this area).

*

*Go to Data Tab.

*Choose Connections, this will open the Workbook Connections dialog.

*In Workbook Connections dialog box it will list all of your connections.

*Select the Connection in question and then click in the area below to see where it's used.

From there you'll also be able to check properties, add or delete connections.  It's a pretty handy place to visit if your worksheet has external data connected.

A: One possible way is to use Ctrl+` (the backwards apostrophe on the ~ key).  This will show all formulas in the cells, instead of just in the formula bar.  Plain data will remain untouched, but any formulas that update remotely should be pretty obvious.  Press the key sequence again to toggle back to normal viewing.

A: In Excel from Office 365 you can click on Data tab and then on "Queries & Connections", it will show the connections you're using on your current workbook.

A: Go to the Data tab, click on Edit Links and you should see a list of source files in which your file is pulling data from (or linked from).


text:
Q: google maps are showing wrong and incomplete directions Sometimes getFromlocationName() method returns null and sometimes it gives values but path which is drawn is not correct. what may be the reason for this? kindly solve the problem ,Thank you.
below is code
 if((place1 != null) || (!place1.equals(" "))&& ((place2!=null)||(!place2.equals(" "))))
                {

                    Geocoder geocoder = new Geocoder(MapsActivity.this);
                    try {
                               Boolean check=geocoder.isPresent();
                        Log.d("check:"," "+check);
                               addressList1 = geocoder.getFromLocationName(place1, 1);
                               addressList2 = geocoder.getFromLocationName(place2, 1);

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    Log.d("ADDRESS","address obj:"+addressList1+","+addressList2);
                    Address address1 = addressList1.get(0);
                    Address address2 = addressList2.get(0);
                    origin = new LatLng(address1.getLatitude(),address1.getLongitude());
                    destination = new LatLng(address1.getLatitude(),address2.getLongitude());
                    Log.d("LATLANG","LatLang:"+origin+","+destination);
      build_retrofit_and_get_response(mode);

                }
            }

     public void build_retrofit_and_get_response(String type) {
          Toast.makeText(this,"retrofit method called"+origin+destination,Toast.LENGTH_LONG).show();
            String url = "https://maps.googleapis.com/maps/";

            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(url)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

            RetrofitMaps service = retrofit.create(RetrofitMaps.class);

            Call<Example> call = service.getDistanceDuration("metric", origin.latitude + "," + origin.longitude,destination.latitude + "," + destination.longitude, type);

            call.enqueue(new Callback<Example>() {
                @Override
                public void onResponse(Response<Example> response, Retrofit retrofit) {

                    try {
                        //Remove previous line from map
                        if (line != null) {
                            line.remove();
                        }
                        // This loop will go through all the results and add marker on each location.
                        for (int i = 0; i < response.body().getRoutes().size(); i++) {
                            String distance = response.body().getRoutes().get(i).getLegs().get(i).getDistance().getText();
                            String time = response.body().getRoutes().get(i).getLegs().get(i).getDuration().getText();
                            ShowDistanceDuration.setText("Distance:" + distance + ", Duration:" + time);
                            String encodedString = response.body().getRoutes().get(0).getOverviewPolyline().getPoints();
                            List<LatLng> list = decodePoly(encodedString);
                            line = mMap.addPolyline(new PolylineOptions()
                                    .addAll(list)
                                    .width(10)
                                    .color(Color.RED)
                                    .geodesic(true)
                            );
                        }
                    } catch (Exception e) {
                        Log.d("onResponse", "There is an error");
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Throwable t) {
                    Log.d("onFailure", t.toString());
                }
            });

        }

        private List<LatLng> decodePoly(String encoded) {
            List<LatLng> poly = new ArrayList<LatLng>();
            int index = 0, len = encoded.length();
            int lat = 0, lng = 0;

            while (index < len) {
                int b, shift = 0, result = 0;
                do {
                    b = encoded.charAt(index++) - 63;
                    result |= (b & 0x1f) << shift;
                    shift += 5;
                } while (b >= 0x20);
                int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
                lat += dlat;

                shift = 0;
                result = 0;
                do {
                    b = encoded.charAt(index++) - 63;
                    result |= (b & 0x1f) << shift;
                    shift += 5;
                } while (b >= 0x20);
                int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
                lng += dlng;

                LatLng p = new LatLng( (((double) lat / 1E5)),
                        (((double) lng / 1E5) ));
                poly.add(p);
            }

            return poly;
        }

A: it was beacase i was taking wrong coordinates:
  origin = new LatLng(address1.getLatitude(),address1.getLongitude());
  destination = new LatLng(address1.getLatitude(),address2.getLongitude());

correct code is:
  origin = new LatLng(address1.getLatitude(),address1.getLongitude());
  destination = new LatLng(address2.getLatitude(),address2.getLongitude());

but getting null values from getfromlocationName() of geocoder why??


text:
Q: Multiply two columns in two tables with linq to sql I need this this sql query in c# :
Select cv.manv, cv.luong1h*ct.sogiolam
From congviec cv
inner join chitiet ct on cv.manv=ct.manv

How can I do it with LINQ to sql?

A: from cv in congviec
join ct in chitiet on cv.manv equals ct.manv
select new { cv.manv, cv.luong1h*ct.sogiolam}

sorry my bad, see this edit for working solution
var list = (from cv in congviec
    join ct in chitiet on cv.manv equals ct.manv
    select new { cv.manv, Multiply = cv.luong1h*ct.sogiolam}).toList();

A: It would look almost the same in Linq
var ExampleVariable = (from cv in congviec
                         inner join ct chitiet
                         on cv.manv equals ct.manv
                         select new {
                                cv.manv,
                                //cv.luong1h*ct.sogiolam
                                Product =  cv.luong1h*ct.sogiolam
                                }).ToList();

And using lambda expression, refer this link.
Hope this helps.


text:
Q: My swimming pool would hold 20,000 gallons of water Forgive me for asking numerous questions about "would" on and on.╮(╯-╰)╭Somehow I hate this word and also love it.

13 — used to say that something is possible or likely
▪ I think my swimming pool would [=could] hold 20,000 gallons of water. Source

Is Merriam correct about this usage?
I would think that in this case "would" is more certain than "could", am I right?
And I invent two scenarios here:

*

*A friend of mine ask me, "What size is your pool?" (asking about capacity of the pool). I point to my empty pool and say, "I think my swimming pool would hold 20,000 gallons of water."

*A friend of mine ask me, "How much water is your pool containing now?" (asking about the fact of the amount of water). I point to my full pool and say, "I think my swimming pool would hold 20,000 gallons of water."
Will both of my answer match their respective context and aptly deliver the intended meaning?

A: The first scenario is correct, and would, as you say, sounds more certain.
The second scenario does not sound correct. Saying that the pool would hold 20,000 gallons of water implies that it is not currently holding 20,000 gallons of water.
"I think that my swimming pool has 20,000 gallons of water in it," or "I think that my swimming pool is holding 20,000 gallons of water," are correct.

A: The main thing is you are confused between would and could. As a non-native speaker, I certainly understand you. Whilst others may come up with detail answer using grammar jargon, I'll try to make it short and simple for people like us.
In general cases, would - is a past tense of 'will' and talks about 'probability'. On the other hand, if you use could it talks more about the 'capability'.
So, if you say, your pool would hold it refers to the probability showing your guess that the pool is likely to hold that amount of water. And, if you say your pool could hold, it'll talk about the capacity of the pool to occupy that much water. The dictionary just clarifies that sometimes, would is equal to could as in that case. It won't make a great difference unless you have a grammarian's eye!
Is Merriam correct? Well, I'm too little to justify it!

A: I personally think that case 13 is a bit of an over-reach - this is really just another example of case 2.  The nuance of possible or likely derives from I think rather than would (Try substituting I'm certain in the sentence and then consider whether there remains any sense of possible or likely).
The examples provided in your two scenarios are both idiomatically correct, however I believe the subtext of the second option is subtly different - it actually has the meaning "I think my swimming pool would hold 20,000 gallons of water [if it were measured]." and thus reverts to an example of case 2 again.


text:
Q: Python Shodan API - Can't search with filters When I try to use the Shodan API in Python to search for certain filters, I only get errors. When I search for words as an Example, I do not get these errors. My Python Code:
import sys
import shodan

SHODAN_API_KEY = "xxxxxxxxxxxxxxxxxx"
try:
    api = shodan.Shodan(SHODAN_API_KEY)
    results = api.search("port:21")
    print results["total"]
    for result in results["matches"]:
        print result["ip_str"]+"\n"
except Exception as e:
    print("Code: {c}, Message: {m}".format(c=type(e).__name__, m = str(e)))

So were is the actual error? I have a free Shodan account and when I search for "port:21" on the Website I get results. When I do it in the script, I get an error.
Also I'd like to know if it is possible to go through the whole database and getting more than 100 results. I thought about using CIDR (e.g. 1.1.1.1/27)to only search a special range under 100 and do it over and over again. But is this even possible? Or are there more efficient ways doing it?


text:
Q: magento coupon code new rule function not working error image here: http://s17.postimg.org/d1860kfnj/Screenshot_at_2015_12_28_20_22_49.png
So When I go to add a coupon, the navigation bar has unclickable links and I do not get the form for adding a new rule. I've tried everything I can to enable errors but I'm not getting anything. Please help.

A: go to this location  : app/design/adminhtml/default/default/layout/promo.xml
and check for :
<adminhtml_promo_catalog_edit>
    <reference name="head">
        <action method="setCanLoadExtJs"><flag>1</flag></action>
        <action method="setCanLoadRulesJs"><flag>1</flag></action>
    </reference>
    <reference name="left">
        <block type="adminhtml/promo_catalog_edit_tabs" name="promo_catalog_edit_tabs">
            <block type="adminhtml/promo_catalog_edit_tab_main" name="promo_catalog_edit_tab_main"/>
            <block type="adminhtml/promo_catalog_edit_tab_conditions" name="promo_catalog_edit_tab_conditions"/>
            <block type="adminhtml/promo_catalog_edit_tab_actions" name="promo_catalog_edit_tab_actions"/>
            <action method="addTab"><name>main_section</name><block>promo_catalog_edit_tab_main</block></action>
            <action method="addTab"><name>conditions_section</name><block>promo_catalog_edit_tab_conditions</block></action>
            <action method="addTab"><name>actions_section</name><block>promo_catalog_edit_tab_actions</block></action>
        </block>
    </reference>
    <reference name="content">
        <block type="adminhtml/promo_catalog_edit" name="promo_catalog_edit"/>
    </reference>
    <reference name="js">
        <block type="adminhtml/promo_catalog_edit_js" template="promo/js.phtml" />
    </reference>
</adminhtml_promo_catalog_edit>

is it damaged or not
if not there go to this Block file : adminhtml/promo_catalog_edit
and check it render the layout perfectly
if still not work then let me know i can help you more on this


text:
Q: Alternative to "mostly legacy" ref String Attribute? I was a bit surprised when I read the updated React docs about refs. While their examples on the React front page still use this.refs.textarea, they later "recommend" to not use this approach anymore.
But what's the alternative? I find too long inline code confusing and calling a function instead, like {() => this.initChartLibrary() } (the () => is required to not lose context to this) requires to build a method that gives the wrong impression of that it can be reused.
In other words, I'd still like to use the String way. But since I fear they'll deprecate it, I was wondering, if there are any other approaches?

A: As far as I'm aware the main alternative to ref strings is in fact the ES6 style callback function.
So:
<textarea ref="myTextArea">
...
</textarea>

// Where refs are then accessed by `this.refs.myTextArea` to perform any operations

Becomes, in a basic form:
<textarea ref={ (ref) => this.myTextArea = ref }>
...
</textarea>

// Where refs are then accessed by `this.myTextArea`

This can be pretty powerful because the ref attribute in React automatically receives the referenced component as a parameter, which allows us to immediately implement our callback operations on it if we'd like. This can be used in a simple form, as above, to assign that reference to this.myTextArea, or as you've probably noticed in the docs, you can be a bit more direct and do things like:
<input
  ref = {(input) =>
          { if (input != null) {input.focus()} }
  } />

That being said, although this sometimes means you can express your code in the fewest number of lines, it definitely sacrifices readability. If you are just looking to save a reference to the component for use in an event handler (as is very commonly the case) using a ref string is honestly still the cleanest way to do so.
I really wouldn't anticipate them to be deprecated without warning, as they are used pretty heavily in React & remain convenient, but if they ever are your best bet would be a straightforward refactor with a simple (ref) => this.myRef = ref then accessing your refs by this.myRef.


text:
Q: Pandas/Pytable memory overhead when writing to hdf I use pandas and hdf5 files in order to handle big amounts of data (e.g. 10GB and more). I would like to use the table format in order to be able to query the data efficiently when reading it. However, when I want to write my data to an hdf store (using DataFrame.to_hdf()), it has a enormous memory overhead. Consider the following example:
import pandas as pd
import numpy as np
from random import sample

nrows   = 1000000
ncols   = 500

# create a big dataframe
df = pd.DataFrame(np.random.rand(nrows,ncols))

# 1) Desired table format: uses huge memory overhead
df.to_hdf('test.hdf', 'random', format='table') # use lots of additional memory

# 2) Fixed format,  uses no additional memory
df.to_hdf('test2.hdf', 'random')

When I make df.info() I see that the storage have a size of 3.7GB. When executing version one, with the table format, the memory usage of my system suddenly goes up with approximately 8.5GB, which is more than twice the size of my DataFrame. On the other had, for version two with the fixed format there is no additional memory overhead.
Does anyone know what the issue is or how I can prevent this enormous memory overhead? If I have larger dataframes of around 10GB I always run out of memory because of this overhead.
I know that in therms of speed and other stuff that the performance of the table format is not that great, but I don't see why it should use so much additional memory (this is enough for more than 2 full copies of the dataframe).
It would be great if anoyone have an explanation and/or a solution to this problem.
Thanks,
Markus

A: In <= 0.15.2
In [1]: df = pd.DataFrame(np.random.rand(1000000,500))
df.info()

In [2]: df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1000000 entries, 0 to 999999
Columns: 500 entries, 0 to 499
dtypes: float64(500)
memory usage: 3.7 GB
In [3]: %memit -r 1 df.to_hdf('test.h5','df',format='table',mode='w')
peak memory: 11029.49 MiB, increment: 7130.57 MiB

There is an inefficiency in <= 0.15.2 that ends up copying data 1-2 times. You can do this as a work-around until 0.16.0 (where this is fixed)
In [9]: %cpaste
def f(df):
  g = df.groupby(np.arange(len(df))/10000)
  store = pd.HDFStore('test.h5',mode='w')
  for _, grp in g:
    store.append('df',grp, index=False)
  store.get_storer('df').create_index()

In [11]: %memit -r 1 f(df)
peak memory: 7977.26 MiB, increment: 4079.32 MiB

In 0.16.0 (coming 3rd week of March 2015), after this PR
In [2]: %memit -r 1 df.to_hdf('test.h5','df',format='table',mode='w')
peak memory: 4669.21 MiB, increment: 794.57 MiB


text:
Q: Trinomial Summation Equation I was looking at how to find trinomial coefficients with code and I was puzzled with this equation.
$$\binom n k _2 = \binom{n}{-k}_2$$
I know that (nCk) represents n choose k but what does the 2 at the bottom right do compared to binomial?


text:
Q: An existing connection was forcibly closed by the remote host web api I created a web api using c#, but when I pushed the code in production, users are getting the following error

An existing connection was forcibly closed by the remote host

when I debug with all possibilities, I find that my Route contains something like this
[Route("{string}/{int=-1}/{int2=-1}")]

but when I debug, I am not getting the error in localhost,
what might be the issue here?

A: try to use wireshark to see what the exact issue and why is it persisting.
basically, it means that the remote side closed the connection (most commonly happens during TCP/IP RST packet) and the reason can vary:

*

*You are sending malformed data to the application

*The network link between the client and server is going down for some reason

*You have triggered a bug in the third-party application that caused it to crash

*The third-party application has exhausted system resources

If you said that when you debug everything is working, I'd recommend using the wireshark first, outside of debug mode, before taking any action in order to estimate the cause for the issue and possible solution in order to solve it.


text:
Q: Downloading iFramePlayer Video I want to download a video available here. Like the top right corner indicates, it might be hosted on Crunchyroll so let's inspect the page source.
This is the html code snippet of interest:

Inspection reveals that the video is embedded in an iframe and indeed is hosted on Crunchyroll. It is also important to note that the src attribute is the link going directly to the video player page.
On the player page the HTML looks as follows:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
    <link rel="icon" href="/favicon.png" />
    <title></title>

    <link rel="stylesheet" type="text/css" href="https://www.crunchyroll.com/css//20150727144515.1ae5987b9d8aa2552cc16fb8eadc8e78/crcommon/reset.css"/>

You either have Javascript turned off or an old version of Flash Player.

  Get the latest Flash Player

It becomes clear that the video must be a swf flash video file. embedSWF is called which is defined here and looks like this (after beautifying):
embedSWF: function(ab, ah, ae, ag, Y, aa, Z, ad, af, ac) {
    var X = {
        success: false,
        id: ah
    };
    if (M.w3 && !(M.wk && M.wk < 312) && ab && ah && ae && ag && Y) {
        w(ah, false);
        K(function() {
            ae += "";
            ag += "";
            var aj = {};
            if (af && typeof af === r) {
                for (var al in af) {
                    aj[al] = af[al]
                }
            }
            aj.data = ab;
            aj.width = ae;
            aj.height = ag;
            var am = {};
            if (ad && typeof ad === r) {
                for (var ak in ad) {
                    am[ak] = ad[ak]
                }
            }
            if (Z && typeof Z === r) {
                for (var ai in Z) {
                    if (typeof am.flashvars != D) {
                        am.flashvars += "&" + ai + "=" + Z[ai]
                    } else {
                        am.flashvars = ai + "=" + Z[ai]
                    }
                }
            }
            if (F(Y)) {
                var an = u(aj, am, ah);
                if (aj.id == ah) {
                    w(ah, true)
                }
                X.success = true;
                X.ref = an
            } else {
                if (aa && A()) {
                    aj.data = aa;
                    P(aj, am, ah, ac);
                    return
                } else {
                    w(ah, true)
                }
            }
            if (ac) {
                ac(X)
            }
        })
    } else {
        if (ac) {
            ac(X)
        }
    }
}

This obfuscated code doesn't look like it's going to lead anywhere.
Copying and pasting each of the links found in the html into the browser doesn't seem to allow downloading the video (idea taken from here). How do I get the correct url?
Note:
The programming code for downloading the video file is not the main focus here, but I would use this for html parsing and this for download the file.


text:
Q: Copy data from 1 DB to another DB I have to delete some table data in prod. db and for the records that are going to be deleted a backup of records should be copied to another local db.  This involves two databases, residing in two different servers/instances.
Is it possible to do via sql (mysql) query to do this?

A: I would use mysqldump with a where condition to get the records out. Once you have everything saved, you can then delete them from prod. These commands should work from the command line, including the password to avoid the prompt is optional.
mysqldump -u user -pPassword -h hostname1 dbname tablename
    --where 'field1="delete"'
    --skip-add-drop-table --no-create-db --no-create-info > deleted.sql
mysql -u user -pPassword -h hostname2 dbname < deleted.sql
mysql -u user -pPassword -h hostname1 dbname -e 'DELETE FROM tablename WHERE field1="delete"'

A: I'm trying to do exactly the same thing, copy data from a table to another server, then delete it from the original.
So far I see two options:

*

*copy data to a local database then replicate that database to another server

*use Federated storage engine

Both require some serious reconfiguration of our servers as neither Federated or binary logging (required for replication) are not enabled. This would take time and it would be best if other solutions could be found.
The process needs to be executed on a daily basis, so it needs to be fully automated.
Perhaps a third option is to automate things with a cron job:

*

*copy the data to a separate database on the same server

*backup that database with mysqldump in a folder which is linked on the other server too

*on the second server, restore the database from the sql dump


text:
Q: Converter Timestamp to Date I am getting this timestamp (161128185939) from a legacy black box system. When trying to convert to date in java I'm getting 2/8/1975, but the correct one would be 2/8/2017. How to solve problem?
Timestamp timeStamp = new Timestamp(161128185939L);
Date date = new Date(timeStamp.getTime());

Output: 1975-02-08
UPDATE:
It was sad to have discovered this, but due to the lack of documentation unfortunately happened. In fact this sequence is the date in the format yyMMddHHmmss which does not yet represent 2/8/2017 but instead 11/28/2016. Apologies for the inconvenience.

A: 161128185939L is not the correct time of your date 2/8/2017 you can get the time using this :
DateFormat format = new SimpleDateFormat("yyyy/MM/dd");
Date date = format.parse("2017/8/2");
System.out.println(date.getTime());

This will show you 1501628400000, so this is the correct time of your date, you can use this instead :
Timestamp timeStamp = new Timestamp(1501628400000L);
Date date = new Date(timeStamp.getTime());


text:
Q: Custom Message Headers support when using functional bean definitons I am unable to extract custom Message headers in a Function<Message,?> when using functional bean definitions for Spring cloud function.
Is there any way to extract the user defined Messsage headers that were passed in the request ?
@SpringBootConfiguration
public class Demo implements Function<Message<String>,String> {

    public static void main(String[] args) {
        FunctionalSpringApplication.run(Demo.class,args);

    }
    @Override
    public String apply(Message<String> stringMessage) {
        final MessageHeaders headers = stringMessage.getHeaders();
        headers.entrySet().forEach(System.out::println);
        return stringMessage.getPayload().toUpperCase();
    }
}

Only 3 fixed headers are passed everytime

*

*scf-func-name

*id

*timestamp

However, any custom headers that are passed in the request are not available in the message headers.


text:
Q: I accidentally deleted the home directory on my Amazon Linux EC2. My whole site disappeared. What now? I was using sudo rm -rf to delete some folders, and accidentally deleted the /Users/ec2-user home directory. I had my EC2 and AWS Route 53 running my site. Now, it just disappeared. I have all the files for my website, but don't know how to get it back up and running well. It just says "No Data Received" if I visit my website. Help!

A: If you have taken an AMI of your instance or an EBS snapshot, you can launch a new instance from it. Otherwise, if you have all your important files somewhere else, you can launch a fresh stock instance and redo the setup you did originally. Then just reassign the Elastic IP of the old instance to the new instance, and terminate the old one.


text:
Q: Binary Search or Insertion Sort with list view [Visual Basic .net] Recently when creating a program for my client as part of my computing project in visual basic .net I've came across a problem, which looks like following; In order to receive additional marks for my program I must take an advantage of either Binary Search or Insertion Sort subroutine declared recursively, so far the only place I can use it on is my View form which displays all reports generated by program but the problem with this is since I'm using MS Access to store my data all of the data is downloaded and placed in listview in load part of form. So the only way I can use it is by running it on listview which is a major problem for me due to the fact that I'm not very experienced in vb.
For binary search I have tried downloading all of the items in specified by user column into an array but that's the bit I was struggling on the most because I'm unable to download all items from only one column into an array. Also instead of searching every single column user specifies in my form in which column item is located (For example "19/02/2013" In Column "Date"), In my opinion if I manage to download every single entry in specified column into an array it should allow me to run binary search later on therefore completing the algorithm. Here's what I've got so far.
    Sub BinarySearch(ByVal Key As String, ByVal lowindex As String, ByVal highindex As String, ByVal temp() As String)
    Dim midpoint As Integer

    If lowindex > highindex Then
        MsgBox("Search Failed")
    Else
        midpoint = (highindex + lowindex) / 2
        If temp(midpoint) = Key Then
            MsgBox("found at location " & midpoint)
        ElseIf Key < temp(midpoint) Then
            Call BinarySearch(Key, lowindex, midpoint, temp)
        ElseIf Key > temp(midpoint) Then
            Call BinarySearch(Key, midpoint, highindex, temp)
        End If
    End If
End Sub

Private Sub btnSearch_Click(sender As System.Object, e As System.EventArgs) Handles btnSearch.Click
    Dim Key As String = txtSearch.Text
    Dim TargetColumn As String = Me.lstOutput.Columns(cmbColumns.Text).Index
    Dim lowindex As Integer = 0
    Dim highindex As Integer = lstOutput.Items.Count - 1
    'Somehow all of the items in Target column must be placed in temp array
    Dim temp(Me.lstOutput.Items.Count - 1) As String

    ' BinarySearch(Key, lowindex, highindex, temp)
End Sub

For Insertion sort i don't even have a clue how to start, and the thing is that I have to use my own subroutine instead of calling system libraries which will do it for me.
Code which I have to use looks like following:
Private Sub InsertionSort()
Dim First As Integer = 1
Dim Last As Integer = Me.lstOutput.
Dim CurrentPtr, CurrentValue, Ptr As Integer
For CurrentPtr = First + 1 To Last
CurrentValue = A(CurrentPtr)
Ptr = CurrentPtr - 1
While A(Ptr) > CurrentValue And Ptr > 0
A(Ptr + 1) = A(Ptr)
Ptr -= 1
End While
A(Ptr + 1) = CurrentValue
Next
Timer1.Enabled = False
lblTime.Text = tick.ToString
End Sub

Any ideas on how to implement this code will be very appreciated, and please keep in my mind that I'm not very experienced in this language

A: Perhaps this might give you a place to begin. If you already have a ListView with "stuff" in it you could add a button to the form with the following code to copy the Text property for each item into an array:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim myArray(Me.ListView1.Items.Count - 1) As String
    Dim i As Integer

    ' load array
    For i = 0 To Me.ListView1.Items.Count - 1
        myArray(i) = Me.ListView1.Items(i).Text
    Next

    ' show the results
    Dim s As String = ""
    For i = 0 To UBound(myArray)
        s &= String.Format("myArray({0}): {1}", i, myArray(i)) & vbCrLf
    Next
    MsgBox(s, MsgBoxStyle.Information, "myArray Contents")

    ' now go ahead and manipulate the array as needed
    ' ...
End Sub


text:
Q: Mongomapper throwing error message multiple times I have a simple Model - Shop in my Ruby/MongoMapper application.
I have no idea why sometimes I only get one error message, and sometimes I get three error messages like this one:
'Validation failed: User has already been taken, User has already been taken, User has already been taken'
Yes, I am adding the same user_id multiple times, on purpose.
Here is my code:
class Shop
  include MongoMapper::Document
  key :user_id, String, :required => true, :unique => true

  def self.add
    begin
      ut = Shop.new
      ut.user_id = '11'
      ut.save!
      ut = nil
    rescue Exception => e
      puts e.message
    end
  end
end

Result:
# 'Validation failed: User has already been taken, User has already been taken, User has already been taken'

UPDATE:
Seems like removing the
ut = nil

fixes the 'problem'. But why...


text:
Q: Python: How to use collections? [problem] Problem Statement:
Commonwealth games are here, and Peter Quill, the head of the fixtures department is a big problem. Given a list of countries which are going to participate in the games, he has to create two pools for the games, with each country in either of the two pools. However, due to increasing cases of corruption and collusion between countries in games, there is a new rule this time. No two countries sharing a geographical border will be kept in the same pool, to maintain fair play and diversity. Can you help Peter decide whether two pools can be created as per the rules or not, for a given set of countries?
Input format:
The first line contains two space separated integers n (number of countries) and m (number of pair of countries sharing a geographical border).  Next m lines contain two space separated integers from 1 to n representing two countries which share their geographical borders.
Output format:
If two pools can be created, 'yes', otherwise 'no'
Example:
Input:
5 5
1 2
1 3
2 4
3 4
4 5

Output:
yes

Explanation:
From the given inputs, it is clear that
1 has 2,3 as neighbors.
2 has 1,4 as neighbors.
3 has 1,4 as neighbors.
4 has 2,3,5 as neighbors.
5 has 4 as a neighbor.
By little observation, it is clear that two pools can be formed i.e (1,4) and (2,3,5).

I've tried from this problem to get the inputs the n and m, and the other lines inside a list, each one as a indepedent list. This is the result so far but i dont know how to do the comparison between the lists and neighbors.
I just need the idea of reasoning, not the code solved.
n, m = [int(x) for x in input().split()]
countries=[]
neighbors=[]
for i in range (m):
    countries.append([int(x) for x in input().split()])
print (countries)

>>[[1, 2], [1, 3], [2, 4], [3, 4], [4, 5]]

A: Supposing that your input is a text file, you can read it with:
m = []
with open('input.txt', 'r') as file:
    nm = list(map(int, file.readline().split()))
    for row in file:
        m.append([int(i) for i in row.split()])

In the easiest of the scenarios, if the number of countries is bigger than the number of countries with neighbors, then logically you can make two pools, since at least one of them will surely be able to fit a pool alone:
if nm[0] > nm[1]:
    output = 'yes'

If it's not the case (it's not the case for your example), we'll need to manage m. Surely there're multiple ways to get this task done, but I'll go by creating a dictionary with country-neighbors as key-values, filling up the pools with target-countries if there're not neighbors in that list. If we can fill up all countries to either of the pool lists, output is 'yes', otherwise is 'no':
# Get unique countries (we'll use them in the next line to identify all neighbors by country)
countries = set(sum(m, []))
# Get a dict with country and neighbors like in your provided explanation
country_neighbors = {c: [i if j==c else j for i,j in m if c in [i,j]] for c in countries}

# Create two empty lists
pool1,pool2 = [],[]
output = None

# Iterate through dictionary
for country,neighbors in country_neighbors.items():
    # Add country to first pool1 if there're not neighbors in the list
    if not any([neighbor in pool1 for neighbor in neighbors]):
        pool1.append(country)
    # If there's any country neighbors in pool1, try to place it in pool2
    elif not any([neighbor in pool2 for neighbor in neighbors]):
        pool2.append(country)
    # If no possible, then it's no possible to create two pools at all
    else:
        output = 'no'
        break

if output is None:
    output = 'yes'

If you want, you can wrap it inside a function like this:
def check_pools(input_file):
    m = []
    with open(input_file, 'r') as file:
        nm = list(map(int, file.readline().split()))
        for row in file:
            m.append([int(i) for i in row.split()])
    if nm[0] > nm[1]:
        return 'yes'

    countries = set(sum(m, []))
    country_neighbors = {c: [i if j==c else j for i,j in m if c in [i,j]] for c in countries}

    pool1,pool2 = [],[]

    for country,neighbors in country_neighbors.items():
        if not any([neighbor in pool1 for neighbor in neighbors]):
            pool1.append(country)
        elif not any([neighbor in pool2 for neighbor in neighbors]):
            pool2.append(country)
        else:
            return 'no'
    return 'yes'


text:
Q: how to open the vba form in external application like notepad and notead++ I want to know how to read the ms access form (vba form) via external application
like (notepad,notepad++).
In vb6 application can be able to read the [control name],[code] in the external application (notepad,notepad++).
but, there is no option for to do the same operation in the ms access forms.
when i open the form in the database i can ,but not in the notepad and notepad++.
It is possible or not (or) is there any other way to do this action.

A: You can only access the form code that is shown in the VBA editor.  In VB and C# you can view the code that actually creates the control objects and initialises them (I think it is this that you are referring to).  You can't see this code in Access / VBA.
If you want to edit the code in Notepad++ simply copy and paste it from the VBA code editor (which is shown when you press ALT+F11).
PS. I use a access addin called OASIS-SVN that can export all object definitions as text files, I probably does it as described here

A: If you want to edit VBA projects files outside from VBE, you first need to Export them (using Right-click->Export a file) and save them somewhere.
Then you'll be able to open them with notepad(++).
Don't forget to Import them back into your VBA Project after editing.


text:
Q: Access a DOM element from a helper class angular 6 I have a small helper class that needs to do a little DOM manipulation. I was trying to use ViewChild() following this and a few others but it can't compile. I am guessing ViewChild() requires @Component directive to work?
My current class is:
  @Injectable()
  export class calculator {

   constructor(){}

   calculate(calling_btn:string){

    //while a rather longish calcualtion is done, I need to disable the specific btn that called the calculate method. then display the result.

    @ViewChild(calling_btn) ele: ElementRef;
   }

html:
     <button #stage1 (click)="calculate('stage1')">Stage 1</button>

There can be maximum 15 buttons that will request calculation and I want to disable each button that requests calculation then return result. It is working but sometimes users click one button multiple times and I wanted to stop that.
It works well if I use getElementById but i read it is not good practice. Any idea?

A: First of all, you have the calculate function which will take awhile to be done.
Secondly, you don't want user to interact with button when the calculation is in progress
So I think the simple way to solve these 2 problems is that we will disable the button.
your temlplate:
<button #stage1 (click)="calculate('stage1')" [disabled]="isCaculating">Stage 1</button>

your component, after the calculation, we will assign isCaculating = false again:
 @Injectable()
 export class calculator {
   isCaculating: boolean;
   constructor(){
   }

   calculate(calling_btn:string){
     this.isCaculating = true;
     //while a rather longish calcualtion is done, I need to disable the specific btn that called the calculate method. then display the result.
     this.isCaculating = false;
     @ViewChild(calling_btn) ele: ElementRef;
 }

I just notice that you use the string for the button while calculating, so I guess so could have mutilple buttons with different string such as 'stag2' and 'stage3'.
<button #stage1 (click)="calculate('stage1')" [disabled]="isCaculating['stage1']">Stage 1</button>

@Injectable()
 export class calculator {
   isCaculating: {};
   constructor(){
   }

   calculate(calling_btn:string){
     this.isCaculating[calling_btn] = true;
     //while a rather longish calcualtion is done, I need to disable the specific btn that called the calculate method. then display the result.
     this.isCaculating[calling_btn] = false;
     @ViewChild(calling_btn) ele: ElementRef;
 }

So inside your component the isCaculating now will be come an object, with the key is your button string and the value will be boolean to decide whether we will disable the button while calculating or not.
Hope this could help.