text:
Q: Spring Boot Modals won't work after sorting table I was building database of customers  with Spring Boot with all CRUD operations, paginating, sorting and search function. Because I'm new to web developing, I was following two Youtube tutorials.
For implementing Modals for CRUD operations I was following this:
https://www.youtube.com/watch?t=1747&v=lIgFe20dYq4&feature=youtu.be\
for implementing pagination and sorting I was following this:
https://www.youtube.com/watch?v=Aie8n12EFQc
And everythink works great! But...
After implementing sorting my modals stopped working. After clicking on header of the column, URL gets parameters for sorted filed and sorting order, but then modals won't work. When I don't have parameters in the URL it works. I won't to be able to use modals after sorting and later when I implement searching. I belive modals are very user friendly, I really want them. But i don't know how to deal with this problem, I would be happy and grateful if you help me.
Here is customer_list.html file
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>List of customers</title>
        <meta name = "author" content="Miloš Savić">

        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

List of Customers

            <button class = "btn btn-success" id = "nBtn">New Customer</button>

                            PayPal Username

                            PayPal Adress

                            In-game Name

                        Game
                        Platform
                        Login Email
                        Login Password
                        Kingdom/State
                        Activity
                        Date
                        Currency
                        Old/Other Username
                        Charge Back?
                        Notes

                        Edit
                        Delete

 1}">

                        Total Customers: [[${totalItems}]]

                            [[${i}]]
                            [[${i}]]

                        <a th:if = "${currentPage < totalPages}" th:href = "@{'/page/' + ${currentPage + 1} + '?sortField=' + ${sortField} + '&sortDirection=' + ${sortDirection}}">Next
                        <span th:unless = "${currentPage < totalPages}">Next

                        <a th:if = "${currentPage < totalPages}" th:href = "@{'/page/' + ${totalPages} + '?sortField=' + ${sortField} + '&sortDirection=' + ${sortDirection}}">Last
                        <span th:unless = "${currentPage < totalPages}">Last

            <form th:action = "@{/savecustomer}" method = "POST">

Update Customer

                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                ×
                                </button>

                                    <input type = "hidden" class = "form-control" id="idCustomer" name = "idCustomer" />

                                PayPal Username:
                                <input type="text" maxlength="32" class="form-control" id="paypalUsername" name = "paypalUsername" />

                                    PayPal Address:
                                    <input type = "email" maxlength="32" class="form-control" id="paypalAddress" name = "paypalAddress"  />

                                    Game:
                                    <input type = "text" maxlength="4" class="form-control" id="game" name = "game" />

                                    In-game Name:
                                    <input type = "text" maxlength="32" class="form-control" id="ingameName" name = "ingameName"  />

                                    Platform:
                                    <input type = "text" maxlength="32" class="form-control" id="platform" name = "platform"  />

                                    Login Email:
                                    <input type = "email" maxlength="32" class="form-control" id="loginEmail" name = "loginEmail"  />

                                    Login Password:
                                    <input type = "text" maxlength="32" class="form-control" id="loginPassword" name = "loginPassword"  />

                                    Kingdom/State:
                                    <input type = "text" maxlength="32" class="form-control" id="kingdom" name = "kingdom"  />

                                    Activity:
                                    <select class="form-control" id="active" name = "active" >
                                        <option value="true" selected>Active</option>
                                        <option value="false">Inactive</option>
                                    </select>

                                       Date:
                                    <input type = "date" class="form-control" id="date" name = "date"/>

                                    Currency:
                                    <input type = "text" maxlength="4" class="form-control" id="currency" name = "currency"  />

                                    Old/Other Username:
                                    <input type = "text" maxlength="32" class="form-control" id="oldOtherUsername" name = "oldOtherUsername"  />

                                    Charge Back?
                                    <select class="form-control" id="chargeBack" name = "chargeBack" >
                                        <option value="true" selected>No</option>
                                        <option value="false">Yes</option>
                                    </select>

                                    Notes:
                                    <textarea class="form-control" maxlength="512" id="notes" name = "notes"></textarea>

                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                            <button type="submit" class="btn btn-primary" value = "">Save</button>

            </form>

            <form th:action = "@{/savecustomer}" method = "POST">

New Customer

                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                ×
                                </button>

                                PayPal Username:
                                <input type="text" class="form-control" id="paypalUsername" name = "paypalUsername" />

                                    PayPal Address:
                                    <input type = "email" class="form-control" id="paypalAddress" name = "paypalAddress"  />

                                    Game:
                                    <input type = "text" class="form-control" id="game" name = "game" />

                                    In-game Name:
                                    <input type = "text" class="form-control" id="ingameName" name = "ingameName"  />

                                    Platform:
                                    <input type = "text" class="form-control" id="platform" name = "platform"  />

                                    Login Email:
                                    <input type = "email" class="form-control" id="loginEmail" name = "loginEmail"  />

                                    Login Password:
                                    <input type = "text" class="form-control" id="loginPassword" name = "loginPassword"  />

                                    Kingdom/State:
                                    <input type = "text" class="form-control" id="kingdom" name = "kingdom"  />

                                    Activity:
                                    <select class="form-control" id="active" name = "active" >
                                        <option value="true" selected>Active</option>
                                        <option value="false">Inactive</option>
                                    </select>

                                       Date:
                                    <input type = "date" class="form-control" id="date" name = "date"/>

                                    Currency:
                                    <input type = "text" class="form-control" id="currency" name = "currency"  />

                                    Old/Other Username:
                                    <input type = "text" class="form-control" id="oldOtherUsername" name = "oldOtherUsername"  />

                                    Charge Back?
                                    <select class="form-control" id="chargeBack" name = "chargeBack" >
                                        <option value="true" selected>No</option>
                                        <option value="false">Yes</option>
                                    </select>

                                    Notes:
                                    <textarea class="form-control" id="notes" name = "notes"></textarea>

                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                            <button type="submit" class="btn btn-primary" value = "">Save</button>

            </form>

Delete Customer

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                ×
                </button>

Are you sure you want to delete this customer?

                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                Delete

Javascript main.js for modals:
$(document).ready(function(){
    $('#nBtn, .table #eBtn').on('click', function(event){
        event.preventDefault();
        var href = $(this).attr('href');
        var text = $(this).text();
        var date = new Date();
        if(text == 'Edit')
        {
            $.get(href, function(customerDTO, status){
            $('.myModalFormEdit #idCustomer').val(customerDTO.idCustomer);
            $('.myModalFormEdit #paypalUsername').val(customerDTO.paypalUsername);
            $('.myModalFormEdit #paypalAddress').val(customerDTO.paypalAddress);
            $('.myModalFormEdit #game').val(customerDTO.game);
            $('.myModalFormEdit #ingameName').val(customerDTO.ingameName);
            $('.myModalFormEdit #platform').val(customerDTO.platform);
            $('.myModalFormEdit #loginEmail').val(customerDTO.loginEmail);
            $('.myModalFormEdit #loginPassword').val(customerDTO.loginPassword);
            $('.myModalFormEdit #kingdom').val(customerDTO.kingdom);
            $('.myModalFormEdit #active').val(customerDTO.active);
            $('.myModalFormEdit #date').val(customerDTO.date);
            $('.myModalFormEdit #currency').val(customerDTO.currency);
            $('.myModalFormEdit #oldOtherUsername').val(customerDTO.oldOtherUsername);
            $('.myModalFormEdit #chargeBack').val(customerDTO.chargeBack);
            $('.myModalFormEdit #notes').val(customerDTO.notes);
            $('.myModalFormEdit #exampleModalEdit').modal('show');

        });

        }
        else
        {

            $('.myModalFormInsertNew #exampleModal').modal('show');
        };

    });
            $('.table #delBtn').on('click', function(event){

            event.preventDefault();
            var href = $(this).attr('href');
            $('#myModalDelete #delRef').attr('href', href);
            $('#myModalDelete').modal('show');
        });
    });

Controller Java class:
package com.mitogames.controllers;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.mitogames.dto.CustomerDTO;
import com.mitogames.services.ICustomerService;

@Controller
public class MitogamesController
{

    Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    ICustomerService customerService;

    @GetMapping("/index")
    public String homePage()
    {
        return "index";
    }

    @PostMapping("/savecustomer")
    public String saveCustomer(@ModelAttribute CustomerDTO customerDTO)
    {
        //CustomerDTO emptyCustomer = new CustomerDTO();
        //ModelAndView modelAndView = new ModelAndView();
        try
        {
            customerService.saveCustomer(customerDTO);
        } catch (Exception e)
        {
            log.error("Unabel to save the customer" + e);
            e.printStackTrace();
            return "error";
        }
        //modelAndView.addObject("customerDTO", emptyCustomer);
        //modelAndView.setViewName("newcustomer");
        //return modelAndView;
        return "redirect:/customer_list";
    }

    @GetMapping("/customer_list")
    public String customerList(Model model)
    {

            return findPaginated(1, "paypalUsername", "asc",  model);
    }

    @GetMapping("/findById")
    @ResponseBody
    public CustomerDTO findById(int id)
    {
         CustomerDTO customerDTO = new CustomerDTO();
         customerDTO = customerService.getCustomerById(id);

         return customerDTO;
    }

    @GetMapping("/deleteCustomer")
    public String deleteCustomerById(int id)
    {
        customerService.deleteCustomer(id);

        return "redirect:/customer_list";
    }

    @GetMapping("/page/{pageNumber}")
    public String findPaginated(@PathVariable (value = "pageNumber") int pageNumber, @RequestParam("sortField") String sortField,
            @RequestParam("sortDirection") String sortDirection ,Model model)
    {
        int pageSize = 5;

        Page<CustomerDTO> page = customerService.findPaginated(pageNumber, pageSize, sortField, sortDirection);
        List<CustomerDTO> listOfCustomers = page.getContent();

        model.addAttribute("currentPage", pageNumber);
        model.addAttribute("totalPages", page.getTotalPages());
        model.addAttribute("totalItems", page.getTotalElements());
        model.addAttribute("listOfCustomers", listOfCustomers);
        model.addAttribute("sortField", sortField);
        model.addAttribute("sortDirection", sortDirection);
        model.addAttribute("reverseSortDirection", sortDirection.equals("asc") ? "desc" : "asc");

        return "customer_list";
    }

}

DAO Class
package com.mitogames.dao;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;

import com.mitogames.dto.CustomerDTO;

@Component
public class CustomerDAO implements ICustomerDAO
{
    @Autowired
    ICustomerRepository customerRepository;

    @Override
    public void saveCustomer(CustomerDTO customerDTO) throws Exception
    {
        customerRepository.save(customerDTO);

    }

