text:
Q: Unable to read BLE characteristic with Windows Bluetooth APIs I have a Adafruit Bluefruit UART Friend module (https://learn.adafruit.com/introducing-the-adafruit-bluefruit-le-uart-friend/introduction) and i am trying to make an Universal Windows App from which i can read the bluetooth data. I followed the steps showed on the microsoft page and succesfully connected to the device but when trying to read the data from the specific RX characteristic, i get System.ArgumentException in console. I checked the flags on the characteristic and it looks like th READ flag return false, only the NOTIFY flag being true. Is it possible that I am not reading the right characteristic? I got the UUID from Adafruit site: https://learn.adafruit.com/introducing-the-adafruit-bluefruit-le-uart-friend/uart-service Here is my C# code sample: `
public static async Task connectToAddress() {

      Guid guid = new Guid("6e400001b5a3f393e0a9e50e24dcca9e"); // Base UUID for UART service
      Guid charachID = new Guid("6e400003b5a3f393e0a9e50e24dcca9e"); // RX characteristic UUID

      deviceReference = await BluetoothLEDevice.FromBluetoothAddressAsync(_deviceAddress);
      GattDeviceServicesResult result = await deviceReference.GetGattServicesAsync();

      var characs = await result.Services.Single(s => s.Uuid == guid).GetCharacteristicsAsync();
      var charac = characs.Characteristics.Single(c => c.Uuid == charachID);

      GattCharacteristicProperties properties = charac.CharacteristicProperties;

      if (properties.HasFlag(GattCharacteristicProperties.Read))
            {
            Debug.Write("This characteristic supports reading from it.");
            }
      if (properties.HasFlag(GattCharacteristicProperties.Write))
            {
            Debug.Write("This characteristic supports writing.");
            }
      if (properties.HasFlag(GattCharacteristicProperties.Notify))
            {
            Debug.Write("This characteristic supports subscribing to notifications.");
            }

      GattReadResult data = await charac.ReadValueAsync();
      Debug.WriteLine("DATA: " + data.ToString());

      charac.ValueChanged += Characteristic_ValueChanged;

        }`

A: Because you are reading data just after connecting, there might be nothing to read.
Your Bledevice is an UART Service, so i am sure it will send a Notification to let you know there is somthing to read, or the data is in the notification itself.
If the data is in the notification, get it from the GattValueChangedEventArgs in the Charac_ValueChanged event.
Else read it in the Charac_ValueChanged.
The data you receive is in the format of IBuffer. To convert IBuffer to string I will show in the code example.
Add using Windows.Security.Cryptographyto your code.
The code example compiles OK, but don't expect it to work "out of the box", I cannot see the rest of your code and have no acces to the Ble-device.
Use the debugger and set breakpoints to inspect the code.
 static GattCharacteristic charac = null;

  public static async Task connectToAddress()
  {
     Guid guid = new Guid("6e400001b5a3f393e0a9e50e24dcca9e"); // Base UUID for UART service
     Guid charachID = new Guid("6e400003b5a3f393e0a9e50e24dcca9e"); // RX characteristic UUID

     deviceReference = await BluetoothLEDevice.FromBluetoothAddressAsync(_deviceAddress);
     GattDeviceServicesResult result = await deviceReference.GetGattServicesAsync();
     //Allways check result!
     if (result.Status == GattCommunicationStatus.Success)
     {
        //Put following two lines in try/catch to or check for null!!
        var characs = await result.Services.Single(s => s.Uuid == guid).GetCharacteristicsAsync();
        //Make charac a field so you can use it in Charac_ValueChanged.
         charac = characs.Characteristics.Single(c => c.Uuid == charachID);
        GattCharacteristicProperties properties = charac.CharacteristicProperties;
        if (properties.HasFlag(GattCharacteristicProperties.Read))
        {
           Debug.Write("This characteristic supports reading from it.");
        }
        if (properties.HasFlag(GattCharacteristicProperties.Write))
        {
           Debug.Write("This characteristic supports writing.");
        }
        if (properties.HasFlag(GattCharacteristicProperties.Notify))
        {
           Debug.Write("This characteristic supports subscribing to notifications.");
        }
        try
        {
           //Write the CCCD in order for server to send notifications.
           var notifyResult = await charac.WriteClientCharacteristicConfigurationDescriptorAsync(
                                                     GattClientCharacteristicConfigurationDescriptorValue.Notify);
           if (notifyResult == GattCommunicationStatus.Success)
           {

              Debug.Write("Successfully registered for notifications");
           }
           else
           {
              Debug.Write($"Error registering for notifications: {notifyResult}");
           }
        }
        catch (UnauthorizedAccessException ex)
        {
           Debug.Write(ex.Message);
        }

        charac.ValueChanged += Charac_ValueChangedAsync; ;
     }
     else
     {
        Debug.Write("No services found");
     }
  }

  private static async void Charac_ValueChangedAsync(GattCharacteristic sender, GattValueChangedEventArgs args)
  {
     CryptographicBuffer.CopyToByteArray(args.CharacteristicValue, out byte[] data);
     string dataFromNotify;
     try
     {
        //Asuming Encoding is in ASCII, can be UTF8 or other!
        dataFromNotify = Encoding.ASCII.GetString(data);
        Debug.Write(dataFromNotify);
     }
     catch (ArgumentException)
     {
        Debug.Write("Unknown format");
     }
     GattReadResult dataFromRead = await charac.ReadValueAsync();
     CryptographicBuffer.CopyToByteArray(dataFromRead.Value, out byte[] dataRead);
     string dataFromReadResult;
     try
     {
        //Asuming Encoding is in ASCII, can be UTF8 or other!
        dataFromReadResult = Encoding.ASCII.GetString(dataRead);
        Debug.Write("DATA FROM READ: " + dataFromReadResult);
     }
     catch (ArgumentException)
     {
        Debug.Write("Unknown format");
     }
  }

There is also no need to make your methods  STATIC. I left dat as it was, so it is easier to compare it with you code.
Hope this helps you.


text:
Q: Getting the warning: ' In function 'void dfs(int)' Warning: comparison between signed and unsigned integer expressions' I am working on a simple DFS problem where I have to return the number of respective child nodes having more child nodes as compared to their parents (Child nodes>Parent nodes:Count++).
I have been facing the problem I mentioned in the title and I haven't been able to work around it. I used unsigned int too, but to no avail. I am clear with my logic for this question, but fairly new to coding and hence face difficulties with errors such as this. I will attach only my DFS function below, where the problem seems to be occurring. Please help me with this. (Using adjacency list)
vector<int> adj[100001];
bool visited[100001]={false};
int parent=0;
int child=INT_MAX;
int counterr=0;

/*Recursive DFS:*/

void dfs(int s){
    child=adj[s].size()-1;
    if(child>parent)
        counterr++;
    if(s==1)
        parent=adj[s].size();
    else
        parent=adj[s].size()-1;
    visited[s]=true;
    for(int i=0;i<adj[s].size();i++)
    {
        if(visited[adj[s][i]==false])
            dfs(adj[s][i]);
    }
}

A: For the most part, you can ignore this. However, if your integer exceeds the normal integer limit, or your adj[s] vector is empty, this may become a problem. If parent is never negative you can just change the line
int parent;

to
unsigned int parent;

which will completely prevent this warning.

A: for(int i=0;i<adj[s].size();i++)

You get this warning because adj[s].size() is unsigned integer, but i is signed.
For fix that warning use this instead, and i became unsigned.
for (size_t i=0; i < adj[s].size(); i++)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular material dialog outside iframe I'm having a problem displaying an Angular material dialog outside of an iframe.
I have two applications, an application that is used to present other applications through an iframe and another application that is displayed inside the iframe.
The second app (the one that renders inside the iframe) has different dialogs but they are centered inside the iframe, I would like them to be centered relative to the first app.
I hope that with the images you can understand what I am trying to achieve.
Current:

What I'm trying to achieve:

In my first application, I have a simple iframe where I use a variable to assign the address where the front of the application that I want to display is located.
<iframe id="iframe" allowfullscreen [hidden]="condition" scrolling="no" [src]="url | domsecure" title="Navigation"></iframe>

In my second application, I have called a function to display an Angular material dialog.
import { Component } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { DialogComponent } from '../dialog/dialog.component';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent {

  constructor(private matDialog: MatDialog) { }

  public showDialog(): void {
    this.matDialog.open(DialogComponent);
  }

}

I am using Angular 11.0.5
PD: My first post here :3


text:
Q: CSS Relative background not expanding on insertion of html code Thanks for any help you can offer me/point me in the write direction.
I am not sure how to explain what is happening.
I current have a page with an image background (the image is 4044,2160 so it is larger than you would view on a single screen (normally)).
Currently when the page loads, the image is top-centered and is not on repeat and thus fills the background completely.
However when inserting html code (CRUD) via javascript, etc. with the resulting page becoming larger than the original in the y direction, the background stops and does not fill the space below.
http://postimg.org/image/jqzx0vuzr/
I am not sure what to do to fix it and most likely think it is a css problem.
Below is code:
HTML

        Javascript insertion of code

CSS
.clinic{
    width:100%;
    position:relative;
    background: url(../img/clinic.jpg) no-repeat top center;
}
.index{
    height: 100%;
    padding: 0;
}

#index.index {
    padding:15% 0 0 0;
}
#xcrud_container{
    width: 90%;
    margin: 0 auto;
}

It seems that the javascript does not matter as to what is inserted, (have tried lorem ipsum, etc.)
But just to expand on what is inserted, the size of the x_container changes based on a state and this is altered by javascript. (Thus page is not reloaded and background size recalculated)
I have currently tried a clearfix solution (but to no avail) as well as attempting repeat-y on the background image.
Lastly I have attempted to manually create the page through directly saving the html code (i.e. it is not inserted by anything and is apart of the html code of the page) to the page and attempting to see if the background expands. It does not. The background fills the initial view area, however as soon as you scroll down the page, the white area reappears.
Just to make sure this is known the background image is larger than area viewed, thus the white area should not be present.
Any help would be greatly appreciated, as I have been at this for a few days...
Thanks

A: Change % to Pixels as for example.
.index{
    height:1000px;
    padding: 0;
}

A: Thanks for you help guys,
Through the comments and answer I have been able to figure out my own stupidity in trying to force a  tag to define the background of the page rather than using body. i.e. .
The reason for my defining it as a section tag is due to its use on previous pages where the  was followed by another section and thus the white space area would not be a problem. (Also is the reasoning for the height:100%;, as I had to define the height of the section as being 100% in order to fully create the image within the section.
Thanks again.


text:
Q: Bidirectional Current Source I'm trying to design a bidirectional current source for the purpose of measuring very small (0.0001 Ohm) resistances. I've come across this circuit:

I can see that the transistors are there to 'boost' the current but I don't understand the purpose of the 1K resistors and the capacitor. I also don't follow how I can increase the current rating of this pump to 1A.
I've simulated the circuit in LTSpice and it works very well at 100mA but when I try to source or sink 1A I only get 850mA out.
Any suggestions on increasing the current sourcing/sinking ability of the above circuit to 1A or any other suggestions for such a pump?

A: This technique is called "rail sensing" or "supply sensing" and the 1K resistors that are degenerating the rails are there to measure the supply current, which is dominated by the op-amps output stage.  The signal generated by the these resistors drives the main out board transistors that provide the current boost.  The transistors are within the feedback loop of the amplifier so the non-linearities are partially compensated for.
The large capacitor is to decouple the new "mushy" rails voltage and to provide charge storage while the op-amp is slewing. typical stabilization caps are on the order of 10'2 - 100's of pF's this is 100X to 1000X too large for that purpose.
To understand the operation you need to understand how the device is made.  The feedback is not shown (in the app note schematic) so how the device works in this configuration is not clear. i.e. "how do you get the outside transistors inside the feedback loop?"  Here is the snip from the datasheet.

The op-amp rails respond more to changes in the load than it would if it were just driving the load by itself.  The load comes on, the op-amp slews to make up for it, this increased current is detected and drives the out-board transistors which then shoulder the burden.  As the output approaches the final value the op-amp rail current drops. The decoupling capacitor (10 uF) need only supply the charge for slewing of the op-amp.

A: The capacitor is there because an op-amp usually (almost 100%) needs a capacitor across its supply pins to avoid problems of instability and / or loss of performance.
Without the transistors there to help the op-amp drive current into the small anticipated load resistor the current taken from the supplies would be about the same as what the op-amp is supplying to the load - so, these lines are "kidnapped" for use by the transistors - the 1k in series with the supply is not an issue for the right type of op-amp and the voltage across them produces a base emitter voltage that supplements the miserly output current from the op-amp.
It's not a problem increasing the current out by using Darlington transistors but for much more than 1A drive (from either rail) the transistors are going to get warm. For instance on a +/-5 V rail driving 1 A into a short circuit one of the transistors is going to be producing 5 watts of heat. If you needed 10A that's 50W of heat.
There are circuits that only need a very small supply rail that can produce a constant current into a very small impedance load with maybe 1 volt as the power rail. Your circuit is limited by the power rails for the op-amp.
EDIT Here's an idea for a circuit that can drive either +10A or -10A into the load without needing to disconnect it: -

The main power to the load is from a +/-1V supply (circled in red). At the moment R6 (blue circle at top) is set to 5 ohms and this puts a voltage on X5's +Vin that has to be reproduced across R5 (0.005 ohms) due to negative feedback action on X5. This forces 10A through R5 and hence through the load (R4) of 0.0001 ohm.
To change polarity R5 is shorted out to 0R and R2 is set to 5R and this turns off the top FET drive circuit and turns on the bottom FET drive circuit producing through X1.
It doesn't have to be limited at 10A of course - this just coincides with the values I've chosen. Currents and voltages are marked on the diagram to help you understand what is going on.


text:
Q: become_user with command sudo rootsh -i -u root , ansible I have a question about how to run commands as root. The playbook is really simple, create a folder and after that change the owner and group
  - name: install-home-db | Create scatch directory only if it is needed
    become: yes
    file:
      path: "{{ scratch_patch }}/oracle_{{ db_version | replace('.', '_') }}"
      mode: 775
      owner: "{{ oracle_user }}"
      group: "{{ oracle_group }}"
      state: directory
    register: oracle_medias

The folder is created whitout problem, the problem comes when it wants to setup the user and group
In remote server I do not have permissions to run any sudo command, but I can become root user if launch command
sudo rootsh -i -u root

Please notice that I only can become root if use this exact command, if I run only
sudo rootsh -u root

It does not work and returns
Sorry, user fcruzloz is not allowed to execute '/usr/bin/rootsh -u root' as root on dcplnx22121944.

So how could I run command using root user?
I have tried setting below paramters in ansible.cfg
[defaults]
host_key_checking             = false
# ask_pass                    = True
inventory                     = inventory/hosts
allow_world_readable_tmpfiles = true
remote_user                   = fcruzloz
executable                    = /bin/bash
timeout                       = 50

[privilege_escalation]
become_exe                    = sudo rootsh
become_user                   = root
become_flags                  = -i

But it is still failing because permissions, when running ansible command with -vvv, I think the culprit line is below one
<2a00:da9:2:21ca:111:0:427:1> SSH: EXEC ssh -o ControlMaster=no -o ServerAliveInterval=50 -o StrictHostKeyChecking=no -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o 'User="fcruzloz"' -o ConnectTimeout=50 -tt 2a00:da9:2:21ca:111:0:427:1 '/bin/bash -c '"'"'sudo rootsh -i  -u root /bin/bash -c '"'"'"'"'"'"'"'"'echo BECOME-SUCCESS-eybzqcaxfeytghcwykijkpeqdlpzphdq ; /usr/bin/python /home/admin/fcruzloz/.ansible/tmp/ansible-tmp-1570663425.52-9612101629719/AnsiballZ_file.py'"'"'"'"'"'"'"'"' && sleep 0'"'"''
Escalation succeeded

And that makes sense when checking errors in /var/log/messages
2019-10-09T16:24:15.472458-07:00 dcplnx22121944 sudo: fcruzloz : command not allowed ; TTY=pts/14 ; PWD=/home/admin/fcruzloz ; USER=root ; COMMAND=/usr/bin/rootsh -i -u root /bin/bash -c echo BECOME-SUCCESS-eybzqcaxfeytghcwykijkpeqdlpzphdq ; /usr/bin/python /home/admin/fcruzloz/.ansible/tmp/ansible-tmp-1570663425.52-9612101629719/AnsiballZ_file.py
2019-10-09T16:24:15.625928-07:00 dcplnx22121944 sshd[16027]: Connection closed by 2a00:da9:ffa0:8601::2

If I run the ansible command directly in server, I mean something like below (It is not exactly same command), it fails
fcruzloz@dcplnx22121944:/home/admin/fcruzloz> sudo rootsh -i  -u root /bin/bash -c 'echo test'
Sorry, user fcruzloz is not allowed to execute '/usr/bin/rootsh -i -u root /bin/bash -c echo test' as root on dcplnx22121944.

I guess I need to do something like redirect the command to the new root shell but I could not do this, I tried with openvt but I did not get it
So do you have some idea?
Thanks a lot in advance for your help
My control maching is below linux flavor
NAME="SLES"
VERSION="12-SP2"
VERSION_ID="12.2"
PRETTY_NAME="SUSE Linux Enterprise Server 12 SP2"
ID="sles"
ANSI_COLOR="0;32"
CPE_NAME="cpe:/o:suse:sles:12:sp2"
SUSE Linux Enterprise Server 12 (x86_64)
VERSION = 12
PATCHLEVEL = 2

A: did you tried 'become_user'
  become: yes
  become_method: su
  become_user: root

refer to link to understand privilege escalation methods in ansible.


text:
Q: WiX - CustomAction ExeCommand - Hide Console We've gotten a custom action that runs command-line to work as such:
<CustomAction Id="OurAction"
              FileKey="OurInstalledExe.exe"
              ExeCommand="our command line args"
              Execute="deferred"
              Return="check" />

The problem is, the user sees a console popup when the command runs.
The command line requires UAC elevation, but should not require any user interaction.  We also install the file with the setup, the custom action runs After="InstallFiles".
How do we prevent the user from seeing the console?

A: Note that if you do require UAC elevation, then you need to ensure that it's a deferred execution CA. Here's the example from the manual with command line arguments added.
<CustomAction Id="QtExecDeferredExampleWithProperty_Cmd" Property="QtExecDeferredExampleWithProperty"
              Value=""[#MyExecutable.exe]" /arguments" Execute="immediate"/>
<CustomAction Id="QtExecDeferredExampleWithProperty" BinaryKey="WixCA" DllEntry="CAQuietExec"
              Execute="deferred" Return="check" Impersonate="no"/>
.
.
.
<InstallExecuteSequence>
    <Custom Action="QtExecDeferredExampleWithProperty_Cmd" After="CostFinalize"/>
    <Custom Action="QtExecDeferredExampleWithProperty" After="TheActionYouWantItAfter"/>
</InstallExecuteSequence>

A: If you have the source code of the EXE file this is what you can do. Make the EXE project Win32 Application project instead of Console Application.
If you cannot modify the source code of the EXE file, you can do this by:

*

*Creating a CustomAction DLL

*Calling a CustomAction in DLL (from WiX) to execute the process, by hiding the console window.

A: There is a bit of a chicken and egg problem in that an executable has to be marked as a console app before it starts, and if you want to launch such an exe without the console popping up, it has to have its process created with the right flags. If your installer can't provide these, it is possible to use a third .exe in between. For example, the Keybase installer launches this small utility, called keybaserq.exe, in order to run persistent console apps in the background with no flashing black windows. It is open source and you can see how the Keybase installer makes use of it - no flashing console windows.

A: You just have to add second command "exit" for cmd.exe
ExeCommand="[SystemFolder]cmd.exe /C start MyExe.exe & exit"

Hope, It helps you


text:
Q: When did vampires first come about? I am researching a vampire essay thing and I can not find the exact date as to when they were first seen or what the story was that first had vampires in it.

A: It is commonly claimed that the legends of vampires come from a family of diseases know as Porphyria though this comes in and out of vogue.
According to Wikipedia:

The charismatic and sophisticated vampire of modern fiction was born
  in 1819 with the publication of "The Vampyre" by the English writer
  John Polidori; the story was highly successful and arguably the most
  influential vampire work of the early 19th century.[3]

The basic idea has been around for a very long time but the entity of the Vampire as we know it comes from the 1700s(Wiki section):

The notion of vampirism has existed for millennia. Cultures such as
  the Mesopotamians, Hebrews, Ancient Greeks, Manipuri and Romans had
  tales of demons and spirits which are considered precursors to modern
  vampires. Despite the occurrence of vampire-like creatures in these
  ancient civilizations, the folklore for the entity known today as the
  vampire originates almost exclusively from early 18th-century
  southeastern Europe,[1] when verbal traditions of many ethnic groups
  of the region were recorded and published.

Lastly, the word vampire first appeared in English in 1734
see J. Simpson; E. Weiner, eds. (1989). "Vampire". Oxford English Dictionary (2nd ed.). Oxford: Clarendon Press.


text:
Q: How do i migrate a oracle sql tables to mongodb? i have created a few tables which have related table using Oracle SQL. My lecturer want me to migrate these into a mongodb , i have searched on web but i am clueless on what they are doing . i know how to setup mongodb and get connection but i dont know how to migrate to mongodb.
This is my tables i have created
CREATE TABLE TBL_EVENT_ORDER
 (
  ORDER_ID INT CONSTRAINT PK_TBL_EVENT_ORDER
  PRIMARY KEY,
  CLIENT_ID VARCHAR2(10),
  CONSTRAINT FK_CLIENT FOREIGN KEY (CLIENT_ID) REFERENCES
  TBL_CLIENT(CLIENT_ID),
  ORDER_DATE DATE DEFAULT SYSDATE,
  EVENT_ID INT DEFAULT 1,
  CONSTRAINT FK_WINE_EVENT FOREIGN KEY (EVENT_ID) REFERENCES
  TBL_WINE_EVENT(EVENT_ID)
 );

CREATE INDEX IDX_FK_CLIENT_ID_TBL_CLIENT ON TBL_EVENT_ORDER(CLIENT_ID);
INSERT INTO TBL_EVENT_ORDER VALUES
(1,'1',DEFAULT,'1');
INSERT INTO TBL_EVENT_ORDER VALUES
(2,'2',DEFAULT,'1');
INSERT INTO TBL_EVENT_ORDER VALUES
(3,'3',DEFAULT,'1');
INSERT INTO TBL_EVENT_ORDER VALUES
(4,'4',DEFAULT,'1');

CREATE TABLE TBL_WINE
 (
   WINE_ID INT CONSTRAINT PK_WINE PRIMARY KEY,
   WINE_NAME VARCHAR2(20),
   PRICE NUMBER(6,2) CONSTRAINT NN_PRICE NOT NULL,
   WINE_TYPE VARCHAR2(20) CONSTRAINT NN_WINE_TYPE NOT NULL,
   WINE_YEAR INT CONSTRAINT NN_WINE_AGE NOT NULL,
   WINE_COUNTRY VARCHAR2(20),
   WINE_REGION VARCHAR2(20)
 );

INSERT INTO TBL_WINE VALUES
(1,'AGUILA RED',100.50,'BORDEAUX',2010,'COUNTRY1','REGION1');
INSERT INTO TBL_WINE VALUES
(2,'CLOUD BAY',150,'BORDEAUX',2010,'COUNTRY2','REGION2');
INSERT INTO TBL_WINE VALUES
(3,'HARLAN ESTATE',175.50,'BORDEAUX',2010,'COUNTRY3','REGION3');
INSERT INTO TBL_WINE VALUES
(4,'KRUG',200,'BORDEAUX',2010,'COUNTRY4','REGION4');

CREATE TABLE TBL_ORDER_DETAIL
 (
  ORDER_ID INT,
  WINE_ID INT,
  CONSTRAINT PK_ORDER_DETAIL PRIMARY KEY (ORDER_ID, WINE_ID),
  CONSTRAINT FK_EVENT_ORDER FOREIGN KEY (ORDER_ID) REFERENCES
  TBL_EVENT_ORDER(ORDER_ID),
  ORDER_QTY INT CONSTRAINT NN_ORDER_QTY NOT NULL,
  UNIT_PRICE NUMBER(6,2),
  EXCLUSIVE_IMPORT CHAR(1)
);

CREATE INDEX IDX_FK_ORDER_ID_EVENT_ORDER ON TBL_ORDER_DETAIL(ORDER_ID);
CREATE INDEX IDX_FK_WINE_ID_WINE ON TBL_ORDER_DETAIL(WINE_ID);

INSERT INTO TBL_ORDER_DETAIL VALUES
(1,1,3,100.50,'N');
INSERT INTO TBL_ORDER_DETAIL VALUES
(2,2,1,150,'N');
INSERT INTO TBL_ORDER_DETAIL VALUES
(3,3,4,175.50,'N');
INSERT INTO TBL_ORDER_DETAIL VALUES
(4,4,2,200,'Y');


text:
Q: Analytic functions defined by integrals Suppose I define a function using an integral:
$$f(z)=\int_{\mathbb R} g(z,x)\ dx,$$
where $g$ is some function, $z$ is a complex variable, and $x$ is a real variable. Suppose the integral exists for $z\in U$, where $U$ is some open region. What are sufficient conditions on $g$ so that $f$ is analytic here, and why do they suffice?
I looked in Ahlfors but couldn't find anything relevant.

A: It suffices that $g$ is analytic in $z \in U$ for each $x\in {\mathbb R}$ and $\int_{\mathbb R} |g(z,x)|\ dx$ is locally uniformly bounded on compact subsets of $U$.  For then if $\Gamma$ is any closed triangle in $U$,
Fubini's theorem  says $\oint_\Gamma f(z) \ dz = \int_{\mathbb R} \oint_\Gamma g(z,x)\ dz\; dx = 0$, and Morera's theorem says $f$ is analytic in $U$.
EDIT: I guess we'd better also assume that $g(z,x)$ is measurable.

A: Hint Morera's theorem should tell you something.


text:
Q: Regex IsOne vs Containing I am writing a PostGres checkin order to constrain a text field to one of 4 different values. I am avoiding Enum type on purpose as it has been known to cause issues.
I seem to have more of a "contains" instead of has to be one of these.
ALTER TABLE registrations
  ADD CONSTRAINT proper_confirmation_status CHECK (confirmation_status::
text ~* '^(Unconfirmed|Confirmed|Rejected|NotApplicable)'::text);

So:

*

*The word should be one of those 4 without any additional characters (start or finish).

*The check should be case sensitive

*Currently confirmdddddd is validated correctly, but confirmedSSSS

A: *

*Use ~ (case senstive) instead of ~* (case intenstive)

*The regex should be ^(....)$ (match whole string)

*The syntax looks a bit weired, does it work?
ALTER TABLE registrations
  ADD CONSTRAINT proper_confirmation_status CHECK
    (confirmation_status::text ~ '^(Unconfirmed|Confirmed|Rejected|NotApplicable)$');

A: I think you should use IN operator instead of regex.
ALTER TABLE registrations
  ADD CONSTRAINT proper_confirmation_status CHECK (
    confirmation_status::text IN ('Unconfirmed', 'Confirmed', 'Rejected', 'NotApplicable'));


text:
Q: How would I set a timer with Pygame and Livewires? So in a game I'm creating when the player picks up the speed boost sprite I want the players speed to periodically boosted for around five seconds, could someone help me understand how to do this? The 'Handle Caught' method will contain the code for the speed boost, the actual speed of the player is also set as a global variable 'speed' which is equal to 2. Thank you in advance
class Addspeed(games.Sprite):
    image = games.load_image('addspeed.png')
    speed = 2

    def __init__(self,x,y = 10):
        super(Addspeed, self).__init__(image = Addspeed.image,
                                       x = x, y = y,
                                       dy = Addspeed.speed)
    def update(self):
        if self.bottom>games.screen.height:
            self.destroy()

    def handle_caught(self):
        global speed

A: If your game is big enough, I would suggest a timer manager.
Have one big timer based on the pygame.Clock. Create methods, to register time and methods to be called when the time passes. So something like:
timerMananger.register(self.myMethod,5000)
# registers an event to be called after 5 seconds

The manager should encompass the Clock, as well as have a priority queue of tasks to complete.
A short sketch of how this would look like:
def register(myMethod,t):
    pqueue.add(myMethod,time_now+t)

def tick():
    clock.tick()
    if(time_now > pqueue[0]):
        pqueue.pop()[0]()

This way you only check the most recent event. You could change the if to a while loop, if there will be many events, so that they will be all processed at once.


text:
Q: Running ActiveRecord validations without saving I have a collection of ActiveRecord objects.  I want to be able to run all the validations for each of these objects without actually saving them to the database.  I just want to know if they would be valid were I to save them to the database. In other words, I essentially want to populate the errors data structure for each of my objects. Is there a way to do this?  Or perhaps I'm missing something about the lifecycle of the errors collection?

A: Running the #valid? method on the object will run all validations and populate the errors structure.
dude = Person.new
unless dude.valid?
  # Examine errors
end

A: You can do the following to check if a Model is valid:
@user = User.new
if @user.valid?
  #do things

If you want to see what the errors are, you can do:
@user = User.new
unless @user.valid?
  @user.errors.each {|k, v| puts "#{k.capitalize}: #{v}"}

Calling the ".valid?" method runs your validations, putting all of your errors into an ActiveRecord::Errors object, which can be accessed like I did in the example above.  Give the examples a try in the Console to get a feel for it if you like.


text:
Q: Refresh widget admin page resetting jQuery hidden class I am working on Media Upload widget. When I upload image file, it show the image in the admin page. Until I refresh this page, it is disappeared. After I checked, I found that the hidden class is added automatically.
I tried to google and found only the save widget problem (It is similar with my case). Anyone can help.
More Information: it works in Firefox only. It does not work in Chrome and IE. (just test)
This is my jQuery file.
 function renderMediaUploader() {
'use strict';

var file_frame, image_data, json;

/**
 * If an instance of file_frame already exists, then we can open it
 * rather than creating a new instance.
 */
if ( undefined !== file_frame ) {

    file_frame.open();
    return;

}

file_frame = wp.media.frames.file_frame = wp.media({
    frame:    'post',
    state:    'insert',
    multiple: false
});

file_frame.on('insert', function ()
{
    $ = jQuery;
    // Read the JSON data returned from the Media Uploader
    json = file_frame.state().get('selection').first().toJSON();

    // First, make sure that we have the URL of an image to display
    if (0 > $.trim(json.url.length))
    {
        return;
    }

    // After that, set the properties of the image and display it
    $('.media-upload-container')
    .children('img.wp-post-image')
        .attr('src', json.url)
        .attr('alt', json.caption)
        .attr('title', json.title)
                    .show()
    .parent()
    .removeClass('hidden');

    // Next, hide the anchor responsible for allowing the user to select an image
    $('.media-upload-container')
    .prev()
    .hide();

    // Display the anchor for the removing the background image
    $('.media-upload-container')
    .next()
    .show()

    // Store the image's information into the meta data fields.

    $('.media').val(json.url);

});

// Now display the actual file_frame
file_frame.open();

 }

 jQuery(document).ready(function($) {
     'use strict';

$(function() {
    $( '.set-background-thumbnail' ).on( 'click', function( evt ) {

        // Stop the anchor's default behavior
        evt.preventDefault();

        // Display the media uploader
        renderMediaUploader();

    });
    $( '.remove-background-thumbnail' ).on( 'click', function( evt ) {

        // Stop the anchor's default behavior
        evt.preventDefault();

        // Remove the image, toggle the anchors
        resetUploadForm( $ );

    });

    renderFeaturedImage( $ );
});

 })

 jQuery(document).ajaxSuccess(function (event, xhr, settings)
 {
var widget_id_base = 'image_widget';
if (settings.data !== "undefined")
{
    if (settings.data.search('action=save-widget') != -1 && settings.data.search('id_base=' + widget_id_base) != -1)
    {
        'use strict';

        $(function ()
        {
            $('.set-background-thumbnail').on('click', function (evt)
            {
                // Stop the anchor's default behavior
                evt.preventDefault();

                // Display the media uploader
                renderMediaUploader();

            });
            $('.remove-background-thumbnail').on('click', function (evt)
            {

                // Stop the anchor's default behavior
                evt.preventDefault();

                // Remove the image, toggle the anchors
                resetUploadForm($);

            });

            renderFeaturedImage($);
        });
    }
}
 });

 function resetUploadForm( $ ) {
     'use strict';

// First, we'll hide the image
$( '.media-upload-container' )
    .children( 'img.wp-post-image' )
    .hide();

// Then display the previous container
$( '.media-upload-container' )
    .prev()
    .show();

// Finally, we add the 'hidden' class back to this anchor's parent
$( '.media-upload-container' )
    .next()
    .hide()
    .addClass( 'hidden' );

// Finally, we reset the meta data input fields
    $( '.media-upload-meta' )
    .children()
    .val( '' );
 }

 function renderFeaturedImage( $ ) {

/* If a thumbnail URL has been associated with this image
 * Then we need to display the image and the reset link.
 */
if ( '' !== $.trim ( $( '.media' ).val() ) ) {

    $( '.media-upload-container' ).removeClass( 'hidden' );

    $( '.set-background-thumbnail' )
        .parent()
        .hide();

    $( '.remove-background-thumbnail' )
        .parent()
        .removeClass( 'hidden' );

}

 }

A: I can solve the problem now. Because, I forget to put the label/id of media upload widget in the widget form section.
Regards,
W. Nelson


text:
Q: startActivityForResult does not send extras properly I have a quiz game with 15 levels. After each level I present a popup with some info (game level, and some level rules). After level 15, a present final popup with info on how many points user has won. I use startActivityForResult to open the popups and send some extras and it works fine, until the last popup. After the last game, it should open the final popup with the overall score. But it doesn't do it properly. It opens on of my level popup, but with all the info filled with zeros. I don't know where it comes from. After I press OK, it opens final popup, but instead of overall score, I get 0. Here's the code:
Intent i = new Intent(this, Popup_nivoi.class);
            nivo++;
            REQUEST++;
            switch(nivo) {
                case 2:
                {
                    brojPitanja = 11;
                    greska = 4;
                    mogucnostPreskakanjaPitanja = 3;
                    i.putExtra("brojPitanja", brojPitanja);
                    i.putExtra("vreme", 100);
                    i.putExtra("pravoNaGreske", greska);
                    i.putExtra("nivo", nivo);
                    i.putExtra("mogucnostPreskakanja", mogucnostPreskakanjaPitanja);
                    break;
                }
                case 3:
                {
                    brojPitanja = 12;
                    greska = 4;
                    mogucnostPreskakanjaPitanja = 2;
                    i.putExtra("brojPitanja", brojPitanja);
                    i.putExtra("vreme", 95);
                    i.putExtra("pravoNaGreske", greska);
                    i.putExtra("nivo", nivo);
                    i.putExtra("mogucnostPreskakanja", mogucnostPreskakanjaPitanja);
                    break;
                }
                case 4:
                {
                    brojPitanja = 13;
                    greska = 3;
                    mogucnostPreskakanjaPitanja = 2;
                    i.putExtra("brojPitanja", brojPitanja);
                    i.putExtra("vreme", 90);
                    i.putExtra("pravoNaGreske", greska);
                    i.putExtra("nivo", nivo);
                    i.putExtra("mogucnostPreskakanja", mogucnostPreskakanjaPitanja);
                    break;
                }
                case 5:
                {
                    brojPitanja = 14;
                    greska = 3;
                    mogucnostPreskakanjaPitanja = 2;
                    i.putExtra("brojPitanja", brojPitanja);
                    i.putExtra("vreme", 85);
                    i.putExtra("pravoNaGreske", greska);
                    i.putExtra("nivo", nivo);
                    i.putExtra("mogucnostPreskakanja", mogucnostPreskakanjaPitanja);
                    break;
                }
.
.
.
.
case 15:
            {
                brojPitanja = 24;
                greska = 0;
                mogucnostPreskakanjaPitanja = 0;
                i.putExtra("brojPitanja", brojPitanja);
                i.putExtra("vreme", 35);
                i.putExtra("pravoNaGreske", greska);
                i.putExtra("nivo", nivo);
                i.putExtra("mogucnostPreskakanja", mogucnostPreskakanjaPitanja);
                break;
            }
            case 16:
            {
                brojPitanja = 25;
                greska = 0;
                mogucnostPreskakanjaPitanja = 0;
                i.putExtra("brojPitanja", brojPitanja);
                i.putExtra("vreme", 30);
                i.putExtra("pravoNaGreske", greska);
                i.putExtra("nivo", nivo);
                i.putExtra("mogucnostPreskakanja", mogucnostPreskakanjaPitanja);
                break;
            }
            case 17:
            {
                Intent iFinale = new Intent(Kviz.this, Finale.class);
                iFinale.putExtra("UkupanSkor", brojacTacnihOdgovora);
                startActivityForResult(iFinale, 0);
                finish();
                break;
            }
        }
        cancelAllTimers();
        startActivityForResult(i, REQUEST);
    }

In my levels popup I do this to get extras:
Bundle extras = getIntent().getExtras();
        if(extras != null) {
            brojPitanja = getIntent().getIntExtra("brojPitanja", 0);
            pravoNaGreske = getIntent().getIntExtra("pravoNaGreske", 0);
            mogucnostPreskakanja = getIntent().getIntExtra("mogucnostPreskakanja", 0);
            vreme = getIntent().getIntExtra("vreme", 0);
            nivo = getIntent().getIntExtra("nivo", 0);
        }

And my whole finale popup class:
public class Finale  extends Activity implements OnClickListener{

      TextView cestitamo,ukupanSkor;
      Button ok;
      int brojOdgovora;

    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.finale);

        if (getIntent().getExtras() != null)
            brojOdgovora = getIntent().getIntExtra("brojTacnihOdgovora", 0);

        inicijalizujVarijable();
    }

    private void inicijalizujVarijable()
      {
        Typeface localTypeface = Typeface.createFromAsset(getAssets(), "crazy_moj_3.ttf");
        cestitamo = (TextView) findViewById(R.id.tvCestitamo);
        cestitamo.setTypeface(localTypeface);
        ukupanSkor =(TextView) findViewById(R.id.tvUkupanSkor);
        ukupanSkor.setTypeface(localTypeface);
        ok = (Button) findViewById(R.id.bOKCestitamo);

        ukupanSkor.setText("You answered correctly on " + brojOdgovora + " of 300 questions!");

        ok.setOnClickListener(new View.OnClickListener()
        {
          public void onClick(View paramAnonymousView)
          {
            Intent localIntent = new Intent();
            setResult(RESULT_OK, localIntent);
            finish();
          }
        });
      }

    public void onClick(View v) {
        // TODO Auto-generated method stub

    }

}

The weird thing is that I have a popup for "time is up" and I use the same routine and the same code to send extras and to show how many points user scored and it works fine.

A:
It opens one of my level popup, but with all the info filled with zeros.

This occurs because you put startActivityForResult(i, REQUEST) outside the switch-case. When nova is 17, the Intent i is not initialized with any extras, and it will always be called no matter what stage it is. Hence, the popup appears with all values being 0 (from the default value that you set).

After I press OK, it opens final popup, but instead of overall score, I get 0.

This is because you use different name for your extras. When initializing the Intent iFinale, you use UkupanSkor for overall score. But inside the Finale activity, you use brojTacnihOdgovora instead.

My suggestion is to use same Intent to start the activity, and set the data based on the stage number. You only need to change case 17. Try:
case 17:
{
    REQUEST = 0; // set the request code to 0
    i = new Intent(Kviz.this, Finale.class); // set the intent to open final popup instead
    i.putExtra("brojTacnihOdgovora", brojacTacnihOdgovora); // set the extra name to match with the activity
    finish();
    break;
}


text:
Q: In general, why do smaller guns have more felt recoil? Why is recoil easier to control on a more massive gun compared to a smaller gun with the same bullet. Presumably the bullet leaves both guns with the same momentum, but the larger gun seems easier to control. Since the momentum you have to control is the same in both cases, why do we perceive less recoil on a bigger gun?

A: Newtons 3rd Law:

When one body exerts a force on a second body, the second body simultaneously exerts a force equal in magnitude and opposite in direction on the first body.

Momentum is product of mass and velocity. The heavier gun has more mass, so, for the same momentum, it must have less "backwards" velocity, so less felt recoil.

A: Felt recoil is partly a matter of momentum, partly a matter of force.
When a bullet with mass m leaves a gun with a velocity v, the gun must have an equal-but-opposed momentum MV, where M is the mass of the gun and V is the recoil velocity, or $$mv + MV = 0$$. If there are two possible gun sizes, $M_1$ and $M_2$, each will have a recoil velocity $V_1$ and $V_2$. If, for instance, $M_2 = 2M_1$, $$M_1 V_1 = M_2 V_2$$ and $$V_1 = 2V_2$$ Why does this matter? Consider kinetic energy. Let $K_1$ be the kinetic energy of $M_1$, and $K_2$ is that of $M_2$. Then $$\frac {K_1}{K_2} = \frac {\frac{M_1{V_1}^2}{2}}{\frac{M_2{V_2}^2}{2}} = \frac{M_1}{M_2} {(\frac{V_1}{V_2})}^2 = \frac{1}{2} 2^2 = 2$$
So the lighter gun has twice the kinetic energy of the heavier gun and this shows up in two ways. First, since both guns need to stop in about the same distance, the force applied to the lighter gun must be greater than that applied to the heavier. By Newton's First Law, this means that the lighter gun pushes harder on the hand or shoulder of the shooter. Second, the duration of acceleration must be smaller for the lighter gun, since $$S_1 = \frac{a_1{t_1}^2}{2} = \frac{{V_1}t_1}{2} = S_2 = \frac{a_2{t_2}^2}{2} = \frac{{V_2}t_2}{2} $$and $${V_1}{t_1} = {V_2}{t_2}$$ or $$ \frac {t_1}{t_2} = \frac{V_2}{V_1} = \frac{1}{2}$$ So not only is the recoil force greater for the lighter gun, it lasts a shorter time and is therefore "sharper".

A: The larger firearm has more mass, and therefore more inertia for the recoil momentum of the bullet to overcome.
Also, small firearms may be more difficult to secure a good grip on.


text:
Q: Where are the Razor assemblies? I'm playing around with WebMatrix and I'd just like to explore some of the razor stuff behind the scenes... but my Reflector skills (and my brain) are failing me.  Does anyone know offhand what assembly I should start looking in (and/or a location for it)?

A: All the assemblies are installed into Program Files as well as into the GAC. The local folder is:
C:\Program Files\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies


text:
Q: How to open app after rebooting or charging api 27+ The application should autostart after restarting the phone and when charging is connected, I did it like this:
manifest
<receiver android:name=".ChargingReceiver">
     <intent-filter>
           <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
     </intent-filter>
</receiver>

<receiver
    android:name=".RestartReceiver" >
    <intent-filter>
          <action
                android:name="android.net.conn.CONNECTIVITY_CHANGE"
                tools:ignore="BatteryLife" />
             <action android:name="android.intent.action.BOOT_COMPLETED" />
             <action android:name="android.intent.action.QUICKBOOT_POWERON" />
             <action android:name="com.htc.intent.action.QUICKBOOT_POWERON" />
    </intent-filter>
</receiver>

RestartReceiver
class RestartReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        if (intent!!.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {

            val intent = Intent(context, MainActivity::class.java)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context!!.startActivity(intent)
        }
    }
}

ChargingReceiver
class ChargingReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        val intent = Intent(context, MainActivity::class.java)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        context.startActivity(intent)
    }
}

Everything works up to Api27+. I read that on Api27+ you need to use JobScheduler, but I can't find information on my specific task, can this be done on 27+? If so, please tell me how.

A: Your code looks fine though few things to keep in mind for being able to receive these broadcasts.

*

*Your app should have an activity that is launched at least once by manually clicking on app icon. This makes an app enabled so that it can receive broadcasts.

*If your app does not have a UI then it has to be part of system apps which makes an anpp enabled by default.If in case app is not a system app you have to have a mechanism to make it enabled by sending custom broadcast or other means.
If either of the above conditions is true then only you can receive BOOT COMPLETE intent as per my knowledge.


text:
Q: Avoiding to search for the appropriate type in python in order adapt some code I find myself looking for the appropriate type in my python code. Is there a way to avoid this or do this faster?
Consider the following code for example:
def my_function(my_list)
   for my_entry in [entry for entry in my list if ...]

my_entry in this case is a namedTuple, but I have to look where my_function is used and look up the "invocation"-chain in order to know that my_list is a list of namedTuples. Is there a better solution? I am used to statically typed languages.
Just to make it clear, I am not necessary looking for type hints, but for good solution.


text:
Q: JSF FacesMessage shown only once, but is supposed to be shown each time the error occurs I am using JSF 2.3 (Mojarra 2.3.9.SP02) and PrimeFaces 7.0 running on WildFly 17 (Ubuntu 18.04 TLS / or Windows 10).
In my action method weiterBid() in the backing bean (which is a ViewScoped) I perform a check if the user has just checked a checkbox. If not, then an error message is shown in red in the component <p:panel id="errorMsgPanelId" (see below the facelet)  and the user remains on the same page. This check is performed each time the user clicks on the "Next" button.
Now, my understanding is, that even when the user closes the error message panel, each time when he/she clicks on the "Next" button, the action method is invoked, and the check whether hte user has checked the checkbox is performed again and again. If the check-box has not been checked, then the error message should be shown again in the same
 component as before.
Is this really the supposed behaviour? If yes, than I am having a bug that the error message is only shown on the first click on the "Next" button and is never showhn again, once the user closes the panel showing it.
The minimal working example project on github:
https://github.com/alexmivonwien/pf.error.msg
My backing bean:
    @Named("aveBidUnterlagenBean")
    @javax.faces.view.ViewScoped
    public class AveBidUnterlagenBean implements Serializable {

        private boolean confirmationDocumentsGiven;

        private FacesMessage errorMessageOnDocumentConfirmation;

        public boolean isConfirmationDocumentsGiven() {
            return confirmationDocumentsGiven;
        }

        public void setConfirmationDocumentsGiven(boolean confirmationDocumentsGiven) {
            this.confirmationDocumentsGiven = confirmationDocumentsGiven;

        }

        public String weiterBid() {
            if (!confirmationDocumentsGiven) {
                String errorMessage = "Please confirm documents for the real estate";

                FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMessage, null);
                FacesContext.getCurrentInstance().addMessage(null, message);
                this.errorMessageOnDocumentConfirmation = message;
                return null;
            }

            return null;
        }

        public FacesMessage getErrorMessageOnDocumentConfirmation() {
            return errorMessageOnDocumentConfirmation;
        }

        public void onCloseErrorMsgPanel(CloseEvent event) {
            this.errorMessageOnDocumentConfirmation = null;
        }
    }

In the facelet I have the component

    <!DOCTYPE html>

<h:head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</h:head>
        <h:outputStylesheet name="primeicons/primeicons.css" library="primefaces"/>
        <h:form id="persDatenForm">

                   <h:outputText style="color:red;" value="#{aveBidUnterlagenBean.errorMessageOnDocumentConfirmation.detail}"/>

         </h:form>

Now , my problem is that if I do not check the check-box and I click on the "Next" button for the first time, the action method is invoked and the error message is shown.
If I close the error message panel, and then click on the same "Next" button again, without having checked the checkbox, the error message is never shown again.
Is it a bug or a feature? How could I overcome it?
Thank you and kind regards: Alex

A: The update is executed after the action. Instead, use an actionListener:

update is called after actionListener but before action, I think because of that the view is already refreshed. So your beans confirmationDocumentsGiven is false, but it is never updated to the correct FacesContext.
(I didn't test this)
Ok I think the problem is
rendered="#{aveBidUnterlagenBean.getErrorMessageOnDocumentConfirmation()!=null}".

In your  onCloseErrorMsgPanel you set that errorMessage to null.
1st Visit: works, errormsg is set, close dialog -> error msg is null, update @parent -> panel rendered=false, then the action is called -> server side all values correct, however
2nd Visit: the update="@form" or generaly ajax update will skip all components with rendered=false
What to do? Use an action that sets errormsg =/= PlaceHolder.NotNull, then update is called, the panel (rendered = true because errormsg =/= null) is loaded, than with an actionlistener you set errormsg = actualValue.
By this, the panel should be updated and be contained in your DOM.

A: This is the work-around, hope it solves your problem.

<h:outputText style="color:red;"
value="#{aveBidUnterlagenBean.errorMessageOnDocumentConfirmation.detail}"/>

And change the backing bean method to following:
public void onCloseErrorMsgPanel() {
        this.errorMessageOnDocumentConfirmation = null;
    }


text:
Q: How to use POJO with Quarkus and MongoDB in Kotlin I am using Quarkus and Kotlin, and I need to save and retrieve documents in a MongoDB collection.
I have defined a data class:
data class Result constructor(
    @BsonId
    val id: String? = null,
    val values: Map<String, Any> = mapOf()
)

The StorageService has an attribute like this:
private var collection: MongoCollection<Result>

To insert a result, I define an instance of the class and I use the insertOne method:
val result = Result(id="exampleId", values=mapOf("one" to 1, "two" to 2))
...
collection.insertOne(result)

This works and I see the document stored in the collection with the correct id.
When I do the find it doesn't work:
val result = collection.find(eq("_id", "exampleId")).first()

The println(result) gives:

Result(id=null, values={})

Can you tell me where am I doing wrong, please?
Thanks

A: If you don't provide you own codec for your classes, the POJO codec will be used.
There is some small stuff to be done for it to works with data classes, this is documented inside the MongoDB with Panache guide, even if you don't use MongoDB with Panache it will still apply: https://quarkus.io/guides/mongodb-panache#working-with-kotlin-data-classes
There is a Kotlin version of MongoDB with Panache, but it's not yet documented.


text:
Q: Could not load file or assembly Interop.IWshRuntimeLibrary? I'm trying to use the iWshRuntimeLibrary. When I 'publish' my app, all is well. When I try to create a setup wizard project however, It builds and installs my project, but shows the following error at launch.

Could not load file or assembly 'Interop.IWshRuntimeLibrary, Version=1.0.0.0,
  Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system
  cannot find the file specified.

After I click OK, the app seems to proceed as normal.
I've set my project to build against .NET 3.5, if that matters.

A: Solved by following this for iWshRuntimeLibrary:
http://qa.social.msdn.microsoft.com/Forums/en-US/winformssetup/thread/2f3a074b-08c4-4635-ba38-0fd7d04dcb1e
Then this, for wshom.ocx:
http://msdn.microsoft.com/en-us/library/x97ae5d9(v=vs.80).aspx

A: That link doesn't work, here is a cached version for future searchers
(http://qa.social.msdn.microsoft.com/Forums/en-US/winformssetup/thread/2f3a074b-08c4-4635-ba38-0fd7d04dcb1e)
Please note: This is a PRODUCTION equivalent (PPE/QA) environment. Please do not expect to get answers from the forums here - or for searches to be reflected in production. To get to the production version of this site, please remove "QA." from the URL.
Error using Interop.IWshRuntimeLibrary in SSIS Script Task 2008 R2 Bids
Error using Interop.IWshRuntimeLibrary in SSIS Script Task 2008 R2 Bids
Can't use IWshRuntimeLibrary in both an app and a dependent assembly?
could not load file or assembly
Could not load file or assembly?
Could not load file or assembly 'Interop.IWshRuntimeLibrary' Windows Forms

ClickOnce and Setup & Deployment Projects
Question
I'm using this library to create shortcuts in a custom action. In the reference, copy local is true. I get this error when I try to install on other computers. Any idea why this would happen? Building on Windows 7, error happens on both Windows 7 and XP. I notice that the file isn't in the Install folder of the target directory when the error happens, but I don't know why because copy local is set to true.
Tuesday, June 22, 2010 4:22 PM
Answers/Replies

Copy local is nothing to do with setup projects. If you want to install that assembly on the client system you must add it to the File System view (in whatever folder is needed) in the setup project.

*

*Phil Wilson

*Marked as answer by ScottyDoesKnow Tuesday, June 22, 2010 6:50 PM

*Unmarked as answer by ScottyDoesKnow Wednesday, July 14, 2010 12:15 PM

OK it detects all of the other libraries in the custom action project in Detected Dependencies but not this one, and when you go to add assembly it doesn't list COM libraries.
And I have output from the custom action project in the setup, so shouldn't copy local copy it to the file system?

Strange that it doesn't do it automatically, but manually adding the dll file to the Install folder of the user's application folder worked. Thanks Phil.

OK the problem just came up again. The library is added to the setup project, it's in the File System viewer in the Install folder (it's used in a custom install action), and while trying to install to a 32 bit Vista machine it gave the same error saying it couldn't find the file.
Wednesday, July 14, 2010 12:16 PM

Is this an assembly being installed into the GAC? - Phil Wilson

I'll say no, because I don't know how to do that. I just added it to the setup project and put it in the file system viewer in the Install folder.

*

*Wednesday, July 14, 2010 6:16 PM

Oh and it only screws up on Vista, XP and 7 work fine.

*

*Thursday, July 15, 2010 12:59 PM

Anybody have any clue what's wrong?

*

*Monday, July 19, 2010 5:22 PM

In the PrimaryOutput of the Application folder of your setup project add Interop.IwshRuntimeLibrary.dll. Then rebuild your setup project and try running the setup.exe. this worked in my case.. hope this solution helps you too.. Sameer G

*

*Friday, June 24, 2011 8:51 AM

sameer,
Application folder means exactly folder? I tried copying the same DLL in %AppData% folder but didn't work ... I am using installshield to create the setup project. Are you suggesting to copy the Interop.IwshRuntimeLibrary.dll include with my setup binaries? please help me


text:
Q: Reading WebSphere MQ activity log file Please tell me how do i read the MQ activity logs ? Which inside the QManger  folder.Thats format is human unreadable

A: Please confirm which directory and the filename of the log you are trying to read.  Active log files such as S0000001.LOG are not human readable. They are used internally by the queue manager.
The logs most often used to administer a queue manager are the error logs such as AMQERR01.LOG which are found in the subdirectory under qmgrs/QMGRNAME/errors directory.
If you truly need to see some info stored in the active log files, you can use the dmpmqlog command to dump a formatted version.  Refer to the knowledge center:
http://www-01.ibm.com/support/knowledgecenter/SSFKSJ_7.5.0/com.ibm.mq.ref.adm.doc/q083170_.htm

A: use strings  to read the MQ queue manager logs


text:
Q: AndroidManifest.xml can not resolve symbol TODO style and drawable I wrote a simple app in flutter and then after some research I changed the name and icon. After changing these two I got errors which I never had before on AndroidManifest.xml. I tried few things after research on thew Net. (like invalidate cache and restart) but still I get those errors. I would appreciate every help.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.sarisayfav1"
    android:versionCode="TODO"
    android:versionName="TODO">
    <!-- io.flutter.app.FlutterApplication is an android.app.Application that
         calls FlutterMain.startInitialization(this); in its onCreate method.
         In most cases you can leave this as-is, but you if you want to provide
         additional functionality it is fine to subclass or reimplement
         FlutterApplication and put your custom class here. -->
    <application
        android:name="io.flutter.app.FlutterApplication"
        android:label="Akçakale_Sarı_Sayfa"
        android:icon="@android:mipmap/sym_def_app_icon"
        tools:ignore="NewApi">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize"
            tools:targetApi="honeycomb">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <!-- Displays an Android View that continues showing the launch screen
                 Drawable until Flutter paints its first frame, then this splash
                 screen fades out. A splash screen is useful to avoid any visual
                 gap between the end of Android's launch screen and the painting of
                 Flutter's first frame. -->
            <meta-data
              android:name="io.flutter.embedding.android.SplashScreenDrawable"
              android:resource="@drawable/launch_background"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>

A: android:versionCode="TODO"
android:versionName="TODO"

remove these 2 lines.
TODO is not a recognized android version Name. flutter will set them automatically


text:
Q: How to integrate GOOGLEFINANCE results in an array formula? Following ARRAYFORMULA is giving me an error "parameter 1 value is invalid."
=ARRAYFORMULA(IF(ISBLANK(B2:B), "",  GOOGLEFINANCE(B2:B, "price")))

B column of my sheet contains the stock symbols whose value I wish to fill in my sheet. Example below
Company Name
GOOG
ADBE
MSFT

Can someone help here?

A: This questions seems to be a duplicate of Google finance as an argument for ArrayFormula. I have answered it with more detail. As a new user I'm only able to post an answer here, I cannot comment/flag as duplicate.
Anyway, assuming stock symbols are in range B2:B, then you put the following formula in cell C2:
=IFERROR(MAP(B2:B,LAMBDA(company,GOOGLEFINANCE(company,"price"))))

This is a new method since the introduction of LAMBDA and its helper functions in Google Sheets in August 2022.
The trick here is, as far as I understand, that MAP(LAMBDA) calculates the specified formula for each row in the input array separately (effect similar to manually expanding the formula over the whole range), whereas ARRAYFORMULA passes the whole array as an argument to the formula (GOOGLEFINANCE is special and doesn't work intuitively with such input).

A: LAMBDA and friends are available, so this works:
=BYROW(A2:A, LAMBDA(row, IF(row = "",, GOOGLEFINANCE(row, "price"))))

Old story:
GOOGLEFINANCE cannot be used in array formulas. You'll have to extend your formula downwards.
For example this formula should be in every cell from C2 and down:
=IF(NOT(ISBLANK($B$2:$B)), GOOGLEFINANCE($B$2:$B, "price"), "")


text:
Q: Cannot manage services on remote server, how to remotely execute without services? Background info
I am in a bit of a situation right now.
One of our clients has an application server (Server 2008 R2) which hosts critical medical applications. The server is located in another city, no display attached. It is in a domain network I have access to remotely via VPN and RDP, though. Now today it would not start one of the applications, and when trying to RDP into the machine I got a timeout, while I can ping it and network shares are still available.
Looking further into it, RDP and VNC services are not running. I can still use remote management and try to start/stop/restart services on the server, but it fails with error 1053, stating basically a timeout happened. Now normally I would just reboot but here this isn't an option currently.
The question
So due my inability to start services, I can't even use PSExec to regain remote access. Is there any possibility to start an application remotely without being dependent on a service?

A: If a program requires a service to run properly then the answer is No, the service is a must.
As for RDP, since the service is responsible for opening RDP port (3389) for listening then I believe that you won't be able to connect to the remote machine until the service is up and port is opened.
Edit #1:
PsExec uses the Windows Service control Manager API to start the PsExecsvc service on the remote system which creates a named pipe that PsExec communicates with. This named pipe is what allows for input/output redirection back to the system that launched PsExec.
You can try using PowerShell, follow this guide to do so.
If both PowerShell and psexec are not working for you then as far as I know there are no other ways to run commands on remote machines.


text:
Q: Java method invocation ambigious for javac but not for Eclipse Try to compile the following Test.java source file:
interface A<K> {
    void method(K k);
}

interface B {
    void method(Integer k);
}

interface C extends A<Integer>, B {
}

class D implements C {
    public void method(Integer i) {}
}

public class Test {
    public static void main(String args[]) {
        C c = new D();
        c.method(Integer.valueOf(0));
    }
}

The method call c.method() is declared ambigious by javac, but not by Eclipse. I've seen several examples of this kind of problems on StackOverflow (javac gives an error, Eclipse doesn't) but in this specific case I really don't understand how the call can be considered ambiguous, given that the compiler compiles interface C.
Who's right?
This example fails with both Java 8 and Java 9. Note that making the method explicit:
interface C extends A<Integer>, B {
    void method(Integer k);
}

makes the code compilable, which is quite weird, as the interface is exactly the same.

A: Oracle has just acknowledged that this appears to be a bug.
http://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8177440


text:
Q: Memcache flush_all not working as expected with namespaces on Google App Engine Python Going over the documentation for multitenancy + memcache it seems that memcache entries are separated for each namespace. See documentation here.
The problem is that when we call:
memcache.flush_all()

Everything is flushed in the memcache, not just the entries for the current namespace.
Before calling flush_all() we are explicitly setting the namespace using the following code:
namespace_manager.set_namespace(foo)

How can I flush entries in memcache only for the current namespace?

A: Yes, it is somewhat unexpected that flush_all deletes everything in your app's memcache not just for one namespace. The App Engine development team has a feature request to allow per-namespace flushing. See Issue 5190.
One workaround is for you to maintain a persistent integer "generation count" that you include as part of the namespace name. When you want to flush a namespace, you instead increment the generation count and use the new namespace, which will be brand new and empty.  You can ignore the items in your old namespace, as they will slowly get evicted over time.


text:
Q: Young man turned into cyborg to help defend city against monsters The movie I'm trying to find the name for is a late 80's Sci-Fi action film that came out before Revenge of the Nerds 2 - so 85-87. It was in theaters  during the summer.
In it there is this city that is under constant attack from a neighboring city or civilization of monsters. A young man volunteers to be turned into a cyborg to fight these monsters. He becomes a red and black leather covered cyborg able to change back and forth between human and cyborg.
Humans have been being captured and turned into slaves and mind controlled by a witch with an eye in the palm of her hand.  At one point the hero is thrown or jumps into a pit only to transform and catch himself with a grappling hook from his cyborg arm, then jumping back out to kick butt.
Can anyone identify this movie?

A: There is a very similar question here where the answer seems to be Infra-man although it was released in 1975.

I agree with Andrew, that really does sound like Infra-Man, the character She-Demon has eyes in the palms of her clawed hands, and they do brainwash some of the good guys. Great costumed/kaiju flick with all the elements that make this genre so fun to watch. Despite losing the widescreen format of the recent DVD release "The Super Inframan", the VHS "Infra-Man" version has some of the most hilariously enthusiastic dubbing I've ever heard. All the mutants have great over the top voices, and who could ever forget a villainess like Princess Dragon Mom.
Its possible this could have been shown in some theaters as a revival in '87, but the original was definitely put out in 1975.

There's nothing specific in the trailer that matches, but does this look what you're looking for?

One possibility is that you were watching a 1987 episode of Siskel and Ebert's Guilty Pleasures. They did mention Infra-Man in that year.


text:
Q: How to view source code using Vtune with MinGW I am compiling a C++ source code with MinGW's g++. When analysing the performance of this on Vtune, the "bottom up" tab will let me see the assembly, but not the source code. This is the list of warnings that Vtune gives after running the program:

I assume this is because the symbol files are missing, but I have tried compiling with
-g
-g3
-gstabs
-gdwarf-2
-gdwarf-3

but none of these work, it still cannot locate the debugging information.

A: Consider explicitly specifying "Search Directories" in "Analysis configuration" to provide path to Sources and (if possible) to debug symbols (pdb files).
For vtune 2020/2021 versions they can be added/adjusted at the bottom right of Analysis Configuration (note also that for Intel Inspector and Intel Advisor those configurations are still located in more traditional "Project Properties" (CTRL+P) dialog) :

Usually, source files are automatically integrated, but in some cases (either because of MinGW or because you moved your binaries/sources or project after profiling) - you may need to specify those explicitly as shown above


text:
Q: KeyboardAvoidingView Problems on iOS I am having some problems with the KeyboardAvoidingView on iOS. The problem is that I cannot really reproduce the error. I am using the KeyboardAvoidingView in a relatively normal setting to secure that inputs aren't hidden behind the keyboard, but on some particular devices it keeps bugging out and basically pushes everything thats included in the View off the screen.
Example:
        <Header
          marginTop={screenWidth / 10}
          paddingHorizontal={10}
          onPress={false}
          source={require("../../assets/images/arrowback.png")}
          text={ I18n.t("VERIFY_TITLE")}
        />
        {loading ? (
          <AppIndicator height={screenHeight} position={"absolute"} />
        ) : null}

        <View
        style={[sameStyle.flexOne, { paddingHorizontal: 20 }]}
        >
        <KeyboardAvoidingView>
          <ScrollView
            pointerEvents={loading ? "none" : "auto"}
            showsVerticalScrollIndicator={false}
            style={sameStyle.flexOne}
          >
            <Button
                opacity={opacity}
                disabled={false}
                onPress={this.sendVerifyEmail}
                shapeViewWidth={"48%"}
                shapeView2Width={"48%"}
                marginBottom={35}
                marginTop={50}
                name={I18n.t("SEND_VERIFY_MAIL_BUTTON")}
            />
            {/* <DescriptionText
              marginTop={15}
              desc={I18n.t("VERIFY_MAIL_HINT")}
            /> */}
            <Title
              marginTop={40}
              title={I18n.t("VERIFY_MAIL_TITLE")}
              fontFamily={Font.REGULAR}
            />
            <DescriptionText
              marginTop={15}
              desc={I18n.t("VERIFY_MAIL_DESC")}
            />
            <InputWithIcon
              keyboardType={"numeric"}
              returnKeyType={"send"}
              marginTop={20}
              maxLength={60}
              label={'Code'}
              value={this.state.code.toString()}
              onChangeText={(text) => this.setState({ code: text })}
              onSubmitEditing={this.sendVerifyCode}
            />
            <Button
              opacity={opacity}
              disabled={this.state.code == 0 || this.state.code == null}
              onPress={this.sendVerifyCode}
              shapeViewWidth={"48%"}
              shapeView2Width={"48%"}
              marginBottom={50}
              marginTop={50}
              name={I18n.t("COMMON_SEND_BUTTON")}
            />
          </ScrollView>
        </KeyboardAvoidingView>
        </View>```

On most devices the component renders completely as expected, but on some particular phones it looks like this:
[Excuse the text, but basically the screen is empty apart from the Header][1]

  [1]: https://i.stack.imgur.com/nmzub.png

Because of legacy code we are sadly still using React-Native 0.59

This particular user is using an iPhone 12 on iOS 16, but we have also had Users with this problem  using iPhone Xs and also on other versions such as 15.3.6 etc. Like I said, on some devices with exactly the same specs it is working fine, on others it's not. Any help is appreciated.

A: Since you cannot describe exactly, try this setting:
import { useHeaderHeight } from "@react-navigation/stack";

In your component
const headerHeight = useHeaderHeight();
<KeyboardAvoidingView
            keyboardVerticalOffset={headerHeight}
            behavior={Platform.OS === "ios" ? "padding" : "height"}
>


text:
Q: What is the meaning of this operation So we got this piece of code on a test and I had zero idea what is the meaning and how it works.
unsigned int a = 1, b = 2, c;
and then c = a&b || a&&b;
The question was: What is the value of c. Answer was 1.
Can somebody explain what is happening in initialization of c?

A: The unsigned int variables a and b hold some bit-pattern that represent 1 and 2. It won't be this, but for the sake of the description, let's say
  a = 0b0001
  b = 0b0010

That would be the numbers 1 and 2 in a 4-bit integer.
The & operator does bit-wise and, so bit by bit you evaluate (0,0)->0, (0,1)->0, (1,0)->0 and (1,1). So, for the two integers above
    a = 0b0001
    b = 0b0010
  a&b = 0b0000

We see that a&b is zero, since they do not have any overlapping 1-bits.
The operator && does a logical and, which means that the result is 1 if both arguments are non-zero and zero otherwise. So a && b = 1 because neither a and b are zero.
     a = 0b0001
     b = 0b0010
  a&&b = 0b0001

The || operator is logical or; it gives you 1 if any of the arguments are non-zero and only zero if both arguments are zero. So, since
  a&b = 0b0000
 a&&b = 0b0001

where a&&b is non-zero, you get c = (a&b) || (a&&b) = 1.

A: This assignment statement
c = a&b || a&&b;

may be rewritten for clarity the followinmg way
c = ( a&b ) || ( a&&b );

a & b is the bitwise AND operation.  As a is equal to 1 and b is equal to 2 then the result of the operation is equal to 0 (I am using only 8 bits in the number representations for simplicity)
00000001
&
00000010
========
00000000

From the C Standard (6.5.10 Bitwise AND operator)

4 The result of the binary & operator is the bitwise AND of the
operands (that is, each bit in the result is set if and only if each
of the corresponding bits in the converted operands is set).

In this expression a && b there is the logical AND operation. It is equal to 1 when the both operands are unequal to 0. As a and b are unequal to 0 then the result of the operation is 1.
From the C Standard (6.5.13 Logical AND operator)

3 The && operator shall yield 1 if both of its operands compare
unequal to 0; otherwise, it yields 0. The result has type int.

So you have
c = 0 || 1;

where the logical OR operation is used. It yields 1 if at least one operand is not equal to 0.
From the C Standard (6.5.14 Logical OR operator)

3 The || operator shall yield 1 if either of its operands compare
unequal to 0; otherwise, it yields 0. The result has type int.

So the variable c will be assigned with the value 1.

A: I will explain it from another point of view.
a&b will give non zero only if both have at least one bit set at the same position
a&&b will give 1 only if both are not zero
a&b || a&&b will give be one only if both are not zero and have at least one bit set at the same position.
It can be reduced to:
int c = a&&b;


text:
Q: WinAppDriver WindowsDriver url problems I have got a solution, it's actually a demo on how Win App Driver should work but I can't for the life of me get it to work. Using Win App Driver with selenium and appium web drivers (as mentioned at 5 minutes into this video). I have the solution as shown below and when I run my AddAlarm test I get the error ... "the target machine actively refused it 127.0.0.1:4723".
The full error message is at the bottom of this post.
My question is, what do I need to do to make the application we're testing "Alarm & Clock" actually launch on the url 127.0.0.1:4723 is there anything I have to do to make it available on that url / port? Also, how do I verify is "app"  and "Microsoft.WindowsAlarms_8wekyb3d8bbwe!App" are correct in the setup?
//Class with my test "AddAlarm"
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Appium.Windows;
using System.Threading;
using System;

namespace AlarmClockTest
{
    [TestClass]
    public class ScenarioAlarm : AutoTest_SynTQ.UnitTestSession
    {
        private const string NewAlarmName = "Sample Test Alarm";

        [TestMethod]
        public void AlarmAdd()
        {
            // Navigate to New Alarm page
            session.FindElementByAccessibilityId("AddAlarmButton").Click();

            // Set alarm name
            session.FindElementByAccessibilityId("AlarmNameTextBox").Clear();
            session.FindElementByAccessibilityId("AlarmNameTextBox").SendKeys(NewAlarmName);

            // Set alarm hour
            WindowsElement hourSelector = session.FindElementByAccessibilityId("HourLoopingSelector");
            hourSelector.FindElementByName("3").Click();
            Assert.AreEqual("3", hourSelector.Text);

            // Set alarm minute
            WindowsElement minuteSelector = session.FindElementByAccessibilityId("MinuteLoopingSelector");
            minuteSelector.FindElementByName("55").Click();
            Assert.AreEqual("55", minuteSelector.Text);

            // Save the newly configured alarm
            session.FindElementByAccessibilityId("AlarmSaveButton").Click();
            Thread.Sleep(TimeSpan.FromSeconds(3));

            // Verify that a new alarm entry is created with the given hour, minute, and name
            WindowsElement alarmEntry = session.FindElementByXPath($"//ListItem[starts-with(@Name, \"{NewAlarmName}\")]");
            Assert.IsNotNull(alarmEntry);
            Assert.IsTrue(alarmEntry.Text.Contains("3"));
            Assert.IsTrue(alarmEntry.Text.Contains("55"));
            Assert.IsTrue(alarmEntry.Text.Contains(NewAlarmName));

            // Verify that the alarm is active and deactivate it
            WindowsElement alarmEntryToggleSwitch = alarmEntry.FindElementByAccessibilityId("AlarmToggleSwitch") as WindowsElement;
            Assert.IsTrue(alarmEntryToggleSwitch.Selected);
            alarmEntryToggleSwitch.Click();
            Assert.IsFalse(alarmEntryToggleSwitch.Selected);
        }

        [ClassInitialize]
        public static void ClassInitialize(TestContext context)
        {
            Setup(context);
        }

        [ClassCleanup]
        public static void ClassCleanup()
        {
            // Try to delete any alarm entry that may have been created
            while (true)
            {
                try
                {
                    var alarmEntry = session.FindElementByXPath($"//ListItem[starts-with(@Name, \"{NewAlarmName}\")]");
                    session.Mouse.ContextClick(alarmEntry.Coordinates);
                    session.FindElementByName("Delete").Click();
                }
                catch
                {
                    break;
                }
            }

            TearDown();
        }

        [TestInitialize]
        public override void TestInit()
        {
            // Invoke base class test initialization to ensure that the app is in the main page
            base.TestInit();

            // Navigate to Alarm tab
            session.FindElementByAccessibilityId("AlarmPivotItem").Click();
        }
    }
}

//Inherited class below
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Appium.Windows;
using OpenQA.Selenium.Remote;
using System;
using System.Threading;

namespace AutoTest_SynTQ
{
    [TestClass]
    public class UnitTestSession
    {
        private const string WindowsApplicationDriverUrl = "http://127.0.0.1:4723";
        private const string AlarmClockAppId = "Microsoft.WindowsAlarms_8wekyb3d8bbwe!App";

        protected static WindowsDriver<WindowsElement> session;
        protected static RemoteTouchScreen touchScreen;

        public static void Setup(TestContext context)
        {
            // Launch Alarms & Clock application if it is not yet launched
            if (session == null || touchScreen == null)
            {
                TearDown();

                // Create a new session to bring up the Alarms & Clock application
                DesiredCapabilities appCapabilities = new DesiredCapabilities();
                appCapabilities.SetCapability("app", AlarmClockAppId);
                session = new WindowsDriver<WindowsElement>(new Uri(WindowsApplicationDriverUrl), appCapabilities);
                Assert.IsNotNull(session);
                Assert.IsNotNull(session.SessionId);

                // Set implicit timeout to 1.5 seconds to make element search to retry every 500 ms for at most three times
                session.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(1.5));

                // Initialize touch screen object
                touchScreen = new RemoteTouchScreen(session);
                Assert.IsNotNull(touchScreen);
            }
        }

        public static void TearDown()
        {
            // Cleanup RemoteTouchScreen object if initialized
            touchScreen = null;

            // Close the application and delete the session
            if (session != null)
            {
                session.Quit();
                session = null;
            }
        }

        [TestInitialize]
        public virtual void TestInit()
        {
            WindowsElement alarmTabElement = null;

            // Attempt to go back to the main page in case Alarms & Clock app is started in EditAlarm view
            try
            {
                alarmTabElement = session.FindElementByAccessibilityId("AlarmPivotItem");
            }
            catch
            {
                // Click back button if application is in a nested page such as New Alarm or New Timer
                session.FindElementByAccessibilityId("Back").Click();
                Thread.Sleep(TimeSpan.FromSeconds(1));
                alarmTabElement = session.FindElementByAccessibilityId("AlarmPivotItem");
            }

            // Verify that the app is in the main view showing alarmTabElement
            Assert.IsNotNull(alarmTabElement);
            Assert.IsTrue(alarmTabElement.Displayed);
        }
    }
}

