text:
Q: Mschart get value of a series at the cursor position I have an mschart with values and a cursor line moving based on a timer. Is it possible to get the value of a specific series at the cursor position?
Thanks.

A: You can get current DataPoint value with MouseMove event handler.
private void chart1_MouseMove(object sender, MouseEventArgs e)
{
  var source = sender as Chart;
  HitTestResult result = source.HitTest(e.X, e.Y);

  if (result.ChartElementType == ChartElementType.DataPoint && result.PointIndex != -1)
  {
    var xValaue = source.Series[0].Points[result.PointIndex].XValue;
    var yValaue = source.Series[0].Points[result.PointIndex].YValues[0];
  }
}

A: string ceva = detailChart.Series[1].Points[detailChart.ChartAreas[0].CursorX.Position].GetValueByName("Y").ToString(


text:
Q: Why does the File and FileStream API fail to write binary data with no exception thrown on Ubuntu? I have an application which I have tried to target both .NET Core 2.1 and .NET Core 3.1 for build while still exhibiting this issue. I am replicating the file streaming process that happens from our API (an Ubuntu 18.04.4 VM) to our storage server (also an Ubuntu VM), except it goes from the storage to our OCR service (a third Ubuntu VM). The Ubuntu VMs all have the latest version of .NET Core installed. This file streaming process works on a homegrown "file service" protocol which I would rather avoid explaining in great detail, but suffice to say that there is a "Create" message which tells the recipient to create a file handle and write the first packet of data (packets are up to 64 kB), and upon receiving this "Create" message, a consumer is initialized which consumes the rest of the file data as "Append" messages from a separate queue until a "Close" message is received (contains no payload). This seemed to work great until I actually tried to perform basic manipulations on the file received on OCR (namely, splitting the pages out of a PDF document) and realized that the file is corrupt. On a hunch I checked the size of the file on the OCR server, and sure enough it is exactly 64 kB smaller than the original file. This issue has never occurred in the API-to-storage part of the pipeline. I have checked our storage server to ensure that the data is not corrupted when transferring from the API by downloading it.
On another hunch, I decided to comment out the code which writes the Append message payloads to the file to ensure that the missing packet was not the original Create payload. I was correct, and after processing just the Create message, the file is 0 bytes. I have checked the length of the Create payload and also printed it out as a hash to ensure it's not all 0s for whatever reason -- no issues there. However, every time I get to writing the bytes to the actual file, no data is written and no error is thrown. The file handle and directory is created with a size of 0 bytes and all log messages are printed. I will now post all the different ways I have tried to write this initial 64 kB of data to the file:
File API
public FileServiceResponseEnvelope Create(FileServiceMessageEnvelope message, string filePath)
        {
            var response = CreateResponse(message);
            var payload = SerializationHelper.DeserializeObject<SecureMessage>(message.SignedPayload).Payload;

            if (!File.Exists(filePath))
            {
                // 23 is enough for the first 8 bytes and the hyphens separating them.
                _logger.LogStatement($"Creating new file at [{filePath}] while appending [{payload.Length} bytes] and hash that starts with {BitConverter.ToString(payload).Substring(0, 23)}...", LogLevel.Trace, nameof(Create));
                Directory.CreateDirectory(Path.GetDirectoryName(filePath));
                File.WriteAllBytes(filePath, payload);
            }
            else
            {
                var error = $"File at [{filePath}] already exists and cannot be created.";
                response.ErrorMessage = error;
                response.Success = false;
                throw new InvalidOperationException(error);
            }

            return response;
        }

FileStream API
public FileServiceResponseEnvelope Create(FileServiceMessageEnvelope message, string filePath)
        {
            var response = CreateResponse(message);
            var payload = SerializationHelper.DeserializeObject<SecureMessage>(message.SignedPayload).Payload;

            if (!File.Exists(filePath))
            {
                // 23 is enough for the first 8 bytes and the hyphens separating them.
                _logger.LogStatement($"Creating new file at [{filePath}] while appending [{payload.Length} bytes] and hash that starts with {BitConverter.ToString(payload).Substring(0, 23)}...", LogLevel.Trace, nameof(Create));
                Directory.CreateDirectory(Path.GetDirectoryName(filePath));
                using (var stream = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite))
                {
                    stream.Seek(0, SeekOrigin.Begin);
                    stream.Write(payload, 0, message.Count);
                }
            }
            else
            {
                var error = $"File at [{filePath}] already exists and cannot be created.";
                response.ErrorMessage = error;
                response.Success = false;
                throw new InvalidOperationException(error);
            }

            return response;
        }

FileStream API using WriteByte
public FileServiceResponseEnvelope Create(FileServiceMessageEnvelope message, string filePath)
        {
            var response = CreateResponse(message);
            var payload = SerializationHelper.DeserializeObject<SecureMessage>(message.SignedPayload).Payload;

            if (!File.Exists(filePath))
            {
                // 23 is enough for the first 8 bytes and the hyphens separating them.
                _logger.LogStatement($"Creating new file at [{filePath}] while appending [{payload.Length} bytes] and hash that starts with {BitConverter.ToString(payload).Substring(0, 23)}...", LogLevel.Trace, nameof(Create));
                Directory.CreateDirectory(Path.GetDirectoryName(filePath));;
                using (var stream = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite))
                {
                    stream.Seek(message.Position, SeekOrigin.Begin);
                    foreach (byte b in payload)
                    {
                        _logger.LogStatement($"Writing [{b}] to file...", LogLevel.Trace, nameof(Create));
                        stream.WriteByte(b);
                    }
                }
            }
            else
            {
                var error = $"File at [{filePath}] already exists and cannot be created.";
                response.ErrorMessage = error;
                response.Success = false;
                throw new InvalidOperationException(error);
            }

            return response;
        }

For reference, here is the Append message handler, which works.
AppendStream = new FileStream(DestinationPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);

...

public FileServiceResponseEnvelope Append(FileServiceMessageEnvelope message, FileStream appendStream)
        {
            var response = CreateResponse(message);
            var payload = SerializationHelper.DeserializeObject<SecureMessage>(message.SignedPayload).Payload;

            _logger.LogStatement($"Appending [{message.Count} bytes] to [{appendStream.Name}]. Actual length: [{payload.Length} bytes]", LogLevel.Trace, nameof(Append));
            if (appendStream == null)
                throw new InvalidOperationException($"The filestream was null and therefore cannot be appended to.");

            appendStream.Write(payload, 0, message.Count);

            return response;
        }

AppendStream is a member of the consumer class and AppendStream.Dispose() is called when the Close message mentioned earlier is received.
Any help with this would be much appreciated. I have also tried invoking Flush(true) and Close() even though I'm about 99% sure those are already called on disposal at the end of the using block. I'm running completely dry on things to try here and am starting to be convinced that this is some sort of System.IO library bug. All of the code above runs without errors, but no data is written on the "Create" handler. My only remaining idea is that something else is taking control of the file handle, but I tried to be careful to write all of this part of the code synchronously and driven by events signaled when the last piece is finished (for example the file is only processed by the actual OCR service, when the "Done" event on the consumer is invoked, which only happens when Close is received). I can't find anything else that might take control of that file handle in my code as of yet.  Apologies for the long-winded post, but I felt I had to lay it all out to show how stubborn this issue is and what I've tried.

redpajama_set_name: RedPajamaStackExchange


text:
Q: UIPickerView UIButton in viewForRow doesn't respond Button doesn't respond in viewForRow:
UIView * rowView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 44)] autorelease];

UIButton* deleteButton = [[[UIButton alloc]init]autorelease];
deleteButton.frame = CGRectMake(200, 10, 20,20);
[deleteButton setImage:[UIImage imageNamed:@"IconTrash.png"] forState: UIControlStateNormal];
[deleteButton addTarget: self action:@selector(removeCellAtIndexPath:) forControlEvents: UIControlEventTouchUpInside];

UILabel *labelText = [[UILabel alloc]init];
labelText.text =  [NSString stringWithFormat:@"%@",[[localFlagNotes objectAtIndex:row] value]];
labelText.font = [UIFont fontWithName:@"Arial" size: 24];
labelText.frame = CGRectMake(0, 10, 200, 28);
labelText.backgroundColor = [UIColor clearColor];

[rowView addSubview:labelText];
[rowView addSubview:deleteButton];
[labelText release];
return rowView;

removeCellAtIndexPath doesn't call after press button. Does anyone have some idea why and some solution?
I think button even not pressed only cell become active.

A: Your deleteButtonUr button's frame(width) exceeds the rowView's frame.so increase the view's frame as like,
UIView * rowView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 44)] autorelease];

otherwise adjust the label and deleteButton's frame with in your rowView's frame

A: I find ways.  just in
- (UIView*)pickerView:(UIPickerView *)pickersView viewForRow:(NSInteger)row
          forComponent:(NSInteger)component reusingView:(UIView *)view
     {
           PickerCustomView * rowView = [[PickerCustomView alloc]initWithFrame:CGRectMake(5, 0, 310, 50) withText:[[localFlagNotes objectAtIndex:row] value]] ;
           rowView.delegate = self;
           return rowView;
     }

Create custom View with button
Like this
- (id)initWithFrame:(CGRect)frame withText:(NSString*)text
{
   self = [super initWithFrame:frame];
   if (self)
{
     deleteButton = [[UIButton alloc]init];

    [deleteButton setImage:[UIImage imageNamed:@"IconTrash"] forState: UIControlStateNormal];
    [deleteButton addTarget:self action:@selector(deleteButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    deleteButton.frame = CGRectMake(250, 10, 35,35);

    textLabel = [[UILabel alloc]init];
    originText = text;
    NSString *trimmed = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    textLabel.text =  trimmed;
    textLabel.font = [UIFont fontWithName:@"Arial" size: 24];
    textLabel.frame = CGRectMake(20, 10, 230, 28);
    textLabel.backgroundColor = [UIColor clearColor];

    [self addSubview:textLabel];
    [self addSubview:deleteButton];

}
return self;

}
And use:
-(void)deleteButtonAction:(id)sender
 {
     [delegate removeCellAtIndexPath:originText];
 }

Or:
 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView:touch.view];

    if ( (location.x > 10 && location.x < 38) && (location.y > 240 && location.y < 265)    )
     {
        [self deleteButtonAction:nil];
     }
}


text:
Q:  at the bottom of the page above footer I'm trying to put this
 and text at the bottom of the page, so once the page loads it will stay at the bottom of the page even if I open developer tools in the browser.
It looks like this:

My code is currently like this:

    @RenderBody()

© @DateTime.Now.Year

I've tried wrapping hr and footer in a div, giving it id and css style
#footer {
position: absolute;
bottom: 0px;
}

but it causes
 to shrink from current width to the width of text date below it. If I add width: 100% in css,
 extends all the way to the right side of the screen, meanwhile I want it to be same as the current width. I've also tried giving wrapping
 class="container" which almost do the job, but then it moves text a bit to the right, so it's not aligned with the text fields and submit button. How can I solve this?

A: HTML:

Login

        <input type="text" placeholder="email">
        <input type="text" placeholder="password">
        <button>Sign In</button>

© @DateTime.Now.Year

