text:
Q: Conditionally render border colour React Native I'm trying to conditionally change my border color based on whether the textInput is under focus or not.
<View
style={focus? { ...styles.inputRow, ...bgColorOnFocus }: { ...styles.inputRow, ...bgColorOnBlur }}>

This works as expected, but I'm having to repeat inputRow styles twice. I've been trying to improve the code with the following code where I add the object based on whether it's on focus or not and it's throwing an error.
<View style ={
{...styles.inputRow, focus? ...bgColorOnFocus: ...bgColorOnBlur}}
>

I'm not sure if I'm being silly, or if there's something missing that I'm not familiar with? Thanks for looking into this!

A: Typically a style prop accept an array as a value:
<View style={[styles.inputRow, isFocus ? bgColorOnFocus : bgColorOnBlur]}>

is a valid way to conditionally render some style.


text:
Q: HTML filter not working I buy a website in templatemonster but the filter search not working
( my website with filter ).
Example when i choose Italy and press filter button nothing happen, and i don't know what is wrong with it.
HTML filter panel:

Guides Filter

                <form class="offset-top-30 offset-sm-top-20">

                        Country

                          <select id="guides-country" name="country" data-minimum-results-for-search="Infinity" class="form-control">
                            <option value="1">All</option>
                            <option value="2">Italy</option>
                            <option value="3">France</option>
                            <option value="4">USA</option>
                            <option value="5">Spain</option>
                            <option value="6">Germany</option>
                            <option value="7">England</option>
                          </select>

                        Sorting

                          <select id="guides-sorting" name="sorting" data-minimum-results-for-search="Infinity" class="form-control">
                            <option value="1">By Popularity</option>
                            <option value="2">By Area</option>
                          </select>

                      <button type="button" class="btn btn-warning">filter</button>

                </form>

HTML post:

Italy

Venice

redpajama_set_name: RedPajamaStackExchange


text:
Q: Proper Autoresizing mask configuration I am trying to duplicate this programmatically:

I have seen there is a lot of confusion with how Apple handles this. I tried the following, but it doesn't work for me:
[buttonTop setAutoresizingMask:UIViewAutoresizingFlexibleHeight];

Any ideas where to go from here?
Update:
The code for my button is as follows:
buttonTop = [UIButton buttonWithType:UIButtonTypeCustom];
buttonTop.frame = CGRectMake(0, 0, 100, 100);
buttonTop.center = self.view.center;
buttonTop.layer.cornerRadius = buttonTop.frame.size.width / 2;
buttonTop.clipsToBounds = YES;
buttonTop.layer.masksToBounds = YES;
[buttonTop setAutoresizingMask:UIViewAutoresizingFlexibleHeight];

if (GetUserProPic){
    [buttonTop sd_setImageWithURL:[NSURL URLWithString:GetUserProPic] forState:UIControlStateNormal];
    [buttonTop sd_setImageWithURL:[NSURL URLWithString:GetUserProPic] forState:UIControlStateSelected];
} else {
    [buttonTop setImage:[UIImage imageNamed:@"avatar_icon"] forState:UIControlStateNormal];
    [buttonTop setImage:[UIImage imageNamed:@"avatar_icon"] forState:UIControlStateSelected];
}

[self.view addSubview:buttonTop];

The output looks like this:

However, I would like it to look like this:

A: The button's autoResizeMask affects the button's size when the view containing the button changes size.  It does not affect the content inside the button.  (And I think the default settings will shrink the image as needed, but not expand it.)
Try code from this SO answer: How do I scale a UIButton's imageView?
buttonTop.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;


text:
Q: Python subprocess check_output decoding specials characters I'm having some issues with python encoding. When I try to execute this:
subprocess.check_output("ipconfig", shell=True)

it gives me an output with special characters in it, like:
"Statut du m\x82dia"
"M\x82dia d\x82connect\x82"

(i'm french)
When I try decoding it with a .decode() at the end, it gives me this error:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x82 in position 78: invalid start byte

I tried using .decode("utf-8"), I played around with encoding and decoding for hours, and I can't find the answer. Everything I looked on the internet didn't work. Maybe I'm just dumb, but hey.
What can I do to get rid of those decoding errors and get my special characters to be printed?
Thanks.

A: You're invoking the command through CMD, which has a Unicode mode and an ANSI mode. The "correct" way is to invoke the Unicode mode, but you can add encoding="437" or encoding="850" to the subprocess call to make it work. This depends on you knowing what the current codepage is.


text:
Q: How to skip setting an attribute using the Builder pattern Using Lombok to build Phone object. How to skip setting an attribute say "name" using the Builder pattern, if for some reason it would be null
protected Phone createPhone(String number, String name) {
    return Phone.builder()
        .number(number)
        .name(name)
        .type(PhoneType.MOBILE)
        .build();
}

A: It is possible to "override" builder methods in Lombok. For example you could do it this way (simplified Phone):
@Builder
@Getter @Setter
public class Phone {
    private String number;
    private String name;

    public static class PhoneBuilder {
        // Lombok does not generate name "setter" but uses this instead
        public PhoneBuilder name(String name) {
            if (null == name) {
                // throw or ignore or whatever
                throw new NullPointerException("Name NULL");
            }
            this.name = name;
            return this;
        }
    }
}


text:
Q: Using file input field field on modal to update hidden field on main view I have a HTML page with a hidden field:
<input type="hidden" id="imageInput1T1" name="imageInput1T1" />

Within this main page I also have a modal window that is shown up click of a button:
<div id="templateModal1" class="reveal-modal friend-modal">
  ...............................
</div>

I have a browse field within my modal, how can I use the selection of a file in this field to populate the imageInput1 field on my main page so that I can post it through a form submit? If I select the file in the modal using the input and then post files then my Request.Files is empty. I have a hidden field on the form field how can i send the file chosen in the modal input to the hidden field?

A: --- EDITED -----
You can try this:
$(document).ready(function () {
            var fileInput = $("#yourInputFileId").on('change', function () {
                $("#imageInput1T1").val = $(this).val();
            });
        });

--- EDITED 2 ----
So the code is no teste but should work (do correct syntax if is the case):
$(document).ready(function () {
        var saveButton = $("#your-save-button-id");
        saveButton.on('click', function () {
            var form = $("#your-form-id"),
                yourFile = $("#your-file-field-id"),
                modelContentHidden = $("#modal-content-hidden-id-in-your-form"),
                modalContent = $("#templateModal1").htlm();

            modalContentHidden.val(modalContent);
            yourFile.remove();
            form.append(yourFile[0]);
            form.submit();
        });
    });


text:
Q: Resume music after pause Phonegap I already have succeeded playing, pausing and stopping music in Android. The problem is that when I want to resume my music, if I press pause button and play, it will start the music from the beginning.

A: If you are using the android mediaplayer class.. the
mediaplayer.pause();<-- will pause the player

and
  mediaplayer.start();<-- will resume the player from the point it was paused...

A: Here is the link to phonegap 1.5 Media API.
http://docs.phonegap.com/en/1.5.0/phonegap_media_media.md.html#media.pause
Hope this help
~K

A:

       public void pauseAndResume() {
               if (_mediaPlayer != null && _mediaPlayer.isPlaying()) {
               _mediaPlayer.pause();

               }else{
                            _mediaPlayer.start();
                       }
       }


text:
Q: Firebase custom password reset link not working For the last two days I've been trying to implement a custom password reset link for my users, instead of the standard '.firebaseapp.com' domain. So, in the setup there was a short 'setup guide', with a rather small code snippet of what I am supposed to include on my web server.
Therefore I created a new directory on my root, called "users". Then I made a 'index.php' file inside that directory, that I want to handle the password reset. Lastly, I updated the code for 'index.php' according to the docs. Which was this:
<script src="https://www.gstatic.com/firebasejs/3.4.0/firebase.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
  // TODO: Implement getParameterByName()

  // Get the action to complete.
  var mode = getParameterByName('mode');
  // Get the one-time code from the query parameter.
  var actionCode = getParameterByName('oobCode'};
  // (Optional) Get the API key from the query parameter.
  var apiKey = getParameterByName('apiKey'};

  // Configure the Firebase SDK.
  // This is the minimum configuration required for the API to be used.
  var config = {
    'apiKey': apiKey  // This key could also be copied from the web
                      // initialization snippet found in the Firebase console.
  };
  var app = firebase.initializeApp(config);
  var auth = app.auth();

  // Handle the user management action.
  switch (mode) {
    case 'resetPassword':
      // Display reset password handler and UI.
      handleResetPassword(auth, actionCode);
      break;
    case 'recoverEmail':
      // Display email recovery handler and UI.
      handleRecoverEmail(auth, actionCode);
      break;
    case 'verifyEmail':
      // Display email verification handler and UI.
      handleVerifyEmail(auth, actionCode);
      break;
    default:
      // Error: invalid mode.
  }
}, false);
</script>

Obviously I tweaked the code, providing the valid apiKey for my app, as well as changing the two quite unnecessary errors, changing this:
var actionCode = getParameterByName('oobCode'};

to
var actionCode = getParameterByName('oobCode');

as well as:
var apiKey = getParameterByName('apiKey'};

to
var apiKey = getParameterByName('apiKey');

So when I did this, I noticed that there was no function 'getParamtersByName()'. After a Google search, I ended up with this code:
function getParameterByName(name) {
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);

    if(results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));

}

So after this, I realized that the docs is significantly lacking code. According to Firebase, I also need this snippet in order to set up a password reset form:
function handleResetPassword(auth, actionCode) {
  var accountEmail;
  // Verify the password reset code is valid.
  auth.verifyPasswordResetCode(actionCode).then(function(email) {
    var accountEmail = email;

    // TODO: Show the reset screen with the user's email and ask the user for
    // the new password.

    // Save the new password.
    auth.confirmPasswordReset(actionCode, newPassword).then(function(resp) {
      // Password reset has been confirmed and new password updated.

      // TODO: Display a link back to the app, or sign-in the user directly
      // if the page belongs to the same domain as the app:
      // auth.signInWithEmailAndPassword(accountEmail, newPassword);
    }).catch(function(error) {
      // Error occurred during confirmation. The code might have expired or the
      // password is too weak.
    });
  }).catch(function(error) {
    // Invalid or expired action code. Ask user to try to reset the password
    // again.
  });
}