Test Name:  AlarmAdd
Test FullName:  AlarmClockTest.ScenarioAlarm.AlarmAdd
Test Source:    C:\Users\ECombe.OPTIDOORS\Documents\SynTQCodedUITesting\AutoTest_SynTQ\SCN_Alarm.cs : line 30
Test Outcome:   Failed
Test Duration:  0:00:00
Result StackTrace:
at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebDriver.StartSession(ICapabilities desiredCapabilities)
   at OpenQA.Selenium.Remote.RemoteWebDriver..ctor(ICommandExecutor commandExecutor, ICapabilities desiredCapabilities)
   at OpenQA.Selenium.Appium.AppiumDriver1..ctor(Uri remoteAddress, ICapabilities desiredCapabilities)
   at OpenQA.Selenium.Appium.Windows.WindowsDriver1..ctor(Uri remoteAddress, DesiredCapabilities desiredCapabilities)
   at AutoTest_SynTQ.UnitTestSession.Setup(TestContext context) in C:\Users\ECombe.OPTIDOORS\Documents\SynTQCodedUITesting\AutoTest_SynTQ\UnitTestSession.cs:line 28
   at AlarmClockTest.ScenarioAlarm.ClassInitialize(TestContext context) in C:\Users\ECombe.OPTIDOORS\Documents\SynTQCodedUITesting\AutoTest_SynTQ\SCN_Alarm.cs:line 71