    @Override
    public List<CustomerDTO> getAllCustomers() throws Exception
    {
        return customerRepository.findAll();
    }

    @Override
    public CustomerDTO getCustomerById(int id)
    {
        Optional<CustomerDTO> optional = customerRepository.findById(id);
        CustomerDTO customerDTO = null;

        if (optional.isPresent())
        {
            customerDTO = optional.get();
        }
        else
        {
            throw new RuntimeException("Customer not found for id: " + id);
        }

        return customerDTO;

    }

    @Override
    public void deleteCustomer(int id)
    {
        customerRepository.deleteById(id);

    }

    @Override
    public Page<CustomerDTO> findPaginated(int pageNumber, int pageSize, String sortField, String sortDirection)
    {
        Sort sort = sortDirection.equalsIgnoreCase(Sort.Direction.ASC.name()) ? Sort.by(sortField).ascending() :
            Sort.by(sortField).descending();
        Pageable pageable = PageRequest.of(pageNumber - 1, pageSize, sort);
        return this.customerRepository.findAll(pageable);
    }

}

I have a Service class, but in this case it just passes  arguments to DAO object. For CRUD operations, my Interface customerRepository extends JpaRepository.


text:
Q: Excel range to plane string I am trying to read an Excel range to a variable of type string.
Currently I have achieved it with a work around. I copied the range to clipboard and used a ReadClipBoard function that reads the clipboard as assigns to variable. This method is not efficient and also some times it gives error due to clipboard issues with VBA.
Workaround Code:
 Dim variable as string
 Range("A1:C5").Copy
 variable = ReadClipBoard()'Function that returns clipboard text

Is there a better way to do it?

A: This will turn each line into a tab-separated string and the whole range into a line-separated string.
Public Function RangeToText(ByRef r As Range)

    Dim vaData As Variant
    Dim aOutput() As String
    Dim i As Long
    Dim wf As WorksheetFunction

    Set wf = Application.WorksheetFunction

    'Put range into a two dim array
    vaData = r.Value

    'Make one dim array the same number of rows
    ReDim aOutput(1 To UBound(vaData, 1))

    'Make strings With tabs out of each row
    'and put into one dim array
    For i = LBound(vaData, 1) To UBound(vaData, 1)
        aOutput(i) = Join(wf.Index(vaData, i), vbTab)
    Next i

    'join all the strings into one multi-line string
    RangeToText = Join(aOutput, vbNewLine)

End Function

In the Immediate Window
?rangetotext(sheet1.Range("A1:C5"))
Here    Here    Here
is  is  is
some    some    some
column 1    column 2    column 3
text    text    text

The Index worksheet function is used to process only one row at a time because Join requires a one dimensional array

A: If you are reading more than once cell, then the variable would be an array  For example:
Sub ArrayDemo()
   Dim r As Range
   Set r = Range("A1:C5")
   variable = r
End Sub

is nearly equivalent to :
Sub ArrayDemo2()
   Dim r As Range
   Set r = Range("A1:C5")
   Dim variable(1 To 5, 1 To 3) As Variant
   For i = 1 To 5
      For j = 1 To 3
         variable(i, j) = Cells(i, j).Value
      Next j
   Next i
End Sub

A: Naive way is to concatenate all the content into a string, is that ok for you?
Function ConcatCells(r as range, optional sep as string) as string
  dim c as range
  dim s as string

  s=""
  if sep is missing then sep=" "
  for each c in r.cells
    s = s & c & sep
  next c
  s=left(s, len(s) - len(sep))
  ConcatCells=s
end sub

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to pack a hard drive I need to take a hard drive on a 3hr car drive tomorrow, and I don't have any antistatic bags/bubblewrap.
What's the best way to pack an hard drive for a car trip without antistatic bags/bubblewrap so it doesn't break?

A: Wrap some rubber bands around it and then put it in a sock and then wrap it in a towel.  You may want to destatic the towel and sock using this method
Make sure you secure it (like in the dashboard compartment).  And don't crash.

A: Wrapping it in newspaper or bubble-wrap inside a box should be fine.

A: If you wrap the drive and then cushion it in a briefcase and store it so it can't slide off the seat it should be fine.
For further travel arrangements you may consider the Fortress Ultra-Rugged Hard Drive:

Safeguard your data from a drop-height of 7 feet onto concrete!
Something I must get myself now after the '"Big Freeze" in Ireland!


text:
Q: What does it mean that image if formed in front of mirror Today my teacher told me about plain mirror that distance of image formed(inside mirror) is same as distance of object.
And clearly I can understand like the frame of mirror shown here is a door and someone exactly like me is standing away from me.
But when it comes to concave mirror, I don't get it how do I understand that image is formed in front of mirror ?

A: I think you are very much confuse, first thing you should get clear is, images formed by plane mirror are virtual mean incident rays will never intersect in real world, image formed by concave mirror are real with exception,  when object range between (0,F],(where F is the focal distance and 0 is at pole), real image are inverted, when your teacher said  the image formed in front of mirror, he mean the object and image are on the same side.


text:
Q: WinForm : Application built using .net Framework 1.1 I have one application built using .Net Framework 1.1 and .net framework 4.0 already installed on client machine so does microsoft provides backward compatibility or do i still need to install .net Framewok 1.1 on client machine

A:
The .NET Framework 4 is backward-compatible with applications that
  were built with the .NET Framework versions 1.1, 2.0, 3.0, and 3.5. In
  other words, applications and components built with previous versions
  of the .NET Framework will work on the .NET Framework 4.

Source: https://msdn.microsoft.com/en-us/library/ff602939(v=vs.100).aspx
Edit: You must check the migration issues and changes that might affect your application.


text:
Q: Delete item from SQLite and then RecyclerView my sqlite delete code
public void deleteItem(int position) {
   SQLiteDatabase db = getWritableDatabase();
   db.delete(TABLE_PLACE, ID + "=?" + position , null);
}

recyclerview
@Override
    public void onItemRemoved(int position) {
        places.remove(position);
        notifyItemRemoved(position);
        notifyDataSetChanged();
    }

How can i delete any row from SQLite database and then delete it from RecyclerView too

A: I had a similar problem. The problem with passing the position to your SQLite DELETE statement is that the item's position index always changes while your databases ID stays the same.
Instead of relying on the row ID (assuming that's your auto increment primary key) to match up with the position you are passing you should create another column in your table; let's call it item_index. Every time you create a new row in your database you should first set the item_index value(integer) to the size of your ArrayList (like the one you use to inflate your recyclerview) this will make the first row's item_index = 0, the second = 1, third = 2, and so on.
//EXAMPLE:
YourDataBaseHelper yourDataBaseHelper = new YourDataBaseHelper(/*proper parameters*/);//your database Class object
YourData yourData = new YourData(); //your setters and getters Class object
ArrayList<YourData> yourDataCounter = yourDataBaseHelper.getItems();//yourDataBaseHelper.whatever method you use to populate your ArrayList
yourData.set_itemIndex(yourDataCounter.size());
yourDataBaseHelper.addRow(yourData);//whatever method you use to insert rows

Now we still have the problem with the item_index and the position value that's being passed not matching up. You can solve this by going into your dataBaseHelper class and in your deleteItem method you can do the following:
        public void deleteItem(int position){
        SQLiteDatabase db = getWritableDatabase();
        db.execSQL("DELETE FROM " + TABLE_PLACE + " WHERE " +
                ITEM_INDEX + " = " + position + ";");
        db.execSQL("UPDATE " + TABLE_PLACE + " SET " + ITEM_INDEX + " = " +
                ITEM_INDEX + " -1 " + " WHERE " + ITEM_INDEX + " > " + position + ";");
        db.close();
    }

The UPDATE statement is important because it ensures that your item_index value always matches your recyclerview position simply by subtracting 1 by all the values in your item_index column that is greater than the value of the position that was passed.
All of this can be kicked off in your Adapter Class in a method called itemRemoved which can be called by an onClick method:
private ArrayList<YourData> yourData = new ArrayList<>();
private Context context;

public YourAdapter(ArrayList<YourData> yourData, Context context) {
    this.yourData = yourData;
    this.context = context;
}

public void itemRemoved(int position) {
    YourDataBaseHelper yourDataBaseHelper = new YourDataBaseHelper(/*proper parameters*/);

    yourData.remove(position);
    notifyItemRemoved(position);

    yourDataBaseHelper.deleteItem(position);

}

I hope this helped.

A: Can you try this way :
public void deleteItem(int position) {
    SQLiteDatabase db = getWritableDatabase();
    db.delete(TABLE_PLACE, ID + "=?" + position , null);
    //you can try theese following 2 lines to delete
    db.execSQL("DELETE FROM " + TABLE_NAME+ " WHERE "+COlUMN_NAME+"='"+value+"'");
    db.close();
    places.remove(position);
    adapter.notifyDataSetChanged();
    //or like this
    adapter.notifyItemRemoved(position);
    }


text:
Q: why is the pronoun "it" wrong in the given sentence?
Although the term "supercomputer" may sound fanciful or exaggerated, it is simply an extremely fast mainframe that can execute trillions of calculations every second.

What is the antecedent? Why is it wrong?

A:
Although the term "supercomputer" may sound fanciful or exaggerated, it is simply an extremely fast mainframe that can execute trillions of calculations every second.

Taking this sentence in isolation, the antecedent is the term "supercomputer", so it is a word.
A word cannot be a mainframe computer, so it is simply a mainframe doesn't make sense.
The sentence would work if you changed the verb is for means:

Although the term "supercomputer" may sound fanciful or exaggerated, it simply means an extremely fast mainframe that can execute trillions of calculations every second.


text:
Q: C# Download file from URL Can anybody tell me how i can download file in my C# program from that URL:
http://www.cryptopro.ru/products/cades/plugin/get_2_0
I try to use WebClient.DownloadFile, but i'm getting only html page instead of file.

A: I belive this would do the trick.
WebClient wb = new WebClient();
wb.DownloadFile("http://www.cryptopro.ru/products/cades/plugin/get_2_0/cadeplugin.exe","file.exe");

A: Looking in Fiddler the request fails if there is not a legitimate U/A string, so:
WebClient wb = new WebClient();
wb.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.33 Safari/537.36");
wb.DownloadFile("http://www.cryptopro.ru/products/cades/plugin/get_2_0/cadeplugin.exe", "c:\\xxx\\xxx.exe");

A: If you need to know the download status or use credentials in order to make the request, I'll suggest this solution:
WebClient client = new WebClient();
Uri ur = new Uri("http://remoteserver.do/images/img.jpg");
client.Credentials = new NetworkCredential("username", "password");
client.DownloadProgressChanged += WebClientDownloadProgressChanged;
client.DownloadDataCompleted += WebClientDownloadCompleted;
client.DownloadFileAsync(ur, @"C:\path\newImage.jpg");

And her it is the implementation of the callbacks:
void WebClientDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);
}