But then again, after providing this code as well - my page is still blank. And yes, that is because there is simply no code to show a reset password screen. So my question is; how would my approach be to complete this?
Is there any projects that I can take a look at? I mean, there has to be a solution for this, as I doubt that noone is using a custom email validation link.
Help would be much appreciated.
(Please note that I have very little experience with using Firebase for web, and JavaScript is not a language that I am extremely familiar with either, but I understand it).

A: This is what you should put as a firebase custom password rest link.
function sendEmailClick() {
    var auth = firebase.auth();
    var email, photoUrl, uid, emailVerified;
    var email;
    var user = firebase.auth().currentUser;
    var emailAddress = user.email;

    auth.sendPasswordResetEmail(emailAddress).then(function() {
        // Email sent.
    }).catch(function(error) {
        // An error happened.
    });
};


text:
Q: Watchkit interfaceController for interfaceControllerID:random Not Found Developing a new stand-alone WatchKit 5 app in Xcode 10.1
I am just cleaning up now that features added and bugs squashed, and the App runs fine with no crashes etc. However, I get two debugger alert when running on Sim or hardware:
    2019-01-15 12:10:56.907672-0500
App WatchKit Extension[7263:261438]
[default] -[SPRemoteInterface _interfaceControllerWithID:]:2087:
ComF: interfaceController for interfaceControllerID:1C5F0002 not found
(clientIdentifier=(null))

Prior SO discussion of this error does not seem to apply since

*

*Occurs before applicationDidFinishLaunching()

*All scenes in storyboard have names, storyboardID's and correct modules (all inherit from Target). All except Static Notification view which does not allow for module entry

*I am not using anything that need handling in didDeactivate like MMWormHole

*The app is strictly Page-based Nav. There are no pushController calls.

*I never explicitly call reloadRootControllersWithNames.

*Looking at storyboard source shows all controllers have appropriate "customModule"

*Never renamed WatchKit Target