Result Message:
Class Initialization method AlarmClockTest.ScenarioAlarm.ClassInitialize threw exception. OpenQA.Selenium.WebDriverException: OpenQA.Selenium.WebDriverException: Unexpected error. System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 127.0.0.1:4723
   at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
   --- End of inner exception stack trace ---
   at OpenQA.Selenium.Appium.Service.AppiumCommandExecutor.Execute(Command commandToExecute)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary2 parameters).

A: The answer in my case was to use Developer mode. The actual problem was winappdriver.exe closing immediately. More details here.


text:
Q: FragmentTransaction replace causes overlay I read this FragmenManager replace makes overlay and the solution which stated the problem was due to defining the fragment statically in the xml.  I have the same problem, but I did not define my fragment statically, I use a framelayout and the fragment manager to pop in and out my DYNAMICALLY created fragments using support fragment transactions.  Here is my scenario:
Activity 1 has a framelayout called "content" in its xml.

*

*fragment X is created and replaces framelayout "content".

*When a listview item in fragment X is clicked, add fragment Y to the backstack.  "content", which shows fragment X, is replaced with fragment Y.

*When a button in fragment Y is clicked, fragment Z is added to the backstack.  "content", which shows fragment Y, is replaced with fragment Z.

*Clicking a button in fragment Z pops the backstack and replaces "content" with a new instance of fragment Y.
These steps work as expected, except after, when I press back to reach fragment X, click on a listview item, and do step 3 again.  Instead of fragment Z replacing fragment Y like earlier, it overlays it.  Why is this happening and how do I resolve it?  Thanks
Code for step 2:
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.addToBackStack("y_screen");
ft = ft.replace(R.id.content_frame, FragmentY.newInstance(qTitle, qDetails, qObjectID));
ft.commit();