void WebClientDownloadCompleted(object sender, DownloadDataCompletedEventArgs e)
{
    Console.WriteLine("Download finished!");
}

A: Try WebClient.DownloadData
You would get response in the form of byte[] then you can do whatever you want with that.

A: Sometimes a server would not let you download files with scripts/code. to take care of this you need to set user agent header to fool the server that the request is coming from browser. using the following code, it works. Tested ok
 var webClient=new WebClient();
 webClient.Headers["User-Agent"] =
                "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36";
 webClient.DownloadFile("the url","path to downloaded file");

this will work as you expect, and you can download file.


text:
Q: How can I recover my gamertag? My Xbox 360 was recently stolen! I managed to get it back but by then the memory had been wiped clean; I want to use the same gamer tag but unfortunately the last time I was online was about a year ago. Is this possible? Can I recover my original gamertag?

A: Gamertags are not stored on the console, so it should still be available.
To be sure you can try logging into the xbox website. There is many ways to recover your gamertag if you forgot the login information as well.

A: Press the Xbox button once the console is on and connected to an active internet connection. Choose 'recover gamertag'. Then enter your email relating to the gamertag. You will then be promted to enter the password for that email. The profile will be downloaded to the storage of your device chosen. You won't have your save games, however your achievements as of the last time you were online will still be there.


text:
Q: Ionic Cordova Build Ending With xcodebuild: Command failed with exit code 65 When running cordova build ios on my ionic project, I received this error:
xcodebuild: Command failed with exit code 65
I've tried this solution: Ionic ios build fails, error archive not found
And this: https://forum.ionicframework.com/t/build-ios-error-code-65/120058
And this: https://github.com/apache/cordova-ios/issues/407
But nothing seems to work. I am running Ionic 5 with Angular 9.
I am on a Macbook Pro Mojave 10.14.6 and Xcode 11.3.1.
Any help would be greatly appreciated. Also, this was returned to me in yellow during the build: "No simulator found for ". Falling back to the default target."
Update:
People have asked for a full log of the error, so I ran cordova build ios --verbose:
NUS12256-9-darhart:status-app darhart$ cordova build ios --verbose
No scripts found for hook "before_build".
No scripts found for hook "before_prepare".
Checking config.xml and package.json for saved platforms that haven't been added to the project
Config.xml and package.json platforms are the same. No pkg.json modification.
Package.json and config.xml platforms are different. Updating config.xml with most current list of platforms.
PlatformApi successfully found for platform ios
Checking for saved plugins that haven't been added to the project
Checking for any plugins added to the project that have not been installed in ios platform
No differences found between plugins added to project and installed in ios platform. Continuing...
Generating platform-specific config.xml from defaults for iOS at /Users/darhart/Desktop/Repositories/Darrow_Projects/status-app/status-app/platforms/ios/MyApp/config.xml
Merging project's config.xml into platform-specific iOS config.xml
Merging and updating files from [www, platforms/ios/platform_www] to platforms/ios/www
Current launch storyboard CDVLaunchScreen
Not changing launch storyboard setting in info plist.
Wrote out iOS Bundle Version "0.0.1" to /Users/darhart/Desktop/Repositories/Darrow_Projects/status-app/status-app/platforms/ios/MyApp/MyApp-Info.plist
No need to update build settings for launch storyboard support.
Set IPHONEOS_DEPLOYMENT_TARGET to "11.0".
Did not update build settings for launch storyboard support.
iOS Product Name has not changed (still "MyApp")
Updating icons at platforms/ios/MyApp/Images.xcassets/AppIcon.appiconset/
Updating splash screens at platforms/ios/MyApp/Images.xcassets/LaunchImage.launchimage/
Updating launch storyboard images at platforms/ios/MyApp/Images.xcassets/LaunchStoryboard.imageset/
Updating Storyboard image set contents.json
This app does not have additional resource files defined
Prepared iOS project successfully
No scripts found for hook "after_prepare".
No scripts found for hook "before_compile".
No simulator found for ". Falling back to the default target.
Building for "iPhone 11 Pro Max" Simulator (com.apple.CoreSimulator.SimDeviceType.iPhone-11-Pro-Max, iPhone-11-Pro-Max).
Building project: /Users/darhart/Desktop/Repositories/Darrow_Projects/status-app/status-app/platforms/ios/MyApp.xcworkspace
        Configuration: Debug
        Platform: emulator
        Target: iPhone 11 Pro Max
Running command: xcodebuild -workspace MyApp.xcworkspace -scheme MyApp -configuration Debug -sdk iphonesimulator -destination platform=iOS Simulator,name=iPhone 11 Pro Max build CONFIGURATION_BUILD_DIR=/Users/darhart/Desktop/Repositories/Darrow_Projects/status-app/status-app/platforms/ios/build/emulator SHARED_PRECOMPS_DIR=/Users/darhart/Desktop/Repositories/Darrow_Projects/status-app/status-app/platforms/ios/build/sharedpch
Build settings from command line:
    CONFIGURATION_BUILD_DIR = /Users/darhart/Desktop/Repositories/Darrow_Projects/status-app/status-app/platforms/ios/build/emulator
    SDKROOT = iphonesimulator13.2
    SHARED_PRECOMPS_DIR = /Users/darhart/Desktop/Repositories/Darrow_Projects/status-app/status-app/platforms/ios/build/sharedpch

note: Using new build system
note: Planning build
note: Constructing build description
error: /Users/darhart/Desktop/Repositories/Darrow_Projects/status-app/status-app/platforms/ios/cordova/../pods-debug.xcconfig:2: could not find included file 'Pods/Target Support Files/Pods-MyApp/Pods-MyApp.debug.xcconfig' in search paths (in target 'MyApp' from project 'MyApp')
error: /Users/darhart/Desktop/Repositories/Darrow_Projects/status-app/status-app/platforms/ios/cordova/../pods-debug.xcconfig:2: could not find included file 'Pods/Target Support Files/Pods-MyApp/Pods-MyApp.debug.xcconfig' in search paths (in target 'MyApp' from project 'MyApp')
error: /Users/darhart/Desktop/Repositories/Darrow_Projects/status-app/status-app/platforms/ios/cordova/../pods-debug.xcconfig:2: could not find included file 'Pods/Target Support Files/Pods-MyApp/Pods-MyApp.debug.xcconfig' in search paths (in target 'MyApp' from project 'MyApp')

** BUILD FAILED **

Command finished with error code 65: xcodebuild -workspace,MyApp.xcworkspace,-scheme,MyApp,-configuration,Debug,-sdk,iphonesimulator,-destination,platform=iOS Simulator,name=iPhone 11 Pro Max,build,CONFIGURATION_BUILD_DIR=/Users/darhart/Desktop/Repositories/Darrow_Projects/status-app/status-app/platforms/ios/build/emulator,SHARED_PRECOMPS_DIR=/Users/darhart/Desktop/Repositories/Darrow_Projects/status-app/status-app/platforms/ios/build/sharedpch
xcodebuild: Command failed with exit code 65
Error: xcodebuild: Command failed with exit code 65
    at ChildProcess.whenDone (/Users/darhart/Desktop/Repositories/Darrow_Projects/status-app/status-app/node_modules/cordova-common/src/superspawn.js:135:23)
    at ChildProcess.emit (events.js:311:20)
    at maybeClose (internal/child_process.js:1021:16)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:286:5)

A: Use the legacy build system of XCode to build app for iOS.
Open XCode, Go to File-> Workplace Settings-> Change build system to Legacy Build System.
Then you can run your app on iPhone simulator from the XCode itself.

A: In my case I resolved this issue by changing cordova-ios version from 4.5.5 to 5.1.1.
ionic cordova platform rm ios
ionic cordova platform add ios@5.1.1

Also check if any plugin is creating an issue, If it does then removing and again adding that plugin would be helpful.
check this one also https://github.com/apache/cordova-ios/issues/855#issuecomment-669214469


text:
Q: Error message when training CNF example from Julia documentation I'm new with Julia trying to run the example proposed at https://diffeqflux.sciml.ai/stable/examples/normalizing_flows/ to define and train a continuous normalizing flow using sciml_train.
I just copy/pasted the written code and gets the following error:
ERROR: MethodError: no method matching (::var"#5#7")(::Array{Float32,1}, ::Float32)

Does someone know why I get this error? Here is the code:
nn = Chain(Dense(1, 3, tanh), Dense(3, 1, tanh))
tspan = (0.0f0,10.0f0)
ffjord_test = FFJORD(nn,tspan, Tsit5())
data_train = Float32.(rand(Normal(6.0,0.7), 1, 100))

function loss_adjoint(θ)
    logpx = ffjord_test(data_train,θ)[1]
    loss = -mean(logpx)
end

res1 = DiffEqFlux.sciml_train(loss_adjoint, ffjord_test.p, ADAM(0.1), cb = cb, maxiters = 100)

res2 = DiffEqFlux.sciml_train(loss_adjoint, res1.minimizer, LBFGS(), allow_f_increases = false)

Thank you

A: Given, the error message seems a little bit cryptic, due to issuing "#5#7" instead of a proper function name for the method which is seemingly not callable for the two input arguments of types ::Array{Float32,1}, ::Float32.
This is presumably due to some not properly defined variable/symbol, which is assumed by a caller to be callable like a function. The caller probably seems to be stemming from within the code you are using.
The thing which seems like the most probable source of this error seems to me to be the cb in res1 = DiffEqFlux.sciml_train(loss_adjoint, ffjord_test.p, ADAM(0.1), cb = cb, maxiters = 100) . It is meant to be shorthand for "callback" and assumed to be a function defined by the user, and is called from within sciml_train. Comparing with the linked document where you took the example from, I can verify that your snippet matches the code over there. I haven't tested it out myself by now, but could you check that the error is gone as soon as you either define a cb function or remove it from the function call? If that'd be the case, there'd be an error within the official documentation.

A: You have to note the callback function as
cb = function(p,l)
println("parameters p = $p \n loss l = $l")
return false
end

See also this issue #433: Plug - Post on Neural ODEs


text:
Q: Generating class diagram from source code I'm using Enterprise Architect and I wish to generate some class diagrams for a specific set of C++ objects within a massive project. By right clicking on a particular model and choosing Code Engineering from the context menu I can import the entire source directory for the project and generate class diagrams for all objects in the project.
I can also simply generate a class diagram for a single source file.  However what I'd ideally like is to generate individual class diagrams for a particular set of files within the project (for example ones which only contain the text SNMP within their names).  Can anyone help me apply this filter as the class diagram for the entire project is too large and unwieldy to manage in any capacity.