Trying to check out the calling arguments inside watchkit (po $arg1 etc.) fails with an $arg1 not declared
WatchKit`-[SPRemoteInterface _interfaceControllerWithID:]:
->  0x225977 <+0>:   pushl  %ebp
    0x225978 <+1>:   movl   %esp, %ebp
    0x22597a <+3>:   pushl  %ebx

So, this issue occurs in WatchKit code long before my code starts running, but it could be a problem with loading the storyboard, in which case I should try to find and fix it. Otherwise it could be another Xcode bug.  The prior Radar'd reports seem to be different circumstances. Is this another harmless Xcode report?


text:
Q: How to expose port from locally-deployed AzureML container? I want to be able to debug a running entry_script.py script in VSCode. This code runs in the container created through az ml deploy with its own docker run command. This is a local deployment so I'm using a deployment config that looks like this:
{
    "computeType": "LOCAL",
    "port": 32267
}

I was thinking about using ptvsd to set up a VSCode server but I need to also expose/map the 5678 port in addition to that 32267 port for the endpoint itself. So it's not clear to me how to map an additional exposed port (typically using the -p or -P flags in the docker run command).
Sure, I can EXPOSE it in the extra_dockerfile_steps configuration but that won't actually map it to a host port that I can connect to/attach to in VSCode.
I tried to determine the run command and maybe modify it but I couldn't find out what that run command is. If I knew how to run the image that's created through AzureML local deployment then I could modify these flags.
Ultimately it felt too hacky - if there was a more supported way through az ml deploy or through the deployment configuration that would be preferred.
This is the code I'm using at the start of the entry_script to enable attachment via ptvsd:
# 5678 is the default attach port in the VS Code debug configurations
print("Waiting for debugger attach")
ptvsd.enable_attach(address=('localhost', 5678), redirect_output=True)

A: Unfortunately az ml deploy local doesn't support binding any ports other then the port hosting the scoring server.

A: build a second docker file:
FROM [YOUR_GENERATED_IMAGE]
EXPOSE [YOUR_PORT]

from cmd line in your folder:
docker build -t my_new_image .
docker run -p <port>:<port>  my_new_image

You may need to add additional run options depending on ports and environment variables etc you need.
How to get your generated image name:
 image = Image.create(workspace = az_ws, name=resolve_image_name(), models=[model], image_config = image_config)
image.wait_for_creation()
print("created image")
if(image.creation_state != "Succeeded"):
    raise Exception("Failed to create image.")
print("image location: {}".format(image.image_location))
artifacts = {"image_location" : image.image_location}
if(not os.path.exists("/artifacts/")):
    os.makedirs("/artifacts/")
with open("/artifacts/artifacts.json", "w") as outjson:
    json.dump(artifacts, outjson)


text:
Q: Push Notification Device Token I have a live app. in apple store that implements a push notification procedure. As known I communicate with my server to send and save device tokens.
My server is receiving device tokens correctly for some devices(Requests) and also receives null values for some other devices.
How is that could be possible in any case?!

A: Then you have a bug in your code, the device never generates a null token, or you have failed to implement the following delegate:
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err

If this delegate gets called then you could/should implement a retry algorithm that retries to re-register for the APN token a few times.


text:
Q: BouncyCastle PGP API: How to add user attribute packets to the key ring? I am using BouncyCastle PGP library in my current project and I need to add additional packets to the my PGP Public/Secret keys (ImageAttribute, ExpirationDate and etc.).
During deep investigation of bcpg-prov.jar I've found that BC allows to do it. But I didn't find any examples in Google how can I do it.
Does anyone know how to add image and expiration date to the PGP keys using BC libraries?


text:
Q: MVC web application Development in Visual Studio 2017 I am newbie in ASP.net MVC. Using VS 2017,  I'm trying to develop a application in MVC but can not create empty solution at the beginning of the project, it always gives me the templete with Home, about and Contact pages. how can I get a empty solution in which I can add model, views and Controllers.

A: Open your Visual Studio 2017, Click File-> New -> Project
A window will open,
-at the Left side Select Visual C#-> Web
-select ASP.NET Web application (.NET Framework)
After Entering the name of the project Click Next,
[Here is the trick]
Choose Empty for template, on the same window, there will be three check-boxes [web Forms, MVC and Web API]
Make sure  that the MVC Checkbox is checked and click OK and you will have the Empty MVC project


text:
Q: How to run PLINK on m1 MacBook I am a new user of PLINK. I installed plink1.07 on the website and followed the instruction. However, my terminal returned no file when I type ./plink.
Here is the return:
zsh: no such file or directory: ./plink

A: I am a m1 macbook user too. I downloaded the file for intel mac, but it reveals that I am using the wrong cpu. So maybe the m1 macbooker now can't use plink on a macsystem. But through the parallels desktop, I can use it.


text:
Q: C# Printing a list from another class I am new to C# and I am trying to print a list that has been created in another class. The list consists of values from an enumerator along with integers and strings.
Here is the code for the list:
using System.Collections.Generic;

namespace Risk
{
    public class RiskService
    {
        private readonly Resource _matt = new Resource { Id = 1, Name = "Matt Sharpe" };
        private readonly Resource _john = new Resource { Id = 2, Name = "John Hillhouse" };
        private readonly Resource _julian = new Resource { Id = 3, Name = "Julian Jelfs" };
        private readonly Resource _darren = new Resource { Id = 4, Name = "Darren Thorpe" };
        private readonly Resource _jonm = new Resource { Id = 5, Name = "Jon Moore" };

        public List<Risk> GetRisks()
        {
            var risks = new List<Risk>();
            risks.Add(new Risk { Id = 1, Owner = _matt, RiskScore = 5, Status = RiskStatus.Approved, Title = "Lack Build Capacity In Dockyard" });
            risks.Add(new Risk { Id = 2, Owner = _john, RiskScore = 10, Status = RiskStatus.Unapproved, Title = "Small scale fire in warehouse" });
            risks.Add(new Risk { Id = 3, Owner = _matt, RiskScore = 17, Status = RiskStatus.Mitigated, Title = "Contract delays" });
            risks.Add(new Risk { Id = 4, Owner = _julian, RiskScore = 23, Status = RiskStatus.Open, Title = "Supplier insolvency" });
            risks.Add(new Risk { Id = 5, Owner = _darren, RiskScore = 13, Status = RiskStatus.Closed, Title = "Loss of key staff" });
            risks.Add(new Risk { Id = 6, Owner = _jonm, RiskScore = 97, Status = RiskStatus.Open, Title = "Fire in plant" });
            risks.Add(new Risk { Id = 7, Owner = _jonm, RiskScore = 97, Status = RiskStatus.Open, Title = "Fire in backup plant" });
            risks.Add(new Risk { Id = 8, Owner = _jonm, RiskScore = 45, Status = RiskStatus.Unapproved, Title = "Disaster recovery doesn't cover fire" });
            risks.Add(new Risk { Id = 9, Owner = _darren, RiskScore = 36, Status = RiskStatus.Approved, Title = "Component fails to meet performance" });
            risks.Add(new Risk { Id = 10, Owner = _john, RiskScore = 36, Status = RiskStatus.Approved, Title = "Component fails to meet performance" });
            return risks;
        }
    }

    public class Risk
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public Resource Owner { get; set; }
        public RiskStatus Status { get; set; }
        public int RiskScore { get; set; }
    }

    public class Resource
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public enum RiskStatus
    {
        Unapproved,
        Approved,
        Open,
        Closed,
        Mitigated
    }
}

This is the class where I want to print the list.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Risk;

namespace printRisk
{
    public class Program
    {

        RiskService myRisk = new RiskService();

        public void Risks()
        {
            List<Risk> riskList = myRisk.GetRisks();
        }

        static void Main(string[] args)
        {
        }
    }
}

A: You can do this by iterating over the list with foreach:
static void Main(string[] args)
{
    foreach (var risk in myRisk.GetRisks()) {
        Console.WriteLine("ID: " + risk.Id + ", Title: " + risk.Title);
    }
}

A: You could also improvise on the solution provided by Glorfindel by overriding the ToString method in your Risk class as ...
public class Risk
{
    public int Id { get; set; }
    public string Title { get; set; }
    public Resource Owner { get; set; }
    public RiskStatus Status { get; set; }
    public int RiskScore { get; set; }

    public override string ToString()
    {
        return string.Format("Risk Id: {0}, Risk Title: {1}, Owner Id: {2}, Owner Name: {3}, Risk Status: {4}, Risk score: {5}",
                                this.Id, this.Title, this.Owner.Id, this.Owner.Name, this.Status.ToString(), this.RiskScore);
    }
}

and now you can use the for loop to print these as follows
foreach (Risk risk in riskList)
{
    Console.WriteLine(risk.ToString());
}

A: Console.WriteLine(string combindedString = string.Join( ", ", myList.ToArray() ))

Should fix your problems, can see a few ways too improve your code structure too

A: foreach (var r in riskList) {
    Console.WriteLine(String.Format("Id = {0} Name = {1}",r.Id, r.Name));
 }


text:
Q: load multiple views on my route but i could load one view only with return view(); I am using codeigniter 4  and I want to load multiple views on my route but I could load one view only with return view();
$this-load->view(); function is not working..
I am able to load only one view with return view(); please help me with this.
My controller - Home.php :
// in index only return view()  works
    public function index()
        {   $data['page_title'] = 'Your title';
            return view('welcome_message');
           // $this->load->view('header');
            //$this->load->view('welcome_message');
            //$this->load->view('footer');
        }
    //the views in homepge function are not loaded
        public function homePage()
        {
            $data['page_title'] = 'Your title';
            $this->load->view('header');
            $this->load->view('welcome_message');
            $this->load->view('footer');
        }

Route.php
$routes->get('/', 'Home::index');
$routes->get('dash', 'Home::homePage');

A: Codeigniter 4 does not have a $this->load->view function. That was the old way of loading views in codeigniter 3.
When you're using codeigniter 4 you need to use the view() function to load views. There's two ways you can do that. You can either return it or echo it.
If its just one view my advise is to return it like you're doing in your first example. But if its more than one you need to echo them in order.
Something like this:
    public function index()
    {
       $data['page_title'] = 'Your title';
       echo view('header');
       echo view('welcome_message');
       echo view('footer');
    }


text:
Q: Motor current calculations? So i've got a question about electrical motors.
I put 5V through a small motor and my lab bench PS reads 150mA. If I calculate this using ohms law, my motor resistance should be approximately 33Ω, but when measured, works out at 2Ω.
Is there an issue with my multimeter or am I in need of some more education?

A: Your measured value may not be very accurate but the actual value will be much less than 33ohms .The approx 2 ohm value represents the current drawn when the rotor speed and hence back emf are zero .If your power feed including and solid state components is rated at 2.5amps then the electronics will withstand a locked rotor .Remember that if 5VDC is suddenly applied at standstill the peak current could be 2.5 amp tapering down to your steady state value of 150mA after  the full rotor speed has been reached .

A: If you measure the current with the motor stalled you'll probably get more like 2.5A, at least until the motor begins to smoke or your supply current-limits.
The simplest useful model of a DC motor is a resistance (the one you measured) in series with a voltage source that bucks the applied voltage as the motor spins. That "back EMF" is proportional to how fast the motor is spinning. If you were to spin the motor with another motor, you'd measure that voltage at the open motor terminals (it would act as a generator). The resistance represents the losses in the copper windings mostly.
If the motor was perfect, no friction in the bearings or air resistance on the spinning armature, the current with no load on the shaft would go down to zero as the motor winds up from a start. As it turns out, for your motor, it goes from 2.5A to 0.15A so about 94% of the way there. As you load the motor, the armature RPM drops and the current increases.
If your motor runs at (say) 5,000 RPM with no load, and 5V applied, there is 150mA so the back EMF must 5V-300mV = 4.7V.  So back EMF = (RPM/5000)* 4.7V.
If you load the shaft so that the RPM drops to 3,000 RPM, the back EMF will be 2.82V and therefore the current will be
I = (5V-2.82V)/2\$\Omega\$ = 1.09A.
Here is a speed/torque/efficiency curve for a random brushed DC motor (Mabuchi RS-555SH):

As you can see, as the speed drops (under load, with fixed voltage applied) the current increases. The \$\eta\$ (efficiency) peaks at relatively low current, but the maximum power output will be close to where \$\eta\$ = 50%.
If you start applying fast-varying voltage (as in microseconds or milliseconds) to the motor you also have to consider the inductance, but for slow-varying 'DC' it doesn't matter.

A: V = Eb + Ia.Ra
where
V  = Applied voltage
Eb = Back EMF generated by the motor as it rotates (Eb α RPM)
Ia = Armature current
Ra = Armature resistance.


text:
Q: Compare two big tables in PL/SQL I need to implement comparing 2 tables by set of keys (columns of compared tables). By this comparing i should check equal records (equal = equal by set of defined keys (columns in these input tables)) and then insert these records to report table with some calculated columns.
Also i need to get the different (by keys) records in these 2 tables and insert them to result table. This pl/sql stored procedure works correct, but completely unusable on real datasets (~ 30 million entries in each input table).
CREATE OR REPLACE procedure ASUPR_OUP."6.3.2" (
    upd_date in date
)

as

-- filtered first input table
cursor c_end is select * from mon_end inner join dep on dep.dep = mon_end.depprod and dep.gpp_op = 1 and mon_end.division != 9 and mon_end.tehind not in (7,23) and (mon_end.depprod != mon_end.depcons or (mon_end.depprod = mon_end.depcons and dep.s_s = 1)) and mon_end.cyphdir in (1,7);

-- filtered second input table
cursor c_begin is select * from mon_begin inner join dep on dep.dep = mon_begin.depprod and dep.gpp_op = 1 and mon_begin.division != 9 and mon_begin.tehind not in (7,23) and (mon_begin.depprod != mon_begin.depcons or (mon_begin.depprod = mon_begin.depcons and dep.s_s = 1)) and mon_begin.cyphdir in (1,7);

is_found boolean;

begin

    for b_row in c_begin loop
        for e_row in c_end loop
            if (b_row.depprod = e_row.depprod) and (b_row.depcons = e_row.depcons) and
            (b_row.detail = e_row.detail) and (b_row.series = e_row.series) and (b_row.stk = e_row.stk) then
            begin
                if (b_row.trs != e_row.trs) or (b_row.trn != e_row.trn) or (b_row.kolsd != e_row.kolsd) or (b_row.applic != e_row.applic) then
                begin
                    if e_row.s_s = 0 then
                        begin
                            -- insert to result table
                        end;
                    else
                        begin
                            -- insert to result table
                        end;
                    end if;
                end;
             end if;
            end;
            end if;
        end loop;
    end loop;
    for b_row in c_begin loop
        is_found := false;
        for e_row in c_end loop
            if (b_row.depprod = e_row.depprod) and (b_row.depcons = e_row.depcons) and (b_row.detail = e_row.detail)
            and (b_row.series = e_row.series) and (b_row.stk = e_row.stk) then
                begin
                    is_found := true;
                end;
            end if;
        end loop;
        if is_found = false
        then
            begin
                if b_row.s_s = 0 then
                    begin
                        -- insert to result table
                    end;
                else
                    begin
                       -- insert to result table
                    end;
                end if;
            end;
        end if;
    end loop;
    for e_row in c_end loop
        is_found := false;
        for b_row in c_begin loop
            if (b_row.depprod = e_row.depprod) and (b_row.depcons = e_row.depcons) and (b_row.detail = e_row.detail)
            and (b_row.series = e_row.series) and (b_row.stk = e_row.stk) then
                begin
                    is_found := true;
                end;
            end if;
        end loop;
        if is_found = false then
            begin
                if e_row.s_s = 0 then
                    begin
                        -- insert to result table
                    end;
                else
                   begin
                        -- insert to result table
                    end;
                end if;
            end;
        end if;
    end loop;
end;

Can anyone suggest some way to boost performance of this procedure (i am using oracle 11g2) ? All input tables have indexes on used columns.

A: Find a small recordset and see how many loops your code does. How many does it do for 10, 100 and 1,000 records? You will see that the number of loops increases exponentially as the number of rows increases. My rough guess is that you have asymptotically big O(2^n+2^n+2^n). Asymptotics is a way of estimating work where the amount of rows processed is not known. Can't you just write some minus selects that are union all joined together? My example is looking at indexes and I use different filters so that the data sets will not be the same. Hence you will see the difference.
SELECT 'SDO_NETWORK_METADATA_TABLE_a' table_name, index_name, column_name, column_position
  FROM dba_ind_columns
 WHERE index_owner = 'MDSYS'
   AND table_name = 'SDO_NETWORK_METADATA_TABLE'
   AND index_name
   NOT IN ( SELECT index_name
              FROM dba_ind_columns
             WHERE index_owner  = 'MDSYS'
               AND table_name   = 'SDO_NETWORK_METADATA_TABLE'
               AND column_name  = 'LRS_TABLE_NAME' )
MINUS
SELECT 'SDO_NETWORK_METADATA_TABLE_a' table_name, index_name, column_name, column_position
  FROM dba_ind_columns
 WHERE index_owner = 'MDSYS'
   AND table_name = 'SDO_NETWORK_METADATA_TABLE'
   AND index_name
   NOT IN ( SELECT index_name
              FROM dba_ind_columns
             WHERE index_owner  = 'MDSYS'
               AND table_name   = 'SDO_NETWORK_METADATA_TABLE'
               AND column_name  = 'PATH_LINK_TABLE_NAME' )
UNION ALL
SELECT 'SDO_NETWORK_METADATA_TABLE_b' table_name, index_name, column_name, column_position
  FROM dba_ind_columns
 WHERE index_owner = 'MDSYS'
   AND table_name = 'SDO_NETWORK_METADATA_TABLE'
   AND index_name
   NOT IN ( SELECT index_name
              FROM dba_ind_columns
             WHERE index_owner  = 'MDSYS'
               AND table_name   = 'SDO_NETWORK_METADATA_TABLE'
               AND column_name  = 'PATH_LINK_TABLE_NAME' )
MINUS
SELECT 'SDO_NETWORK_METADATA_TABLE_b' table_name, index_name, column_name, column_position
  FROM dba_ind_columns
 WHERE index_owner = 'MDSYS'
   AND table_name = 'SDO_NETWORK_METADATA_TABLE'
   AND index_name
   NOT IN ( SELECT index_name
              FROM dba_ind_columns
             WHERE index_owner  = 'MDSYS'
               AND table_name   = 'SDO_NETWORK_METADATA_TABLE'
               AND column_name  = 'LRS_TABLE_NAME' )
 ORDER BY 1,2,4;


text:
Q: How to solve the error of collect2: ld returned 1 exit status When I make a use of Qwebview in my application. and then build it I get an error of
:: error: collect2: ld returned 1 exit status
:: error: [debug\Browseweb.exe] Error 1

so it does not run I have seached Quit But didn't got the solution So what should I do to solve this error. if You have a Solution kindly help me.

A: That error is coming from the linker ld and, based on error: [debug\Browseweb.exe] Error 1, my first thought is that it's a problem creating the executable file.
If that error 1 matches what's in errno.h, then it's an EPERM error which is related to permissions. You should check whether the debug directory exists and, if it does, check to make sure you can create files in there.
However, given that you seem to be on a Windows platform (due to the backslash path separator and an exe extension), I'm not sure that's the actual case.
One other thing that may be causing the problem is if your executable is running when you try to rebuild it.
I've seen this problem before under Windows since the OS locks the executable while it's running.


text:
Q: MatTableDataSource making alphabetical order mistakes I have the MatTableDataSource and MatSort directives set up on a table on my page, and they work great for the most part. However, I've noticed that it's making one curious mistake when alphabetizing the following fields in one of the columns:
↑
Company - David Moore
Company - David Moore
Company - Contractor
Company - Contractor
Company Inc. - Beta Testing
Company Inc. - Beta Testing
Why is it sorting D before C? Both alphabetical and numerical order are working fine everywhere else but in this case. Could it be something with the hyphen in between confusing it?

A: So it's been a while since I've used the MatSort directive, but I don't think the MatSort directive actually sorts anything for you. I think it just provides you with the UI for a sortable table, and you need to handle the sorting yourself. If this is the case, my guess is your other data just happens to be properly sorted (for the most part).
You can check out the example code for MatSort from material.angular.io. The directive doesn't handle the sorting (they provide a sortData() function).


text:
Q: C# WCF Service Reference - can not create UserNameToken In my desktop application (C#, WPF, WCF, .NET4.0) I addes a service reference.
This is Web Service (SOAP) using certificate and UserNameToken in Soap Envelope Header.
I add service reference (Solution -> Service Reference -> Add Service Reference) using WSDL of this web service.
In my app.config I have got:
    <customBinding>
<binding name="tmsIntegrationServiceSOAP">
          <!--    WsdlImporter encountered unrecognized policy assertions in ServiceDescription 'urn:CDM/tmsIntegrationService/':    -->
          <!--    <wsdl:binding name='tmsIntegrationServiceSOAP'>    -->
          <!--        <sp:SupportingTokens xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">..</sp:SupportingTokens>    -->
          <mtomMessageEncoding messageVersion="Soap11" />
          <httpsTransport />
        </binding>
      </customBinding>

<endpoint address="https://XXX/CDM/tmsIntegrationService"
        binding="customBinding" bindingConfiguration="tmsIntegrationServiceSOAP"
        contract="RABEN.GS1.tmsIntegrationService" name="tmsIntegrationServiceSOAP" />

I'm passing user name and password like this:
var ssc = new GS1.tmsIntegrationServiceClient();
ssc.ClientCredentials.UserName.UserName = "test";
ssc.ClientCredentials.UserName.Password = "testPassword";
ssc.Endpoint.Behaviors.Add(new InspectorBehavior());

When I get the request XML (with message inspector) I see that there is no UserNameToken in soap header
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header>
    <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">urn:CDM/tmsIntegrationService/importTransportInstruction</Action>
    <VsDebuggerCausalityData xmlns="http://schemas.microsoft.com/vstudio/diagnostics/servicemodelsink">uIDPoy3hcoBMqQ5Kme7yqEiHKs0AAAAAyxy+QnWD8U60kqJZWaGfvYD8RN14nUVIjC0RuEyVBa8ACQAA</VsDebuggerCausalityData>
  </s:Header>
  <s:Body ...

I try to user basicHttpBinding:
<binding name="secured">
          <security mode="TransportWithMessageCredential">
            <transport clientCredentialType="None" />
            <message clientCredentialType="UserName" />
          </security>
        </binding>

<endpoint address="https://XXX/CDM/tmsIntegrationService"
        binding="basicHttpBinding" bindingConfiguration="secured" contract="RABEN.GS1.tmsIntegrationService"
        name="tmsIntegrationServiceSOAP" />

End the result:
<s:Header>
    <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">urn:CDM/tmsIntegrationService/importTransportInstruction</Action>
  </s:Header>

When i try to use wsHttpBinding:
<wsHttpBinding>
        <binding name="RabenBinding">
          <security mode="TransportWithMessageCredential">
            <message clientCredentialType="UserName" />
          </security>
        </binding>
      </wsHttpBinding>

<endpoint address="https://XXX/CDM/tmsIntegrationService"
        binding="wsHttpBinding" bindingConfiguration="RabenBinding"
        contract="RABEN.GS1.tmsIntegrationService" name="tmsIntegrationServiceSOAP" />

The result:
<s:Header>
    <a:Action s:mustUnderstand="1">urn:CDM/tmsIntegrationService/importTransportInstruction</a:Action>
    <a:MessageID>urn:uuid:701a0fff-c4aa-4f37-a299-ec6d272e51e7</a:MessageID>
    <a:ReplyTo>
      <a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
    </a:ReplyTo>
  </s:Header>

Could some one tell me what I'm doing wrong?
EDIT - 2017-06-21 20:00
The certificate is installed on my local machine
<behaviors>
      <endpointBehaviors>
        <behavior name="RabenBehavior">
          <clientCredentials>
            <clientCertificate findValue="this is footprint of certificate"
              storeLocation="CurrentUser" storeName="My" x509FindType="FindByThumbprint" />
          </clientCredentials>
        </behavior>
      </endpointBehaviors>
    </behaviors>

I'm attaching this behavion in endpoint:
<endpoint address="https://XXX/CDM/tmsIntegrationService"
        behaviorConfiguration="RabenBehavior" binding="wsHttpBinding"
        bindingConfiguration="RabenBinding" contract="RABEN.GS1.tmsIntegrationService"
        name="tmsIntegrationServiceSOAP" />

EDIT 2017-06-21 20:58
I try to use  <mtomMessageEncoding messageVersion="Soap11" />
<binding name="myCustomBindingConfig">
          <security defaultAlgorithmSuite="Default"
                    authenticationMode="UserNameOverTransport"
            requireDerivedKeys="true"
          includeTimestamp="false" messageSecurityVersion="WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10" />
          <mtomMessageEncoding messageVersion="Soap11" />
          <httpsTransport maxReceivedMessageSize="2000000000" />
        </binding>

But the header is still do not containt user name token
<s:Header>
    <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">urn:CDM/tmsIntegrationService/importTransportInstruction</Action>
    <VsDebuggerCausalityData xmlns="http://schemas.microsoft.com/vstudio/diagnostics/servicemodelsink">uIDPo0OlG2DVOLdKniJmYU2kvwUAAAAAujMM+x53aEWJYYd4GKyk+PlCKXIih9xLrE0V5TayKhQACQAA</VsDebuggerCausalityData>
  </s:Header>

EDIT 2017-06-21 21:36
Try to use <textMessageEncoding messageVersion="Soap11" /> in custom binding generatet by VS
<binding name="tmsIntegrationServiceSOAP">
          <!--    WsdlImporter encountered unrecognized policy assertions in ServiceDescription 'urn:CDM/tmsIntegrationService/':    -->
          <!--    <wsdl:binding name='tmsIntegrationServiceSOAP'>    -->
          <!--        <sp:SupportingTokens xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">..</sp:SupportingTokens>    -->
          <textMessageEncoding messageVersion="Soap11" />
          <httpsTransport />
        </binding>

But it bring no effect - there is no user name token in request XML:
<s:Header>
    <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">urn:CDM/tmsIntegrationService/importTransportInstruction</Action>
    <VsDebuggerCausalityData xmlns="http://schemas.microsoft.com/vstudio/diagnostics/servicemodelsink">uIDPo0wJNixU4QRBhGEUAC3pw50AAAAA/fPJ+e50KUSGbYXwcmoGwgqymCvLXJZIhKg/nKdV97cACQAA</VsDebuggerCausalityData>
  </s:Header>

A: but what happend if you add by click on the solution explorer add service reference, what it is telling you?. Or you don't have this option.

A: To modify SOAP Header you will need to implement IClientMessageInspector
interface.To do this create new class MessageInspector and add
three following classes nested in it:
public class CustomMessageHeader : MessageHeader
        {
            private const string NAMESPACE_SECURITY = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
            public CustomMessageHeader()
            {
            }
            public override string Name
            {
                get { return "wsse:Security"; }
            }
            public override string Namespace
            {
                get { return ""; }
            }
            protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
            {
                writer.WriteAttributeString("xmlns", "wsse", null, NAMESPACE_SECURITY);
                writer.WriteStartElement("wsse:UsernameToken");
                writer.WriteElementString("wsse:Username", "YOUR_USERNAME");
                writer.WriteElementString("wsse:Password", "YOUR_PASSWORD");
                writer.WriteEndElement();
            }
        }
public class ClientMessageInspector : IClientMessageInspector
        {
            public object BeforeSendRequest(ref Message request, IClientChannel channel)
            {
                CustomMessageHeader header = new CustomMessageHeader();
                request.Headers.RemoveAt(0);
                request.Headers.Add(header);
                return request;
            }
public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
            {
            }
        }
public class CustomEndpointBehavior : IEndpointBehavior
        {
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
            {
                clientRuntime.ClientMessageInspectors.Add(new ClientMessageInspector());
            }
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
            {
            }

            public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
            {
            }

            public void Validate(ServiceEndpoint endpoint)
            {
            }
}

To trigger this class to be called, add new Endpoint Behavior in your Main class
serviceClient.Endpoint.EndpointBehaviors.Add(new CustomEndpointBehavior());


text:
Q: json parse booleans into html I'm currently having to parse some json, into html and all were looking good util a new request came up.
I have to parse also a value true or false. How do I do that?
Now, the requirement is that if is ´true´ I should display some specific html.
if Value is == to false then I hide that specific html.
I'm completely new/clueless to parsing booleans into html so here I am asking for help.

const friendAndFamily = [{
  name: "Serena Gosling",
  supporterNumber: "0123456789",
  isStrongRelationship: true,
  ticketingPoints: "2,500 Ticket Points",
  thumbnailUrl: "https://i.pravatar.cc/100"
}];

function supporterTemplate(supporter) {
  return `

            ${supporter.name}

            ${supporter.isStrongRelationship}

             (${supporter.supporterNumber})

        ${supporter.ticketingPoints}

    `;
}
//GRAP THE ID HERE
document.getElementById("crmFriendsAndRelativesContent").innerHTML = `