Code for step 3:
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.addToBackStack("z_screen");
ft.replace(R.id.content_frame, FragmentZ.newInstance(questionTitle, questionDetails,
                                                     qObjectID));
ft.commit();

Code for step 4:
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
fm.popBackStack();
ft.replace(R.id.content_frame, FragmentY.newInstance(questionTitle, questionDetails,
                                                     qid));
ft.commit();


text:
Q: Algoritmo para cálculo de rota mais rápida entre dois pontos em camadas cartesianas paralelas (3D) Eu estou trabalhando em uma solução que envolve determinar a rota de menor esforço entre dois pontos de um prédio. (Imagine estudantes em seu primeiro dia de universidade, e que precisam saber onde fica e como chegar a uma dada sala de aula em um prédio, ou como ir da sala atual para a próxima aula.)
Basicamente eu tenho uma estrutura cartesiana onde cada andar está mapeado. Eu também tenho indicadores de pontos de acesso (portas, rampas para deficientes, escadarias) e os pontos onde estes pontos se conectam (Escadaria do Térreo se conecta com escadaria do 2º andar em X48 Y4, por exemplo), mais ou menos como a imagem abaixo:

Onde ciano indica uma escadaria, e azul-estranho elevadores, entre outros marcadores não exibidos.
(Para os daltônicos, minhas sinceras desculpas e algumas informações adicionais: as escadarias estão localizadas na parte superior direita dos mapas; os elevadores, próximos ao centro.)
Eu comecei meu código baseado em uma variante do algoritmo de Dijkstra chamado A-Estrela (A*), que é basicamente o problema do caminho mais curto com algumas otimizações. (Curiosidade: Vários jogos implementam variantes do A* para determinar a rota de personagens em um mapa.)