A: In Enterprise Architect once you have imported the entire model like you have already done you can create additional diagrams to show only the parts of the model you need.  In fact I consider this normal practice.
First create a new diagram with Add->New View -> Class View & diagram.
Then drag only the classes you want from Model in the Project Browser onto the new Diagram.

A: If you comment your code using doxygen then you can generate these class diagrams automatically. Please look at our code at github/nvmecompliance/tnvme for example. I'm not sure if this directly applies to your case if the source code you are not going to modify..


text:
Q: How to bypass base-8 number identification in python? I was doing an exercide I saw somewhere online that consisted of manipulating binary sequences (for example swaping every one by a zero and every zero for a one), at somepoint in the code, i wanted to print 0101 like this:
seq = 0101
print seq

And the output was 65 instead of 0101, I discovered this is because the 0 in the begginning of a integer identifies a base-8 number, how can I bypass this?

A: You should either use a string "0101" or use binary 0b0101.
A string will print 0101 and the binary will print the binary number it represents (5).

A: Python has binary literals, but you need to prefix them with 0b. So your example should look like:
> seq = 0b0101
> print seq
5

You can also print the binary back:
> print bin(seq)
0b101

A: You can't. When you put 0101, it automatically translates to the value of oct(101). You can save it as binary:
seq = 0b101

but this does not keep the leading 0. Your best bet would be to save it as a string.
seq = "0101"
swapped = ''.join(['1' if b in '0' else '0' for b in seq]) # or maketrans
print(swapped)  # => 1010
print(int(swapped, 2))  # => 10


text:
Q: Convert associative array to key=>value I have the following array
Array
(
    [0] => Array
        (
            [id] => 5
            [name] => 44
        )

    [1] => Array
        (
            [id] => 9
            [name] => 55
        )

)

i need to convert it to
array( '5' => '44', '9' => '55' )

i tried all function of arrays from php.net but i could not figure out how to do it

A: did you try foreach?
$result = array();
foreach($yourarray as $entry) {
  $result[$entry['id']] = $entry['name'];
}


text:
Q: dprp paypal confusion - displaying live I have read through the forums on here and see that the 'DPRP is disabled' message is due to not paying the additional fee for recurring payments.
I did not set the account up so Im not sure exactly what was paid for, I do know that we are using website payments pro.
My confusion comes from the top of the page where is says Recurring Payments are live, is this separate from the direct payment recurring? Does this mean that the account does have dprp or is this displaying live just a generic thing that all accounts have?
We currently do take recurring payments from a hosted paypal page so im wondering whether that is why it is set to live?
We plan to have our own page to take payments rather than a hosted page so any advice would be great.
Thanks in advance
CHeers
Nadeem

A: The error of you don not have DPRP enabled, is just that.  It means that you do not have recurring payments enabled on the account.  You may just have DP (Direct Payments) enabled on your account and not DPRP (Direct Payment Recurring Payments), meaning you would only be able to process single payment transactions not recurring payments.  If you can provide the email adddress to test account I can take a look at it and see what you have enabled on it and can enable it if its not enabled.


text:
Q: window.location redirect works, but original URL not showing up in browser history The code below works well. Here is my problem: The window url redirects, but the original url is not logged in my browser history.
For example, if I visit "http://example.com/page1", the browser redirects to "http://example.com/test", as it should. However, I need the original url visited ("http://example.com/page1") to show up in my browser history so that I can call upon it in a different function.
Is there anyway to get the original url visited to log in my browser's history before redirecting?
<!-- script to enable age verification cookies and ensure people have age checked -->
<script type="text/javascript">
    $(document).ready(function(){
       if (window.location =="http://example.com/home") {//do nothing
       } else {
           window.location = "http://example.com/test";
       }
    });
</script>

A: I think what you need is window.location.href. This adds the previous URL to the browser history.

A: I came across this behavior myself and it was because I was loading pages into chrome via the filesystem, i.e. using the file:// protocol. I started an HTTP server, and using that got it to keep the history.

A: tl;dr, just show me the code
var newUrl = "https://example.com.page2";

// Navigate to newUrl, adding a new entry to the Browser History
window.location.assign(newUrl);
window.open(newUrl, "_top");

JavaScript Browser Navigation With History
There are at least two methods to navigate (redirect) while retaining browser history. With Vanilla JavaScript, one of these are likely what we're looking for:

*

*Easiest: window.location.assign() - part of the Location object in the Browser Window API.

*Most Powerfull: window.open() - part of the Browser Window API. window.open() is far more powerful than location.assign() - as it can affect not just the current browser tab, but can also be used within an <iframe>, control which browsing context (a tab, window or iframe) to control, as well as change window features - including options such as the window's default size and position, whether to open a minimal popup window, and so forth.

Keep in mind that window.open() has caveats and usability/user experience issues, as it can open Popups - the exact same popups that most browsers block (Chrome, Firefox) because advertisers / spammers abuse(d) the functionality provided by window.open(). It's still a viable API to use, when used properly.
Browser History can also be managed and controlled directly via the Browser History API, including reading from, modifying existing, and adding new history entries. The History API however does not control navigation, and cannot be used for redirection. It's very often used with Single Page Applications, such as AngularJS, React, Vue.js, Svelte, etc.
Most of the text / descriptions below are directly sourced from MDN Web Docs. Please see the included links for more information. I have slightly modified the descriptions and examples from the MDN API Reference to be more relative to the question asked.
window.location.assign()
Source / Reference: https://developer.mozilla.org/en-US/docs/Web/API/Location/assign
The window.location.assign() method causes the window to load and display the document at the URL specified. After the navigation occurs, the user can navigate back to the page that called window.location.assign() by pressing the "back" button.
If the assignment can't happen because of a security violation, a DOMException of the SECURITY_ERROR type is thrown. This happens if the origin of the script calling the method is different from the origin of the page originally described by the Location object, mostly when the script is hosted on a different domain.
If the provided URL is not valid, a DOMException of the SYNTAX_ERROR type is thrown.
window.location.assign() Syntax
window.location.assign(url)

window.location.assign() Parameters
url: Is a string containing the URL of the page to navigate to.
window.location.assign() Example
var newUrl = "https://example.com.page2";

// Navigate to newUrl, adding a new entry to the Browser History
window.location.assign(newUrl);

window.open()
Source / Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/open.
⚠ NOTE: I've only included a VERY small amount of information related to the extremely versitile window.open() method. I highly recommend you review the full documentation for window.open().
The open() method of the Window interface loads a specified resource into a new or existing browsing context (that is, tab, window, or <iframe>) under a specified name.
window.open() Syntax
open()
open(url)
open(url, target)
open(url, target, windowFeatures)

window.open() Parameters
url: Optional
A string indicating the URL or path of the resource to be loaded. If an empty string ("") is specified or this parameter is omitted, a blank page is opened into the targeted browsing context.
target: Optional
A string, without whitespace, specifying the name of the browsing context the resource is being loaded into. If the name doesn't identify an existing context, a new context is created and given the specified name. The special target keywords, _self, _blank, _parent, and _top, can also be used.
This name can be used as the target attribute of <a> or <form> elements.
windowFeatures: Optional
A string containing a comma-separated list of window features in the form name=value — or for boolean features, just name.
⚠ NOTE: See the window.open() syntax for the full reference of Window Features.
window.open() Return value
A WindowProxy object. The returned reference can be used to access properties and methods of the new window as long as it complies with Same-origin policy security requirements.
window.open() Description
The Window interface's open() method takes a URL as a parameter, and loads the resource it identifies into a new or existing tab or window. The target parameter determines which window or tab to load the resource into, and the windowFeatures parameter can be used to control the size and position of a new window, and to open the new window as a popup with minimal UI features.
Note that remote URLs won't load immediately. When window.open() returns, the window always contains about:blank. The actual fetching of the URL is deferred and starts after the current script block finishes executing. The window creation and the loading of the referenced resource are done asynchronously.
window.open() Basic Example
For answering the question, the minimal form of window.open() to browse to a new URL, in the same browser tab, retaining browser navigation history.
var newUrl = "https://example.com/page2";

// Navigate to newUrl, adding a new entry to the Browser History
window.open(newUrl, "_top");


text:
Q: IPSEC tunnel from Libreswan routed mode to DRG I have a scenario in which i want to connect to the DRG from a Libreswan. I followed the official documentation:
https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/libreswan.htm
Tunnel is up, but no traffic is flowing.
My config is:
    config setup
plutoopts="--perpeerlog"
protostack=auto
conn oracle-tunnel-1
left=DRG tunnel 1 public IP address
right=192.168.12.4
rightid=Libreswan public IP # See preceding note about 1-1 NAT device
authby=secret
leftsubnet=0.0.0.0/0
rightsubnet=0.0.0.0/0
auto=start
mark=5/0xffffff1 # Needs to be unique across all tunnels
vti-interface=vti1
vti-routing=no
encapsulation=no
conn oracle-tunnel-2
left=DRG tunnel 2 public IP address
right=192.168.12.4
rightid=Libreswan public IP # See preceding note about 1-1 NAT device
authby=secret
leftsubnet=0.0.0.0/0
rightsubnet=0.0.0.0/0
auto=start
mark=5/0xffffff2 # Needs to be unique across all tunnels
vti-interface=vti2
vti-routing=no
encapsulation=no

Tunnel is up:
    #1: "oracle-tunnel-1":500 STATE_MAIN_I4 (ISAKMP SA established);
EVENT_SA_REPLACE in 2847s; newest ISAKMP; lastdpd=-1s(seq in:0 out:0);
idle; import:admin initiate
#4: "oracle-tunnel-1":500 STATE_QUICK_I2 (sent QI2, IPsec SA established);
EVENT_SA_REPLACE in 27828s; newest IPSEC; eroute owner; isakmp#1; idle;
import:admin initiate
#4: "oracle-tunnel-1" esp.bbba50fa@DRG-IP esp.7db55be9@192.168.12.4
tun.0@DRG-IP tun.0@192.168.12.4 ref=0 refhim=0 Traffic: ESPin=0B
ESPout=0B! ESPmax=4194303B
#2: "oracle-tunnel-2":500 STATE_MAIN_I4 (ISAKMP SA established);
EVENT_SA_REPLACE in 2606s; newest ISAKMP; lastdpd=-1s(seq in:0 out:0);
idle; import:admin initiate
#3: "oracle-tunnel-2":500 STATE_QUICK_I2 (sent QI2, IPsec SA established);
EVENT_SA_REPLACE in 27837s; newest IPSEC; eroute owner; isakmp#2; idle;
import:admin initiate
#3: "oracle-tunnel-2" esp.9dfaf013@DRG-IP esp.43348c8c@192.168.12.4
tun.0@DRG-IP tun.0@192.168.12.4 ref=0 refhim=0 Traffic: ESPin=84B
ESPout=0B! ESPmax=4194303B