CSS:
footer {
    width: 100%;
    box-sizing: border-box;
    margin: 0 auto;
}

.inner {
    border-top: 1px solid black;
    width: 100%;
}

input {
    display: block;
    margin-bottom: 15px;
}

button {
    margin-bottom: 15px;
}

.container {
    width: 75%;
    margin: 0 auto;
}


text:
Q: List from 2 unrelated objects only show one object as result I want to show the result in Postman from 2 unrelated objects using native queries as below:
    @Query(value = "select * from product p where p.id like concat('%', :productId, '%') ", nativeQuery = true)
    List<Product> findProductById(String productId);

    @Query(value = "select * from customer c where c.id like concat('%',:id,'%')", nativeQuery = true)
    List<Customer> findCustomerById(String id);

and I'd like to add their results with conditions:

*

*if productId is empty, I only want to show result from  List<Customer>, and vice versa

*if both are empty/not, it should show the result from both queries, product and customer as shown below:

    @Override
    public List<Object> findById(String customerId, String productId) {
        List<Object> obj = new ArrayList<>();
        if(customerId.isEmpty()){
            obj.addAll(productRepository.findProductById(productId));
        } else if(productId.isEmpty()){
            obj.addAll(customerRepository.findCustomerById(customerId));
        } else {
            obj.addAll(productRepository.findProductById(productId));
            obj.addAll(customerRepository.findCustomerById(customerId));
        }
        return obj;
    }

and this is my controller:
    @GetMapping("/custom")
    public List<Object> findById(@RequestParam(name = "customer") String customer, @RequestParam(name = "product") String product){
        return service.findById(customer, product);
    }

However, in Postman when both are empty they only show results from  List<Product>. Is there any way to show both?

A: You can use map for this ?
Simply  use the map instead of List and you will be good to go.
Map<String, List<Object>> foo = new HashMap<String, List<Object>>();
List<Product> list = new ArrayList<Product>();
list.add("key1_value1");
list.add("key1_value2");
foo.put("key1",list);
List<Customer> list2 = new ArrayList<Customer>();
list2.add("key1_value1");
list2.add("key1_value2");
foo.put("key2",list2);


text:
Q: Anomaly detection within periodic time series I would like to detect anomalies in a time series data using a moving average approach. Basically, the system will rise an alarm when a data point is far away (3*std for example) from the current mean.
The problem is that the data contains periodic deviations and I do not want to rise alarms for these periodic deviations (even if they are far away from the mean). In other words I would like to rise alarms only at non-periodic deviations. What basic approaches I can try to achieve this?
Thank you.
Mario


text:
Q: GitLab: Not allowing me to push My friend has recently set up a GitLab on his Centos machine, and he has configured it all.
Information given from him:

*

*He has assigned me my RSA key to my email, and it is linked to my account.

*My SSH key is used in my profile section.

*I show up in the authorized_keys and in the repos.

He is able to create projects, commit, and push. However, I can do all of that except for pushing.
I have my global configuration correct (username and email), and I have set up everything according to what the project page will tell me:
mkdir project
cd project
git init
touch README
git add README
git commit -m 'first commit'
git remote add origin git@website.com:CoderMusgrove/project.git
git push -u origin master

Doing this, it starts to ask me for a password. There is no password. We have tried reconfiguring everything from the bottom, but we cannot seem to find the issue. He has reset all of my keys, and has given me all of his permissions. He is able to do everything on his end just fine.
At an older point in time, and at other times, it will say something about something failing, or being invalid. Such as a key being invalid, but we worked out that issue just fine. The first issue was when I would try to push a commit, and it will say that the repository didn't exist.
What is not allowing me to push commits, but he can, even though our accounts are configured exactly the same?
Edit
I attempted the command ssh -vvvT gitlab@localhost, replacing localhost with my host, and this is the output (HOST is the replacement of my host)
OpenSSH_4.6p1, OpenSSL 0.9.8e 23 Feb 2007
debug2: ssh_connect: needpriv 0
debug1: Connecting to _HOST_ [209.141.61.72] port 22.
debug1: Connection established.
debug1: identity file /c/Users/Michael/.ssh/identity type -1
debug3: Not a RSA1 key file /c/Users/Michael/.ssh/id_rsa.
debug2: key_type_from_name: unknown key type '-----BEGIN'
debug3: key_read: missing keytype
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug2: key_type_from_name: unknown key type '-----END'
debug3: key_read: missing keytype
debug1: identity file /c/Users/Michael/.ssh/id_rsa type 1
debug3: Not a RSA1 key file /c/Users/Michael/.ssh/id_dsa.
debug2: key_type_from_name: unknown key type '-----BEGIN'
debug3: key_read: missing keytype
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug3: key_read: missing whitespace
debug2: key_type_from_name: unknown key type '-----END'
debug3: key_read: missing keytype
debug1: identity file /c/Users/Michael/.ssh/id_dsa type -1
debug1: Remote protocol version 2.0, remote software version OpenSSH_5.3
debug1: match: OpenSSH_5.3 pat OpenSSH*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_4.6
debug2: fd 3 setting O_NONBLOCK
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha256,diffie-hellman-g
roup-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: ssh-rsa,ssh-dss
debug2: kex_parse_kexinit: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour1
28,arcfour256,arcfour,aes192-cbc,aes256-cbc,rijndael-cbc@lysator.liu.se,aes128-c
tr,aes192-ctr,aes256-ctr
debug2: kex_parse_kexinit: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour1
28,arcfour256,arcfour,aes192-cbc,aes256-cbc,rijndael-cbc@lysator.liu.se,aes128-c
tr,aes192-ctr,aes256-ctr
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,hmac-ripemd160,hmac-ripemd160@open
ssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,hmac-ripemd160,hmac-ripemd160@open
ssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,zlib@openssh.com,zlib
debug2: kex_parse_kexinit: none,zlib@openssh.com,zlib
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha256,diffie-hellman-g
roup-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: ssh-rsa,ssh-dss
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour12
8,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rij
ndael-cbc@lysator.liu.se
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour12
8,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rij
ndael-cbc@lysator.liu.se
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-sha2-256,
hmac-sha2-512,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96

debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-sha2-256,
hmac-sha2-512,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96

debug2: kex_parse_kexinit: none,zlib@openssh.com
debug2: kex_parse_kexinit: none,zlib@openssh.com
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: mac_init: found hmac-md5
debug1: kex: server->client aes128-cbc hmac-md5 none
debug2: mac_init: found hmac-md5
debug1: kex: client->server aes128-cbc hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug2: dh_gen_key: priv key bits set: 127/256
debug2: bits set: 504/1024
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug3: check_host_in_hostfile: filename /c/Users/Michael/.ssh/known_hosts
debug3: check_host_in_hostfile: match line 1
debug3: check_host_in_hostfile: filename /c/Users/Michael/.ssh/known_hosts
debug3: check_host_in_hostfile: match line 1
debug1: Host '_HOST_' is known and matches the RSA host key.
debug1: Found key in /c/Users/Michael/.ssh/known_hosts:1
debug2: bits set: 496/1024
debug1: ssh_rsa_verify: signature correct
debug2: kex_derive_keys
debug2: set_newkeys: mode 1
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug2: set_newkeys: mode 0
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug2: key: /c/Users/Michael/.ssh/identity (0x0)
debug2: key: /c/Users/Michael/.ssh/id_rsa (0xa01a3f8)
debug2: key: /c/Users/Michael/.ssh/id_dsa (0x0)
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mi
c,password
debug3: start over, passed a different list publickey,gssapi-keyex,gssapi-with-m
ic,password
debug3: preferred publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Trying private key: /c/Users/Michael/.ssh/identity
debug3: no such identity: /c/Users/Michael/.ssh/identity
debug1: Offering public key: /c/Users/Michael/.ssh/id_rsa
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mi
c,password
debug1: Trying private key: /c/Users/Michael/.ssh/id_dsa
debug1: read PEM private key done: type RSA
debug3: sign_and_send_pubkey
debug2: we sent a publickey packet, wait for reply
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mi
c,password
debug2: we did not send a packet, disable method
debug3: authmethod_lookup password
debug3: remaining preferred: ,password
debug3: authmethod_is_enabled password
debug1: Next authentication method: password
git@_HOST_'s password:

A: Looks like your SSH key is invalid, try regenerating one, and adding it to your GitLab user account.
After that, you can re-push your commit

A: The issue that occurred was that the installation was corrupt, which made me fully have no permission. The issue has been solved with a re-installation.


text:
Q: Cassandra Column families list using JMX I want to retrieve column families list from JMX approach in cassandra. I am using JMX approach to retrieve data from cassandra. I am able to retrieve keyspaces list but there is no any predefined mbean to get list of column families which belongs to this keyspaces.
I want to know is there any way to get list of this column families specific to keyspaces using JMX or JAVA.

A: You can use wildecard character (*) in object name to get list of column families in specified keyspace e.g.:
JMXConnector connector = JMXConnectorFactory.connect( url, env );
            MBeanServerConnection mbsc = connector.getMBeanServerConnection();
ObjectName oName = new ObjectName( "org.apache.cassandra.db:type=ColumnFamilies,keyspace=your_keyspace,columnfamily=*" );
        Set<ObjectName> names = mbsc.queryNames( oName, null);
        Set<ObjectInstance> mbeans = mbsc.queryMBeans( oName, null );

So name will contain jmx names for all column failies in the keyspace and mbeans will contain MBeans for all column families in the keyspace.
More dateails about name patterns in JMX documentation


text:
Q: Please explain the syntax in solr query fq = {!frange l=1 u=1}strdist(PR_EMP_ID_s, POSTN_PR_EMP_ROW_ID_s,edit) In the below syntax:
fq = {!frange l=1 u=1}strdist(PR_EMP_ID_s, POSTN_PR_EMP_ROW_ID_s,edit)

how to interpret this expression?
I know the basic fq working.
I have one query where I found this expression, but I am not able to interpret this syntax.


text:
Q: I am trying to join a dataframe with a pandas series but get Nan values for the dataframe I have a pandas series called mean_return:
BHP     0.094214
GOOG    0.180892
INTC   -0.179899
MRK     0.065741
MSFT    0.205519
MXL     0.153332
SHEL    0.001714
TSM     0.162741
WBD    -0.233863
dtype: float64
pandas.core.series.Series

When i try to merge the above with the dataframe below I get Nan values for mean return: (excuse the formatting Im not sure how to copy and paste the dataframe). I see the tickers are not ordered the same for the series as the DF , what can i do to merge both DF and series?
0
mkt_value   weights investment  shares  mean_return
 0  GOOG    51.180000   0.115308    14413.469698    281.623087  NaN
 1  BHP 99.570000   0.140488    17560.996495    176.368349  NaN
    INTC    25.719999   0.092804    11600.473577    451.029311  NaN
    MXL 87.599998   0.110175    13771.865664    157.213081  NaN
    MRK 234.240005  0.102416    12801.944297    54.653108   NaN
    MSFT    34.220001   0.123298    15412.217160    450.386225  NaN
    SHEL    51.970001   0.142114    17764.225757    341.816920  NaN
    TSM 69.750000   0.134963    16870.389838    241.869388  NaN
    WBD 11.980000   0.038435    4804.417515 40