My Friends & Family (${friendAndFamily.length} results)

    ${friendAndFamily.map(supporterTemplate).join("")}

  `;

A: Create a new variable called relationship and depending on whether it isStrongRelationship is true or false set its value to an appropriate string. Then use that variable in the template instead.

const friendAndFamily = [{
  name: "Serena Gosling",
  supporterNumber: "0123456789",
  isStrongRelationship: true,
  ticketingPoints: "2,500 Ticket Points",
  thumbnailUrl: "https://i.pravatar.cc/100"
}];

function supporterTemplate(supporter) {

  const {
    thumbnailUrl,
    name,
    isStrongRelationship,
    supporterNumber,
    ticketingPoints
  } = supporter;

  const relationship = isStrongRelationship
    ? 'Strong relationship'
    : 'Not a strong relationship';

  return `

          ${name}

          ${relationship}

          (${supporterNumber})

        ${ticketingPoints}

    `;
}

document.getElementById("crmFriendsAndRelativesContent").innerHTML = `

My Friends & Family (${friendAndFamily.length} results)

  ${friendAndFamily.map(supporterTemplate).join("")}`
;

Additional documentation

*

*Destructuring assignment

A: Use the boolean in the object, as-is:
function supporterTemplate(supporter) {
  // Destructure the fields off of the object as local variables
  const {
    isStrongRelationship,
    name,
    supporterNumber,
    thumbnailUrl,
    ticketingPoints,
  } = supporter;

  if (isStrongRelationship) {
    return '<SOMETHING_ELSE>'; // Return alternate HTML text
  }

  // Default HTML text
  return `

        ${name}

        ${isStrongRelationship}

        (${supporterNumber})

      ${ticketingPoints}

    `;
}


text:
Q: How to resize the length of the two ends of the arrow heads in TiKz / PGF? Are you looking for alternatives and simpler than my MWE below
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{arrows.meta}
\begin{document}
    \begin{tikzpicture}
        \draw [draw, black,help lines, xstep=1cm, ystep=1cm] (0,0) grid  (7.5,16.5);
        \draw (0,0) [->,>=angle 45,line width=2pt] --(4.5,9);
        \draw[-{Straight Barb[angle=35:.3cm 1,length=9mm]},line width=1pt] (0,0) - - (1,5);
    \end{tikzpicture}
\end{document}

Reference to alternatives solutions

A: If I have understood your question, you are searching for a way to draw your arrows without writing all the options every time.
In this case, you can create some TikZ styles and use them every time you need them.
Off-topic:

*

*don't put draw as an option of draw, it is useless

*if xstep is equal to ystep you can simply use step

*as marmot suggested, avoid using arrows, just use the arrows.meta (for example, see mythickarrowmeta style instead of mythickarrow in my MWE).

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{arrows,arrows.meta}
\tikzset{
    mygrid/.style={help lines, step=1cm},
    mythickarrow/.style={->,>=angle 45,line width=2pt},
    mythickarrowmeta/.style={-{Straight Barb[angle=45:.25cm 1,length=8pt]}
    ,line width=2pt},
    mythinarrow/.style={-{Straight Barb[angle=35:.3cm 1,length=9mm]},line width=1pt},
    }
\begin{document}
    \begin{tikzpicture}
        \draw[mygrid] (0,0) grid (7.5,16.5);
        \draw[mythickarrow] (0,0) -- (4.5,9);
        \draw[mythickarrowmeta] (0,0) -- (5,9);
        \draw[mythinarrow] (0,0) -- (1,5);
    \end{tikzpicture}
\end{document}


text:
Q: Validate in Shiny doesn't work as expected when making a highcharter treemap When trying to make a highcharter treemap in Shiny I encountered this strange thing. When the condition for validate a highchart isn't met I get this interactive text treemap togehter with my validate message (instead of just the text).
Am I doing something wrong or is this just a bug within Highchart?

## app.R ##
require(shiny)
require(treemap)
require(highcharter)
ui <- fluidPage(numericInput(inputId = "n",
                             "Input number", value = 1),
                highchartOutput("tree"))

server <- function(input, output, session) {
  data(GNI2014)
  tm <-  treemap(
    GNI2014,
    index = c("continent", "iso3"),
    vSize = "population",
    vColor = "GNI",
    type = "value"
  )
  output$tree <- renderHighchart({
    validate(need(input$n == 1, "Please input number 1"))
    hctreemap(tm = tm)
  })
}

shinyApp(ui, server)

A: Here is a work around using the renderUI
## app.R ##
require(shiny)
require(treemap)
require(highcharter)
ui <- fluidPage(numericInput(inputId = "n","Input number", value = 1),
                htmlOutput("tree"))

server <- function(input, output, session) {
  data(GNI2014)
  tm <-  treemap(
    GNI2014,
    index = c("continent", "iso3"),
    vSize = "population",
    vColor = "GNI",
    type = "value"
  )

  output$tree <- renderUI({
    validate(need(input$n == 1, "Please input number 1"))
    if(input$n != 1){
      h1 <- highchart()
    }
    else{
      h1 <- hctreemap(tm = tm)
    }
    hw_grid(h1,rowheight = 390)
  })

}

shinyApp(ui, server)


text:
Q: Hover on image to add overlay in JavaScript If I have more than one image in a div wrapper. I want to add overlay on image when user hover over the image. I am trying to do using code shown below.

for(var i=0; i<document.getElementsByTagName('img').length; i++) {
document.getElementsByTagName('img')[i].addEventListener('mouseover', function(event){

    let elementExists = document.getElementById('wrapper');
    let Center = document.createElement('div');
    let Text = document.createElement('div');

    if (!elementExists) {
      let Wrapper = document.createElement('div');
      let parentElement = event.currentTarget.parentElement;
      Wrapper.classList.add('Wrapper');
      Wrapper.id = 'wrapper';

     Center.classList.add('Center');
     Text.innerHTML = "Sample text";

     parentElement.appendChild(Wrapper);
     Wrapper.appendChild(Center);
     Center.appendChild(Text);

      Wrapper.addEventListener('mouseout', function(event){
        if (document.getElementById('wrapper')) {
            document.getElementById('wrapper').remove();
        }
      });
    }
});
}
.col-md-6 {
        width: 375px;
        height: 211px;
        margin: 20px;
        position: relative;
    }

        .Wrapper {
        display: table;
        position: absolute;
        background-color: rgba(0, 0, 0, 0.5);
        height: 100% !important;
        width: 100%;
        text-align: center;
        z-index: 1000;
        font-family: arial;
        color: #fff;
        top: 0;
    }

    .Center {
        display: table-cell;
        vertical-align: middle;
    }

Every time I hover on first image, code just works fine. But when I hover on 2nd image it adds overlay on 1st image only.(It should add overlay on second image) I tried to debug the code and let parentElement = event.currentTarget.parentElement; is showing the a href only.
NOTE: I came to know its because I am giving position: absolute to Wrapper. I only want to make changes in JavaScript file and at max to css.
Please let me know if you found error in the code.

A: It's simply a css problem. Just add this to what you currently have:
a {
  position: relative;
  display: inline-block;
}

.Wrapper {
    display: inline-block;
    left: 0;
}

.Center {
    display: flex;
    justify-content: center;
    flex-direction: column;
    text-align: center;
    height: 100%;
}

Also I removed the final Text div and added its text to the Center div, as it triggered the mouseout event and made it flicker.

for(var i=0; i<document.getElementsByTagName('img').length; i++) {
document.getElementsByTagName('img')[i].addEventListener('mouseover', function(event){

    let elementExists = document.getElementById('wrapper');
    let Center = document.createElement('div');

    if (!elementExists) {
      let Wrapper = document.createElement('div');
      let parentElement = event.currentTarget.parentElement;
      Wrapper.classList.add('Wrapper');
      Wrapper.id = 'wrapper';

     Center.classList.add('Center');
     Center.innerHTML = "Sample text";

     parentElement.appendChild(Wrapper);
     Wrapper.appendChild(Center);

      Wrapper.addEventListener('mouseout', function(event){
        if (document.getElementById('wrapper')) {
            document.getElementById('wrapper').remove();
        }
      });
    }
});
}
.col-md-6 {
  width: 375px;
  height: 211px;
  margin: 20px;
  position: relative;
}

a {
  position: relative;
  display: inline-block;
}

.Wrapper {
  display: inline-block;
  left: 0;
  position: absolute;
  background-color: rgba(0, 0, 0, 0.5);
  height: 100% !important;
  width: 100%;
  text-align: center;
  z-index: 1000;
  font-family: arial;
  color: #fff;
  top: 0;
}

.Center {
  display: flex;
  justify-content: center;
  flex-direction: column;
  text-align: center;
  height: 100%;
}


text:
Q: Latex: How to produce a "Black Board Bold" Epsilon Symbol
I have been unable to find a latex command for a black board bold variant of epsilon. Is there an easy way to produce this symbol?
I have drawn a rough outline of the kind of thing I have in mind.


text:
Q: Libre Office: Compare value in cells several times and change action depending on the result So I am trying to put together a Libre Office Calc that will make a friends work a bit easier, by calculating some of his employees statistics automatically for him. The employees are allowed some extra break time, depending on how well they work.
Normally, they are allowed 30 minutes of break time a day.
If they take at least 74 cases, they are allowed a total of 45 minutes break time.
If they take more than 80 cases, they are allowed a full 60 minutes.
The statistics are sent to the employees every day and so that they can easily see where they need to improve, the cells needs to change color based on if they have followed the rules or not. I have tried several diffrent functions with little success, so I defaulted to a bunch of "if else" functions. Here you can see the mess I've made:
=if(b2<=64);(if(f2<=30);"green";
(if(b2<=74);(if(f2<=45));"green2";
(if(b2<=80);(if(f2<=60));"green3"
)));"red"

Each employee is required to take at least 64 cases each, therefore the first check. The column B is the amount of cases taken and F is the amount of break they used in minutes.


text:
Q: I am upgrading to spring boot 2.5.12, and am getting this error below Here is the pom file, I read somewhere it might be a spring-coud dependency issue? I can also see that is saying in the error output it may be related to spring core.
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-kubernetes-config</artifactId>
            <version>1.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

This is the error I am getting when trying to run the application. ( no class definition found )
Caused by: java.lang.NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
    at java.base/java.lang.Class.getDeclaredMethods0(Native Method) ~[na:na]
    at java.base/java.lang.Class.privateGetDeclaredMethods(Class.java:3166) ~[na:na]
    at java.base/java.lang.Class.getDeclaredMethods(Class.java:2309) ~[na:na]
    at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:467) ~[spring-core-5.3.18.jar:5.3.18]
    ... 36 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581) ~[na:na]
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178) ~[na:na]
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521) ~[na:na]

A: After </dependencies>, add Spring cloud in dependency management
<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

Edit:
You can use
<spring-cloud.version>2020.0.5</spring-cloud.version>

as per https://spring.io/projects/spring-cloud


text:
Q: How to run groups of commands in parallel? I am trying to run groups of commands in parallel. There are 10 groups and each group has 3 commands. I want sequential execution within each group and parallel execution of the 10 groups. I am trying something like this, but this does not seem to work:
(command11; command12; command13 &)
(command21; command22; command23 &)
(command31; command32; command33 &)
(command41; command42; command43 &)
...

A: As you wish
Nearly hit. The correct syntax is:
(command11; command12; command13) &
(command21; command22; command23) &
(command31; command32; command33) &
(command41; command42; command43) &

As you wish, but better
Or, if you want inside a group the commands to be left out after a command failed, then the syntax is
command11 && command12 && command13 &
command21 && command22 && command23 &
command31 && command32 && command33 &
command41 && command42 && command43 &

Note, "&&" has a very different meaning as "&". "&&" means, that the command will run only after the previous is ready, and only if it was executed without a failure (i.e. its exit code is zero). "&" means that the command before it will be run parallel with the main execution line, and its failure or success doesn't matter.
Using the xargs tool
However, these solutions have the disadvantage, that you can't wait after all of these commands were executed. To do that, we have a little bit more trickery. Specially in your case, the required command to do this would be
for i in 1 2 3 4 5 6 7 8 9 10
do
  echo "command${i}1 && command${i}2 && command${i}3"
done | xargs -P 10 -l 1 bash -c

It uses the very useful xargs tool. Of course you can pipe anything into it, for example if you want to process thousands of things in 10 threads parallel, it will do.
It works on a way, that it calls the command bash -c for all lines of input, parallel, but so, that always at most 10 child processes will coincidentally run (this is done by the -P 10). The xargs command end only if all of the bash processes were executed.
Parallel tool (see other answers)
The GNU has also written a tool named parallel as well. As far I know, its syntax is a little bit more clear as of the xargss, although it has lesser features and it is not so common. Likely other answers will explain it.
NodeJs "parallel" module
If you are working in the nodejs framework, also there is a very commonly used tool (npm install parallel), which is used mainly for parallelizing automatized build tasks, but it can be used also in shellscripts easily.
It is not a very good idea in common environments, because npm packages don't integrate very well with the Unix packet-handling environment. Although its syntax are far more easy, its features are far behind all of the other solutions.

In the case of your specific problem, I would likely choose the second solution in a simple case, and the xargs-based solution in a more complex one.

A: With GNU Parallel it would be:
parallel 'command{}1; command{}2; command{}3' ::: {1..4}

or if you prefer Command substitution:
parallel 'command{}1; command{}2; command{}3' ::: $(seq 4)

GNU Parallel has about 150 job control option which you might want to study but start with the video tutorial.


text:
Q: Error [ERR_HTTP_HEADERS_SENT] : Cannot set headers after they are sent to the client in updating profile API in Node.js I'm fairly new to Node.js and I am having some issues.
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:393:5)
at ServerResponse.setHeader (node:_http_outgoing:644:11)
at ServerResponse.header (F:\projects\Node_js\Node_js\node_modules\express\lib\response.js:794:10)
exports.update_profile = async (req, res) => {
  try {
    let rules =
    {
      username: req.body.username,
      email: req.body.email,
      mobile: req.body.mobile,
      companyname: req.body.companyname,
    };

    if (req.files && req.files.Profile_images) {
      req.body['Profile_images'] = req.files.Profile_images;
    }

    const user = new User(req.body, rules);
    user.save(err => {
          if (err) {
            res.status(500).send({ message: err });
            return;
          }
        });

    let current_user = req.User;

    if (req.files && req.files.Profile_images) {
      var image_file = req.files.Profile_images;
      var image_file_name = Date.now() + '-Profile-images-' + image_file_name;
      var image_path = publicPath + '/Profile_images/' + image_file_name;
      await image_file.mv(image_path);
      if (current_user.profile_image && current_user.profile_image == '') {
        let old_path = publicPath + '/Profile_images/' + current_user.Profile_images;
        if (fs.existsSync(old_path)) {
          fs.unlinkSync(old_path);
        }
      }
    } else {
      var image_file_name = current_user.Profile_images;
    }

    await User.updateOne({
      _id: current_user._id
    }, {
      username: req.body.username,
      email: req.body.email,
      mobile: req.body.mobile,
      companyname: req.body.companyname,
      profile_image: image_file_name,
      profession: req.body.profession ? req.body.profession : ''
    });

    let userData = await User.findOne({ _id: current_user._id })
    let jwt_secret = process.env.JWT_SECRET || 'mysecret';
    let token = jwt.sign({
      data: userData
    }, jwt_secret, { expiresIn: '12h' });

    return res.status(200).send({ message: 'Profile Updated Successfully Updated', data: userData, token: token });

  } catch (error) {
    return res.status(404).send({ message: error.message });
  }
}

This is my code of Update Profile
May I know what is wrong with my code?

A: The error handler in user.save() throw an error -> a 500 response has been sent to client but the code continue -> ERR_HTTP_HEADERS_SENT. Please change your code:
From:
user.save(err => {
          if (err) {
            res.status(500).send({ message: err });
            return;
          }
        });

To: await user.save()
Then it will log something more useful.


text:
Q: cannot get ls --color working even though dir --color works properly I spend a couple of hours on here and other sites searching for how to set ls color as default. There are a tons of resource and I try a lot of them. Somehow get command "dir --color" working with color display but not "ls --color".
After typing dir --color, the directory will appear in color CYAN while in it's only bold but not colorful.
Attached is my .bashrc.
#!/bin/bash

### add dircolor evaluation

eval `dircolors ~/.dir_colors`

### adding command alias

#alias ll='ls -l '
alias ll='ls -l --color'
alias lla='ls -la --color'
alias dir='dir --color'
alias ls='ls --color -l'

and i have my .dir_colors setup
# Configuration file for dircolors, a utility to help you set the
# LS_COLORS environment variable used by GNU ls with the --color option.
# Copyright (C) 1996-2015 Free Software Foundation, Inc.
# Copying and distribution of this file, with or without modification,
# are permitted provided the copyright notice and this notice are preserved.
# The keywords COLOR, OPTIONS, and EIGHTBIT (honored by the
# slackware version of dircolors) are recognized but ignored.
# Below, there should be one TERM entry for each termtype that is colorizable
TERM Eterm
TERM ansi
TERM color-xterm
TERM con132x25
TERM con132x30
TERM con132x43
TERM con132x60
TERM con80x25
TERM con80x28

TERM mach-color
TERM mach-gnu-color
TERM mlterm
TERM putty
TERM putty-256color
....
TERM vt100
TERM xterm
TERM xterm-16color
TERM xterm-256color
# Below are the color init strings for the basic file types. A color init
# string consists of one or more of the following numeric codes:
# Attribute codes:
# 00=none 01=bold 04=underscore 05=blink 07=reverse 08=concealed
# Text color codes:
# 30=black 31=red 32=green 33=yellow 34=blue 35=magenta 36=cyan 37=white
# Background color codes:
# 40=black 41=red 42=green 43=yellow 44=blue 45=magenta 46=cyan 47=white
#NORMAL 00 # no color code at all
#FILE 00 # regular file: use no color at all
RESET 0 # reset to "normal" color
DIR 01;36 # directory
LINK 01;36 # symbolic link. (If you set this to 'target' instead of a

 # numerical value, the color is as for the file pointed to.)
MULTIHARDLINK 00 # regular file with more than one link
FIFO 40;33 # pipe
SOCK 01;35 # socket
DOOR 01;35 # door
BLK 40;33;01 # block device driver
CHR 40;33;01 # character device driver
ORPHAN 40;31;01 # symlink to nonexistent file, or non-stat'able file ...
MISSING 00 # ... and the files they point to
SETUID 37;41 # file that is setuid (u+s)
SETGID 30;43 # file that is setgid (g+s)
CAPABILITY 30;41 # file with capability
STICKY_OTHER_WRITABLE 30;42 # dir that is sticky and other-writable (+t,o+w)
OTHER_WRITABLE 34;42 # dir that is other-writable (o+w) and not sticky
STICKY 37;44 # dir with the sticky bit set (+t) and not other-writable
# This is for files with execute permission:
EXEC 01;32
# List any file extensions like '.gz' or '.tar' that you would like ls
# to colorize below. Put the extension, a space, and the color init string.
 # archives or compressed (bright red)
.tar 01;31
.tgz 01;31
.arc 01;31
.arj 01;31
.taz 01;31
.lha 01;31
.lz4 01;31
.lzh 01;31
.lzma 01;31
.tlz 01;31
.txz 01;31


text:
Q: JavaScript + Bootstrap Dropdown list not allowing me to select the item I have this bootstrap layout, which is a container inside an accordion-item. There is a dropdown button, containing messages and there's another button that opens a modal to insert a new message and display it in the dropdown list, using localStorage.
When the page loads or is refreshed, I can select the dropdown item normally, but when I add the item, it actually shows up in the list, but I can't select it nor any other item and the selected item is kept there, until the page is reloaded again.
I can still add more messages using the modal and they will still show up in the list.
There's no error in the console to guide me.
The JavaScript code is located at the bottom of the code.
Demonstrating video: https://www.youtube.com/watch?hd=1&v=fhNfpOaJbGs
HTML:

                <button class="btn btn-secondary" type="button" id="ddMensagens" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                    Selecione Mensagem
                </button>

            <button type="button" class="btn btn-outline-success btn-sm" data-bs-toggle="modal" data-bs-target="#staticBackdrop" title="Clique para cadastrar uma nova mensagem">
                Cadastrar Nova Mensagem
            </button>

Nova Mensagem

                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fechar"></button>

                                            Digite sua mensagem
                                            <input type="text" class="form-control" id="txtMensagem" placeholder="Mensagem" style="width: 400px">

                            <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Fechar</button>
                            <button type="button" class="btn btn-primary" id="saveMensagem" onclick="addItem();" data-bs-dismiss="modal">Salvar</button>

JavaScript:

LINKS:
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">

Had to change in order to solve my issue (which I still don't know):

function getMensagem() {
    let valueMensagem = document.getElementById('mensagem').value;
    if (valueMensagem != 0) {
        $('select option:selected').each(function (e) {
$('#ContentPlaceHolder1_ddMensagensCopy').val(valueMensagem);
                    });
                }
                else {
                    $('#ContentPlaceHolder1_ddMensagensCopy').val('');
                }
            }

function updateSelectMensagem() {
            const select = document.querySelector('#mensagem');
            const oldMessage = JSON.parse(localStorage.getItem('mensagem')) || false;

            if (oldMessage) {
                select.innerHTML = "<option value='0'> Selecione uma mensagem </option>";
                oldMessage.forEach(element => {
                    select.innerHTML += `<option class='dropdown-item'>${element}</option>`
                });
            } else {
                localStorage.setItem('mensagem', '[]')
            }
        }
        function addItemMensagem() {
            const text = document.getElementById('txtMensagem').value;

            const database = JSON.parse(localStorage.getItem('mensagem')) || [];

            if (database && text.length > 3) {
                const repetido = database.find(item => item === text.value);

                if (!repetido) {
                    const novasMensagens = [...database, text];
                    localStorage.setItem('mensagem', JSON.stringify(novasMensagens))
                    updateSelectMensagem();
                    text.value = ''
                }
            }
        }
        updateSelectMensagem()

        <select id="mensagem" class="btn btn-secondary select">
            <option value="0">Selecione uma mensagem</option>
        </select>

.select option {
            background: white;
            color: #212529;
        }

A: In fact, everything works as expected
https://codesandbox.io/s/shy-cookies-1xt96?file=/index.html


text:
Q: USB Flash Drive shows 0 byte of 1.38 and nothing is in the USB drive My flash drive become empty and shows empty, yas, nothing. yesterday it  worked fine but now it shows like a floppy and shows "0 bytes free of 1.38 MB" and "This folder is empty." my laptop still recognises that it's a "USB Drive" even though it's acting like a floppy disk. could you please tell me a solution to this problem?

A: Some USB keys have been found to have various partition table set-ups that the USB software will not work with. You can use Windows Diskpart to re-format a USB key and re-partition it.
->Open a Command Window (cmd)
->Enter diskpart
->Enter list disk (it is important you KNOW which disk is the USB key you are formatting)
->Enter select disk x where x is your USB key (its mostly disk 1 if you only have a hdd)
->Enter clean
->Enter create part primary
->Enter select part 1
->Enter active
->Enter format fs=fat32 label="anything" (Label is optional)

The process can take some time, but the USB is mostly operational now, if not then go with Tetsujin advice and throw it away.


text:
Q: No such file or directory problem I am running Ubuntu on VirtualBox. I have a folder on my Desktop that includes some files I want to compile.
I try to run this
gcc drr.c -o drr -pthread -lcdsl -L./../synch_implementations -I./../synch_implementations

but I get the message no such file or directory.
I have tried using cd to get to the directory of the folder ddtr_exercise, but still get the same message (if go with cd to the folder DRR it says no such file or directory for the synch implementations, and if I cd to the synch implementations it says no such file or directory for the drr.c)


text:
Q: AngularJS - Loading icon whilst waiting for data/data calculation I have a simple Angular http.get:
app.factory('countriesService', function($http) {
return {
    getCountryData: function(done) {
        $http.get('/resources/json/countries.json')
        .success(function(data) { done(data);})
        .error(function(error) {
            alert('An error occured');
        });
    }
}
});

Example .JSON:
{
"NoCities": 66,
"Balance": 2103,
"Population":  63705000,
"CityInfo": [
    {
        "CityName": "London",
        "CityPopulation": "7825200",
        "Facts": {
            "SubFact1": "xzy",
            "SubFact2": "xzy",
            "SubFact3": "xzy",
            "SubFact4": "xzy",
            "SubFact5": "xzy"
        },
    },
    {
        "CityName": "Manchester",
        "CityPopulation": "2584241",
        "Facts": {
            "SubFact1": "abc",
            "SubFact2": "abc",
            "SubFact3": "abc",
            "SubFact4": "abc"
        },
    }

],
"SubmitInfo": null,
"FormAction": null,
"FormController": null,
}

I've noticed when my page is performing a .length, sometimes it can take a while for the data to load, for example:

    Countries : {{Countries.length}}

Does Angular have some form of waiting/loading icon that i could show whilst the data in the DIV is being populated?
Ideally something lightweight and that doesnt require a library to be loaded (my application is using jQuery too)
Thanks

A: This is my usual approach. To OZ_'s point, this requires Font Awesome. The 's classes fa fa-spinner fa-spin are a reference to that library.
Although, you could also opt to show/hide a .gif that indicates loading.
Markup
Using ng-hide and ng-show to control visibility of the spinner and element that will contain your populated data.

    Countries : {{Countries.length}}

JS
Before your call, set $scope.dataLoaded to false. Then, within your success block, set it to true. Also worth noting you'll need to pass $scope to your factory.
app.factory('countriesService', function($http, $scope) {
    return {
        getCountryData: function(done) {
            $scope.dataLoaded = false;
            $http.get('/resources/json/countries.json')
            .success(function(data) {
                done(data);
                $scope.dataLoaded = true;
             })
            .error(function(error) {
                alert('An error occured');
            });
        }
    }
});

A: AngularJS is not a CSS-framework. You can find loading icons in TWBS of FontAwesome:
http://fortawesome.github.io/Font-Awesome/examples/#spinning


text:
Q: using if instead of match on Option[X] I want to replace the below match with an if statement, preferably less verbose than this. I personally find if's to be easier to parse in the mind.
val obj = referencedCollection match{
            case None => $set(nextColumn -> MongoDBObject("name" -> name))
            case Some( collection) =>....}

Is there an equivalent if statement or some other method that produces the equivalent result?

A: You can replace the pattern match by a combination of map and getOrElse:
ox match {
  case None => a
  case Some(x) => f(x)
}

can be replaced by
ox.map(f).getOrElse(a)

A: There is huge number of options (pun intended):
if (referencedCollection != None) { ... } else { ... }
if (referencedCollection.isDefined) { ... } else { ... } // @Kigyo variant
if (referencedCollection.isEmpty) { /* None processing */ } else { ... }

A: You probably ought not indulge yourself in continuing to use if in conditions like this.  It's not idiomatic, rarely is faster, is more verbose, requires intermediate variables so is more error-prone, etc..
Oh, and it's a bad idea to use anything with $ signs!
Here are some other patterns that you might use in addition to match:
val obj = referenceCollection.fold( $set(nextColumn -> MongoDBObject("name" -> name) ){
  collection => ...
}

val obj = (for (collection <- referenceCollection) yield ...).getOrElse{
  $set(nextColumn -> MongoDBObject("name" -> name)
}

val obj = referenceCollection.map{ collection => ... }.getOrElse{
  $set(nextColumn -> MongoDBObject("name" -> name)
}

You can basically think of map as the if (x.isDefined) x.get... branch of the if and the getOrElse branch as the else $set... branch.  It's not exactly the same, of course, as leaving off the else gives you an expression that doesn't return a value, while leaving off the getOrElse leaves you with an unpacked Option.  But the thought-flow is very similar.
Anyway, fold is the most compact.  Note that both of these have a bit of runtime overhead above a match or if statement.

A: You could do it like this:
val obj = if(referencedCollection.isDefined) { (work with referencedCollection.get) } else ...


text:
Q: How to debug external crashing application I have seen a few similar questions, but I hope this is not quite a duplicate. I am using the FO.NET project found here: https://fonet.codeplex.com/ to generate PDF files from within my VB.NET application.
The Fonet.dll and Fonet.exe files are both included with the application, and I am calling it like so:
Public Sub FormatObjectToPdf(intRxNo As Integer, strSourceFileName As String)
    Dim startInfo As New ProcessStartInfo
    Dim strPdfFile As String = StrRootPath & "Paperwork\" & intRxNo & "M.pdf"

    ' if the PDF file already exists, no need to re-create it
    If Not File.Exists(strPdfFile) Then
        Try
            startInfo.Arguments = "-fo """ & strSourceFileName & """ -pdf """ & strPdfFile & """"
            startInfo.FileName = StrAppPath & "FO.NET\fonet.exe"
            startInfo.UseShellExecute = True
            startInfo.WindowStyle = ProcessWindowStyle.Hidden

            Using proc As Process = Process.Start(startInfo)
                proc.WaitForExit()

                If proc.HasExited Then
                    proc.Dispose()
                End If
            End Using
        Catch ex As Exception
            Call InsertLog("ErrorLog", "FormatObjectToPdf: " & ex.Message, ex)
            MessageBox.Show(ex.Message, "Create PDF", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try
    End If

    ' wait 3 seconds to allow file to be released
    Threading.Thread.Sleep(3000)

    ' delete the source FO file when processing is complete
    If File.Exists(strSourceFileName) Then
        Try
            File.Delete(strSourceFileName)
        Catch iEx As IOException
            Call InsertLog("ErrorLog", "[IOException]: Could Not delete file '" & strSourceFileName & "': " & iEx.Message)
        Catch ex As Exception
            Call InsertLog("ErrorLog", "Error deleting file '" & strSourceFileName & "': " & ex.Message, ex)
        End Try
    End If
End Sub

My problem is that occasionally the process will fail, and an unhandled exception will popup and the Fonet.exe application will crash (not the calling application). If I re-run the exact same call, it usually works. It is only happening occasionally, but it seems to be increasingly frequent. Is there a way to catch the exception from the external program for debugging? Or some other way to see what is causing it to crash, so that I can try to fix it?


text:
Q: How can I improve performance of a query with the DATE() function? I would like to compare the date field with time stamp filed, but the below date conversion taking long time and causing performance issue, could you please tell another alternate way in db2?
date_record <> date(date_rec_CREATE_GMTS)

where date_record - date type and date_rec_CREATE_GMTS TimeStamp. please help me?

A: Assuming your platform and version supports it, try creating an "expression based" index.
create index myidx
  on mytbl (date(date_rec_create_gmts) as create_date)


text:
Q: How can I display the contents of a textfile on a Flextable in GWT? How can I display the contents of a textfile (a Notepad) on a Flextable in GWT? I have been trying to use FileInputStream but I get an error that

Plugin failed to Connect at Development mode Server at 127.0.0.9997.

I have tried clearing the cache but it didn't help? Does GWT actually allow reading from a textfile? And how can we print the contents apart from on a FlexTable.

A: You cannot actually read file in GWT(client side). One option would be allow the user to upload the file, and in the server side you read the file and send the contents to client.
In the client you can use the desired widget to show the content.


text:
Q: Can´t re-render a Google Maps with ReactJS I´m trying to re-render a google map based on a location(city). I enter the city in the input type, but nothing happens. Can anyone help me with this? I already tried a lot of things, but nothing happens. Regards,
https://pastebin.pl/view/e31aeb6a
[enter link description here][1]

A: You might be looking for something like this where you will use Geocoding API to Geocode the address from your input then once geocoded, it will get the coordinates and plot it to your map using Maps JavaScript API.
You might also, would like to check Places Autocomplete with Maps JavaScript API where it provides suggestion on the address you are searching for then renders the place you selected on the map.
Please note that if you want to use Google Maps API, you need to use an API key and usage of these APIs are billed accordingly.
Here is how I implemented it on React. Code snippet below:
import React from 'react';
import ReactDOM from 'react-dom';
import './style.css';

var map;
const API_KEY = "PUT_API_KEY_HERE";
class GeocodingApp extends React.Component {
  constructor(props) {
    super(props);
    this.renderMap = this.renderMap.bind(this);
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleClick = this.handleClick.bind(this);
    this.state = {
      input: ""
    };
  }

  componentDidMount() {

       if (!window.google) {
            const script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = `https://maps.googleapis.com/maps/api/js?key=` + API_KEY + `&libraries=geometry,places`;
            script.id = 'googleMaps';
            script.async = true;
            script.defer = true;
            document.body.appendChild(script);
            script.addEventListener('load', e => {
                this.renderMap()
            })
        } else {
            this.renderMap()
        }

  }

  renderMap() {
    const coords = { lat: 41.375885, lng: 2.177813 };
    const el = document.getElementById("map");

    if (el) {
      map = new google.maps.Map(el, {
        zoom: 16,
        center: {
          lat: coords.lat,
          lng: coords.lng
        }
      });

      return map;
    } else {
      return null;
    }
  }

  handleInputChange(event) {
    const target = event.target;
    const value = target.type === "checkbox" ? target.checked : target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }

  handleClick(event) {
    const geocoder = new google.maps.Geocoder();
    this.codeAddress(geocoder);
    event.preventDefault();
  }