But no traffic is flowing.
Any Ideas?


text:
Q: Laravel image issue im trying to make a profile view for my users, but having an issue when showing the profile photo, because i get the box such like its waiting for the foto but it doesn't shows it, here is the code:
@include('layouts.header')
@include('layouts.navbar')

    avatar}}" alt = "Foto de perfil">

{{Auth::user()->name}}

Email: {{Auth::user()->email}}

Telefono: {{Auth::user()->phone}}

@include('layouts.footer')

i have the images saved in public/images/

A: You may try this (Assumed Auth::user()->avatar returns only the file name like - image.png):
avatar }}"
alt = "Foto de perfil"
/>


text:
Q: Rails 5: distinct values in view I have working solution where users who belong to current_user companies can be found.
In /controllers/users_controller.rb I have this:
def index
@companies = current_user.companies.includes(:users)
@users = @companies.map(&:users).flatten
end

In console I can get this (current_user ID=2):
User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 2], ["LIMIT", 1]]
Company Load (0.2ms)  SELECT "companies".* FROM "companies" INNER JOIN "accounts" ON "companies"."id" = "accounts"."company_id" WHERE "accounts"."user_id" = ?  [["user_id", 2]]
Account Load (0.2ms)  SELECT "accounts".* FROM "accounts" WHERE "accounts"."company_id" IN (14, 15, 16)
User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."id" IN (1, 2)

Users: 1, 2 is my desired result.
/models/user.rb
class User < ApplicationRecord
has_many :accounts, dependent: :destroy
has_many :companies, through: :accounts

/models/account.rb
class Account < ApplicationRecord
belongs_to :company
belongs_to :user
accepts_nested_attributes_for :company, :user

/models/company.rb
class Company < ApplicationRecord
has_many :accounts, dependent: :destroy
has_many :users, through: :accounts
accepts_nested_attributes_for :accounts, :users

In view at the moment I have this: <%= render @users %>  with this related partial:
<li>
   <%= link_to user.name, user %>
</li>

How to get unique values of users? At the moment I get multiple values of users if one user is in several companies.

A: You can use uniq method to remove duplicates from array
@companies = current_user.companies
@users = @companies.map(&:users).flatten.uniq

Or you can do it with active record creating queries like
@companies = current_user.companies
@users = User.joins(:accounts).where("accounts.company_id in (?)", @companies.map(&:id)).uniq

A: @users = @companies.map(&:users).flatten.uniq should do I believe
Also building on @idej's answer you could also do
@users = User.joins(:accounts).where("accounts.company_id IN (?)", current_user.companies.pluck(:id)).uniq

which should do the same thing and be more efficient


text:
Q: What did Apple do to the Python framework? [tl;dr? see bottom]
Python on OS X has always been somewhat of an abomination in that it's split up and spread out all across the system. Some in /usr, some in /Library/Python, some /System/Library/Frameworks/Python.framework.
Now, as I understand it, the framework is supposed to contain the Python distribution, i.e. the bits and pieces that aren't going to change. An example would be headers, the standard library, the binary images, etc.
So as a developer of a sort-of-popular Python C extension, I think myself to be pretty good at the OS X ecosystem and how to compile Python extensions on it. It wasn't a month ago that Apple decided to skip on QA, breaking C extension building across the board.
It's broken in yet a new way though, as Apple seem to have decided to remove the better part of the Python distribution. Take a look at the include/ directory:
$ ls -l /System/Library/Frameworks/Python.framework/Versions/Current/include/python2.6
total 16
-rw-r--r--  1 root  wheel    30K Jun 25  2010 pyconfig.h

Missing something? The Python.h header perhaps? What's more, I had woes with zc.buildout because it couldn't find site.py... Have a look-see:
$ python -c 'print __import__("site").__file__'
/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site.pyc

$ ls -l /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site.py*
-rw-r--r--  1 root  wheel    20K May 17 15:40 /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site.pyc

Missing something? The site.py original perhaps?
All in all, it seems Apple are stripping out vital developer resources. I confirmed both of these findings on other MacBooks with OS X 10.6.7.
tl;dr Apple have removed lots of vital headers and source-code from the Python framework. Has this happened anybody else? If so, when did this happen? Why did it happen? And most importantly, how do I get them back?

A: Python.h and other headers are included with Xcode. On my system, it's located in both /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/Python.h and /System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/Python.h. The latter appears to be installed by the Xcode installer.

A: Actually, it doesn't look like you understand the OS X ecosystem at all. /System/Library is for Apple-shipped components of the OS X "distribution"; third parties must not put files in there, but should use /Library instead. That's why the built-in Pythons (multiple versions) are in /System/Library/Frameworks/Python.framework, but place the site-packages directories in /Library/Python, so that third-party modules can be installed there. As for /usr/bin, it contains symlinks to the python executable by version, and programs that autoselect the version based on some parameters (see man python). It's actually quite logical and tidy.
Now to answer your questions. C headers and other developer resources are not included in the default install of OS X. This is not specific to Python, and was done to save space on a default install. To get the developer resources, you need to install the developer tools. What were you going to do with a C header without a C compiler, anyway?

A: I have encountered similar problems in the past. Space_C0wb0y's suggestion works for me, and using python_select I can switch between "default" versions of python. This also de-couples me from XCode. I've installed versions of 2.6 and 2.7 using MacPorts, which by default places the distribution in locations such as /opt/local/Library/Frameworks/Python.framework/Versions/2.7. It is the only way I have managed to have consistent installations, including 3rd party modules.


text:
Q: Terraform AWS Aurora Serverless MySQL - Error: Invalid DB Engine I'm trying to use the aws terraform rds module to spin up an aurora serverless mysql 5.7 version but get the below Error while creating the DB Instance, pointing to an incorrect DBEngine.
Error creating DB Instance: InvalidParameterValue: Invalid DB engine
resource "aws_rds_cluster" "test" {
  cluster_identifier                  = "test-cluster"
  engine                              = "aurora-mysql"
  engine_version                      = "5.7.12"
  engine_mode                         = "serverless"
  database_name                       = "rdstest"
  master_username                     = "xxxxx"
  master_password                     = "xxxxxxx"
  kms_key_id                          = "arn:aws:kms:eu-west-1:792xxxxxx:key/09f01648-daf7-xxxxxxxx"
  backup_retention_period             =  7
  port                                = 3306
  db_cluster_parameter_group_name     = aws_rds_cluster_parameter_group.aurora_cluster_mysql_parameter_group.name
  vpc_security_group_ids              = ["${aws_security_group.cachet_rds.id}"]
  availability_zones                  = ["eu-west-1a"]
  db_subnet_group_name                = aws_db_subnet_group.cachet.id
  skip_final_snapshot                 = true
}

resource "aws_db_instance" "test" {
  identifier              = "test"
  allocated_storage       =  20
  storage_type            = "gp2"
  engine                  = "aurora-mysql"
  engine_version          = "5.7.12"
  instance_class          = "t3a.small"
  db_subnet_group_name    = aws_db_subnet_group.cachet.id
  vpc_security_group_ids  = ["${aws_security_group.cachet_rds.id}"]
  username                = "xxxxx"
  password                = "xxxxx"
  parameter_group_name    = aws_rds_cluster_parameter_group.aurora_cluster_mysql_parameter_group.name
  skip_final_snapshot     = true
  backup_retention_period = 5
  storage_encrypted       = true
  kms_key_id              = "arn:aws:kms:eu-west-1:79xxxxx:key/09f01648-daf7-47e7-af2f-xxxxxx"
}

resource "aws_db_parameter_group" "aurora_db_mysql_parameter_group" {
  name        = "test-aurora-parameter-group"
  family      = "aurora-mysql5.7"
}

resource "aws_rds_cluster_parameter_group" "aurora_cluster_mysql_parameter_group" {
  name        = "test-aurora-cluster-parameter-group"
  family      = "aurora-mysql5.7"
}

According to AWS Docs, the allowed family group is "aurora-mysql5.7" and engine_version is "5.7.12" .https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.Updates.serverless_2_07_01.html
Tried with  EngineVersion: "5.7.mysql_aurora.2.08.2", and EngineVersion 5.7.12 both.

A: I think this is because of a spelling mistake:
engine                  = "aurora-msql"

The available engines are listed here. Thus there should be:
engine                  = "aurora-mysql"

Please note that there could be other errors, which are not apparent yet. But your issue of InvalidParameterValue: Invalid DB engine is most likely due the the spelling mistake.


text:
Q: How to call something after DOM changed in meteor? Template.onRendered :

Callbacks added with this method are called once when an instance of Template.myTemplate is rendered into DOM nodes and put into the document for the first time.

Is there any way to call something after the DOM changed?
For example, a navbar(header) with login/logout button is rendered after user open the homepage, and the navbar is changed after the user logged in(logout button).
I need to do something after the navbar has been changed.