A* é perfeito para determinar rotas em um mesmo andar, porém eu tenho que levar em consideração os vários andares, cada um com um layout diferente.
Pergunta
Existe alguma maneira mais apropriada para solucionar este problema?
Ou, de forma mais clara (obrigado bfavaretto),
Dado o fator adicional de N andares, existe algum algoritmo que seja mais indicado do que o A*?
Disclaimer:
Imagem isométrica original de DougIllustrations.com.

A: Disclaimer: Esta não é uma resposta per se, apenas uma compilação das respostas/possibilidades até o momento. Imagino que o resultado final venha a ser uma combinação das sugestões apresentadas.
A* 3D (@bfavaretto)
Uma implementação possível deste algoritmo mapearia os pontos de contato entre os andares, implementado as 'lajes' como descrito por @bacco. A altura de cada camada pode ser definida como 1, já que não usaremos jetpacks, evitando assim o cálculo de custo horizontal.

Na imagem, vermelho indicaria elevadores e azul, escadarias; verde, as paredes (objetos intransponíveis) e branco o espaço navegacional. (Espero que esta combinação de cores seja válida para daltônicos!)
D* / D* Lite (@Cigano)
Esta é bem interessante por permitir cálculos de custo composto de tempo. Algumas situações possíveis:

*

*O ponto a ser alcançado é em um andar superior. O custo inicial de elevador é 10, +2 por andar. O custo de escadarias é 5 inicialmente, mas é adicionado 10 a cada andar a ser percorrido (+15, +25, etc.) Subir 1 andar pelas escadas pode ser melhor do que esperar pelo elevador, mas não é o caso se você precisar subir 10.