//Handles Geocoding part
  codeAddress(geocoder) {
    var address = this.state.input;
    geocoder.geocode({ address: address }, function(results, status) {
      if (status === "OK") {
        //'results[0].geometry.location' is the coordinates of the address you want to find
        map.setCenter(results[0].geometry.location);
      } else {
        return null;
      }
    });
  }

  render() {
    return (

ADD YOUR API KEY TO MAKE IT WORKIN

        <input
          id="input"
          name="input"
          value={this.state.input}
          onChange={this.handleInputChange}
        />
        <button id="submit" onClick={this.handleClick}>
          {" "}
          Search
        </button>

    );
  }
}

 ReactDOM.render(<GeocodingApp />, document.getElementById("app"));


text:
Q: The relationship between time, relativity and entropy I came across a discussion about the nature of time and whether or not time is an illusion on a physics forum. I'm not so much interested in the philosophical issues regarding time, but the following, which is more related to physics, is something that confuses me:
Is our world a three dimensional world that keeps changing or is it a four dimensional world that remains static?
Relativity seems to say that the world is actually a four dimensional static object, because it is difficult to imagine how the world could be a three dimensional changing world in a spacetime where simultaneity is relative.
On the other hand, statistical mechanics does seem to imply that the world is a three dimensional changing world because entropy increases. The laws of physics are invariant under time reflection, so if the world is a four dimensional static one, why should an arbitrary solution to the laws of physics be the kind of solution were entropy increases in 1 direction of time? I once read somewhere is has something to do with the initial conditions of our universe. This clears things up a little but I'm still confused.