A: You can refactor your code by creating new templates to introduce finer grained lifecycle events on child templates.
HTML
<template name="navbar">

    {{#if currentUser}}
      {{> logoutButton}}
    {{else}}
      {{> loginButton}}
    {{/if}}

</template>

<template name="loginButton">
  <button class="login">Login</button>
</template>

<template name="logoutButton">
  <button class="logout">Logout</button>
</template>

JS
Template.loginButton.onRendered(function(){
  // will print Login after user logged out
  console.log(this.$("button").text());
});

Template.logoutButton.onRendered(function(){
  // will print Logout after user logged in
  console.log(this.$("button").text());
});

Alternatively, you can use an autorun inside Template.navbar.onRendered to listen to user login/logout and perform actions after DOM has been modified using Tracker.afterFlush.
HTML
<template name="navbar">

    {{#if currentUser}}
      <button class="logout">Logout</button>
    {{else}}
      <button class="login">Login</button>
    {{/if}}

</template>

JS
Template.navbar.onRendered(function(){
  // declare a new reactive computation
  // (rerun when the reactive data source is modified)
  this.autorun(function(){
    // listen to the same reactive data source as in the template helper
    // => currentUser
    var user=Meteor.user();
    // this code will run after every other reactive computations depending
    // on the same data source being modified
    Tracker.afterFlush(function(){
      // will print Logout after user logged in
      // will print Login after user logged out
      console.log(this.$("button").text());
    }.bind(this));
  }.bind(this));
});


text:
Q: p:outputLabel not marked as required when target input is inside composite In a very simple way, here is a composite:
<ui:component
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:cc="http://xmlns.jcp.org/jsf/composite"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
    xmlns:c="http://xmlns.jcp.org/jsp/jstl/core"
    xmlns:fn="http://xmlns.jcp.org/jsp/jstl/functions"
    xmlns:p="http://primefaces.org/ui"
>
    <cc:interface>
        <cc:attribute name="value" />
        <cc:attribute name="required" />
        <cc:editableValueHolder name="calendar" />
    </cc:interface>

    <cc:implementation>
        <p:calendar id="calendar" value="#{cc.attrs.value}" required="#{cc.attrs.required}" showOn="button"/>
    </cc:implementation>
</ui:component>

Here how I use it:
<p:outputLabel for="rat:calendar" value="Hello" />
<my:calendar id="rat" required="true"/>

A required=true icon should be displayed but it does not. In OutputLabelRenderer looks fine, except in line 118, input.isRequired() returns false while I explicitly set true. I don't think it is related to Primefaces but looks like a JSF problem (I'm using Mojarra 2.2.13 and reproduced on Myfaces 2.2.4 as well)

A: Explanation provided by Myfaces: https://issues.apache.org/jira/browse/MYFACES-4059


text:
Q: How to make RelativeSizeSpan align to top I have the following String RM123.456. I would like to

*

*Make RM relatively smaller

*Make RM aligned to top exactly

I almost able to achieve it by using
spannableString.setSpan(new RelativeSizeSpan(0.50f), 0, index, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannableString, TextView.BufferType.SPANNABLE);

The outcome looks like

However, it is aligned to the bottom. It doesn't align to the top.
I try to use SuperscriptSpan. It looks like

It doesn't do what I want as

*

*SuperscriptSpan doesn't make the text smaller. I'm not able to control its sizing.

*SuperscriptSpan will make the text "over the top align"

May I know, how can I make RelativeSizeSpan align to top exactly?
This is what I wish to achieve.

Please note, we don't wish to go for 2 TextViews solution.

A: the best suitable solution is go with html.
i will prefer for this solutions,it supports in all android version as well devices.
here is example take it same as you want text

TM 123.456.

i am getting result in android

TM 123.456.

you can easily display text in Textview in android with
Html.fromText("YOUR_STRING_INHTML");
Hope it helps.

A: you have to used html tag like below for subscript and superscript.It works like charm.
 ((TextView) findViewById(R.id.text)).setText(Html.fromHtml("2X"));

or
You can also use below code:
String titleFirst = "Insert GoTechTM device into the vehicle\'s OBDII port.";
SpannableStringBuilder cs = new SpannableStringBuilder(titleFirst);
cs.setSpan(new SuperscriptSpan(), titleFirst.indexOf("TM"), titleFirst.indexOf("TM")+2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
cs.setSpan(new RelativeSizeSpan((float)0.50), titleFirst.indexOf("TM"), titleFirst.indexOf("TM")+2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
txtPairInstructionFirst.setText(cs);

A: However I did in this way:

activity_main.xml:
<TextView
    android:id="@+id/txtView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="50dp"
    android:textSize="26sp" />

MainActivity.java:
TextView txtView = (TextView) findViewById(R.id.txtView);

SpannableString spannableString = new SpannableString("RM123.456");
spannableString.setSpan( new TopAlignSuperscriptSpan( (float)0.35 ), 0, 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE );
txtView.setText(spannableString);

TopAlignSuperscriptSpan.java:
private class TopAlignSuperscriptSpan extends SuperscriptSpan {
        //divide superscript by this number
        protected int fontScale = 2;

        //shift value, 0 to 1.0
        protected float shiftPercentage = 0;

        //doesn't shift
        TopAlignSuperscriptSpan() {}

        //sets the shift percentage
        TopAlignSuperscriptSpan( float shiftPercentage ) {
            if( shiftPercentage > 0.0 && shiftPercentage < 1.0 )
                this.shiftPercentage = shiftPercentage;
        }

        @Override
        public void updateDrawState( TextPaint tp ) {
            //original ascent
            float ascent = tp.ascent();

            //scale down the font
            tp.setTextSize( tp.getTextSize() / fontScale );

            //get the new font ascent
            float newAscent = tp.getFontMetrics().ascent;

            //move baseline to top of old font, then move down size of new font
            //adjust for errors with shift percentage
            tp.baselineShift += ( ascent - ascent * shiftPercentage )
                    - (newAscent - newAscent * shiftPercentage );
        }

        @Override
        public void updateMeasureState( TextPaint tp ) {
            updateDrawState( tp );
        }
    }

Hope this will help you.

A: I had a look at the RelativeSizeSpan and found a rather simple implementation. So you could just implement your own RelativeSizeSpan for your purpose. The only difference here is that it doesn't implement ParcelableSpan, since this is only intended for framework code. AntiRelativeSizeSpan is just a fast hack without much testing of course, but it seems to work fine. It completely relies on Paint.getTextBounds() to find the best value for the baselineShift, but maybe there'd be a better approach.

public class AntiRelativeSizeSpan extends MetricAffectingSpan {
    private final float mProportion;

    public AntiRelativeSizeSpan(float proportion) {
        mProportion = proportion;
    }

    public float getSizeChange() {
        return mProportion;
    }

    @Override
    public void updateDrawState(TextPaint ds) {
        updateAnyState(ds);
    }

    @Override
    public void updateMeasureState(TextPaint ds) {
        updateAnyState(ds);
    }

    private void updateAnyState(TextPaint ds) {
        Rect bounds = new Rect();
        ds.getTextBounds("1A", 0, 2, bounds);
        int shift = bounds.top - bounds.bottom;
        ds.setTextSize(ds.getTextSize() * mProportion);
        ds.getTextBounds("1A", 0, 2, bounds);
        shift += bounds.bottom - bounds.top;
        ds.baselineShift += shift;
    }
}

A: You could achieve top gravity by creating a custom MetricAffectingSpan class
here is the code of custom class:
public class CustomCharacterSpan extends MetricAffectingSpan {
    double ratio = 0.5;

    public CustomCharacterSpan() {
    }

    public CustomCharacterSpan(double ratio) {
        this.ratio = ratio;
    }

    @Override
    public void updateDrawState(TextPaint paint) {
        paint.baselineShift += (int) (paint.ascent() * ratio);
    }

    @Override
    public void updateMeasureState(TextPaint paint) {
        paint.baselineShift += (int) (paint.ascent() * ratio);
    }
}

Applying the span:
spannableString.setSpan(new RelativeSizeSpan(0.50f), 0, index, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableString.setSpan(new CustomCharacterSpan(), 0, index,
                SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannableString, TextView.BufferType.SPANNABLE);

Output:

For more info on MetricAffectingSpan : http://developer.android.com/reference/android/text/style/MetricAffectingSpan.html
Custom MetricAffectingSpan  logic referred from : Two different styles in a single textview with different gravity and hieght

A: I have implemented this in one of my application.
 <TextView
    android:id="@+id/txt_formatted_value"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:textColor="#000000"
    android:textSize="28dp" />

In Activity/Frgament.class
 myTextView = (TextView) view.findViewById(R.id.txt_formatted_value);

Hardcoded for testing purpose,
String numberValue = "123.456";
myTextView.setText(UtilityClass.getFormattedSpannedString("RM"+numberValue,
     numberValue.length(),0));

Add this class in your package,
public class SuperscriptSpanAdjuster extends MetricAffectingSpan {
double ratio = 0.5;

public SuperscriptSpanAdjuster() {
}

public SuperscriptSpanAdjuster(double ratio) {
    this.ratio = ratio;
}

@Override
public void updateDrawState(TextPaint paint) {
    paint.baselineShift += (int) (paint.ascent() * ratio);
}

@Override
public void updateMeasureState(TextPaint paint) {
    paint.baselineShift += (int) (paint.ascent() * ratio);
}

}
Created the format method in UntilityClass.class
 public static SpannableString getFormattedSpannedString(String value, int mostSignificantLength, int leastSignificantLength){

    SpannableString  spanString = new SpannableString(value);
    /* To show the text in top aligned(Normal)*/
    spanString.setSpan(new SuperscriptSpanAdjuster(0.7), 0,spanString.length()-mostSignificantLength-leastSignificantLength, SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
    /* Show the number of characters is normal size (Normal)*/
    spanString.setSpan(new RelativeSizeSpan(1.3f), 0,spanString.length()-mostSignificantLength-leastSignificantLength, 0);
    /*To set the text style as bold(MostSignificant)*/
    //spanString.setSpan(new StyleSpan(Typeface.BOLD), spanString.length()-mostSignificantLength-leastSignificantLength, spanString.length()-leastSignificantLength, 0);
    /*To set the text color as WHITE(MostSignificant)*/
    //spanString.setSpan(new ForegroundColorSpan(Color.WHITE), spanString.length()-mostSignificantLength-leastSignificantLength,  spanString.length()-leastSignificantLength, 0);
    /*Show the number of characters as most significant value(MostSignificant)*/
    spanString.setSpan(new RelativeSizeSpan(2.3f), spanString.length()-mostSignificantLength-leastSignificantLength, spanString.length()-leastSignificantLength, 0);

    /* To show the text in top aligned(LestSignificant)*/
    spanString.setSpan(new SuperscriptSpanAdjuster(1.2), spanString.length()-leastSignificantLength, spanString.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
    /*To set the text style as bold(LestSignificant)*/
    //spanString.setSpan(new StyleSpan(Typeface.BOLD), spanString.length()-leastSignificantLength, spanString.length(), 0);
    /*Show the number of characters as most significant value(LestSignificant)*/
    spanString.setSpan(new RelativeSizeSpan(0.8f), spanString.length()-leastSignificantLength, spanString.length(), 0);

    return spanString;
}

Using this method you can do more circus like changing text style, color separately for SuperScript.
Also you can add superscript both right and left side.(Here I commented all the code, if you want can give a try...)

A: Class for top align which should be used instead of RelativeSizeSpan (not in additional to):
import android.text.TextPaint;
import android.text.style.MetricAffectingSpan;

public class TopRelativeSizeSpan extends MetricAffectingSpan {

    private final float mProportion;

    public TopRelativeSizeSpan(float proportion) {
        mProportion = proportion;
    }

    @Override
    public void updateDrawState(TextPaint ds) {
        ds.baselineShift += (mProportion - 1) * (ds.getTextSize() - ds.descent());
        ds.setTextSize(ds.getTextSize() * mProportion);
    }

    @Override
    public void updateMeasureState(TextPaint ds) {
        updateDrawState(ds);
    }
}

And usage:
spannableString.setSpan(new TopRelativeSizeSpan(0.50f), 0, index, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannableString, TextView.BufferType.SPANNABLE);

A: Many of the provided answers here require you to set a text size scale percentage and guess an offset to account for their mistake in calculating the correct offset or they require you to set multiple spans.
So, to update this question, here's a solution which sets the correct baseline of the superscript and only asks that you provide a text scale percentage for only 1 required span:
class TopAlignSuperscriptSpan(private val textSizeScalePercentage: Float = 0.5f) : MetricAffectingSpan() {

    override fun updateDrawState(tp: TextPaint) {
        tp.baselineShift += (tp.ascent() * textSizeScalePercentage).toInt()
        tp.textSize = tp.textSize * textSizeScalePercentage
    }

    override fun updateMeasureState(tp: TextPaint) {
        updateDrawState(tp)
    }
}

You may use this without having to set other spans, like so:
val spannableString = SpannableString("RM123.456")
spannableString.setSpan(TopAlignSuperscriptSpan(0.6f), 0, 2, SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE)
myTextView.text = spannableString

"RM" will be 60% of the text size of "123.456" and it's top will be exactly aligned to the top of "123.456"
UPDATE: You shouldn't use this because it is inexact, like every other answer here.
Instead, I would suggest calculating the height of each section of the text view and manually setting the y value of each section, like this library does: https://github.com/fabiomsr/MoneyTextView/tree/master/moneytextview/src/main/res/values

A: I know this is an old thread, but I just came across this today, and I'm surprised no one answered with this... I'd recommend not hardcoding the 2, 4 but you can figure out how to
val span = SpannableStringBuilder.valueOf("$temp")
span.append("°F", SuperscriptSpan(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
span.setSpan(RelativeSizeSpan(0.5f), 2, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
tempTextView.setText(span, TextView.BufferType.SPANNABLE)


text:
Q: How do I transfer data parallely from Spring Tool Suite to MySql? Please find my code below and suggest? package com.project.jdbc.model;

import java.util.Scanner;

import org.apache.commons.lang3.RandomStringUtils;

import java.util.Random;
import java.security.SecureRandom;

        class AtRandomNumber
        {
            public static void main(String[] args)
            {
                int maxRange;

                //create objects
                Scanner SC = new Scanner(System.in);
                Random rand = new Random();

            //    System.out.print("Please enter maximum range: ");
             //   maxRange=SC.nextInt();

                for(int loop=1; loop<=100; loop++)
                {
         //           System.out.println("Random string: " + generateRandomString(10));
                    //System.out.println(rand.nextInt(maxRange));
                     System.out.println("\nAlphanumeric String: [a-zA-Z0-9]");
                     System.out.println(RandomStringUtils.randomAlphanumeric(10));
                }
            }
        }

I am able to do only transfer of data from STS to MYSQL by typing the code in Spring and then it gets printed in MYSQL.
But I want an code wherein all data automatically gets printed in MYSQL.
I am unable to transfer the data parallely from Spring to My SQL.
Is it possible?


text:
Q: JavaFX Enter key issue on ComboBox I am encountering an issue with the "ENTER" key event propagation in ComboBox.
I have a form(VBox) which submits or perform validation when it receives "ENTER" key released event. The user will enter the details by tabbing between fields and hitting UP/DOWN keys for selection in combo box (Just to minimize the mouse interaction). So far everything works fine.
When the user tabs to ComboBox and press "DOWN" key, the ComboBox popup is shown. And user can select the options using UP/DOWN keys. After choosing an option, user will press the "ENTER" key to close the popup. Here I want the "ENTER" event to only close the popup but not to submit the form. If the popup not opened, then "ENTER" key on ComboBox should submit the form.
I tried to fix this by consuming the events on ComboBox. But that didn't work. So two questions::
Can anyone let me know "how to prevent the 'ENTER' key event propagation to VBox, only when the ComboBox is showing"?
And also can anyone let me know how come the event is propagated to "VBox" handler, in spite of consuming event on ComboBox filter/handler?
Below is the example show casing the issue:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ComboBoxEnterKeyIssue extends Application {

    private DateFormat df = new SimpleDateFormat("hh:mm:ss");

    @Override
    public void start(Stage primaryStage) throws Exception {
        TextField textField1 = new TextField();
        textField1.setMaxWidth(150);

        ComboBox<String> comboBox = new ComboBox<>();
        comboBox.setPrefWidth(150);
        comboBox.getItems().addAll("Item 1", "Item 2", "Item 3", "Item 4", "Item 5");
        comboBox.addEventFilter(KeyEvent.KEY_RELEASED, ke -> {
            if (ke.getCode() == KeyCode.DOWN && !comboBox.isShowing()) {
                comboBox.show();
                ke.consume();
            } else if (ke.getCode() == KeyCode.ENTER) {
                ke.consume(); // Has no effect !!
            }
        });
        comboBox.addEventHandler(KeyEvent.KEY_RELEASED, ke -> {
            if (ke.getCode() == KeyCode.ENTER) {
                ke.consume(); // Has no effect !!
            }
        });

        TextField textField2 = new TextField();
        textField2.setMaxWidth(150);

        ListView<String> output = new ListView<>();
        VBox.setVgrow(output, Priority.ALWAYS);

        VBox pane = new VBox(textField1, comboBox, textField2, output);
        pane.setPadding(new Insets(10));
        pane.setSpacing(10);
        pane.setOnKeyReleased(ke -> {
            if (ke.getCode() == KeyCode.ENTER) {
                output.getItems().add(df.format(new Date()) + " :: Enter key released on pane...");
                // Form submission/validation is performed here !!
            }
        });

        Scene scene = new Scene(pane, 500, 400);
        primaryStage.setScene(scene);
        primaryStage.setTitle("ComboBox enter key issue");
        primaryStage.show();
    }
}

A: So I came with this nasty solution to differentiate the enter event.
The fix is as below:

*

*Created a custom combo skin to indentify the listView and set a flag when an "enter" key is pressed on listview.

*In the Custom combo event dispatcher,check the flag if the enter is pressed while the popup is opened and then consume the event in dispatcher.

The question is still open for any better ideas.
import com.sun.javafx.scene.control.skin.ComboBoxListViewSkin;
import javafx.application.Application;
import javafx.event.EventDispatcher;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListView;
import javafx.scene.control.Skin;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ComboBoxEnterKeyIssue extends Application {

    private DateFormat df = new SimpleDateFormat("hh:mm:ss");

    @Override
    public void start(Stage primaryStage) throws Exception {
        TextField textField1 = new TextField();
        textField1.setMaxWidth(150);

        MyComboBox<String> comboBox = new MyComboBox<>();
        comboBox.setPrefWidth(150);
        comboBox.getItems().addAll("Item 1", "Item 2", "Item 3", "Item 4", "Item 5");
        comboBox.addEventFilter(KeyEvent.KEY_RELEASED, ke -> {
            if (ke.getCode() == KeyCode.DOWN && !comboBox.isShowing()) {
                comboBox.show();
                ke.consume();
            } else if (ke.getCode() == KeyCode.ENTER) {
                ke.consume(); // Has no effect !!
            }
        });
        comboBox.addEventHandler(KeyEvent.KEY_RELEASED, ke -> {
            if (ke.getCode() == KeyCode.ENTER) {
                ke.consume(); // Has no effect !!
            }
        });

        TextField textField2 = new TextField();
        textField2.setMaxWidth(150);

        ListView<String> output = new ListView<>();
        VBox.setVgrow(output, Priority.ALWAYS);

        VBox pane = new VBox(textField1, comboBox, textField2, output);
        pane.setPadding(new Insets(10));
        pane.setSpacing(10);
        pane.setOnKeyReleased(ke -> {
            if (ke.getCode() == KeyCode.ENTER) {
                output.getItems().add(df.format(new Date()) + " :: Enter key released on pane...");
                // Form submission/validation is performed here !!
            }
        });

        Scene scene = new Scene(pane, 500, 400);
        primaryStage.setScene(scene);
        primaryStage.setTitle("ComboBox enter key issue");
        primaryStage.show();
    }

    class MyComboBox<T> extends ComboBox<T> {
        boolean hiddenByEnter = false;

        public MyComboBox() {
            init();
        }

        public void setHiddenByEnter(boolean hiddenByEnter) {
            this.hiddenByEnter = hiddenByEnter;
        }

        private void init() {
            final EventDispatcher initial = getEventDispatcher();
            setEventDispatcher((event, tail) -> {
                // Consuming the event only if the popup is hidden by 'enter' key event.
                if (event instanceof KeyEvent && ((KeyEvent) event).getCode() == KeyCode.ENTER && hiddenByEnter) {
                    hiddenByEnter = false;
                    return null;
                }
                return initial.dispatchEvent(event, tail);
            });
        }

        @Override
        protected Skin<?> createDefaultSkin() {
            return new MyComboBoxSkin<>(this);
        }
    }

    class MyComboBoxSkin<T> extends ComboBoxListViewSkin<T> {

        private ListView<T> listView;

        public MyComboBoxSkin(MyComboBox<T> comboBox) {
            super(comboBox);
            /* Identifying the "ENTER" event on listView in popup, to differentiate the events. */
            getPopup().showingProperty().addListener((obs, old, showing) -> {
                if (showing) {
                    comboBox.setHiddenByEnter(false);
                    if (listView == null) {
                        listView = (ListView) getPopup().getScene().getRoot().lookup(".list-view");
                        listView.addEventFilter(KeyEvent.KEY_PRESSED, ke -> {
                            if (ke.getCode() == KeyCode.ENTER) {
                                comboBox.setHiddenByEnter(true);
                            }
                        });
                    }
                }
            });
        }
    }
}


text:
Q: how can i have two different object rotating at the same time in a multiplayer game with photon I am currently working on a 2D game in unity using photon for the multiplayer, the player has a gun object that points to the mouse position, however when two people are in a game the object will point to their mouse on their end, even if the other player is holding the gun.
thanks
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class gunRotation : MonoBehaviour
{
    bool nf;
    bool f;
    bool l = true;

    void Start()
    {
    }

    public void FixedUpdate()
    {
        //rotates the gun
        Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
        float rotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
        difference.Normalize();
        transform.rotation = Quaternion.Euler(0f, 0f, rotationZ);

        if (rotationZ < -90 || rotationZ > 90)
        {
            if (gameObject.transform.eulerAngles.y == 0)
            {
                transform.localRotation = Quaternion.Euler(180, 0, -rotationZ);
            }
            else if (gameObject.transform.eulerAngles.y == 180)
            {
                transform.localRotation = Quaternion.Euler(180, 180, -rotationZ);
            }
        }
        // helps gun switch pos
        if (gameObject.transform.eulerAngles.y == 0 && l == true)
        {
            nf = true;
            l = false;
        }

        // switch gun pos
        if (gameObject.transform.eulerAngles.y == 0 && nf == true)
        {
            transform.position = new Vector3(gameObject.transform.position.x + 1.123f, gameObject.transform.position.y, gameObject.transform.position.z);
            nf = false;
            f = true;
        }
        else if (gameObject.transform.eulerAngles.y == 180 && f == true)
        {
            transform.position = new Vector3(gameObject.transform.position.x - 1.123f, gameObject.transform.position.y, gameObject.transform.position.z);
            f = false;
            nf = true;
        }
    }

}


text:
Q: assert is not working when working with cucumber and java I am working with java and cucumber.
In my step def I found that assertion is not working. Even if I write
assert 1==2

exception is not thrown.
I know that I do not provide too much info, but the problem I do not know what start to check. Any idea what it can be?

A: Assert works in Cucumber + Java on IntelliJ. I have been using it for months.
Example: Assert.assertEquals(status, "Success");
This is because I'm using TestNG in my code.
In your class, make sure you have imported import org.testng.Assert;
For details, you can have a look at this git code: SeleniumCucumberGradle


text:
Q: Subclass constructor throws TypeError: __init__() takes 2 positional arguments but 5 were given This is my very first day with classes and Inheritance in Python so please be gentle on me. I have two classes namely Person and Employee and where Employee is a sub class of Person.
class Person:
    def __init__(self, name, place, age, sex):
        self.name = name
        self.place = place
        self.age = age
        self.sex = sex

class Employee(Person):
    def __init__(self, emp_id):
        self.emp_id = emp_id

Now, I am trying to create an instance of the class Employee as follows:
In [9]: A = Employee('Jack', 'Rome', 23, 'M')
TypeError: __init__() takes 2 positional arguments but 5 were given

What am i doing wrong ?

A: Python does very little "magic" in creating classes - you usually get precisely what you specified. In your case, you specified that initialising Employee takes only one additional argument:
class Employee(Person):
    # Employee initialises itself with one argument
    def __init__(self, emp_id):
        self.emp_id = emp_id

That means it is valid to say Employee(1287123), but not Employee('Jack', 'Rome', 23, 'M'). For class Employee, Employee.__init__ is hiding Person.__init__:
>>> Employee.__init__
<function __main__.Employee.__init__(self, emp_id)>
>>> Person.__init__
<function __main__.Person.__init__(self, name, place, age, sex)>
>>> Employee.__init__ is Person.__init__
False

If you want Employee to be initialised like a Person, you have to say so explicitly:
class Employee(Person):
    # Employee initialises itself like Person plus one argument
    def __init__(self, name, place, age, sex, emp_id):
        # initialise self like a Person
        Person.__init__(self, name, place, age, sex)
        # initialise self like an Employee *in addition*
        self.emp_id = emp_id

It is good practice not to directly invoke methods of the base class. Instead, the super builtin allows to dynamically invoke a method from the inheritance hierarchy:
class Employee(Person):
    # Employee initialises itself like Person plus one argument
    def __init__(self, name, place, age, sex, emp_id):
        # initialise self like a Person
        super().__init__(name, place, age, sex)
        # initialise self like an Employee *in addition*
        self.emp_id = emp_id

The purpose of super is to weaken the coupling of inheritance. For example, you could swap the base class Person for something else, and the __init__ method would still work. See also How does Python pass __init__ parameters with multiple inheritance.
Instead of passing through arguments manually, one can use * and ** to capture any unused positional and named parameters:
class Employee(Person):
    # Employee initialises itself with one argument
    # other positional and keyword arguments are passed to the superclass
    def __init__(self, *args, emp_id, **kwargs):
        # initialise self like the superclass
        super().__init__(*args, **kwargs)
        # initialise self like an Employee *in addition*
        self.emp_id = emp_id

A: You need to accept parent class arguments as well, if you're going to override __init__ or any other method for that matter
class Employee(Person):
    def __init__(self, name, place, age, sex, emp_id):
        super(Employee, self).__init__(name, place, age, sex)
        self.emp_id = emp_id

>>> emp_id = '254'
>>> A = Employee('Jack', 'Rome', 23, 'M', emp_id)

A: You have to pass the extra init arguments along to the super class init method.
class Employee(Person):
    def __init__(self, emp_id, *args, **kwargs):
        self.emp_id = emp_id
        super().__init__(*args, **kwargs)

By using *args, **kwargs, the child class will pass all uncaptured positional and named arguments to the superclass init method. This means you don't have to specify the argument names that the parent requires, or their required order. It's enough to specify that in the parent class init method.

A: You defined Employee as follow:
class Employee(Person):
    def __init__(self, emp_id):
        self.emp_id = emp_id

The construictor (function __init__() has only 2 arguments (self and emp_id). You can create an instance passing the name, place, age and sex.

A: you called the class Employee, not a Person, the person will take the 4 params and Employee will take only one param.
The created object of the class Employee, not any Person class.
    A = Employee(20)  # 20 is the emp_id.

Try with this.

A: You can pass args and kwargs to accomodate multiple arguments:
class Person:
    def __init__(self, name, place, age, sex):
        self.name = name
        self.place = place
        self.age = age
        self.sex = sex

class Employee(Person):
    def __init__(self, emp_id, *args, **kwargs):
        Person.__init__(self, *args, **kwargs)
        self.emp_id = emp_id

A = Employee(1111, 'Jack', 'Rome', 23, 'M')


text:
Q: How does hypervisor work in virtualization? In virtualization, the hypervisor doesn't need to use system call?
is it always running in Kernel mode or it can run also in user mode?

A: On x86, a hypervisor runs in VMX root mode. Within this mode, transitions between kernel and user mode work just as they do in VMX non-root mode (i.e., in a guest) or when VMX is off.
However, in my experience, most hypervisors always run in kernel mode.


text:
Q: Finding a basis for a fairly unique set $B = \{(1+y,2-2y,3+3y)\ $|$ $t $\in$ $\mathbb{R}$$\}$
Where vector addition and scalar multiplication are defined by:
$\begin{pmatrix}
1+y_1\\
2-2y_1\\
3+3y_1
\end{pmatrix}$
$\oplus
\ \begin{pmatrix}
1+y_2\\
2-2y_2\\
3+3y_2
\end{pmatrix}$ =  $\begin{pmatrix}
1+y_1 + y_2\\
2-2y_1 - 2y_2\\
3+3y_1 + 3y_2
\end{pmatrix}$
$k \odot \begin{pmatrix}
1+y_1\\
2-2y_1\\
3+3y_1
\end{pmatrix}  = \begin{pmatrix}
1+ky_1\\
2-2ky_1\\
3+3ky_1
\end{pmatrix} $
My answer:
At first I wanted to say that the basis can be defined by $\{(1,0,3),(0,2,0)\}$ but when I go to show linear independence i.e
$k1\odot$$V1\oplus k2\odot V2 = \{(1,2,3)^T\}$
it gets messy and it comes out as a linearly dependent set. Where am I going wrong here? I choose the two vectors as the third element in the vector is a linear combination of the first. Is V one-dimensional as opposed to two-dimensional as I assumed?

A: The fact that the vectors in $V$ only depend on one parameter should indicate to you that $V$ is one dimensional.  In fact, I can define $W=\{u,-2u,3u)|u \in \Bbb R\}$ with usual addition and multiplication, which is clearly one dimensional. Then there is an isomorphism $(t+1,2-2t,3+3t)\in V \leftrightarrow (t,-2t,3t)\in W$


text:
Q: Id is different after JSON deserialization I have the following code:
String m = '{"Id": "a186D000000EYJ2"}';

Reference__c reff = (Reference__c)JSON.deserialize(m, Reference__c.class);

System.debug(reff);
System.debug(reff.Id);

The output is:
16:52:14:005 USER_DEBUG [5]|DEBUG|Reference__c:{Id=a186D000000EYJ2}

16:52:14:005 USER_DEBUG [6]|DEBUG|a186D000000EYJ2QAO

Note that the printed ID is different. What is the cause of this?

A: Salesforce Ids are both 15 and 18 character long. So for salesforce those two ids are the same. (notice that the only difference is the last 3 capital-case characters).
To simplify things,

*

*the 15 character Id is uniquely case-sensitive

*the 18 character Id is uniquely case-insensitive (you can calculate this one based on the 15 chars one)

You could say that a Salesforce id has 3 parts

*

*[3] sObject prefix

*[12] sObject-based case-sensitive Id

*[3] ("optional") calculation that makes the full Id case insensitive

When you use a variable of type Id, salesforce is using the 18 character one (even if you assign the 15 one, salesforce calculates the other 3 characters automatically)
Why do you need a 18 character Id if the 15 is already unique in a case-sensitive way? Well... there are many tools where you can't use the "case", for example VLOOKUP in excel (even salesforce itself has some automatic case insensitivity builted in).
Notice that there are some automations in place in Salesforce regarding this kind of field-types, so for example, if you have in the where-clause of a query a field of type Id (Id, Look-up, etc) and compare it against a string of 15 characters or 18 characters, the query would still return the good values)
Some useful links:

*

*Locate the Unique ID of a Record in Salesforce


text:
Q: Rails Bundle Install Not Finding Gem I'm having a problem with the rails
bundle install

command not being able to find a local gemfile.

The gem is located here::
~/.gem/ruby/2.1.5/gems/mygemname-1.5.0.SNAPSHOT

I included the gem in my Gemfile.  But when I try to bundle my application, it get this error::
Could not find gem 'mygemname-1.5.0.SNAPSHOT' (>= 0) ruby' in the gems available on this machine.

I can see the gem sitting on my hardrive, but the bundle install command says it doesn't exist.  Does anybody have any ideas on what may be going on here?
Thanks for your time.

A: As I can´t comment yet...
I would check:
- Is it really the .gem folder holding the gem or is it symlinked (I am not confident that symlinks work on bundle install)
- Is rbenv or rvm in the game and is the installed gem installed with one of those or globally?


text:
Q: override the header and footer glow Is there any ways to override the header and footer glow in the listview and custom colors/gradient while using actionbarsherlock? or can it be overridden without using actionbarsherlock?

A: From what i know there is no way to do that. For more information see here:
https://groups.google.com/forum/?fromgroups=#!topic/android-developers/i5a3uNN8jpg