*O ponto a ser alcançado é em um andar inferior. Custo de elevador: 10 +2 por andar. Custo de escadarias: 5 +3 por andar (Não é tão cansativo descer uma escada, mas toma tempo.)

Otimizações (@utluiz)
Várias sugestões boas aqui, algumas não relacionadas diretamente à pergunta porém podem ajudar a criar uma solução bem melhor.

*

*A informação sobre a presença de alguma deficiência física nos usuários cadastrados está presente, e a otimização de rota eliminando escadarias é possível. Uma configuração similar pode ser oferecida a usuários públicos via seleção na interface.

*É possível utilizar OpenCV para analizar ruído em imagens das câmeras que observam os elevadores, entradas e escadarias e traçar um histograma por horário. O resultado poderia ser um multiplicador de custo.

*Uma possibilidade de otimização deste algoritmo é definir zonas dentro de cada andar que possuem apenas uma possibilidade de rota de saída, e manter um cache com custos para pontos pré-determinados comuns (pontos de acesso, etc.) Isso pouparia um pouco do workload.

A: A* é o que é normalmente usado, mas existe uma família de algoritmos chamada D* que considera que o cálculo pode variar de etapa pra etapa, mas esse seria interessante se o caminho não fosse constante, como acredito que é o caso da sua realidade.
Há ainda uma versão mais simples de ser implementada chamada D* Lite, que é bem diferente do D* original.