A: There is an ongoing philosophical argument about this between the presentists (only the present world exists) and the four-dimensionalists (things elsewhere in time exist just as things do elsewhere in space). I personally think relativity theory and especially nontrivial wormhole spacetimes make presentism untenable, but one can make presentist arguments even in time travel situations (see Keller, S., & Nelson, M. (2001). Presentists should believe in time-travel. Australasian Journal of Philosophy, 79(3), 333-345. )
That entropy increases does not necessarily imply presentism. We could imagine a universe that had a preferred direction in space, for example that the CMB was hotter on one side than the other and that travel in that direction would make things warmer. That would not be particularly weird, it is just initial conditions making things anisotropic. Similarly we may argue that it is just initial conditions that give us a time direction where entropy increases that is also roughly orthogonal to spacetime slices where matter is roughly static. A universe where half had high entropy and the other half low entropy from the start would in a sense have a time direction defined by entropy that made an angle to the time direction defined by matter being roughly static.
But the actual source of time's arrow is still an issue. It is just separate from whether there is just a present. The arrow issue is about the nature of time and entropy, the present issue is about the metaphysics about what stuff actually exists (a full 4-manifold, or an evolving 3-manifold).


text:
Q:  : could not find an object to spy upon I have a simple component:
.html:
<h1>
  {{title}}