Here is the code is used:
df=pd.DataFrame(tickers_list)
df.rename({'index':'tickers_list'},axis='columns',inplace=True)
df['mkt_value']=data.values[-1]
df['weights']=weights
df['investment']=port_size*weights
df['shares']=df['investment']/df['mkt_value']
df['mean_return']=mean_return
df

A: If the tickers in the df are unique, then I would set them as an index. and then use pd.concat which concatenates based on index.
df = df.set_index('tickers_list')
mean_returns.name = "mean_returns"
df = pd.concat([df, mean_returns], axis=1)

You set the name attribute as that will be the name of the new column.


text:
Q: Create parameterized 3D primitives with cgal I'm using cgal to evaluate scientfic data (Polyhedron surface, mass fraction, void fraction,...).
I preforme boolean operations to cut out my measurment volumes (subvolume where I want to average the data). In this special case it is a cylinder. By now I'll read a generic cylinder from an STL file and transform it to its needed size and position. This is not very elegant. For example it is not possible to adjust the resolution of surface triangulation.
A much better (more general approach) would be to generate my probe volume at runtime. Does cgal have a module to create 3D primitives? I couldn't find something like that in the documentation.
I'm quite new to cgal and a little bit confused by this documents. So it is quite possible that I've overlook something.
It would be very nice if someone could give me a hint on how to start solving this problem!
Thanks in advance!

A: For everyone whos trying something similar here is my solution:
#include <CGAL/Polyhedron_3.h>
#include <CGAL/IO/Polyhedron_iostream.h>
#include <CGAL/Nef_polyhedron_3.h>
#include <CGAL/convex_hull_3.h>

Nef_polyhedron_3 create_probe_cylinder(unsigned int argNum_segments, double argRadius, double argZmin, double argZmax)
{

    std::vector<Point_3> probecylinder_points;
    double x, y;
    for (unsigned int point_index = 0; point_index < argNum_segments; point_index++)
    {
        x = argRadius*cos(2*M_PI*point_index/argNum_segments);
        y = argRadius*sin(2*M_PI*point_index/argNum_segments);;

        Point_3 point_bot(x,y, argZmin);
        Point_3 point_top(x,y, argZmax);

        probecylinder_points.push_back(point_bot);
        probecylinder_points.push_back(point_top);
    }

    std::cout << "creating convex hull.." << std::endl;

    Polyhedron_3 poly_cylinder;
    CGAL::convex_hull_3(probecylinder_points.begin(), probecylinder_points.end(), poly_cylinder);

    std::cout << "converting to nef poly.." << std::endl;
    Nef_polyhedron_3 nef_cylinder(poly_cylinder);

    return nef_cylinder;
}

Code summary:
1) create list of points (rim of the bottom / top). argNum_segments sets the resolution of the cylinder (number of segments)
2) create a convex hull from the point list
3) convert polyhedron to nef representation (needed for the boolean operations)
There might be a better solution. If someone knows how to performe this task in a more elegant way please let me know.


text:
Q: Can i improve the efficiency of this Matlab function? I have written a matlab function that performs some cpu intensive operations on images. I would like to improve the speed of this function, but cannot think of anymore ways to optimize it. Does anyone know how to further optimise the function below?
function imageMedoid(imageList, resizeFolder, outputFolder, x, y)

    % local variables
    medoidImage = zeros([1, y*x, 3]);
    alphaImage = zeros([y x]);
    medoidContainer = zeros([y*x, length(imageList), 3]);

    % loop through all images in the resizeFolder
    for i=1:length(imageList)

        % get filename and load image
        fname = imageList(i).name;
        container = im2double(imread([resizeFolder fname]));

        % load alpha channel, convert to zeros and ones, add to alphaImage
        [~,~,alpha] = imread([resizeFolder fname]);
        alpha = double(alpha) / 255;
        alphaImage = alphaImage + alpha;

        % add (r,g,b) values to medoidContainer and reshape to single line
        medoidContainer(:, i, :) = reshape(container, [y*x 3]);

    end

    % loop through every pixel in medoidContainer
    for i=1:length(medoidContainer)

        % calculate distances between all values for current pixel
        distances = pdist(squeeze(medoidContainer(i,:,1:3)));

        % convert found distances to matrix of distances
        distanceMatrix = squareform(distances);

        % find index of image with the medoid value
        [~, j] = min(mean(distanceMatrix,2));

        % write found medoid value to medoidImage
        medoidImage(1, i, 1:3) = medoidContainer(i, j, 1:3);

    end

    % replace values larger than one in alpha channel
    alphaImage(alphaImage > 1) = 1;

    % reshape image to original proportions
    medoidImage = reshape(medoidImage, y, x, 3);

    % save medoid image
    imwrite(medoidImage, [outputFolder 'medoid.png'], 'Alpha', alphaImage);

Any suggestions would be greatly appreciated!

A: I would suggest that you use the built-in profiler of MATLAB in order to have a better idea on what are the most time consuming operations and then try to optimize there.
Tools -> Open Profiler -> imageMedoid(...)

A: You are calling
imread([resizeFolder fname])

twice in your first for-loop. Call it once as
[A,~,alpha] = imread([resizeFolder fname]);

This should result in some improvement.


text:
Q: Right angle link style in a d3.js hierarchical tree I am trying to render a simple hierarchical tree using d3.js.
I can find a lot of code example of such tree, but none of them have the style of links that I want.
This example is fine for my needs, but I can't manage to display everything vertically with right-angle turn: https[:]//codepen.io/zhulinpinyu/pen/EaZrmM
How can I change this to fit the following layout ?

Thanks

A: You are looking for an indented tree.
See below, based on this example:

const margin = {top: 30, right: 20, bottom: 30, left: 20}
const width = 960;
const barHeight = 20;
const barWidth = (width - margin.left - margin.right) * 0.8;
const duration = 400;
let i = 0;
let root;

const elbow = d => `M${d.source.y},${d.source.x} V${d.target.x} H${d.target.y}`;

const color = d => d._children ? "#3182bd" : d.children ? "#c6dbef" : "#fd8d3c";

const update = (source) => {

  // Compute the flattened node list
  const nodes = root.descendants();

  const height = Math.max(500, nodes.length * barHeight + margin.top + margin.bottom);

  d3.select("svg").transition()
    .duration(duration)
    .attr("height", height);

  // Compute the layout
  root.eachBefore((n, i) => {
    n.x = i * barHeight;
    n.y = n.depth * 40;
  });

  // Update the nodes…
  const node = svg.selectAll(".node")
    .data(nodes, d => d.id || (d.id = ++i));

  const nodeEnter = node.enter()
    .append("g")
    .attr("class", "node")
    .attr("transform", d => `translate(${source.y0},${source.x0})`)
    .style("opacity", 0)
    .on("click", click);

  nodeEnter.append("circle")
    .attr("r", 7)
    .style("fill", d => d.children ? "lightsteelblue" : "#fff");

  nodeEnter.append("text")
    .attr("dy", 3.5)
    .attr("dx", d => 10 + d.depth)
    .text(d => d.data.name);

  // update
  var nodeUpdate = node.merge(nodeEnter)
    .transition()
    .duration(duration);

  nodeUpdate
    .attr("transform", d => `translate(${d.y},${d.x})`);

  nodeUpdate
    .attr("r", 7)
    .style("fill", d => d.children ? "lightsteelblue" : "#fff");

  nodeUpdate
    .select("text")
    .style("fill-opacity", 1);

  // Transition nodes to their new position.
  nodeEnter.transition()
    .duration(duration)
    .attr("transform", d => `translate(${d.y},${d.x})`)
    .style("opacity", 1);

  node.transition()
    .duration(duration)
    .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })
    .style("opacity", 1);

  // Transition exiting nodes to the parent's new position.
  node.exit()
    .transition()
    .duration(duration)
    .attr("transform", d => `translate(${source.y}, ${source.x}")`)
    .style("opacity", 0)
    .remove();

  var nodeExit = node.exit()
    .transition()
    .duration(duration);

  nodeExit.attr("transform", d => `translate(${source.y},${source.x})`)
    .remove();

  nodeExit.select("circle")
    .attr("r", 1e-6);

  nodeExit.select("text")
    .style("fill-opacity", 1e-6);

  // Update the links…
  var link = svg.selectAll(".link")
    .data(root.links(), d => d.target.id);

  // Enter any new links at the parent's previous position.
  link.enter()
    .insert("path", "g")
    .attr("class", "link")
    .attr("d", d => {
      const o = {x: source.x0, y: source.y0};
      return elbow({source: o, target: o});
    })
    .transition()
    .duration(duration)
    .attr("d", elbow);

  // Transition links to their new position.
  link.transition()
    .duration(duration)
    .attr("d", elbow);

  // Transition exiting nodes to the parent's new position.
  link.exit()
    .transition()
    .duration(duration)
    .attr("d", d => {
      const o = {x: source.x, y: source.y, parent: {x: source.x, y: source.y}};
      return elbow({source: o, target: o});
    })
    .remove();

  // Stash the old positions for transition.
  root.each(function(d) {
    d.x0 = d.x;
    d.y0 = d.y;
  });
}

const click = (event, d) => {
  if (d.children) {
    d._children = d.children;
    d.children = null;
  } else {
    d.children = d._children;
    d._children = null;
  }
  update(d);
}

// svg
const svg = d3.select("body")
  .append("svg")
  .attr("width", width)
  .append("g")
  .attr("transform", `translate(${margin.left},${margin.top})`);

// initial tree
root = d3.hierarchy(data);
root.x0 = 0;
root.y0 = 0;
update(root);
.node circle {
  fill: #fff;
  stroke: steelblue;
  stroke-width: 1px;
}