A: De uma forma bem simples, conectar os andares por uma aresta, criando uma espécie de grafo tridimensional me parece a solução mais adequada.
O algoritmo, no entanto, deve ser customizado conforme certas condições. Por exemplo, a configuração para deficientes iria colocar um custo infinito nas escadas e demais vias sem acessibilidade para que estas nunca fossem selecionadas.
A questão de evitar elevadores em horários de picos poderia ser outra configuração a cargo do usuário. Já uma opção de "andar no máximo X andares" seria um pouco mais trabalhosa, exigindo armazenar um estado adicional para cada rota.
E para a coisa funcionar bem na prática, seria ideal ter métricas de tempo média de espera dos elevadores em cada horário.
A ideia geral é que os pesos de cada aresta, isto é, de andar cada trecho, teria que baseado numa função dinâmica que considerasse as configurações do usuário e também informações de tráfego daquele trecho.
Porém, dependendo da quantidade de nós e da carga de uso do sistema, isto pode ser pouco eficiente. Neste caso, seria possível definir rotas subótimas, por exemplo, pré-calculando para cada andar a menor distância entre um determinado ponto e a escada ou elevador mais próximo, juntando então essa informação para selecionar uma global.
Enfim, essas são algumas ideias. Elas não respondem de forma conclusiva ou matemática a questão (e são grandes demais para comentários), mas espero que possam gerar novas ideias que incrementem sua solução atual.