</h1>

<button (click)="changeTitle()">Change title</button>

.ts:
export class AppComponent {
  title = 'app works!';

  changeTitle() {
    this.title = 'New Title!';
  }
}

spec:
import {TestBed, async} from '@angular/core/testing';

import { AppComponent } from './app.component';

describe('AppComponent', () => {
  let fixture;
  let component;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
    }).compileComponents().then(() => {
      fixture = TestBed.createComponent(AppComponent);
      component = fixture.componentInsance;
    });
  }));

  it('should create the app', async(() => {
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));

  it(`should have as title 'app works!'`, async(() => {
    const app = fixture.debugElement.componentInstance;
    expect(app.title).toEqual('app works!');
  }));

  it('should render title in a h1 tag', async(() => {
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('h1').textContent).toContain('app works!');
  }));

  it('should change the title to `New Title!`', async(() => {
    fixture.detectChanges();
    spyOn(component, 'changeTitle').and.callThrough();
    const compiled = fixture.debugElement.nativeElement;

    const button = compiled.querySelector('button');
    button.click();
    return fixture.whenStable().then(() => {
      fixture.detectChanges();
      expect(compiled.querySelector('h1').textContent).toBe('New Title!');
    });
  }));

});

The first 3 tests are passing, the last one returns Error: <spyOn> : could not find an object to spy upon for changeTitle()
Any idea what's wrong?

A: Fixed by updating:
spyOn(component, 'changeTitle').and.callThrough();

to:
jasmine.createSpy('changeTitle').and.callThrough();