.link {
  fill: none;
  stroke: #9ecae1;
  stroke-width: 1.5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.7.0/d3.min.js"></script>
<script>
const data = {
 "name": "Visualisation tools",
 "children": [
   {
    "name": "Interactive tools",
    "free": true,
    "description": "Interactive authoring tools",
    "children": [
     {
      "name": "Browser-based",
      "description": "Web-based 'cloud' applications for authoring data visualisations",
      "free": true,
      "children": [
       {
        "name": "Datawrapper",
        "description": "An open-source platform for publishing charts on the web. Cloud-based or self-hosted.",
        "url": "https://datawrapper.de/",
        "free": true
       },
       {
        "name": "Google Sheets",
        "description": "Spreadsheet in the cloud with charting",
        "free": true
       },
       {
        "name": "plotly",
        "description": "Cloud-based interactive tool for creating data visualisations",
        "url": "https://plot.ly/",
        "free": true
       },
       {
        "name": "RAW",
        "description": "Open-source interactive tool for creating and exporting D3-like charts",
        "url": "http://raw.densitydesign.org/",
        "free": true
       }
      ]
     },
     {
      "name": "Desktop",
      "children": [
       {
        "name": "Tableau Desktop",
        "description": "Powerful tool for data analytics and visualisation",
        "url": "http://www.tableausoftware.com/products/desktop"
       },
       {
        "name": "Tableau Public",
        "description": "Free version of Tableau Desktop where charts are public",
        "url": "http://www.tableausoftware.com/products/public",
        "free": true
       }
      ]
     }
    ]
   },
   {
    "name": "Coding",
    "description": "Code-based data visualisation creation",
    "free": true,
    "children": [
     {
      "name": "JavaScript",
      "description": "The language behind most (all?) browser-based data visualisations",
      "free": true,
      "children": [
       {
        "name": "Charting libraries",
        "description": "Off-the-shelf pre-designed charts. Easy to use but less flexible.",
        "free": true,
        "children": [
         {
          "name": "Google Charts",
          "description": "A good selection of charts including bar, line, scatter, geo, pie, donut, org etc.",
          "url": "https://developers.google.com/chart/",
          "free": true
         },
         {
          "name": "HighCharts",
          "description": "A well maintained commercial library of commonly used chart types",
          "url": "https://www.highcharts.com/"
         },
         {
          "name": "InfoVis",
          "description": "A lovely selection of charts including bar, pie, sunburst, icicle, network, trees etc.",
          "url": "https://philogb.github.io/jit/",
          "free": true
         },
         {
          "name": "Mapping",
          "description": "Libraries for visualising geographic data",
          "free": true,
          "children": [
           {
            "name": "Kartograph",
            "description": "Lovely vector based mapping library with good browser support",
            "url": "http://kartograph.org/",
            "free": true
           },
           {
            "name": "Leaflet",
            "description": "Tile-based mapping library",
            "url": "http://leafletjs.com/",
            "free": true
           }
          ]
         },
         {
          "name": "MetricsGraphics.js",
          "description": "Beautiful line, scatter and histogram charts built on top of D3",
          "url": "http://metricsgraphicsjs.org/",
          "free": true
         },
         {
          "name": "NVD3",
          "description": "A general purpose charting library built on top of D3",
          "url": "http://nvd3.org/",
          "free": true
         },
         {
          "name": "Sigma",
          "description": "Library for visualising networks",
          "url": "http://sigmajs.org/",
          "free": true
         }
        ]
       },
       {
        "name": "Custom coded",
        "description": "For maximum flexibility, custom coding is the way to go. These libraries will lend a hand.",
        "free": true,
        "children": [
         {
          "name": "D3",
          "description": "The jewel in the crown of web-based data visualisation. A library packed full of components for building any data visualisation you can imagine.",
          "url": "https://d3js.org/",
          "free": true
         },
         {
          "name": "Ractive",
          "description": "Relatively new, Ractive helps you make your HTML and SVG interactive",
          "url": "http://www.ractivejs.org/",
          "free": true
         },
         {
          "name": "Raphaël",
          "description": "A general purpose drawing library with good browser support",
          "url": "http://raphaeljs.com/",
          "free": true
         },
         {
          "name": "Snap.svg",
          "description": "A modern version of Raphaël that supports modern browsers",
          "url": "http://snapsvg.io/",
          "free": true
         },
         {
          "name": "Variance",
          "description": "A declarative, mark-up based data visualisation library",
          "url": "https://variancecharts.com/"
         },
         {
          "name": "Vega",
          "description": "A declarative language for specifying data visualistions",
          "url": "https://trifacta.github.io/vega/",
          "free": true
         }
        ]
       }
      ]
     },
     {
      "name": "Other",
      "description": "Non-JavaScript languages for producing web-based data visualisations",
      "free": true,
      "children": [
       {
        "name": "Python",
        "description": "Python's a very popular language in data science and is a pleasant language to learn and use",
        "free": true,
        "children": [
         {
          "name": "Bokeh",
          "description": "A powerful tool for producing interactive plots, dashboards and data applications",
          "url": "https://bokeh.pydata.org/",
          "free": true
         }
        ]
       },
       {
        "name": "R",
        "description": "Very popular language for data science",
        "free": true,
        "children": [
         {
          "name": "Shiny",
          "description": "A platform for producing web applications using R",
          "url": "http://shiny.rstudio.com/",
          "free": true
         }
        ]
       }
      ]
     }
    ]
   }
 ]
}</script>


text:
Q: Calculating the shape matrix I am stuck on this problem. I need to calculate the curvatures but my shape matrix is not happening. Any help is appreciated. So far I have done this:
$X(u,v) = (cosv-(u+v)sinv, sinv+(u+v)cosv, u+2v)$
So I take the partial velocities
$X_u = (-sinv,cosv,1)$ and,
$X_v = (-2sinv-(u+v)cosv, 2cosv-(u+v)sinv,2)$
Taking the cross product gives me:
$((u+v)sinv,-(u+v)cosv,u+v)$
Hence the unit normal is:
=$1/\sqrt{2} (sinv,-cosv,1)$
So the shape operators are
$S_p(X_u) = 0$ and,
$S_p(X_v) = 1/\sqrt2 (cosv,sinv,0)$
This is where I get stuck. How do I calculate the shape matrix from here? If there is a more efficient way that would be enlightening.

A: Ah, so the matrix of the shape operator $S_p$ (with respect to the basis $\{X_u,X_v\}$) is
$$\begin{bmatrix} a & c \\ b & d \end{bmatrix},$$
where $S_p(X_u) = aX_u + bX_v$ and $S_p(X_v) = cX_u + dX_v$.
In your case, you find that $a=b=0$ and $c=-\dfrac{\sqrt2}{u+v}$ and $d=\dfrac1{\sqrt2(u+v)}$. (By the way, you dropped the negative sign in your computation.)
The customary way of computing this is to note that (using $n\cdot X_u = n\cdot X_v = 0$)
\begin{align*}
S_p(X_u)\cdot X_u &= -n_u\cdot X_u = n\cdot X_{uu} \\
S_p(X_u)\cdot X_v &= -n_u\cdot X_v = n\cdot X_{uv} = n\cdot X_{vu} = S_p(X_v)\cdot X_u \tag{$\star$}\\
S_p(X_v)\cdot X_v &= -n_v\cdot X_v = n\cdot X_{vv}.
\end{align*}
You then make the second fundamental form matrix
$$II = \begin{bmatrix} X_{uu}\cdot n & X_{uv}\cdot n \\ X_{vu}\cdot n & X_{vv}\cdot n\end{bmatrix}$$
and the first fundamental form matrix
$$I = \begin{bmatrix} \|X_u\|^2 & X_u\cdot X_v \\ X_v\cdot X_u & \|X_v\|^2\end{bmatrix},$$
and note that the equations ($\star$) can be written in matrix form as
$$I\begin{bmatrix}a & c\\b& d\end{bmatrix} = II,$$
so $S_p = I^{-1}II$.
(You might want to download my differential geometry text for more examples and explanations.)


text:
Q: What is the verb or expression for describing some kids in this situation?
Suppose there are some naughty kids who are playing with each other in a room, they nudge each other and wrestle and climb (?) on each other! I want to tell them to stop. Which verb should I use? "Hey kids! Stop ...?"
(Like the baby elephants in the picture.)
I also want to know if there is some verb that describes the activity shown in the second picture; "A group of refugees are ....(verb) for their gifts."

A: 1.) My parents were always yelling at my little brothers, "Hey kids! Stop that roughhousing!" Other colorful words usually accompanied these demands, but I'm saving those for another OP.

roughhouse verb: gerund or present participle: roughhousing: act in a boisterous, violent manner. "in front of the stage hundreds of teens and young adults roughhouse, flinging themselves into each other"
Google

PS - In more or less the same vein there is, "grab-assing"; i.e., The boss was furious because his employees were always grab-assing instead of working.

2.) The crowd of people in the second picture are "jostling" for with each other to get into a better position to receive whatever those goodies are that are being handed-out to the crowd.

jostle verb: gerund or present participle: jostling: to push, elbow, or bump against (someone) roughly, typically in a crowd. "passengers arriving and departing, jostling one another"; "jostled by the crowd"
synonyms: bump into/against, knock into/against, bang into, collide with, plow into, jolt;
• struggle, vie, jockey, scramble, crowd one another. "media empires jostle to catch the eye of Asian readers and viewers"
• struggle or compete forcefully for. "a jumble of images jostled for attention"

A: Scrambling

*

*Struggle or compete with others for something in an eager or    uncontrolled and undignified way.

*Perform (an action) or achieve (a result) hurriedly, clumsily, or    with difficulty.

Horseplaying

Rough or rowdy play that can often result in unintentional physical harm.


text:
Q: Replacing NA values with the next value in a column in R I'm trying to mutate a column in a Dataframe using the lag() function as a condition without producing NA values. Let me create an example:
df <- data.frame("Score" = as.numeric(c("20", "10", "15", "30", "15", "10")),
             "Time" = c("1", "2", "1", "2", "1", "2"),
             "Team" = c("A", "A", "B", "B", "C", "C"))

After that, I created a new column named Diff that calculates the difference of the Score of every Team:
 df <- df %>%
 group_by(Team) %>%
 mutate(Diff = Score - lag(Score))

My problem is that this method creates NA values, obviously:
  Score Time  Team   Diff
  20     1     A        NA
  10     2     A       -10
  15     1     B        NA
  30     2     B        15
  15     1     C        NA
  10     2     C        -5

My goal is to have this at the end:
  Score Time  Team   Diff
  20     1     A       -10
  10     2     A       -10
  15     1     B        15
  30     2     B        15
  15     1     C        -5
  10     2     C        -5

I've tried mutating again using the case_when() function to substitute the NA for the next value, but it also didn't work:
 df %>%
 group_by(Team) %>%
 mutate(Diff = Score - lag(Score)) %>%
 mutate(Diff = case_when(
 NA ~ lead(Diff)
 ))

Anyway, how do I make the NA values be replaced by the next Diff value?
Thanks a lot!

A: Just use fill() after the fact:
library(tidyverse)

df <- data.frame("Score" = as.numeric(c("20", "10", "15", "30", "15", "10")),
                 "Time" = c("1", "2", "1", "2", "1", "2"),
                 "Team" = c("A", "A", "B", "B", "C", "C"))
df <- df %>%
  group_by(Team) %>%
  mutate(Diff = Score - lag(Score)) %>%
  fill(Diff, .direction = 'up')

df
# output
#   Score Time  Team   Diff
#   <dbl> <chr> <chr> <dbl>
#1    20 1     A       -10
#2    10 2     A       -10
#3    15 1     B        15
#4    30 2     B        15
#5    15 1     C        -5
#6    10 2     C        -5


text:
Q: Why React Stripe CardElement not rendering? I was coding a project using React. It's been 3 days I've looking for a solution. I learned to code and tried to integrate the stripe payment option on my web app. However, unable to get the proper result. I searched a lot but found no solution.
This is My App.js
import React, { useEffect } from "react";
import "./App.css";
import Header from "./Header";
import Home from "./Home";
import { BrowserRouter as Router, Routes, Route, Link } from "react-router-dom";
import Checkout from "./Checkout";
import Login from "./Login";
import Payment from "./Payment";
import { getAuth, onAuthStateChanged } from "./firebase.js";
import { useStateValue } from "./StateProvider";
import { loadStripe } from "@stripe/stripe-js";
import { Elements } from "@stripe/react-stripe-js";