text:
Q: BJT Current limiter for linear power supply I am trying to design a current limiter or my LM317 based power supply using this schema.
The power supply must be able to provide a maximum of 1.5A@30V.
I made some calculations and I would like to understand if I am on the right way.
Goal is to find suitable values for the resistors and the right BJTs.
1) Q1:
Assuming the power supply is working at its limit, on Q1 we will have a Ic=1.5A and Vce=Vcc-Vq2be=30-0.7=29.3V.
A suitable BJT able to support this values could be the D44H8.
2) Value of R1:
The D44H8 has a worst case current gain of 10. So, on Q1, if Ic=1.5A the Ib=1.5/10=0.15A. Being near the limit of 1.5A, we can assume Vq2be=VRsen=0.7V, thus: VR1 = 30-0.7-0.7=28.6. This lead to R1 = 28.6/0.15=190 Ohm
3) Value of Rsen:
On Q1: Ic=1.5, Ib= 0.15, Ie=1.65
Voltage drop across Rsen is circa 0.7. Then: Rsen=0.7/1.65=0.42 Ohm
4) Q2:
Q2 must be able to support at least 30-0.7-0.7=28.6V on its collector, but much smaller current. I choose a BJT in the BC337 family, which will guarantee 45Vce and a max collector current of 800mA
Keeping R1 constant and varying Rsen I can set different maximum current values on the load.
Am I more or less right?

simulate this circuit – Schematic created using CircuitLab

A: You are more or less right, but this is not a good solution.
Your voltage at the collector of q2 will never get much above 1.4v. And your 190 ohm R1 will dissipate 30x0.15 = 4.5W
Because you have feedback you can use a fet to pass the current and make R1 much bigger. You will probably have to use heat sinks on Rsense (1W+), and your pass transistor q1 will have to take the full whack of power. That is near enough 45W. Also, your limit will vary by at least 300mA across the temperature range, maybe 1.3A minimum to 1.6A maximum.
There are many more efficient and more accurate solutions. What other design criteria do you have? Eg Cost, Accuracy, board space?
Followup to comments:
Below, Enrico asked to see some alternatives. One possibility is to use Lmp8646 which is a current sense amplifier from TI. You would need Rsense of about 0.1R. Set the gain accordingly then feed the output into a comparator. Use the comparator to turn off the supply (does your regulator have an enable input?). For this circuit you would need a fixed supply less to power the ic, comparator, and reference. The resistor would dissipate just under 0.25W. I would suggest putting a lot of hysteresis on the comparator and also a capacitor on the output to stop the thing switching on and off very fast during fault condition. You could instead latch the supply off until a reset button is pressed.
This IC is also suitable for more sophisticated current control, such as variable current limiting and folding back the supply voltage by connecting the output into the regulator feedback. It is just the first one I came across - other brands / circuits are available.