const stripePromise = loadStripe(
  "pk_test_51Ku8iiSHAST6F5x2egU8YwHdYkqKAOcJIfrfXKa0b7kxeHm0ECkvFOLVW0KeaiudzfAfU31m954rOkIKGsoXhiAE00EQx04Did"
);

function App() {
  const [{}, dispatch] = useStateValue();
  const auth = getAuth();
  useEffect(() => {
    // will only run once when the app component loads...
    onAuthStateChanged(auth, (user) => {
      console.log("THE USER IS >>> ", user);
      if (user) {
        // User is signed in, see docs for a list of available properties
        // https://firebase.google.com/docs/reference/js/firebase.User
        // ...
        dispatch({
          type: "SET_USER",
          user: user,
        });
      } else {
        // User is signed out
        // ...
        dispatch({
          type: "SET_USER",
          user: null,
        });
      }
    });
  }, []);
  return (
    // BEM
    <Router>

        <Routes>
          <Route path="/login" element={<Login />} />
          <Route path="/checkout" element={[, <Checkout />]} />
          <Route
            path="/payment"
            element={[
              ,
              <Elements stripe={stripePromise}>
                <Payment />
              </Elements>,
            ]}
          />
          <Route path="/" element={[, <Home />]} />
        </Routes>

    </Router>
  );
}

export default App;
//https://cloned-4270b.web.app

this is my Payment.js where CardElement is written.
import React, { useState, useEffect } from "react";
import "./Payment.css";
import { useStateValue } from "./StateProvider";
import { Link, useNavigate } from "react-router-dom";
import CheckoutProduct from "./CheckoutProduct";
import { CardElement, useStripe, useElements } from "@stripe/react-stripe-js";

function Payment() {
  const [{ basket, user }, dispatch] = useStateValue();
  const navigate = useNavigate();

  const stripe = useStripe();
  const elements = useElements();

  return (

          Checkout (<Link to="/checkout">{basket?.length} items</Link>)

        {/* Payment section - delivery address */}

Delivery Address

{user?.email}

123 React Lane

Los Angeles, CA

        {/* Payment section - Review Items */}

Review items and delivery

            {basket.map((item) => (
              <CheckoutProduct
                id={item.id}
                title={item.title}
                image={item.image}
                price={item.price}
                rating={item.rating}
              />
            ))}

        {/* Payment section - Payment method */}

Payment Method

            {/* Stripe magic will go */}
            <CardElement />

  );
}
export default Payment;

version using stripe:
"dependencies": {
    "@emotion/react": "^11.9.0",
    "@emotion/styled": "^11.8.1",
    "@mui/icons-material": "^5.6.2",
    "@mui/material": "^5.6.4",
    "@stripe/react-stripe-js": "^1.7.2",
    "@stripe/stripe-js": "^1.29.0",
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.2.0",
    "@testing-library/user-event": "^13.5.0",
    "firebase": "^9.8.0",
    "react": "^18.1.0",
    "react-currency-format": "^1.1.0",
    "react-dom": "^18.1.0",
    "react-router-dom": "^6.3.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"

After every attempts, CardElement is not rendering in the image below


text:
Q: Is it possible to get the neighborhood of an address using google maps api or bing maps api? Is it possible to get the neighborhood using either the Google Maps API or Bing Maps API?  For example would it be possible to get the value of "Financial District" neighborhood for a search of the address in that neighborhood in San Francisco?  If not, are there other resources online for this?  Thanks!

A: Yes, neighborhood is returned in the address_components[] array as part of the Geocoding API.
Google has a live demo app that shows off the Geocoding API. The neighborhood field is available for places that appear in cities which have neighborhoods.
Here's a simple example to fetch neighborhood data using the Python client for Google Maps:
import googlemaps

API_KEY = "YOUR_API_KEY"
gmaps = googlemaps.Client(key=API_KEY)
print gmaps.geocode('3027 16th St, San Francisco, CA 94103, United States')

This will print the following:
[{'address_components': [{'long_name': '3027',
                          'short_name': '3027',
                          'types': ['street_number']},
                         {'long_name': '16th Street',
                          'short_name': '16th St',
                          'types': ['route']},
                         {'long_name': 'Mission District',
                          'short_name': 'Mission District',
                          'types': ['neighborhood', 'political']},
                         {'long_name': 'San Francisco',
                          'short_name': 'SF',
                          'types': ['locality', 'political']},
                         {'long_name': 'San Francisco County',
                          'short_name': 'San Francisco County',
                          'types': ['administrative_area_level_2',
                                    'political']},
                         {'long_name': 'California',
                          'short_name': 'CA',
                          'types': ['administrative_area_level_1',
                                    'political']},
                         {'long_name': 'United States',
                          'short_name': 'US',
                          'types': ['country', 'political']},
                         {'long_name': '94110',
                          'short_name': '94110',
                          'types': ['postal_code']},
                         {'long_name': '3402',
                          'short_name': '3402',
                          'types': ['postal_code_suffix']}],
  'formatted_address': '3027 16th St, San Francisco, CA 94110, USA',
  'geometry': {'bounds': {'northeast': {'lat': 37.764927, 'lng': -122.4201635},
                          'southwest': {'lat': 37.7646504,
                                        'lng': -122.4203792}},
               'location': {'lat': 37.7647804, 'lng': -122.4202906},
               'location_type': 'ROOFTOP',
               'viewport': {'northeast': {'lat': 37.7661376802915,
                                          'lng': -122.4189223697085},
                            'southwest': {'lat': 37.76343971970851,
                                          'lng': -122.4216203302915}}},
  'place_id': 'ChIJxT0SpyN-j4ART07xF7G8NGE',
  'types': ['premise']}]

See the official Geocoding API Guide for more information.

A: You can download this example on Google
https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform
var componentForm = {
  ...,
  neighborhood: 'short_name',
  ...,
};

In HTML table add

    Neighbourhood
    <input class="field"
          id="neighborhood" disabled="true"></input>

You can see neighborhood information displayed after address is entered

A: Google Places API enables you to get neighborhood information.
But the information got from the API have to use for Google Maps.
https://developers.google.com/places/documentation/


text:
Q: docker volume rm --force has no impact According to the official documentation it is possible to "force" remove a volume. The documentation remains quite unspecific what is meant by --force. To what I have found so far in the web this implicates the removal of volumes that are still in use by other containers.
Using the --force option appears to have no impact:
$ docker volume create mydata
$ docker docker run -v mydata:/mydata alpine:latest /bin/sh -c "touch /mydata/mydata.test; ls /mydata"
$ docker volume rm --force mydata
Error response from daemon: unable to remove volume: remove mydata: volume is in use - [1cbcfa3d47a32db7b0075e113216f7146a436a4da22a97dc2f7b60c68de95c3d]

This is the same output as when omitting the --force flag. Is this a bug or am I misunderstanding something?
$ docker version
Client:
 Version:       18.01.0-ce
 API version:   1.35
 Go version:    go1.9.2
 Git commit:    03596f5
 Built: Wed Jan 10 20:09:13 2018
 OS/Arch:       linux/amd64
 Experimental:  false
 Orchestrator:  swarm
Server:
 Engine:
  Version:      18.01.0-ce
  API version:  1.35 (minimum version 1.12)
  Go version:   go1.9.2
  Git commit:   03596f5
  Built:        Wed Jan 10 20:07:43 2018
  OS/Arch:      linux/amd64
  Experimental: false

A: use the --filter flag to see which containers are using the volume:
docker ps --filter volume=mydata

then, stop the container that is using that volume.
Finally, remove the volume if you wish to do so:
docker volume rm --force mydata

A: I am annoyed by all answers on all posts which do NOT provide a solution for the case which is mentioned by OP: The --force flag DOES NOT HELP.
Workaround (ATTENTION, you really should know what you do!):
docker volume ls # To list the volumes which currently exist

# To get the absolute path to the directory on your system where docker
# actually stores this volume
docker volume inspect --format '{{ .Mountpoint }}' <volume-name>

# E.g. sudo rm -rf /var/lib/docker/volumes/database_volume (without the
# _data directory)
sudo rm -rf <path-from-above>

# Needed so docker will reload its volumes-directory to no longer list the
# deleted volume under docker volume ls and no longer make headaches on any
# build- or run-attempts.
sudo service docker restart

A: In my experience, the -f flag makes the command not to fail if the volume does not exists. This is similar to how the classic rmcommand works.
This is useful if the command is executed inside scripts.

A: docker volume rm will not let you remove a volume still referenced by a container, even if the container is stopped and you use the --force parameter.
The error message tells you which container has to be removed in order to be able to remove the volume. In your case it's the container with the ID 1cbcfa3d47a32db7b0075e113216f7146a436a4da22a97dc2f7b60c68de95c3d.
See this issue on GitHub for more information.


text:
Q: Second time values are not taken correctly from an array randomly in Javascript I have four boxes I selected 4 items from an array items.
I have placed the randomly selected item inside 4 boxes.
Class box002 can be dragged and dropped to corresponding number in four boxes displayed. then digit in box dissappears.
My problem is that after dropping all four boxes correctly, second time values are not filled correctly, ie, reandomly selected values from array **items** does notmatch with **tempimages** stored for displaying in **box002** for dragging and dropping.
How to solve this? And make second level work?

var items = [{
    label: '1',
    url: 'https://via.placeholder.com/75x75?text=1'
  },
  {
    label: '2',
    url: 'https://via.placeholder.com/75x75?text=2'
  },
  {
    label: '3',
    url: 'https://via.placeholder.com/75x75?text=3'
  },
  {
    label: '4',
    url: 'https://via.placeholder.com/75x75?text=4'
  },
  {
    label: '5',
    url: 'https://via.placeholder.com/75x75?text=5'
  },
  {
    label: '6',
    url: 'https://via.placeholder.com/75x75?text=6'
  },
  {
    label: '7',
    url: 'https://via.placeholder.com/75x75?text=7'
  },
  {
    label: '8',
    url: 'https://via.placeholder.com/75x75?text=8'
  },
  {
    label: '9',
    url: 'https://via.placeholder.com/75x75?text=9'
  },
  {
    label: '10',
    url: 'https://via.placeholder.com/75x75?text=10'
  }
];

var tempimages = [];
var array2 = [];
array2 = items.slice();

var backimgcount = 1;
var len = array2.length;

var item;
var displaycounter = 0;

var images = ['https://picsum.photos/200/300', 'https://picsum.photos/g/200/300'];
var index = 0;

function buildImage() {
  document.getElementById('content').style.backgroundImage = 'url(images/' + images[index] + ')';
}

function changeImage() {
  index++;
  if (index >= images.length) index = 0;
  document.getElementById('content').style.backgroundImage = 'url(images/' + images[index] + ')';
}

function rvalue() {

  elements = document.getElementsByClassName("box");

  elements = document.getElementsByClassName("box");

  for (var i = 0; i < elements.length; i++) {
    elements[i].style.backgroundColor = "#ff66ff";
    //elements[i].borderRadius = "2px";
    elements[i].style.border = "2px solid  #e3a89e ";
    //object.style.borderRadius = "1-4 length|% / 1-4 length|%|initial|inherit"

  }

  ptags = document.querySelectorAll('[name="values"]');
  boxtags = document.getElementsByClassName("box");

  for (var index = 0; index < 4; index++) {
    randomIndex = Math.floor(Math.random() * array2.length)

    item = array2[randomIndex];
    //item = array2.splice(randomIndex, 1);

    ptags[index].style.visibility = "visible";
    ptags[index].textContent = item.label;
    boxtags[index].style.backgroundImage = 'url(' + item.url + ')';
    tempimages.push({
      data: item,
      index: randomIndex
    });

    ptags[index].dataset.itemIndex = randomIndex;

  }

  var tlen = tempimages.length;

}

function displayAllImages() {
  if (tempimages.length == 0) {

    rvalue();
  }
  //tempimages = tempimages.concat(tempimages.splice(0,2));
  //item = tempimages.splice(0, 1);

  function shuffle(array) {
    var currentIndex = array.length,
      temporaryValue, randomIndex;

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {

      // Pick a remaining element...
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex -= 1;

      // And swap it with the current element.
      temporaryValue = array[currentIndex];
      array[currentIndex] = array[randomIndex];
      array[randomIndex] = temporaryValue;
    }

    return array;
  }

  var arr = tempimages;
  arr = shuffle(arr);

  item = arr.shift();
  image = document.getElementById('slide');
  image.src = item.data.url;
  image.dataset.itemIndex = item.index;

};

$(function() {

  displayAllImages();

});

function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("Text", ev.target.id).classList.add('dashed');
}

function drop(ev) {

  ev.preventDefault();
  var data = ev.dataTransfer.getData("Text");
  var el = document.getElementById(data);

  var x = document.getElementById("slide").dataset.itemIndex;
  var y = ev.target.dataset.itemIndex;

  if (x == y) {
    //el.parentNode.removeChild;

    ev.currentTarget.style.backgroundColor = 'initial';
    ev.currentTarget.style.border = 'initial';

    var pParagraph = ev.currentTarget.firstElementChild;
    //ev.currentTarget.removeChild(pParagraph);
    pParagraph.style.visibility = "hidden";

    item = this.item;
    var arrayvalue = item.dataindex;
    array2.splice(arrayvalue, 1);

    //alert("sucessfull");
    if (tempimages.length == 0) {
      rvalue();
      hiddenimage();
      //changeImage();
      changeImage();
    }
    displayAllImages();
  } else {
    playAudio2();
    alert("WRONG TIME PLACED");
  }

}
body {
  overflow: hidden;
}

.box {
  width: calc(33.3% - 4px);
  display: inline-block;
  border-radius: 5px;
  border: 2px solid #333;
  border: #000 border-color: #e6e600;
  margin: -2px;
  border-radius: 0%;
  background-color: #99ffff;
}

.box {
  height: 15vh;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  background-size:contain;
}

.box002 {
  position: absolute;
  top: 27.3vh;
  left: 72.98vw;
  cursor: pointer;
}

.box002 img {
  width: 14.0vw;
  height: 23.0vh;
  border-radius: 50%;
}
p{
font: "Courier New", Courier, monospace;
font-size:30px;

 color: rgba(0,0,0,0.6);
text-shadow: 2px 8px 6px rgba(0,0,0,0.2),
                 0px -5px 35px rgba(255,255,255,0.3);

color: #005ce6;
text-align: center;
}

A: I can't even imagine how are you work with this code. Before posting example on stackoverflow try to clear it (remove unused code, remove function that doesn't exists).
Issues:
1) drag function, .classlist was commented out
2) playAudio2 was commented out
3) hiddenimage function was commented out
4) ok, maybe index should be on p tag, but it's can be figured out from example (maybe you should add to boxtags too.
So, on this example you can see, that second time values working properly, but when all images are finished there is some new issues.

    var items = [{
    label: '1',
    url: 'https://via.placeholder.com/75x75?text=1'
  },
  {
    label: '2',
    url: 'https://via.placeholder.com/75x75?text=2'
  },
  {
    label: '3',
    url: 'https://via.placeholder.com/75x75?text=3'
  },
  {
    label: '4',
    url: 'https://via.placeholder.com/75x75?text=4'
  },
  {
    label: '5',
    url: 'https://via.placeholder.com/75x75?text=5'
  },
  {
    label: '6',
    url: 'https://via.placeholder.com/75x75?text=6'
  },
  {
    label: '7',
    url: 'https://via.placeholder.com/75x75?text=7'
  },
  {
    label: '8',
    url: 'https://via.placeholder.com/75x75?text=8'
  },
  {
    label: '9',
    url: 'https://via.placeholder.com/75x75?text=9'
  },
  {
    label: '10',
    url: 'https://via.placeholder.com/75x75?text=10'
  }
];

var tempimages = [];
var array2 = [];
array2 = items.slice();

var backimgcount = 1;
var len = array2.length;

var item;
var displaycounter = 0;

var images = ['https://picsum.photos/200/300', 'https://picsum.photos/g/200/300'];
var index = 0;

function buildImage() {
  document.getElementById('content').style.backgroundImage = 'url(images/' + images[index] + ')';
}

function changeImage() {
  index++;
  if (index >= images.length) index = 0;
  document.getElementById('content').style.backgroundImage = 'url(images/' + images[index] + ')';
}

function rvalue() {

  elements = document.getElementsByClassName("box");

  elements = document.getElementsByClassName("box");

  for (var i = 0; i < elements.length; i++) {
    elements[i].style.backgroundColor = "#ff66ff";
    //elements[i].borderRadius = "2px";
    elements[i].style.border = "2px solid  #e3a89e ";
    //object.style.borderRadius = "1-4 length|% / 1-4 length|%|initial|inherit"

  }

  ptags = document.querySelectorAll('[name="values"]');
  boxtags = document.getElementsByClassName("box");

debugger;
  for (var index = 0; index < 4; index++) {
    randomIndex = Math.floor(Math.random() * array2.length)

    item = array2[randomIndex];
    //item = array2.splice(randomIndex, 1);

    ptags[index].style.visibility = "visible";
    ptags[index].textContent = item.label;
    boxtags[index].style.backgroundImage = 'url(' + item.url + ')';
    tempimages.push({
      data: item,
      index: randomIndex
    });

    ptags[index].dataset.itemIndex = randomIndex;

  }

  var tlen = tempimages.length;

}

function displayAllImages() {
  if (tempimages.length == 0) {

    rvalue();
  }
  //tempimages = tempimages.concat(tempimages.splice(0,2));
  //item = tempimages.splice(0, 1);

  function shuffle(array) {
    var currentIndex = array.length,
      temporaryValue, randomIndex;

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {

      // Pick a remaining element...
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex -= 1;

      // And swap it with the current element.
      temporaryValue = array[currentIndex];
      array[currentIndex] = array[randomIndex];
      array[randomIndex] = temporaryValue;
    }

    return array;
  }

  var arr = tempimages;
  arr = shuffle(arr);

  item = arr.shift();
  image = document.getElementById('slide');
  image.src = item.data.url;
  image.dataset.itemIndex = item.index;

};

$(function() {

  displayAllImages();

});

function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("Text", ev.target.id);//.classList.add('dashed');
}

function drop(ev) {

  ev.preventDefault();
  var data = ev.dataTransfer.getData("Text");
  var el = document.getElementById(data);

  var x = document.getElementById("slide").dataset.itemIndex;
  var y = ev.target.dataset.itemIndex;

  if (x == y) {
    //el.parentNode.removeChild;

    ev.currentTarget.style.backgroundColor = 'initial';
    ev.currentTarget.style.border = 'initial';

    var pParagraph = ev.currentTarget.firstElementChild;
    //ev.currentTarget.removeChild(pParagraph);
    pParagraph.style.visibility = "hidden";

    item = this.item;
    var arrayvalue = item.dataindex;
    array2.splice(arrayvalue, 1);

    //alert("sucessfull");
    if (tempimages.length == 0) {
      rvalue();
      //hiddenimage();
      //changeImage();
      changeImage();
    }
    displayAllImages();
  } else {
    //playAudio2();
    alert("WRONG TIME PLACED");
  }

}
body {
  overflow: hidden;
}

.box {
  width: calc(33.3% - 4px);
  display: inline-block;
  border-radius: 5px;
  border: 2px solid #333;
  border: #000 border-color: #e6e600;
  margin: -2px;
  border-radius: 0%;
  background-color: #99ffff;
}

.box {
  height: 15vh;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  background-size:contain;
}

.box002 {
  position: absolute;
  top: 27.3vh;
  left: 72.98vw;
  cursor: pointer;
}

.box002 img {
  width: 14.0vw;
  height: 23.0vh;
  border-radius: 50%;
}
p{
font: "Courier New", Courier, monospace;
font-size:30px;

 color: rgba(0,0,0,0.6);
text-shadow: 2px 8px 6px rgba(0,0,0,0.2),
                 0px -5px 35px rgba(255,255,255,0.3);

color: #005ce6;
text-align: center;
}


text:
Q: Maximum number of lines for generated CSV file using PHP I have problem with function that generate CSV in my site. It give me Error 500. When I check in apache error log, there is no record for this problem. After i dig the code, i find out that this error will come out if the data for CSV file is more than 1550 lines.
I was thought that setting for max_execution_time in php.ini is too low but after I increased it to 600sec, it still cannot generate CSV file more than 1550 lines of data.
Any idea how to solve this problem? Anyone know what happen actually?

A: Also, look into set_time_limit.
One thing to consider, is that some cloud side host providers (e.g. RackSpace) implement timeouts in their load balancers, which will terminate connections if there is no traffic (see Rackspace Connection Timed Out Error).
One possible workaround for that, is to echo and flush data back to the client to keep the connection open. This can be a simple HTML comment of whatever you want.
The more recommended solution is to offload lengthy processes to a script executed via a CRON job.  There are plenty of PHP job daemon examples out there.  A job daemon isn't necessary, a simple PHP script that processes a database table is sufficient enough for smaller solutions.

A: try adding
ini_set('auto_detect_line_endings',TRUE);
Also test the csv file, try opening it and resaving it.


text:
Q: PHP: ImageDestroy() with imagecopy()? It is possible to delete the Image-Memory for the PHP-function "imagecopyresampled()"

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 12288 bytes)

For example, I have to create images in a loop:
<?php

  while($break===false){

    $img=imagecreate($x);

  }

  function imagecreate($x){
    $tmp= imagecreatefromjpeg($x);

    imagecopyresampled($img,$tmp,0,0,0,0,100,100,100,100);
    //imagedestroy($img); ??This would be destroying before return the $img
    return $img;
  }

?>

How do I use imagedestroy() for imagecopyresampled()?

A: Dude there is a difference between imagedestroy() which destroy the tmp_image from temporary folder.
imagecopyresampled() create a resampling image from original copy of image.


text:
Q: HL7-Fhir : Nested (child) resources and _include supported/allowed in read result from a single resource This page describes the simple read.
However it's not clear to me if _include (web-page) is supported (see chapter 2.2.4.1 Include Paths) and if nested resource(s) can also be returned ?
So is the following request :https://example.com/MedicationOrder/5?_include=MedicationOrder.medication valid ?
And should the json-response be like:
{
  "resourceType": "MedicationOrder",
  "id": "5",
  "detail" : "abc",
  "medication":
  {
      "resourceType": "Medication",
      "id": "example",
      "otherDetails": "xyz"
  }
}

A: _include is only supported as part of a search. So
https://example.com/MedicationOrder/5?_include=MedicationOrder.medication
is not valid. This is:
https://example.com/MedicationOrder?_id=5&_include=MedicationOrder:medication
Then you get back a bundle with the MedicationOrder and the medication, if there is one.
What you call 'nested resources' - do you mean contained resources? - well, if there are contained resources in the MedicationOrder, they they are always returned with it - they are part of it. But they don't appear in the medication as you show in the example above. Instead:
{
  "resourceType": "MedicationOrder",
  "id": "5",
  "detail" : "abc",
  "medication": {
    "reference" : "#m1"
  },
  "contained": [
    {
      "resourceType": "Medication",
      "id": "m1",
      "otherDetails": "xyz"
    }
  ]
}


text:
Q: How to extract a Key/Value from a nested array of objects in an array of objects using Javascript I have the following array of object, and I need to extract the name of the object where the url matches 'lll/iii'
I know I can do a .find in a .find and then repeat the inner find but that seems pretty messy. Is there a more elegant solution using es6 or lodash here?
[
   {
      "name":"A",
      "Links":[
         {
            "url":"/xxx/yyy"
         }
      ]
   },
   {
      "name":"B",
      "Links":[
         {
            "url":"zzz/bbb"
         },
         {
            "url":"lll/iii"
         }
      ]
   }
]


text:
Q: Google Map Api with Search button Hi i'm trying to implement google api in android. I got the map displayed.Now I want to implement the same with routes of 2 user given addresses. First of all i tried to display with a single text box  and a button. I am getting the following error in the logcat :
 01-28 07:14:29.500: W/GooglePlayServicesUtil(827): Google Play Store is missing.
        01-28 07:14:29.550: W/GooglePlayServicesUtil(827): Google Play Store is missing.
        01-28 07:14:29.550: W/GooglePlayServicesUtil(827): Google Play Store is missing.
        01-28 07:14:29.590: W/GooglePlayServicesUtil(827): Google Play Store is missing.
        01-28 07:14:29.590: W/GooglePlayServicesUtil(827): Google Play Store is missing.
        01-28 07:14:29.670: W/GooglePlayServicesUtil(827): Google Play Store is missing.
        01-28 07:14:29.690: W/GooglePlayServicesUtil(827): Google Play Store is missing.
        01-28 07:14:30.030: I/Choreographer(827): Skipped 54 frames!  The application may be                          doing too much work on its main thread.
        01-28 07:14:31.530: D/gralloc_goldfish(827): Emulator without GPU emulation detected.
        01-28 07:10:03.846: I/Choreographer(827): Skipped 61 frames!  The application may be doing too much work on its main thread.
        01-28 07:10:12.196: D/AndroidRuntime(827): Shutting down VM
        01-28 07:10:12.196: W/dalvikvm(827): threadid=1: thread exiting with uncaught exception (group=0xb3aaeb90)
        01-28 07:10:12.236: E/AndroidRuntime(827): FATAL EXCEPTION: main
        01-28 07:10:12.236: E/AndroidRuntime(827): Process: com.example.locationgooglemap, PID: 827
        01-28 07:10:12.236: E/AndroidRuntime(827): java.lang.NullPointerException
        01-28 07:10:12.236: E/AndroidRuntime(827):  at android.app.Instrumentation.execStartActivity(Instrumentation.java:1417)
        01-28 07:10:12.236: E/AndroidRuntime(827):  at android.app.Activity.startActivityForResult(Activity.java:3423)
        01-28 07:10:12.236: E/AndroidRuntime(827):  at android.app.Activity.startActivityForResult(Activity.java:3384)
        01-28 07:10:12.236: E/AndroidRuntime(827):  at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:839)
        01-28 07:10:12.236: E/AndroidRuntime(827):  at android.app.Activity.startActivity(Activity.java:3626)
        01-28 07:10:12.236: E/AndroidRuntime(827):  at android.app.Activity.startActivity(Activity.java:3594)
        01-28 07:10:12.236: E/AndroidRuntime(827):  at com.google.android.gms.dynamic.a$5.onClick(Unknown Source)
        01-28 07:10:12.236: E/AndroidRuntime(827):  at android.view.View.performClick(View.java:4424)
        01-28 07:10:12.236: E/AndroidRuntime(827):  at android.view.View$PerformClick.run(View.java:18383)
        01-28 07:10:12.236: E/AndroidRuntime(827):  at android.os.Handler.handleCallback(Handler.java:733)
        01-28 07:10:12.236: E/AndroidRuntime(827):  at android.os.Handler.dispatchMessage(Handler.java:95)
        01-28 07:10:12.236: E/AndroidRuntime(827):  at android.os.Looper.loop(Looper.java:137)
        01-28 07:10:12.236: E/AndroidRuntime(827):  at android.app.ActivityThread.main(ActivityThread.java:4998)
        01-28 07:10:12.236: E/AndroidRuntime(827):  at java.lang.reflect.Method.invokeNative(Native Method)
        01-28 07:10:12.236: E/AndroidRuntime(827):  at java.lang.reflect.Method.invoke(Method.java:515)
        01-28 07:10:12.236: E/AndroidRuntime(827):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
        01-28 07:10:12.236: E/AndroidRuntime(827):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
        01-28 07:10:12.236: E/AndroidRuntime(827):  at dalvik.system.NativeStart.main(Native Method)
        01-28 07:10:12.296: D/dalvikvm(827): GC_FOR_ALLOC freed 159K, 8% free 3122K/3364K, paused 35ms, total 47ms

Can anyone give me a solution? I am pretty new to Android and find it.little bit difficult.


text:
Q: Problema con la definición de la sobrecarga operador + como función externa ante todo y basándome en vuestras grandes explicaciones Aquí
Ahora estoy intentando definir una función de sobrecarga para el operador + pero externa a la clase.
Ante todo, pido que no os "asustéis" ya que la definición la he hecho yo por mí propia y puede contener lo que para ustedes son "graves" errores, pero bueno, ando aprendiendo.
La cuestión es que me falla cuando en el main realizo la suma (con sobrecarga obviamente):
res = p+q;

Veréis, esto es lo que he construido para tratar de entender la sobrecarga y a implementarla:
MAIN:
#include <iostream>
#include "Racional.h"
using namespace std;

int main()
{
  Racional res, p(1,1), q(2,2);

  res = p+q;
}

CLASE RACIONAL:
#ifndef Racional_h_
#define Racional_h_

class Racional
{
private:
  int numerador;
  int denominador;
public:
  Racional(int = 0, int = 0);
  int obtenerNumerador() const;
  int obtenerDenominador() const;
  void almacenarSuma(int num, int den);
};

#endif

IMPLEMENTACIÓN CLASE RACIONAL Y FUNCIONES EXTERNAS:
#include <iostream>
#include "Racional.h"
using namespace std;

Racional::Racional(int num, int den) : numerador(num), denominador(den) { }

Racional operator+(const Racional& r1, const Racional& r2)
{
  Racional res;
  int num,den;
  num = r1.obtenerNumerador() + r2.obtenerNumerador() ;
  den = r1.obtenerDenominador() + r2.obtenerDenominador(); //Corregido
  res.almacenarSuma(num, den);
  return res;
}

int Racional::obtenerNumerador() const
{
  return numerador;
}

int Racional::obtenerDenominador() const
{
  return denominador;
}

void Racional::almacenarSuma(int num, int den)
{
  numerador = num;
  denominador = den;
}

Si fuerais tan amable de ver con mi propia definición inventada porqué no funciona os lo agradecería.
Sé, que esta solución es infinitamente mejor, lo que hace es llamar al constructor pasándole directamente como parámetro la suma de los numeradores y por otra parte la suma de los denominadores, pero me gustaría saber el porqué mi versión no funciona.
Racional operator+(const Racional& r1, const Racional& r2)
{
  return Complejo(r1.obtenerNumerador()+r2.obtenerNumerador(), r1.obtenerDenominador()+r2.obtenerDenominador());
}

Sin más, muy agradecido, un saludo a todos.
EDITO: Estos son los fallos que recibo del compilador:

EDITO2:
main.cpp:9:10: error: invalid operands to binary expression ('Racional' and 'Racional')
  res = p+q;
        ~^~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/iterator:743:1: note: candidate template ignored: could not match 'reverse_iterator<type-parameter-0-0>' against
      'Racional'
operator+(typename reverse_iterator<_Iter>::difference_type __n, const reverse_iterator<_Iter>& __x)
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/iterator:1163:1: note: candidate template ignored: could not match 'move_iterator<type-parameter-0-0>' against
      'Racional'
operator+(typename move_iterator<_Iter>::difference_type __n, const move_iterator<_Iter>& __x)
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/iterator:1576:1: note: candidate template ignored: could not match '__wrap_iter<type-parameter-0-0>' against
      'Racional'
operator+(typename __wrap_iter<_Iter>::difference_type __n,
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/string:3698:1: note: candidate template ignored: could not match 'basic_string<type-parameter-0-0,
      type-parameter-0-1, type-parameter-0-2>' against 'Racional'
operator+(const basic_string<_CharT, _Traits, _Allocator>& __lhs,
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/string:3711:1: note: candidate template ignored: could not match 'const _CharT *' against 'Racional'
operator+(const _CharT* __lhs , const basic_string<_CharT,_Traits,_Allocator>& __rhs)
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/string:3723:1: note: candidate template ignored: could not match 'basic_string<type-parameter-0-0,
      type-parameter-0-1, type-parameter-0-2>' against 'Racional'
operator+(_CharT __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs)
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/string:3734:1: note: candidate template ignored: could not match 'basic_string<type-parameter-0-0,
      type-parameter-0-1, type-parameter-0-2>' against 'Racional'
operator+(const basic_string<_CharT, _Traits, _Allocator>& __lhs, const _CharT* __rhs)
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/string:3746:1: note: candidate template ignored: could not match 'basic_string<type-parameter-0-0,
      type-parameter-0-1, type-parameter-0-2>' against 'Racional'
operator+(const basic_string<_CharT, _Traits, _Allocator>& __lhs, _CharT __rhs)
^

A: Limitandonos al problema principal: el operator+ como función externa;
Tu planteamiento es correcto; te ha faltado un único detallito: informar al compilador de que dicha función existe:
#ifndef Racional_h_
#define Racional_h_

class Racional {
private:
  int numerador;
  int denominador;
public:
  Racional(int = 0, int = 0);
  int obtenerNumerador() const;
  int obtenerDenominador() const;
  void almacenarSuma(int num, int den);
};

// Añade esto
Racional operator+( const Racional &, const Racional & );

#endif

Si no lo haces, el compilador no sabe que tal función existe, y te mostrará un error cada vez que intentes usarla (como es tu caso).
Al declarar la función, el compilador ya sabe que es, que argumentos requiere, y que tipo de dato devuelve; de encontrarla y enlazarla, ya se encarga el linker.

A: No sé si te haya funcionado, pero hay algo muy importante saber. Es que los operadores que pertenecen al grupo llamado aritmetica binaria requieren dos valores uno del objeto que invocas y el otro del objeto en el lado derecha.
Mi primera pregunta es porque hiciste esto?
Racional operator+(const Racional& r1, const Racional& r2)
{
  Racional res;
  int num,den;
  num = r1.obtenerNumerador() + r2.obtenerNumerador() ;
  den = r1.obtenerDenominador() + r2.obtenerDenominador(); //Corregido
  res.almacenarSuma(num, den); //<--justo aquí
  return res;
}

Estabas intentando actualizar el objeto con el nuevo valor? recuerda que la suma no fue para el objeto al lado izquierda sino para un nuevo objeto. Si quisite actualizar el valor del objeto al lado por agregar el valor del lado derecha, necesitas usar el operador +=.
Espero que esto te haya servido. Es mi primera vez respondiendo en stackoverflow en español.


text:
Q: Image looks different in chrome and Firefox This is(https://gorgelogic.atlassian.net/secure/useravatar?ownerId=ashah&avatarId=11101) a image url. I am getting different view in chrome and firefox. And when download this image using Webclient in C# getting same image as seen in Firefox.
Actually uploaded image is same as Chrome one.
SO question is:
I want to show image on my website page. I have attached image link here. If you check that link in Firefox and chrome, you see two different images. Image seems in Chrome is actual uploaded image. Problem is when I download this image using code I m getting different image which you can see in Firefox. So in short I am getting wrong image.

A: This is most definitely a cache/temp files issue. I am getting the same picture with Firefox as w ith Chrome.
Reload the link in Chrome by hitting Ctrl+F5, this will force a complete refresh/reload from Server.


text:
Q: How to convert a mutablelist to a collection to use addAll? I'm trying to retrieve some data from a service, and I'm working with a mutablelist to store the objects. The problem is that I need to add the retrived data to this mutablelist, but addAll says me that the type is mismatched.

A: the problem here is nullability. you are passing a nullable collection( your MutableList) to a not-nullable collection. one approach is to mark the MutableList as not-nullable by adding !! at the end of your nullable Mutablelist.
to give you some idea, check this snippet code:
    var collection:Collection<String> = emptyList()
    var myList:MutableList<String>? = mutableListOf()

    collection = myList!!

A: Here's what you're doing
data.addAll(recursiveResponse.body()?.data)

You're having to null-check (with ?) before accessing data, because body() can return null. If body() returns a value, the whole expression evaluates to data. If it returns null, the whole expression evaluates to null - and calling addAll with null is not allowed. So you can't pass in a nullable collection.
That means you need to null-check your results before you try to add them:
recursiveResponse.body()?.data?.let { results -> data.addAll(results) }

This null-checks everything down to data, and if nothing in the chain evaluates to null, then it calls the let block. Because the list being passed in has been null-checked, it definitely isn't null, so it's cast to the non-null type that addAll accepts. This is how you handle potentially null stuff safely - by ensuring that it isn't null before you try to use it.


text:
Q: How to calculate difference MySQL date in PHP? I try lots of things but I can not find the solution.
$con=mysqli_connect('localhost','root','root','hidroist');
if(! $con)
    echo "Error" . mysqli_error($con);
$maxresult = mysqli_query($con, "SELECT MAX(var) as 'max' FROM date");
$row = mysqli_fetch_array($maxresult);
echo $row['max'];

 $minresult = mysqli_query($baglanti, "SELECT min(var) as 'min' FROM date;");
 $row = mysqli_fetch_array($minresult);
 echo "
";
 echo $row['min'];
 echo "
";

I need to calculate difference between $row['min'] and $row['max'] after that database should delete all data from table .

A: you coudl do this with a single query  and use backtics for  reserver or keyword  or column name alis and  not single quote
$allresult = mysqli_query($con, "SELECT MAX(var) as `max` ,
         min(var) as `min` , MAX(var) - min(var) as my_diff FROM date");

for my this you can access to the value using the same alias name  eg as in you code using $row
     echo $row['my_diff'];


text:
Q: Permission / attribute based authorization in loopback js In LoopbackJS, authorization is built to depend on roles for authorization like: if user is in role x then he is allowed/denied to access method y.
I'm looking to build a system with more flexible authorization management module that allows creating new roles and assigning permissions to those roles, then adding users to them. Hence, authorization should be permission-based instead of role-based. Like: if user has any role with permission x then he is allowed to access method y.
I tried to look for any online resources that allow deeper mapping to permissions for authorization instead of roles but failed to find any. I can try to twist the use of role resolver to do this job, but I feel that there should be something I missed which should be easier to implement with such a rich framework like loopbackJS.


text:
Q: Object reference not set to an instance of an object. It is even showing treeView1 was null I created two forms one for getting the value and in other for assigning the value in treeView in the second form. When I pass the value in the textbox which contains the treeView (both are in the same Form) it works but when I passes the value from the second  Form it gives the mentioned error.
1st Form
public void addToTreeView()
        {
            string store = _name + " - " + _role + "( S$" + _salary.ToString() + ") ";

            MessageBox.Show(store);

            treeView1.SelectedNode.Nodes.Add(store); //error line

            name.Add(_name); //list
            role.Add(_role); //list
            salary.Add(_salary); //list
        }

2nd Form

private void button1_Click(object sender, EventArgs e)
        {
            string store = comboxObj.SelectedItem.ToString();

            Form2 obj = new Form2(textBox3.Text.ToString() , store , int.Parse(textBox4.Text)); //parameterized constructor
            obj.addToTreeView();
            this.Close();
        }

In this I am getting the value from the Form2 into Form1 treeView. I even created the parameterized function addToTreeView() but it still gives the error. I used message box to check whether I am getting the value from the other Form it is even getting the correct value from the Form2.


text:
Q: JSON JsonPath -> get Array Value that contains String Hi I have a JSON Object:
{
    "idContainer":
    [
        "213=135864",
        "312=35947"
    ]
}

Now I want to access the string 135864 that is after 213= (213 is a kind of key inside of the array value, I get the data formatted like this)

*

*I can not say for certain that it is the first element in the Array,
just that it begins with  the "key" 213=

*The String result of my Xpath expression should be optimally just 135864 and no single or double quotes

1.) I am trying to find a filter expression like this idContainer[?('213=*')] which returns me this element "213=135864"
2.) More convenient would be if I could filter the result even more and just return 135864 but I don't know if this is possible with JSON XPath Syntax
Thanks for help :)
If necessary I could also use Java expressions, but my favorite Solution would be pure JsonPath

A: If you're using Jayway JSONPath, and if you're working in JAVA you probably are, you can use regular expressions in a filter condition, viz.
$.idContainer[?(@ =~ /213=.*/)]

That produces
[
   "213=135864"
]

But there's no way using Jayway to produce
[
    135864
]


text:
Q: Java Null Pointer Exception with ListSelectionEvent I'm going mad with this method which results in a runtime NullPointer exception when I remove a row in my database:
private void menuListValueChanged(javax.swing.event.ListSelectionEvent evt) {
    int index = menuList.getSelectedIndex();
    int size = model.getSize();
    if (index >= 0) {
        bDeleteMenu.setEnabled(true);
    } else {
        bDeleteMenu.setEnabled(false);
        }
    Menu selectedMenu = (Menu)menuList.getSelectedValue();
    menuName.setText(selectedMenu.getMenuName());
}

The error is in this line:
menuName.setText(selectedMenu.getMenuName());
and occurs only when I remove an item.
This is the error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException.
I guess this happens because when I remove the item in the Jlist the selection doesn't change automatically to the next one, or something like that.
And this is the method which I use to remove an item:
private void bDeleteMenuActionPerformed(java.awt.event.ActionEvent evt) {
    Menu selectedMenu = (Menu)menuList.getSelectedValue();
    selectedMenu.getMenuName();
    int index = menuList.getSelectedIndex();
    DBConnection.deleteMenu(selectedMenu);
    int size = model.getSize();
    if (size == 0) {
        bDeleteMenu.setEnabled(false);
    } else {
        if (index == model.getSize()) {
            index--;
        }
        menuList.setSelectedIndex(index);
        menuList.ensureIndexIsVisible(index);
    }
    model.removeElement(selectedMenu);
    menuName.setText("");
}

Thank you!

A: Retrieving the name of the selected menu only makes sense in case where something is selected.
Replce
if (index >= 0) {
    bDeleteMenu.setEnabled(true);
} else {
    bDeleteMenu.setEnabled(false);
}
Menu selectedMenu = (Menu)menuList.getSelectedValue();
menuName.setText(selectedMenu.getMenuName());

with
if (index >= 0) {
    bDeleteMenu.setEnabled(true);
    Menu selectedMenu = (Menu)menuList.getSelectedValue();
    menuName.setText(selectedMenu.getMenuName());
} else {
    bDeleteMenu.setEnabled(false);
}

Hope this helps.


text:
Q: .NET Framework 4 VB.Net Call an API I am working in an "old" VB.Net application. I wish to make a call to an API, check if I got a 404, parse the JSON result and all the other usual things you can do with an API call.
What is the cleanest way of doing this? I thought I can use the HttpClient class, but I can't apparently! VS 2017 is not giving me the option of adding System.Net.Http as an Import.
CODE
Right now I'm doing this which seems messy.
Public Function GetUserInfo(ByVal authTokenBytes As Byte()) As WebPayWS.GetUserInfoResult
  Dim token As New token
  token.token1 = authTokenBytes
  Dim userInformation As GetUserInfoResult = _myService.GetUserInfo(token)
  If AccountExists(userInformation.accountno) Then
    Dim response As String = GetAccountInfoFromApi(userInformation.accountno)
  End If
  Return userInformation
End Function

Private Function GetAccountInfoFromApi(accountno As String) As String
  Dim accountInformationUrl As String = "URL"
  Dim webClient As WebClient = New WebClient()
  Return webClient.DownloadString(New Uri(accountInformationUrl))
End Function

Am I stuck with WebClient? If yes, how do I check for a 404 using WebClient?

A: You can wrap it in an exception with the WebClient check this out
Private Function GetAccountInfoFromApi(accountno As String) As String
Dim accountInformationUrl As String = "URL"
Dim webClient As WebClient = New WebClient()
'Return webClient.DownloadString(New Uri(accountInformationUrl))
Dim retString As String

Try
    retString = webClient.DownloadString(New Uri(accountInformationUrl))

   Catch ex As WebException
    If ex.Status = WebExceptionStatus.ProtocolError AndAlso ex.Response IsNot Nothing Then
        Dim resp = DirectCast(ex.Response, HttpWebResponse)
        If resp.StatusCode = HttpStatusCode.NotFound Then
            ' HTTP 404
            'other steps you want here
        End If
    End If
    'throw any other exception - this should not occur
    Throw
End Try
Return retString

End Function

A: Add a reference first

*

*Right click on project

*Add...

*

*Reference...

*Browse

*C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies\System.Net.Http.dll

*Ok

Now, you can import
Imports System.Net.Http

You can also use NuGet, see https://stackoverflow.com/a/13668810/832052