text:
Q: Getting a SIGABRT From Deleting a Row in a Table View I am trying to have a table view list a number of objects that are stored in an array and it's working fine other than when I try to delete a row, it throws a SIGABRT. I checked at it is correctly updating the array. It seems that the SIGABRT has something to do with the number of sections in the table. Here is the code for the table view controller:
CalendarViewController.h
#import <UIKit/UIKit.h>
#import "Job.h"
#import "Shift.h"
#import "AppDelegate.h"

@interface CalendarViewController : UITableViewController

@property (nonatomic, strong) NSMutableArray *currentShiftsList;
@property (nonatomic, strong) AppDelegate *dataCenter;

@end

CalendarViewController.m
#import "CalendarViewController.h"

@interface CalendarViewController ()

@property (nonatomic, strong) NSMutableDictionary *sections;
@property (nonatomic, strong) NSArray *sortedShifts;
@property (strong, nonatomic) NSDateFormatter *sectionDateFormatter;
@property (strong, nonatomic) NSDateFormatter *cellDateFormatter;

@end

@implementation CalendarViewController

@synthesize sections, sortedShifts, currentShiftsList, dataCenter, sectionDateFormatter, cellDateFormatter;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (NSDate *)dateAtBeginningOfDayForDate:(NSDate *)inputDate {

    // Use the user's current calendar and time zone
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
    [calendar setTimeZone:timeZone];

    // Selectively convert the date components (year, month, day) of the input date
    NSDateComponents *dateComps = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:inputDate];

    // Set the time components manually
    [dateComps setHour:0];
    [dateComps setMinute:0];
    [dateComps setSecond:0];

    // Convert back
    NSDate *beginningOfDay = [calendar dateFromComponents:dateComps];
    return beginningOfDay;
}

- (NSDate *)dateByAddingYears:(NSInteger)numberOfYears toDate:(NSDate *)inputDate
{
    // Use the user's current calendar
    NSCalendar *calendar = [NSCalendar currentCalendar];

    NSDateComponents *dateComps = [[NSDateComponents alloc] init];
    [dateComps setYear:numberOfYears];

    NSDate *newDate = [calendar dateByAddingComponents:dateComps toDate:inputDate options:0];
    return newDate;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    dataCenter = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    currentShiftsList = [[NSMutableArray alloc] initWithArray:dataCenter.shiftsList];

    self.sectionDateFormatter = [[NSDateFormatter alloc] init];
    [self.sectionDateFormatter setDateStyle:NSDateFormatterLongStyle];
    [self.sectionDateFormatter setTimeStyle:NSDateFormatterNoStyle];

    self.cellDateFormatter = [[NSDateFormatter alloc] init];
    [self.cellDateFormatter setDateStyle:NSDateFormatterNoStyle];
    [self.cellDateFormatter setTimeStyle:NSDateFormatterShortStyle];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    self.navigationItem.rightBarButtonItem = self.editButtonItem;

    self.sections = [NSMutableDictionary dictionary];
    for (Shift *shift in dataCenter.shiftsList) {

        // Reduce event start date to date components (year, month, day)
        NSDate *dateRepresentingThisDay = [self dateAtBeginningOfDayForDate:shift.startDate];

        // If we don't yet have an array to hold the events for this day, create one
        NSMutableArray *shiftsOnThisDay = [self.sections objectForKey:dateRepresentingThisDay];
        if (shiftsOnThisDay == nil) {
            shiftsOnThisDay = [NSMutableArray array];

            // Use the reduced date as dictionary key to later retrieve the event list this day
            [self.sections setObject:shiftsOnThisDay forKey:dateRepresentingThisDay];
        }

        // Add the event to the list for this day
        [shiftsOnThisDay addObject:shift];
    }

    // Create a sorted list of days
    NSArray *unsortedShifts = [self.sections allKeys];
    self.sortedShifts = [unsortedShifts sortedArrayUsingSelector:@selector(compare:)];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return [self.sections count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    NSDate *dateRepresentingThisDay = [self.sortedShifts objectAtIndex:section];
    NSArray *eventsOnThisDay = [self.sections objectForKey:dateRepresentingThisDay];
    return [eventsOnThisDay count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *reuseIdentifier = @"shifts";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];

    NSDate *dateRepresentingThisDay = [self.sortedShifts objectAtIndex:indexPath.section];
    NSArray *eventsOnThisDay = [self.sections objectForKey:dateRepresentingThisDay];
    Shift *shift = [eventsOnThisDay objectAtIndex:indexPath.row];

    cell.textLabel.text = shift.jobtitle;

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"h:mm a"];

    NSString *start = [formatter stringFromDate:shift.startDate];
    NSString *end = [formatter stringFromDate:shift.endDate];

    NSString *detail = [[NSString alloc] initWithFormat:@"%@ to %@", start, end];
    cell.detailTextLabel.text = detail;
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSDate *dateRepresentingThisDay = [self.sortedShifts objectAtIndex:section];
    return [self.sectionDateFormatter stringFromDate:dateRepresentingThisDay];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source

        [currentShiftsList removeObjectAtIndex:indexPath.row];
        dataCenter.shiftsList = currentShiftsList;

        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     */
}

@end

A: This doesn't make sense to me.
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

Why isn't it just:
[tableView deleteRowsAtIndexPaths:indexPath.row withRowAnimation:UITableViewRowAnimationFade];

Also remember a reload TableView after delete (if you want it).

A: When you delete a row, you are removing an item from the currentShiftsList array.  However, you are not using that array in your UITableViewDataSource related methods.  The TableView is expecting there to be 1 less item from its DataSource, but you will be returning the original number of items instead.
Overall, things are very confusing because you have several collections that are trying to manage the same set of data (or copies of that data).  Try looking into CoreData and the NSFetchedResultsController which is specifically made to managed a set of data and propagate any changes to a UITableView.


text:
Q: gulp.series() not function when running multiple tasks I am trying to run multiple gulp tasks one after another in synchronised fashion
but i got the following error

TypeError: gulp.series is not a function

Code
gulp.task('default',function () {
    gulp.watch('resources/assets/js/components/*.js', function() {
        gulp.series('scripts','compress');
    });
})

A: If you want to use gulp.series and gulp.parallel you need gulp 4.0.
To get 4.+ which is technically in beta but has been around for a long time, use gulp v4
npm i gulp@4.0.0-alpha.2

Update 13 July 2020
Gulp v4 was released December 2018
npm i gulp@4.0.0 --save-dev

A: Also you may install gulp version 4 using:
npm i gulpjs/gulp#4.0 --save-dev

redpajama_set_name: RedPajamaStackExchange


text:
Q: STM32F4461re: mapping peripheral register using structures. I need to understand the meanings of the pointers I have two questions.
First question:
I am writing the code for the mapping of the peripheral and I come across to simple code like this:
typedef struct
{
    __IO uint32_t MODER;
    __IO uint32_t OTYPER;
    __IO uint32_t OSPEEDR;
    __IO uint32_t PUPDR;
    __IO uint32_t IDR;
    __IO uint32_t ODR;
    __IO uint32_t BSRR;
    __IO uint32_t LCKR;
    __IO uint32_t AFR[2];

}GPIO_Typedef;

and
#define GPIOA           ((GPIO_TypeDef*)) GPIOA_BASE)

what is the use of the pointer? Usually what I have come across is that if you typecast a pointer you have
double *c;
int *p = (int*) c;

So how typecasting and pointers are used here? Thanks for the answers!
Second question:
I have seen this code on another thread.
typedef struct {
    unsigned IN; /* offset 0 */
    unsigned _unused1[3];
    unsigned OUT; /* offset 0x10 */
    unsigned _unused2[3];
    unsigned DIR; /* offset 0x20 */
} PortStruct;

#define PORTA (*(volatile PortStruct *)0x80001000))
#define PORTB (*(volatile PortStruct *)0x80002000))

What the second * is used for? I have heard it is used for dereferencing, does that mean that it takes the value inside the pointed register instead of the address?

A: The typedef describes a variable with a intricatly designes structure.
It is designed so that the internal layout reflects exactly a part of the memory-mapped peripheral array of your environment.
The problem with using it directly is that defining any variable of that type will end up creating a variable anywhere, but not in the peripheral array. Specifically not at the precise location you need it to be located, at the address you find in e.g. in PORTA and PORTB.
However, you do not need the compiler/linker to create a variable there, you can get them to trust you that such a variable exists exactly in the right place.
That is done with the special definition of PORTA.
If you use PORTA in code it gets expanded by preprocessor to
(*(volatile PortStruct *)0x80001000)).
It means
"Dear compiler, please

*

*take this literal number

*consider it to be a pointer to a variable of type PortStruct

*dereference it"

In effect, using PORTA can be used like using a variable of type PortStruct which happens to be exactly at the right address.
The second * you ask about is the dereferencing, which turns what is conisdered a pointer into what can be used as a variable.


text:
Q: Pass large amount of data to MVC get method I have an angularjs form that I would like users to be able to download a filled out PDF of what they requested.  I have an [HTTPGet] method that accepts a base64 encoding of the json request.  Everything works except when my base64 encoding goes above 2027 characters in length.  When that happens, I don't receive anything more than the 2027 characters.  Is there another way to send the data on a get call or a better way to do this.
My angular js app does this.
scope.DownloadTempResults = function () {
                window.open('/Home/GetCopyOfRequest?strRequest=' + window.btoa(JSON.stringify(scope.request)), '_blank', '');
            }

My C# code behind does this.
[HttpGet]
public ActionResult GetCopyOfRequest(string strRequest)
{
     byte[] data = Convert.FromBase64String(strRequest);
     string request = Encoding.UTF8.GetString(data);
     ExternalModel model = JsonHelper.Deserialize<ExternalModel>(request);

     byte[] filedata = ObjectFactory.GetInstance<ManagerFactory>().Create().CreateRequestForm(model);
     string contentType = "application/pdf";
     var cd = new System.Net.Mime.ContentDisposition
     {
          FileName = "name of File",
          Inline = true
     };
     Response.AppendHeader("Content-Disposition", cd.ToString());
     return File(filedata, contentType);
}

At the end of the day, what we are trying to do is encode the json in the query string so that you can not look directly at the query string and get the values of the json object.  If I am going about this completely wrong, please let me know what to look up to accomplish this.
Updated below here.
So based on the comments, I changed to a post method that looks like this.
[HttpPost]
public HttpResponseMessage GetCopyOfRequest(string strRequest)
{
     ExternalModel model = JsonHelper.Deserialize<ExternalModel>(strRequest);
     byte[] filedata = ObjectFactory.GetInstance<IManagerFactory>().Create().CreateRequestForm(model);
     string fileName = "Request form for request";

     HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
     httpResponseMessage.Content = new ByteArrayContent(filedata);
     httpResponseMessage.Content.Headers.Add("x-filename", fileName);
     httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
     httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
     httpResponseMessage.Content.Headers.ContentDisposition.FileName = fileName;
     httpResponseMessage.StatusCode = HttpStatusCode.OK;
     return httpResponseMessage;
}

In the angularjs app, I have the following code.
$http({
            url: '/Home/GetCopyOfRequest',
            method: 'POST',
            data: { strRequest: JSON.stringify(request) },
            responseType: 'arraybuffer'
        }).success(function (data, status, headers) {
            var file = new Blob([data], { type: 'application/pdf' });
            var fileURL = URL.createObjectURL(file);
            window.open(fileURL);
        }).error(function (response) {

        });

When I do this on the server, my byte array has a length of 400000.  On the client side, I have an array of 270.  I followed an example from How to display a server side generated PDF stream in javascript sent via HttpMessageResponse Content .


text:
Q: bootstrap 5 position-relative with row not working I want to place the * sign on the left. But every time I do, it will not work unless I eliminate the row class.
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <link href="{{ asset('themes/fontawesome/css/all.min.css') }}" rel="stylesheet">

    نام فیلتر
    <input type="text" id="name" class="form-control" name="filters[1][name]">

    نام لاتین فیلتر
    <input type="text" id="latin" class="form-control" name="filters[1][latin]">

    انتخاب فیلد
    <select id="field" class="form-select" name="filters[1][field]">
    <option value="1">چک باکس</option>
    <option value="2">رنگ</option>
    <option value="3">آپشن</option>
    </select>

A: Only columns should be the immediate children of row, and content should be placed inside the columns.. not directly in the row.

            نام فیلتر
            <input type="text" id="name" class="form-control" name="filters[1][name]">

            نام لاتین فیلتر
            <input type="text" id="latin" class="form-control" name="filters[1][latin]">

            انتخاب فیلد
            <select id="field" class="form-select" name="filters[1][field]">
                <option value="1">چک باکس</option>
                <option value="2">رنگ</option>
                <option value="3">آپشن</option>
            </select>

Codeply


text:
Q: Creating New Folder/Directory in Python/Pandas Want to create a new folder, getting an error.
Method:
def IDW_to_df(conn, quarter, file_name,sql_statement, *columns):
cursor = conn.cursor()
cursor.execute(sql_statement)
Dict = {}
for column in columns:
    Dict[column]=[]
while 1:
    row = cursor.fetchone()
    if not row:
        break
    x = 0
    for column in columns:
        Dict[column].append(row[x])
        x += 1
df = pd.DataFrame(Dict)
df.to_csv('H:/Q{0}/{1}.csv'.format(quarter,file_name))
return df

The method itself functions properly, just the folder creation throws the error. When called, I get the following error.
IOError: [Errno 2] No such file or directory: 'H:/Q4/FOO_IND.csv'

A: Thanks, had to create directory first.  Will probably add some checks in the future to ensure the "new" directory doesn't already exist.
import pyodbc
import pandas as pd
import os
def IDW_to_df(conn, quarter, file_name,sql_statement, *columns):
    cursor = conn.cursor()
    cursor.execute(sql_statement)
    Dict = {}
    for column in columns:
        Dict[column]=[]
    while 1:
        row = cursor.fetchone()
        if not row:
            break
        x = 0
        for column in columns:
            Dict[column].append(row[x])
            x += 1
    df = pd.DataFrame(Dict)
    os.makedirs('H:/Q{0}'.format(quarter))
    df.to_csv('H:/Q{0}/{1}.csv'.format(quarter,file_name))
    return df


text:
Q: Showing the first image from a nested array in angularjs This is my json. I need to show only the first image in my imageview. i tried with {{p.url}} to get the images. but its not worked fine.
 [{

        "comment": "",
        "adoptId": null,
        "images": [
          {
            "id": 4,
            "name": "3_1.jpg",
            "url": "Content\\RacePictures\\YRMTH-2017-04-15-HT09.jpg"
          },
          {
            "id": 5,
            "name": "3_2.jpg",
            "url": "Content\\RacePictures\\YRMTH-2017-04-15-HT09.jpg"
          }
        ]

HTML

Angular Controller
    var httpRequest = $http({
                method: 'GET',
                url: urls.api + 'Library/treeImages/Filter/' + images,
      }) .success(function (data, status) {
    $scope.photos = angular.fromJson(data);
                            }
)
}

A:

try this

A: just remove the ng-repeat and access the image array by the index


text:
Q: Is there a way to output the result of a "git blame" to a text file? I am running the git blame command on a large file and would like to see the results in a text file.

A: Sure. On the command line simply direct the output to your own file instead of STDOUT:
git blame source_file > blame_result_file

A: command line redirect which works for any command that prints to standard out:
git blame > output.txt


text:
Q: Uploading a local file to a remote hdfs with Java API but connect to localhost I have this very simple upload method to upload a file to a one-node hdp2.5 cluster:
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(new URI("webhdfs://hdsfhost:50070", conf);
fs.copyFromLocalFile(false, true, new Path(localFilePath), new Path(hdfsPath));

Tracing what happens the flow starts correctly:

*

*connect to hdfshost:50070,

*check if file already exists (no),

*connect to datanode.

That is where it fails: the datanode is found to be localhost:50075 instead of hdfshost:50075, resulting in a "java.net.ConnectException: Connection refused".
I have the following relevant settings on hdp:

*

*dfs.client.use.datanode.hostname => true

*dfs.datanode.http.address => 0.0.0.0:50075

*dfs.namenode.http-address => 0.0.0.0:50070

I could not find any reason why localhost is used instead of hdfshost (and there is no override in /etc/hosts, neither on the local machine neither on the cluster). Any help would be very appreciated.

A: You need to change your configuration of the http-address to your local IP address instead of 0.0.0.0.
0.0.0.0 gets resolved to localhost and will then be used by dfs.client.use.datanode.hostname => true while your local IP address will be resolved to the DNS name and then be used by hostname again.
Since it works I will post this as an answer, thus I don't know if my reasoning for the solution is correct. If anybody knows the exact reason please add it as a comment or edit my answer.


text:
Q: User Function to slice query output So I'm performing a query on my Neo4j database and getting back the expected results, although it's in a different format. What I want my output to look like is this...
{"nodes":[
  {"id":"James Gunn"},
  {"id":"Zoe Saldana"},
  {"id":"Bradley Cooper"},
  {"id":"Vin Diesel"},
  {"id":"Chris Pratt"},
  {"id": "Guardians of the Galaxy",
    "year":2014.0,
    "director":"James Gunn",
    "rating":8.1,
    "runtime":121.0,
    "description":"<Enter long desc here>",
    "label":"Movie",
    "actors":["Chris Pratt","Vin Diesel","Bradley Cooper","Zoe Saldana"],
    "revenue":333.13,
    "genres":["Action","Adventure","Sci-Fi"],
    "name":"Guardians of the Galaxy",
    "rank":1.0,
    "votes":757074.0,
    "metascore":76.0}],
"links":[
    {"source":"Zoe Saldana","target":"Guardians of the Galaxy"},
    {"source":"Bradley Cooper","target":"Guardians of the Galaxy"},
    {"source":"Vin Diesel","target":"Guardians of the Galaxy"},
    {"source":"Chris Pratt","target":"Guardians of the Galaxy"}]}

Instead, I'm getting the same, just with an extra "{"nodes" : " at the beginning I'd like to omit.
Here's what I mean
{"nodes":  (<----- REMOVE/OMIT THIS LINE)
  {"nodes":[
  {"id":"James Gunn"},
  {"id":"Zoe Saldana"},
  {"id":"Bradley Cooper"},
  {"id":"Vin Diesel"},
  {"id":"Chris Pratt"},
  {"id": "Guardians of the Galaxy",
    "year":2014.0,
    "director":"James Gunn",
    "rating":8.1,
    "runtime":121.0,
    "description":"<Long desc>",
    "label":"Movie",
    "actors":["Chris Pratt","Vin Diesel","Bradley Cooper","Zoe Saldana"],
    "revenue":333.13,
    "genres":["Action","Adventure","Sci-Fi"],
    "name":"Guardians of the Galaxy",
    "rank":1.0,
    "votes":757074.0,
    "metascore":76.0}],

  "links":[
    {"source":"Zoe Saldana","target":"Guardians of the Galaxy"},
    {"source":"Bradley Cooper","target":"Guardians of the Galaxy"},
    {"source":"Vin Diesel","target":"Guardians of the Galaxy"},
    {"source":"Chris Pratt","target":"Guardians of the Galaxy"}
   ]
   }
}   <-----(ALSO THIS LINE THAT CLOSES IT)

Here is my current query
`CALL apoc.export.json.query("MATCH (m:Movie)
WHERE m.name = 'Guardians of the Galaxy'
CALL apoc.path.subgraphAll(m, {maxLevel:1}) YIELD nodes, relationships
WITH [node in nodes | node {.*, id:node.name, label:labels(node)[0]}] as nodes,
     [rel in relationships | rel {.*, source:startNode(rel).name, target:endNode(rel).name}] as rels
WITH {nodes:nodes, links:rels} as nodes
RETURN nodes"
        , "file://./limit.json", {})`

What my question is is how do I write a user function that would allow me to slice the string to be formatted how I'd like?
I'm assuming it'd be something like RETURN Slicing(nodes) but from what I've read user functions are only allowed in Java and I'm using JavaScript in React.

A: Instead of composing a new json doc, maybe you can try returning the nodes and links directly as in,
Instead of,
...
WITH {nodes:nodes, links:rels} as nodes
RETURN nodes
...

try
...
RETURN nodes, rels as links
...


text:
Q: Python BST not working I'm new to Python thus the question,this is the implementation of my my BST
class BST(object):
    def __init__(self):
        self.root = None
        self.size = 0

    def add(self, item):
        return self.addHelper(item, self.root)

    def addHelper(self, item, root):
        if root is None:
            root = Node(item)
            return root

        if item < root.data:
            root.left = self.addHelper(item, root.left)
        else:
            root.right = self.addHelper(item, root.right)

This is the Node object
class Node(object):
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

This is my implmentation of str
def __str__(self):
    self.levelByLevel(self.root)
    return "Complete"

 def levelByLevel(self, root):

        delim = Node(sys.maxsize)
        queue = deque()
        queue.append(root)
        queue.append(delim)
        while queue:
            temp = queue.popleft()
            if temp == delim and len(queue) > 0:
                queue.append(delim)
                print()
            else:
                print(temp.data, " ")
                if temp.left:
                    queue.append(temp.left)
                if temp.right:
                    queue.append(temp.right)

This is my calling client,
def main():
    bst = BST()
    bst.root = bst.add(12)
    bst.root = bst.add(15)
    bst.root = bst.add(9)

    bst.levelByLevel(bst.root)

if __name__ == '__main__':
    main()

Instead of the expected output of printing the BST level by level I get the following output,
9
9223372036854775807

When I look in the debugger it seems that the every time the add method is called it starts with root as None and then returns the last number as root. I'm not sure why this is happening.
Any help appreciated.

A: If the root argument of your addHelper is None, you set it to a newly-created Node object and return it. If it is not, then you modify the argument but return nothing, so you end up setting bst.root to None again. Try the following with your code above — it should help your understanding of what your code is doing.
bst = BST()

bst.root = bst.add(12)
try:
    print(bst.root.data)
except AttributeError:
    print('root is None')

# => 12
# `bst.addHelper(12, self.root)` returned `Node(12)`,
#     which `bst.add` returned too, so now `bst.root`
#     is `Node(12)`

bst.root = bst.add(15)
try:
    print(bst.root.data)
except AttributeError:
    print('root is None')

# => root is None
# `bst.addHelper(15, self.root)` returned `None`,
#     which `bst.add` returned too, so now `bst.root`
#     is `None`.

bst.root = bst.add(9)
try:
    print(bst.root.data)
except AttributeError:
    print('root is None')

# => 9
# `bst.addHelper(9, self.root)` returned `Node(9)`,
#     which `bst.add` returned too, so now `bst.root`
#     is `Node(9)`

So you should do two things:

*

*make you addHelper always return its last argument — after the appropriate modifications —, and

*have your add function take care of assigning the result to self.root (do not leave it for the class user to do).

Here is the code:
def add(self, item):
    self.root = self.addHelper(item, self.root)
    self.size += 1    # Otherwise what good is `self.size`?

def addHelper(self, item, node):
    if node is None:
        node = Node(item)
    elif item < node.data:
        node.left = self.addHelper(item, node.left)
    else:
        node.right = self.addHelper(item, node.right)
    return node

Notice that I changed the name of the last argument in addHelper to node for clarity (there already is something called root: that of the tree!).
You can now write your main function as follows:
def main():
    bst = BST()
    bst.add(12)
    bst.add(15)
    bst.add(9)

    bst.levelByLevel(bst.root)

(which is exactly what @AaronTaggart suggests — but you need the modifications in add and addHelper). Its output is:
12

9
15
9223372036854775807

The above gets you to a working binary search tree. A few notes:

*

*I would further modify your levelByLevel to avoid printing that last value, as well as not taking any arguments (besides self, of course) — it should always print from the root of the tree.

*bst.add(None) will raise an error. You can guard against it by changing your add method. One possibility is
def add(self, item):
    try:
        self.root = self.addHelper(item, self.root)
        self.size += 1
    except TypeError:
        pass

Another option (faster, since it refuses to go on processing item if it is None) is
def add(self, item):
    if item is not None:
        self.root = self.addHelper(item, self.root)
        self.size += 1

*From the point of view of design, I would expect selecting a node from a binary search tree would give me the subtree below it. In a way it does (the node contains references to all other nodes below), but still: Node and BST objects are different things. You may want to think about a way of unifying the two (this is the point in @YairTwito's answer).

*One last thing: in Python, the convention for naming things is to have words in lower case and separated by underscores, not the camelCasing you are using — so add_helper instead of addHelper. I would further add an underscore at the beginning to signal that it is not meant for public use — so _add_helper, or simply _add.

A: Based on the following, you can see that bst.root in None after the second call to add():
>>> bst.root = bst.add(12)
>>> bst.root
<__main__.Node object at 0x7f9aaa29cfd0>
>>> bst.root = bst.add(15)
>>> type(bst.root)
<type 'NoneType'>

Your addHelper isn't returning the root node. Try this:
def addHelper(self, item, root):
    if root is None:
        root = Node(item)
        return root

    if item < root.data:
        root.left = self.addHelper(item, root.left)
    else:
        root.right = self.addHelper(item, root.right)

    return root

And then it works as expected:
>>> bst.root = bst.add(12)
>>> bst.root = bst.add(15)
>>> bst.levelByLevel(bst.root)
(12, ' ')
()
(15, ' ')
(9223372036854775807, ' ')
>>> bst.root = bst.add(9)
>>> bst.levelByLevel(bst.root)
(12, ' ')
()
(9, ' ')
(15, ' ')
(9223372036854775807, ' ')

A: You're using the BST object basically only to hold a root Node and the add function doesn't really operate on the BST object so it's better to have only one class (BtsNode) and implement the add there. Try that and you'll see that the add function would be much simpler.
And, in general, when a member function doesn't use self it shouldn't be a member function (like addHelper), i.e., it shouldn't have self as a parameter (if you'd like I can show you how to write the BtsNode class).
I tried writing a class that uses your idea of how to implement the BST.
class BstNode:
    def __init__(self):
        self.left = None
        self.right = None
        self.data = None

    def add(self,item):
        if not self.data:
            self.data = item
        elif item >= self.data:
            if not self.right:
                 self.right = BstNode()
            self.right.add(item)
        else:
            if not self.left:
                 self.left = BstNode()
            self.left.add(item)

That way you can create a BST the following way:
bst = BstNode()
bst.add(13)
bst.add(10)
bst.add(20)

The difference is that now the add function actually operates on the object without any need for the user to do anything. The function changes the state of the object by itself.
In general a function should do only what it's expected to do. The add function is expected to add an item to the tree so it shouldn't return the root. The fact that you had to write bst.root = bst.add() each time should signal that there's some fault in your design.

A: Your add method probably shouldn't return a value. And you most certainly shouldn't assign the root of the tree to what the add method returns.
Try changing your main code to something like this:
def main():
    bst = BST()
    bst.add(12)
    bst.add(15)
    bst.add(9)

    bst.levelByLevel(bst.root)

if __name__ == '__main__':
    main()


text:
Q: background image command defined in header not working I have been scratchingmy head about why the background image function is not working for me. Any suggestions? Yes I already know that Im a dumbass with severe attention problems..

this is text

"

A: Change background image: to background-image:. Also there is no property like background-url

A: There is no background-url. There is no background<space>image. There is background-image and there is background.
Once you fix those problems the images should display correctly.


text:
Q: Can you iterate over only tags with the .children iterator from BeautifulSoup? I am pulling down an xml file using BeautifulSoup with this code
dlink = r'https://www.sec.gov/Archives/edgar/data/1040188/000104018820000126/primary_doc.xml'
dreq = requests.get(dlink).content
dsoup = BeautifulSoup(dreq, 'lxml')

There is a level I'm trying to access and then place the elements into a dictionary. I've got it working with this code:
if dsoup.otherincludedmanagerscount.text != '0':
    inclmgr = []
    for i in dsoup.find_all('othermanagers2info'):
        for m in i.find_all('othermanager2'):
            for o in m.find_all('othermanager'):
                imd={}
                if o.cik:
                    imd['cik'] = o.cik.text
                if o.form13ffilenumber:
                    imd['file_no'] = o.form13ffilenumber.text
                imd['name'] = o.find('name').text
                inclmgr.append(imd)
    comp_dict['incl_mgr'] = inclmgr

I assume its easier to use the .children or .descendants generators, but every time I run it, I get an error. Is there a way to only iterate over tags using the BeautifulSoup generators?
Something like this?
for i in dsoup.othermanagers2info.children:
        imd['cik'] = i.cik.text

AttributeError: 'NavigableString' object has no attribute 'cik'

A: Assuming othermanagers2info is a single item; you can create the same results using 1 for loop:
for i in dsoup.find('othermanagers2info').find_all('othermanager'):
    imd={}
    if i.cik:
        imd['cik'] = i.cik.text
    if i.form13ffilenumber:
        imd['file_no'] = i.form13ffilenumber.text
    imd['name'] = i.find('name').text
    inclmgr.append(imd)
comp_dict['incl_mgr'] = inclmgr

You can also do for i in dsoup.find('othermanagers2info').findChildren():. However this will produce different results (unless you add additional code). It will flattened the list and include both parent & child items. You can also pass in a node name


text:
Q: Find file in program files and launch that file I'm attempting to write a program that downloads Team Viewer and installs it and if its already installed, launch teamviewer from programfiles instead of re-downloading it.
I have it so it downloads and installs teamviewer into the correct folder but i cant figure out how to tell my program to search in either Program Files (x86) for 64bit or program files for 32 bit search the directory and sub directories for teamviewer.exe and launch the program. Here is the code i have so far.
Thanks.
I solved it using this code. It searches for Teamviewer in the correct program files folder and launches the program . This does not check if you have it installed or not, i have a check earlier in my program that detects it but it would be easy to add.
private void teamviewerbtn_Click(object sender, EventArgs e)
    {
        //start button

        if (Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE").Contains("64"))
        {
            string path = @"c:\Program Files (x86)\Teamviewer\"; //specify starting folder location for searching
            string searchPattern = "teamviewer.exe*"; //what do you want to search for?

            DirectoryInfo di = new DirectoryInfo(path);

            FileInfo[] files =
                di.GetFiles(searchPattern, SearchOption.AllDirectories);

            foreach (FileInfo file in files)
            {
                string tvE = (file.FullName.ToString()); //takes found file and references full file path
                Process.Start(tvE);
            }
        }
        else
        {
            string path = @"c:\Program Files\Teamviewer\"; //specify starting folder location for searching
            string searchPattern = "teamviewer.exe*"; //what do you want to search for?

            DirectoryInfo di = new DirectoryInfo(path);

            FileInfo[] files =
                di.GetFiles(searchPattern, SearchOption.AllDirectories);

            foreach (FileInfo file in files)
            {
                string tvE = (file.FullName.ToString()); //takes found file and references full file path
                Process.Start(tvE);
            }
        }

        //end button
    }

A: if (files.Length == 1)
{
    Process.Start(files[0]);
}


text:
Q: How to use a cell as a filename in a reference in excel? If I have a cell, "a2" which has part of a filename/filepath, "sheet2.xlsx" in it which I want to use as a reference another workbook, how can I accomplish this?
I have tried using the INDIRECT function but always get a reference error.
I am trying to find a way to summarize a list of spreadsheets with column a containing the spreadsheet name and another column referencing a cell inside that respective sheet.

A: If the referenced workbook is open, then here is an example of getting a value from it:
=INDIRECT( "'" & A1 & "[" & B1 & "]" & C1 & "'!" & D1)

where the components are like:

Note we have specified:

*

*the path

*the filename

*the worksheet name

*the cell address

If the file is not open, you can still retrieve data with a ExecuteExcel4Macro (assuming you have a version of Excel that supports this function)  For an example of this type of code, see:
Get Data from External Files


text:
Q: How can I call a python script from an asp.net Azure app service? I have an existing .NET Core / asp.net app service hosted on Azure. I need to call (on demand) a python script to return data based on custom user input.
It does not appear that I can use IronPython, since I need python modules that are built in CPython, which unfortunately aren't supported by IronPython.
The two options I see are:

*

*I might be able to install the right python version and libraries on the app service and call it from the .NET code. This seems like it might be deprecated: https://learn.microsoft.com/en-us/visualstudio/python/publishing-python-web-applications-to-azure-from-visual-studio?view=vs-2017

*I can create a whole new and separate app service for just the python script and call it as a REST API on demand from the .NET app service. This seems like overkill, and introduces the problem of opening up a whole new service publicly, which I don't want to do. This also appears to have the limitation that Flask isn't mean for production, so hosting many calls at once is not really workable. https://learn.microsoft.com/en-us/visualstudio/python/publish-to-app-service-windows?view=vs-2017
What is the best way to call a python script on demand from .NET app service on Azure?

A: Per my experience, there are two ways to call a Python script in C# without IronPython.

*

*Directly use System.Diagnostics.Process in C# to run a command as same as the SO thread Run Command Prompt Commands to get the result via parse the content of the process standard output. Simply to do it, you can use py2exe to wrap a Python script as a .exe file to avoid for installing Python modules and setting environment variables on Azure App Service. However, considering for concurrency, it's not a good idea for performance.

*The second option as you said is to deploy a Python script as a REST API in the same instance of Azure Web App. You can follow the blog Deploying multiple virtual directories to a single Azure Website to deploy a flask app with your Python script as a child project via Visual Studio with PTVS to expose an API url like https://<your web app name>.azurewebsites.net/pyapi which can be called from your ASP.NET via HttpClient. I tried this solution, it works.
Note: Due to the restriction of Azure Web App sandbox for Local Address Requests, you have to use <your web app name>.azurewebsites.net as hostname, neither localhost or 127.0.0.1.


text:
Q: Can not focus (click) on controls in container blackberry cascades I have a Page like below :
import bb.cascades 1.0

NavigationPane {
    id: nav
    Page {
        // Root container
        Container {
            layout: DockLayout {
            }
        // Background
        ImageView {
            imageSource: "asset:///bg.png"
            verticalAlignment: VerticalAlignment.Fill
            horizontalAlignment: HorizontalAlignment.Fill
        }

        // Container for contents
        Container {
            layout: StackLayout {
                orientation: LayoutOrientation.TopToBottom
            }

            // Top navigation : Login and Register buttons
            Container {
                layout: StackLayout {
                    orientation: LayoutOrientation.LeftToRight
                }

                ImageView {
                    id: tabLogin
                    imageSource: "asset:///ic_login_selected_tab.png"
                    onTouch: {
                        // Show login & hide register
                        loginContainer.setVisible(true)
                        registerContainer.setVisible(false)

                        // Change backgrounds
                        tabLogin.setImageSource(qsTr("asset:///ic_login_selected_tab.png"))
                        tabRegister.setImageSource(qsTr("asset:///ic_register_normal_tab.png"))
                    }

                }

                ImageView {
                    id: tabRegister
                    imageSource: "asset:///ic_register_normal_tab.png"

                    onTouch: {
                        loginContainer.setVisible(false)
                        registerContainer.setVisible(true)
                        tabLogin.setImageSource(qsTr("asset:///ic_login_normal_tab.png"))
                        tabRegister.setImageSource(qsTr("asset:///ic_register_selected_tab.png"))
                    }
                }

            }

            // Container for Login and Register pages
            Container {
                horizontalAlignment: HorizontalAlignment.Fill
                layout: DockLayout {
                }

                // Login container
                Container {
                    id: loginContainer
                    visible: true
                    horizontalAlignment: HorizontalAlignment.Fill
                    layout: StackLayout {
                        orientation: LayoutOrientation.TopToBottom
                    }

                    topPadding: 200

                    // safeMATE text
                    ImageView {
                        verticalAlignment: VerticalAlignment.Top
                        horizontalAlignment: HorizontalAlignment.Center
                        imageSource: "asset:///safemate.png"
                    }

                    // Container for email, passcode and login button
                    Container {
                        horizontalAlignment: HorizontalAlignment.Fill
                        verticalAlignment: VerticalAlignment.Center

                        topMargin: 100
                        bottomMargin: 50.0
                        Container {
                            layout: StackLayout {
                                orientation: LayoutOrientation.LeftToRight
                            }

                            background: Color.White
                            horizontalAlignment: HorizontalAlignment.Fill

                            leftPadding: 20.0
                            rightPadding: 30.0
                            topPadding: 25
                            bottomPadding: 25
                            bottomMargin: 5.0
                            topMargin: 5.0
                            leftMargin: 5.0
                            rightMargin: 5.0
                            layoutProperties: StackLayoutProperties {

                            }

                            ImageView {
                                imageSource: "asset:///ic_email.png"
                            }
                            TextField {
                                hintText: "Email"
                                inputMode: TextFieldInputMode.EmailAddress
                            }

                        }

                        Container {
                            layout: StackLayout {
                                orientation: LayoutOrientation.LeftToRight
                            }

                            background: Color.White
                            horizontalAlignment: HorizontalAlignment.Fill

                            leftPadding: 20.0
                            rightPadding: 30.0
                            topPadding: 25
                            bottomPadding: 25

                            bottomMargin: 5.0
                            topMargin: 5.0
                            leftMargin: 5.0
                            rightMargin: 5.0
                            layoutProperties: StackLayoutProperties {

                            }
                            ImageView {
                                imageSource: "asset:///ic_passcode.png"
                            }

                            TextField {
                                hintText: "Passcode"
                                inputMode: TextFieldInputMode.Password
                            }

                        }

                        ImageButton {
                            horizontalAlignment: HorizontalAlignment.Fill
                            defaultImageSource: "asset:///btn_login.png"
                            pressedImageSource: "asset:///btn_login_clicked.png"

                            onClicked: {
                                var page = homePage.createObject();

                                nav.push(page);
                            }
                        }
                    }
                }

                // Register container
                ScrollView {

                    Container {
                        id: registerContainer
                        visible: false
                    horizontalAlignment: HorizontalAlignment.Fill
                    layout: StackLayout {
                        orientation: LayoutOrientation.TopToBottom
                    }

                    topPadding: 30

                    // safeMATE text
                    ImageView {
                        verticalAlignment: VerticalAlignment.Top
                        horizontalAlignment: HorizontalAlignment.Center
                        imageSource: "asset:///safemate.png"
                    }

                    // Container for email, passcode and login button
                    Container {
                        horizontalAlignment: HorizontalAlignment.Fill
                        verticalAlignment: VerticalAlignment.Center

                        topMargin: 30
                        bottomMargin: 50.0

                        // Email
                        Container {
                            layout: StackLayout {
                                orientation: LayoutOrientation.LeftToRight
                            }

                            background: Color.White
                            horizontalAlignment: HorizontalAlignment.Fill

                            leftPadding: 20.0
                            rightPadding: 30.0
                            topPadding: 25
                            bottomPadding: 25
                            bottomMargin: 5.0
                            topMargin: 5.0
                            leftMargin: 5.0
                            rightMargin: 5.0
                            layoutProperties: StackLayoutProperties {

                            }

                            ImageView {
                                imageSource: "asset:///ic_email.png"
                            }
                            TextField {
                                hintText: "Email"
                                inputMode: TextFieldInputMode.EmailAddress
                            }

                        }

                        // Full name
                        Container {
                            layout: StackLayout {
                                orientation: LayoutOrientation.LeftToRight
                            }

                            background: Color.White
                            horizontalAlignment: HorizontalAlignment.Fill

                            leftPadding: 20.0
                            rightPadding: 30.0
                            topPadding: 25
                            bottomPadding: 25
                            bottomMargin: 5.0
                            topMargin: 5.0
                            leftMargin: 5.0
                            rightMargin: 5.0
                            layoutProperties: StackLayoutProperties {

                            }

                            ImageView {
                                imageSource: "asset:///ic_fullname.png"
                            }
                            TextField {
                                hintText: "Full name"
                                inputMode: TextFieldInputMode.Default
                            }

                        }

                        // Passcode
                        Container {
                            layout: StackLayout {
                                orientation: LayoutOrientation.LeftToRight
                            }

                            background: Color.White
                            horizontalAlignment: HorizontalAlignment.Fill

                            leftPadding: 20.0
                            rightPadding: 30.0
                            topPadding: 25
                            bottomPadding: 25

                            bottomMargin: 5.0
                            topMargin: 5.0
                            leftMargin: 5.0
                            rightMargin: 5.0
                            layoutProperties: StackLayoutProperties {

                            }
                            ImageView {
                                imageSource: "asset:///ic_passcode.png"
                            }

                            TextField {
                                hintText: "Passcode"
                                inputMode: TextFieldInputMode.Password
                            }

                        }

                        // Phone
                        Container {
                            layout: StackLayout {
                                orientation: LayoutOrientation.LeftToRight
                            }

                            // Country code
                            Container {
                                layout: StackLayout {
                                    orientation: LayoutOrientation.LeftToRight
                                }

                                background: Color.White

                                leftPadding: 20.0
                                rightPadding: 30.0
                                topPadding: 35
                                bottomPadding: 35
                                bottomMargin: 5.0
                                topMargin: 5.0
                                leftMargin: 5.0
                                rightMargin: 5.0
                                layoutProperties: StackLayoutProperties {

                                }

                                ImageView {
                                    imageSource: "asset:///ic_phonenumber.png"
                                }

                            }

                            // Phone
                            Container {
                                horizontalAlignment: HorizontalAlignment.Fill
                                layout: StackLayout {
                                    orientation: LayoutOrientation.LeftToRight
                                }

                                background: Color.White

                                leftPadding: 20.0
                                rightPadding: 30.0
                                topPadding: 23
                                bottomPadding: 23
                                bottomMargin: 5.0
                                topMargin: 5.0
                                leftMargin: 5.0
                                rightMargin: 5.0
                                layoutProperties: StackLayoutProperties {

                                }

                                // Phone number text box
                                TextField {
                                    hintText: "Phone number"
                                    inputMode: TextFieldInputMode.Default
                                }
                            }
                        }

                        // Contact info title
                        Container {
                            topMargin: 20
                            horizontalAlignment: HorizontalAlignment.Fill
                            layout: StackLayout {
                                orientation: LayoutOrientation.LeftToRight
                            }

                            ImageView {
                                imageSource: "asset:///ic_contactinfo.png"
                            }

                            Container {
                                leftPadding: 20
                                layout: StackLayout {
                                    orientation: LayoutOrientation.TopToBottom
                                }

                                Label {
                                    verticalAlignment: VerticalAlignment.Center
                                    text: "CONTACT INFO"
                                }
                                Label {
                                    text: "These information will be used for emergencies"
                                    multiline: true
                                    textStyle.fontSize: FontSize.XSmall
                                }
                            }

                        }

                        // Contact info container
                        Container {
                            topMargin: 20
                            horizontalAlignment: HorizontalAlignment.Fill
                            verticalAlignment: VerticalAlignment.Center
                            layout: StackLayout {
                                orientation: LayoutOrientation.TopToBottom
                            }

                            // Phone
                            Container {

                                layout: StackLayout {
                                    orientation: LayoutOrientation.LeftToRight
                                }

                                // Country code
                                Container {
                                    layout: StackLayout {
                                        orientation: LayoutOrientation.LeftToRight
                                    }

                                    background: Color.White

                                    leftPadding: 20.0
                                    rightPadding: 30.0
                                    topPadding: 35
                                    bottomPadding: 35
                                    bottomMargin: 5.0
                                    topMargin: 5.0
                                    leftMargin: 5.0
                                    rightMargin: 5.0
                                    layoutProperties: StackLayoutProperties {

                                    }

                                    ImageView {
                                        imageSource: "asset:///ic_phonenumber.png"
                                    }
                                }

                                // Phone
                                Container {
                                    horizontalAlignment: HorizontalAlignment.Fill
                                    layout: StackLayout {
                                        orientation: LayoutOrientation.LeftToRight
                                    }

                                    background: Color.White

                                    leftPadding: 20.0
                                    rightPadding: 30.0
                                    topPadding: 23
                                    bottomPadding: 23
                                    bottomMargin: 5.0
                                    topMargin: 5.0
                                    leftMargin: 5.0
                                    rightMargin: 5.0
                                    layoutProperties: StackLayoutProperties {

                                    }

                                    // Phone number text box
                                    TextField {
                                        hintText: "Phone number"
                                        inputMode: TextFieldInputMode.Default
                                    }
                                }
                            }

                            // Address
                            Container {
                                layout: StackLayout {
                                    orientation: LayoutOrientation.LeftToRight
                                }

                                background: Color.White
                                horizontalAlignment: HorizontalAlignment.Fill

                                leftPadding: 20.0
                                rightPadding: 30.0
                                topPadding: 25
                                bottomPadding: 25
                                bottomMargin: 5.0
                                topMargin: 5.0
                                leftMargin: 5.0
                                rightMargin: 5.0
                                layoutProperties: StackLayoutProperties {

                                }

                                ImageView {
                                    imageSource: "asset:///ic_address.png"
                                }
                                TextField {
                                    hintText: "Address"
                                    inputMode: TextFieldInputMode.EmailAddress
                                }

                            }
                        }

                        // Register button
                        ImageButton {
                            horizontalAlignment: HorizontalAlignment.Fill
                            defaultImageSource: "asset:///btn_register.png"
                            pressedImageSource: "asset:///btn_register_clicked.png"

                            onClicked: {
                                var page = homePage.createObject();

                                nav.push(page);
                            }
                        }
                    }
                }
        }
            }
        }
    }
}

attachedObjects: [
    ComponentDefinition {
        id: homePage
        source: "home.qml"
    }
]

onPopTransitionEnded: {
    // Transition is done destroy the Page to free up memory.
    page.destroy();
}

}
I have 2 buttons on top of page to navigate between Login and Register.
The problem is : I can not focus (input texts or press on button) on Login container (But Register container is working well).
Please let me know how to solve this problem

A: If I put it in IDE I immediately get

The default property for the component 'Page' does not accept several objects.

So, put a Container around your two containers, so Page will only have one element inside.
import bb.cascades 1.0
Page {
    Container {

        // Login container
        Container {
            // Email
            TextField {
            }
            // Password
            TextField {
            }
            // Button login
            Button {
            }
        }
        // Register container
        Container {
            // Email
            TextField {
            }
            // Password
            TextField {
            }
            // Button register
            Button {
            }
        }
    }
}

EDIT:
Since you added full code, there is another problem there. You created your Login Container, and then you create "ScrollView" which is for registering new user. The problem ScrollView was created on top of login Container, and even though it isn't visible it blocks container below. Two solutions:

*

*Create a separate page for registering new user

*Move your login Container UNDER ScrollView. With a bit of luck that should do the job (and not disable registering). Since you use DockLayout that shouldn't destroy your design


text:
Q: write a rule to detect customer location in a department in a store based on visits I am new to Drools and have some questions. I am working on creating rules which detects customers in departments in a store.
My model is as below:
Customer: Id, Point(x,y)
Department: Id, Rectangle
CustomerEvent
I currently have customers represented with x,y location or a point and a department is represented by rectangle.
1.) How do I write a rule to detect if a customer is in a rectangle?
2.) If a customer changes location within a department at least 2 times, trigger an event.  How do I write a rule to detect if the customer is in a department and has changed location two times?
Please let me know.
Thanks!
Customer
public class CustomerObj {
public CustomerObj(String custId, Integer timestamp) {
    super();
    this.custId = custId;
    this.timestamp = timestamp;
}
private String custId;
private long timestamp;
private Integer classification;
private Point location;
private Department department;

public long getTimestamp() {
    return timestamp;
}
public void setTimestamp(Integer timestamp) {
    this.timestamp = timestamp;
}
public String getCustId() {
    return custId;
}
public void setCustId(String custId) {
    this.custId = custId;
}
public Integer getClassification() {
    return classification;
}
public void setClassification(Integer classification) {
    this.classification = classification;
}
public Point getLocation() {
    return location;
}
public void setLocation(Point location) {
    this.location = location;
}
public Department getDepartment() {
    return department;
}
public void setDepartment(Department department) {
    this.department = department;
}

}
Department
public class Department {
public Department(Integer departmentId) {
    super();
    this.departmentId = departmentId;
}

private Integer departmentId;
private Rectangle deptLocation;

public Integer getDepartmentId() {
    return departmentId;
}

public void setDepartmentId(Integer departmentId) {
    this.departmentId = departmentId;
}

public boolean containsCustomer(CustomerObj c) {
    if (this.deptLocation.contains(c.getLocation())) return true;
    else return false;
}

}

A: Assuming Rectangle and Point are from java.awt, things are rather simple.
rule "customer in department"
when
    CustomerObj( $cid: custId, $p: point )
    Department( $did: departmentId, $dloc: deptLocation,
                $dloc.contains( $p ) )
then
    System.out.println( "customer " + $cid + " in " + $did );
end

As for the movements, you'll need an CustomerEvent showing customer and department id and the location.
rule "customer moves frequently in same department"
when
    CustomerEvent( $cid: custId, $did: dptmtId, $p: Point )
    $dep: Department( departmentId == $did )
    $cust: CustomerObj( custId == $cid, department == $dep, moves >= 1 )
then
    // whatever
end

Note that you'll need additional rules for changing the department reference in a customer and for registering the 1st move, and, possibly for counting the moves beyond the second move.


text:
Q: Read Access Violation on Virtual Function This is a simplified version of my program.
#include <iostream>
#include <vector>
class Base
{
public:
    Base()
    {

    }

    void virtual update()
    {
        std::cout << "no update function\n";
    }
    void virtual draw()
    {
        std::cout << "no draw function\n";
    }
};

class Derived : public Base
{
public:
    Derived();
    void draw() override;
    void update() override;
};

Derived::Derived()
{

}

void Derived::draw()
{
    std::cout << "draw";
}

void Derived::update()
{
    std::cout << "update";
}

class Caller
{
public:
    Caller();

    void update();
    void draw();

    void reg_obj(Base* obj);
private:
    std::vector<std::shared_ptr<Base>> all_objects;
};

Caller::Caller()
{
    Derived derived_class{};
    reg_obj(&derived_class);
}

void Caller::update()
{
    for (int i = 0; i < all_objects.size(); i++)
    {
        all_objects[i]->update();
    }
}

void Caller::draw()
{
    for (int i = 0; i < all_objects.size(); i++)
    {
        all_objects[i]->draw();
    }
}

void Caller::reg_obj(Base* obj)
{
    all_objects.push_back(std::shared_ptr<Base>{obj});
}

int main()
{
    Caller caller{};

    while (true)
    {
        caller.update();
        caller.draw();
    }
}

This code works, but when it's in my full program between caller.update(); and caller.draw(); the __vfptr value in memory does not stay the same.  When approaching caller.draw() the __vfptr value changes every step through the debugger.  I'm not sure how to diagnose memory corruption in __vfptr as it's not something I programmed, but part of the C++ standard.  Any help is appreciated. And no, I can't make a reproducible version.  I don't know why.  I did make an effort to make it reproducible.
https://youtu.be/yd-76qDa7xc <- this video shows the problem
https://github.com/Sage-King/Alienor <- source for non-functional code

A: Solution from Remy Lebeau:
Derived derived_class{}; reg_obj(&derived_class); is causing undefined behavior in the rest of your code. You are storing a pointer to a local object that is destroyed afterwards, leaving a dangling pointer in the all_objects vector. All of your method calls on all_objects elements are acting on invalid memory. To fix that, change void reg_obj() to take a shared_ptr<Base> and store it as-is, and then change Caller() to create the Derived object using std::make_shared()like this: void Caller::reg_obj(std::shared_ptr<Base> obj) { all_objects.push_back(obj); } Caller::Caller() { reg_obj(std::make_shared<Derived>()); }


text:
Q: Is it possible to restore USB port firmware at BIOS level? I am not very interested in the hardware implications, rather in a possible corruption of the firmware (ie, there is a software solution).
[The following is just to illustrate that the computerhas unusual peripherals:A controller PCI card (for a microscope) was installed in a not too ancient computer (Intel Core Duo). This card required installing an additional Firewire card and uses a USB thumbdrive to deliver a license key for a custom-made software (made by the microscope manufacturer). The controller card, the microscope are second-hand, so help from the manufacturer is not a direct option. The computer had 4 back USB 2.0 ports and 2 front USB 2.0 ports.]
That card was installed more than two years ago, and has been working reasonably well. At first, more than one year ago, the front ports stopped working, there is power on them (devices' led light up), the device is simply not seen. I ignored that at the time.
A month ago, XP started complaining about unknown USB device, sometimes all USB ports went off, and restarting did not solve the problem - the solution was to shut down, unplug from the mains for several minutes and restart. In the end USB ports 3 and 4 behaved as the front ports: there is power but no device is seen.
I am suspecting that the controller PCI card has done something at BIOS level. The leds on the PCI card light up before the OS starts. Also the USB port behaviour using an Ubuntu LiveDVD, is exactly the same, only USB port 1 and 2 work, the others (front and back) have power but no device is detected.
The motherboard is an Asus with (American Megatrend's) ACPI BIOS v.0310.
I would like to change or even reinstall whatever the BIOS is using to control the USB ports in order to restore their functionality.
I am completely unfamiliar about modifying computers' firmware (my only experience has been, at user level, follow instructions to upgrade firmware or enable/installing RAID BIOS software).
Am I far off guessing that this might have been caused by the card corrupting the firmware and that that can be restored once again? Is it possible to target the USB port behaviour at "BIOS" level?
Any help/hint will be greatly appreciated.

A: If you want to rule out a BIOS/Firmware corruption issue, you could download the latest BIOS from your motherboard vendor and install it per the manufacturer's instructions.  That will completely re-flash the BIOS on the motherboard.  Any "corruption" would be eliminated.
As an extra precaution, after re-flashing the BIOS, reset your settings to the defaults (use the CMOS clear jumper on the motherboard).  Make sure you write down your BIOS settings before you do that!
However, you most likely have a hardware problem, not a BIOS/Firmware problem.
A few things to understand:

*

*In any modern PC, the BIOS has multiple layers of checksums.  If the BIOS was corrupt somehow, it would fail those checksum tests, and your PC would not boot, probably with an error message about boot block recovery.

*There is not a standard mechanism for a PCI slot card to silently manipulate the BIOS, especially if this is an off-the-shelf Firewire card with no option ROM firmware.

*There is very little the BIOS can do that would have a "lasting" effect on the behavior of individual USB ports (except for a global disable/enable of the USB controller).  The BIOS initializes the USB controller to provide pre-OS keyboard/mouse/boot device support.  Once the Operating System loads, the BIOS does a hand-off to the OS (section 5.1 of the EHCI Spec).  From that point, the OS "owns" the USB controller, and is responsible for detecting an enumerating any attached USB devices.

*There can be issues with the hand-off method used (some BIOSes have an option to change it), but that would not cause the behaviour you describe.
My guess would be the USB overcurrent protection circuitry on the motherboard is failing, and it is falsely tripping.  When it trips, it cuts power to the attached USB device, and that can lead to undetected devices, devices disappearing, or random "unknown device" messages.  Many USB current-limiting components are thermal-based, so unplugging it for a while may allow it to work again (until it warms back up and fails again).  I have seen a number of similar failures on older Lenovo desktops.
Note that if the overcurrent is tripping you may see a pop-up message in Windows about this, but not always.  It depends on motherboard and if the overcurrent trip signals are connected to the chipset.  There may also be a BIOS option to control whether or not overcurrent conditions are reported to the OS.
The fact that you see the problem in multiple OSes further points to a hardware issue.  The Linux dmesg command may give you some USB debug info.
If I were you, I would replace the motherboard, or install a PCI/PCIe slot USB controller to replace the onboard USB port.  Note that an slot USB board will probably not be usable for pre-boot BIOS stuff.  A USB keyboard attached to the slot USB controller would not be able to get into the BIOS setup for example (depends on how BIOS legacy USB is configured).


text:
Q: Use Taylor Polynomial to approximate a definite integral. i have this problem:
Get the Taylor Polynomial of grade 3 of $\frac{1}{1-x}$ at the point a=0
Then use the polynomial to approximate the definite integral:
$$\int_0^\frac{1}{10} \frac{1}{1-x^2}$$
Here is what I did:
Taylor polynomial degree 3, center a=0:
$1+x+x^2+x^3$
then I replace $x$ for $x^2$ and I have:
$1+x^2+x^4+x^6$
then integrating
$(0.1)+\frac{(0.1)^3}{3}+\frac{(0.1)^5}{5}+\frac{(0.1)^7}{7}$
and that is the result.
Is this correct? I mostly taught myself through books and have no way of checking if i understood the topic correctly.
Thanks

A: So, for any integer $n\ge0$, we define the polynomial
$$p_n(x)=\sum_{k=0}^{n}x^k$$
which is the $n$-th order Taylor polynomial for $\frac1{1-x}$. So the polynomial for $\frac1{1-x^2}$ is of course
$$P_n(x)=\sum_{k=0}^{n}x^{2k}$$
and thus
$$Q_n=\sum_{k=0}^{n}\int_0^{1/10}x^{2k}dx=\sum_{k=0}^{n}\frac{1}{10^{2k+1}(2k+1)}$$
which confirms your results.


text:
Q: HttpURLConnection and download large files I use HttpURLConnection to download files from a url.
 URL obj = new URL(url);
 HttpURLConnection con = (HttpURLConnection) obj.openConnection();

 // optional default is GET
 con.setRequestMethod("GET");
 con.setRequestProperty("Cache-Control", "no-cache");

 int responseCode = con.getResponseCode();

 System.out.println("\nSending 'GET' request to URL : " + url);
 System.out.println("Response Code : " + responseCode);

 try {
     InputStream inputStream = con.getInputStream();
     FileOutputStream outputStream = new FileOutputStream("C:\\programs\\TRYFILE.csv");

     int bytesRead = -1;
     byte[] buffer = new byte[4096];

     while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
     }

 } catch(Exception e) {

 } finally {
       outputStream.close();
       inputStream.close();
 }

The code works to download small sized files (i.e. 25 KB). I didn't try to download large files (on the order of 100 MB), because the files from the particular URL are always small.
I want to know what happens if I try to download larger files with this code: will it continue to work or throw an exception? Do I need to implement code (utilizing, say, setConnectTimeout or setReadTimeout) for bigger files?
Is there a url you can suggest where I can try to download large file using this code?

A: As suggested in the comments, create a large file yourself. To serve it over HTTP, the easiest way is probably to run Python 3 from the directory where you put the file -
python -m http.server

which will start a server on 8000. See this blog post for more details, or check out the python documentation.
Then you can test this yourself.


text:
Q: How to do a division sum with a whole number as an anwer I am working on a maths quiz but I have come across a big problem.
The whole script runs great up until you choose division. The sum itself works fine but I have been trying to make it only give questions with whole numbers as answers.
Notes:
-All variables that are not declared HAVE been declared
-It is something wrong with the while loop (I think)
    //level 4
else if(level==4){
    alert(name + ", welcome to level 4 - Division!\nI will give you a sum and you must give me the answer. It's simple!");
    alert("For every one you get wrong, you lose one of your 3 lives. For every one you get right, you gain a point!");
    while(lives>0){
        var correctFloorAns = 1;
        var correctAns = 2;
        while(correctAns==correctFloorAns){
            alert("hi")
        }
        {
            primaryNumber = random(200);
            primaryNumber = primaryNumber * 1;
            secondaryNumber = random(200);
            secondaryNumber = secondaryNumber * 1;
            correctAns = primaryNumber / secondaryNumber;
            correctAns = correctAns * 1;
            correctFloorAns = Math.floor(correctAns);
        }
        playerAns = prompt(name + ", here is your sum: " + primaryNumber + " divided by " + secondaryNumber + "\n" + correctAns + "\n" + correctFloorAns);
        if(playerAns==correctAns){
            alert("Well done " + name + "! You got it right!");
            points = points + 1;
        }
        else{
            alert("Nope! You got it wrong");
            lives = lives - 1;
        }
        alert("You are now on " + lives + " live(s) and " + points + " point(s)!");
    }
    {
        alert("You died on " + points + " points! You are clearly not very good at maths, " + name + "!\nI got " + (points + 100) + " points!!!");
    }

Thanks,
Reece C.

A: You wrote this :
    while(correctAns==correctFloorAns){
        alert("hi")
    }
    {
        primaryNumber = random(200);
        primaryNumber = primaryNumber * 1;
        secondaryNumber = random(200);
        secondaryNumber = secondaryNumber * 1;
        correctAns = primaryNumber / secondaryNumber;
        correctAns = correctAns * 1;
        correctFloorAns = Math.floor(correctAns);
    }

The code in the second block { } won't be executed in the while loop, it's executed only once.
I think what you wanted to write is this :
while(correctAns==correctFloorAns){
// I advise you to comment your alert once your debug is done, it will be very annoying
        alert("hi");
        primaryNumber = random(200);
        primaryNumber = primaryNumber * 1;
        secondaryNumber = random(200);
        secondaryNumber = secondaryNumber * 1;
        correctAns = primaryNumber / secondaryNumber;
        correctAns = correctAns * 1;
        correctFloorAns = Math.floor(correctAns);
    }

Cheers

A: Thanks for your help everyone! Sadly, the scripts you gave me didn't work but I have found a solution! Here it is:
        var wrong = true
        //creates a random sum and loops until answer is a whole number bigger that 0
        while (wrong){
            primaryNumber = random(200);
            primaryNumber = (primaryNumber * 1) + 1;
            secondaryNumber = random(200);
            secondaryNumber = (secondaryNumber * 1) + 1;
            correctAns = primaryNumber / secondaryNumber;
            correctAns = correctAns * 1;
            correctFloorAns = Math.floor(correctAns);
            if(correctAns==correctFloorAns){
                wrong = false
            }
        }


text:
Q: Using AJAX to execute a PHP script through a JavaScript function I have an anchor link with no destination, but it does have an onClick event:

 Delete

I understand that I cannot directly execure PHP code blocks in JavaScript due to the nature of PHP and it being a server side language, so I have to utilize AJAX to do so.
When the delete link is clicked, I need it to execute this query (del_post.php)
<?php include("connect.php");

$delete_query = mysqli_query ($connect, "DELETE FROM user_thoughts WHERE id = 'id' ");

?>

I have tried to understand AJAX using similar past questions, but due to being relatively new, I cannot completely grasp it's language. Here is what I have tried:
 function deletePost() {
        xmlhttp=new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
         if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
             xmlhttp.open("GET", "del_post.php", false);
             xmlhttp.send();
         }
       }
}

But clicking the link just changes the URL to http://localhost/.

A: I believe the (main) problem is your empty "href" attribute. Remove that, or change it to href="#" or old school href="javascript:void()" (just remove it, imo).
It's been a while since I used XMLHttpRequest and not something like jQuery's .ajax, but I think you need to do it like so (mostly you need to .open/send before you watch for the state change):
var xmlHttpReq = new XMLHttpRequest();
if (xmlHttpReq) {
    xmlHttpReq.open('GET', 'your-uri-here.php', true/false);
    xmlHttpReq.onreadystatechange = function () {
        if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200) {
            console.log('success! delete the post out of the DOM or some other response');
        }
        else {
            console.log('there was a problem');
        }
    }
    xmlHttpReq.send();
}

A: Can you please provide your : del_post.php file?
Normally you can show a text or alert in a

by using callback in an AJAX request :
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("yourname").innerHTML = xmlhttp.responseText;
        }

This response is coming from your PHP file for example :
function remove_record(ARG){
    if ($condition==true)
       echo "TRUE";
    else
       echo "FALSE";
}

A: You should remove href attribute from anchor tag and style the element with CSS.
Also, your script should look like this:

A: You are trying to make the http request inside the callback.
You just need to move it outside:
function deletePost() {
    var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                alert(xmlhttp.responseText);
            }
        }
        xmlhttp.open("GET", "del_post.php", false);
        xmlhttp.send();
}

Removing the href attribute will prevent the refresh. I believe that is valid in HTML5.

A: Ok... I'm just a hobbyist, so please forgive me any inaccuracies in the typing but this works: A format I use for an ajax call in an  element is:

So that I have more flexibility(in case I need to check something before I send the ajax). Now, for an ajax call you need:

*

*What file to call

*What to do with the response from the file you called

*What to do if an I/O error happens

So we have this function - not mine, leeched amongst thousands from somewhere - probably here :) -  and probably well known, my apologies to the author, he is a genius: This is what you call for the ajax thing, where 'url' is the file you want to 'ajax', 'success' is the name of the function that deals with results and error is the name of the function that deals with IO errors.
function doAjaxThing(url, success, error) {
    var req = false;
    try{
        // most browsers
        req = new XMLHttpRequest();
    } catch (e){
        // IE
        try{
            req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
             // try an older version
            try{
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
                return false;
             }
        }
    }
    if (!req) return false;
    if (typeof success != 'function') success = function () {};
    if (typeof error!= 'function') error = function () {};
    req.onreadystatechange = function(){
        if(req.readyState == 4) {
            return req.status === 200 ?
                success(req.responseText) : error(req.status);
        }
    }
    req.open("GET", url, true);
    req.send(null);
    return req;
}

You will naturally need to include the success+error functions:
function dealWithResponse(textFromURL)
{
    //textFromURL is whatever, say, a PHP you called in the URL would 'echo'
}

function ohNo()
{
    //stuff like URL not found, etc.
    alert("I/O error");
}

And now that you're armed with that, this is how you compose the real call inside the function you called at the :
function functionThatReallyCallsAjax()
{
    //there are probably many scenarios but by having this extra function,
    //you can perform any processing you might need before the call

    doAjaxThing("serverFile.php",dealWithResponse,ohNo);
}

One scenario might be when you need to pass a variable to the PHP you didn't have before. In this case, the call would become:
doAjaxThing("serverFile.php?parameter1=dogsRock",dealWithResponse,ohNo);

And now not only you have PHP sending stuff to JS, you have JS sending to PHP too. Weeeee...
Final words: ajax is not a language, its a javascript 'trick'. You don't need to fully understand what the first 'doAjaxThing' function does to use this, just make sure you are calling it properly. It will automatically 'call' the 'deal WithResponse' function once the response from the server arrives. Notice that you can continue doing your business (asynchronous - process not time-tied) till the response arrives - which is when the  'deal WithResponse' gets triggered -, as opposed to having a page stop and wait (synchronous - time tied) until a response arrives. That is the magic of ajax (Asynchronous JAvascript and Xml).
In your case you want to add the echo("success") - or error! - in the PHP, so that the function 'dealWithResponse' knows what to do based on that info.
That's all I know about ajax. Hope this helps :)


text:
Q: Passing an array of undefined size to a subroutine I am trying to pass an array of unspecified size to a subroutine like so
PROGRAM GOL
IMPLICIT NONE

INTEGER, PARAMETER :: size_x = 16, size_y = 16
LOGICAL, DIMENSION(1:size_x,1:size_y) :: universe
universe(:,:) = .FALSE.

CALL COUNT_NEIGHBOURS(universe, 1, 1)

END PROGRAM GOL

SUBROUTINE COUNT_NEIGHBOURS (universe, x, y)
LOGICAL, DIMENSION(:,:) :: universe
INTEGER :: x,y

!test
universe(x,y) = .TRUE.

RETURN
END SUBROUTINE COUNT_NEIGHBOURS

However I get the error from gfortran
CALL COUNT_NEIGHBOURS(universe, 1, 1)
                     1
Error: Procedure 'count_neighbours' at (1) with assumed-shape dummy argument 'universe' must have an explicit interface

What is the correct way to do this?

A: As described in the error message the compiler needs the explicit interface for your callable procedure. This answer shows three ways how to provide an interface. In most cases the preferred way to put the procedure in a module or make it a contained procedure, but sometimes it's easier to use the interface block (in the code below) when, for example, you need to update some old code.
PROGRAM GOL
IMPLICIT NONE

interface
    subroutine COUNT_NEIGHBOURS(universe, x, y)
        logical :: universe(:,:)
        integer :: x, y
    end subroutine COUNT_NEIGHBOURS
end interface

INTEGER, PARAMETER :: size_x = 16, size_y = 16
LOGICAL, DIMENSION(1:size_x,1:size_y) :: universe
universe(:,:) = .FALSE.

CALL COUNT_NEIGHBOURS(universe, 1, 1)

END PROGRAM GOL

SUBROUTINE COUNT_NEIGHBOURS (universe, x, y)
LOGICAL :: universe(:,:)
INTEGER :: x,y

!test
universe(x,y) = .TRUE.

RETURN
END SUBROUTINE COUNT_NEIGHBOURS


text:
Q: Rectangle is divided into 14 identical smaller rectangles of width $x$. What is its perimeter in terms of $x$? Rectangle region ABCD show in below partitioned into 14 identical small rectangles, each of which has width x.
What is perimeter of ABCD in terms of x?

I have used rectangle perimeter formula but answer getting wrong . what is method to find answer in shortest way ?

A: If each small rectangle has width $x$, then we can see that the length of the small rectangles is 7 widths of the small rectangle, thus $7x$. Therefore, sides $AP$, $DQ$ and $BC$ have length $7x$. Finally, $AD$, $QC$, and $PB$ have length $7x$. Thus, we have six sides with length $7x$, so the perimeter has length $6\cdot 7x = 42x$.


text:
Q: Best Approach to Get Country Code by Country Name (in Japanese text) I know how to get country codes by using Country Name (english) but my task needed to get the country code using a country name that is translated in Japanese text. Example for Indonesia:
Country : インドネシア
Code : ID
Right now, I made an array list of countries (in jp) with the code but it's too manual and needed to add the all other countries possible. I am thinking if there are still other way to do it.
private function getCountryCode($countryName)
    {
        $list = [
            ['value' => 'インドネシア', 'code' => 'ID'],
            ['value' => 'カンボジア', 'code' => 'KH'],
            ['value' => 'ベトナム', 'code' => 'VN'],
            ['value' => 'アフガニスタン', 'code' => 'AF']
        ];

        if($countryName){
            foreach($list as $l){
                if($l['value'] == $countryName){
                    return $l['code'];
                }
            }

            return '';
        }

    }

A: I just found the answer to my question and this might also be useful for others. I used below code to get the translated list of countries in Japanese
$locale = new \Zend_Locale('ja_JP');
$countries = $locale->getTranslationList('Territory', $locale->getLanguage(), 2);


text:
Q: React Native: require() with Dynamic String? I have read several posts about issues that people are having with React Native and the require() function when trying to require a dynamic resource such as:
Dynamic (fails):
urlName = "sampleData.json";
data = require('../' + urlName);

vs. Static (succeeds):
data = require('../sampleData.json');

I have read on some threads that this is a bug in React Native and in others that this is a feature.
Is there a new way to require a dynamic resource within a function?
Related Posts (all fairly old in React time):

*

*Importing Text from local json file in React native

*React Native - Dynamically List/Require Files In Directory

*React Native - Image Require Module using Dynamic Names

*React Native: how to use require(path) with dynamic urls?

A: As i have heard of, react's require() only uses static url not variables, that means that you have to do require('/path/file'), take a look at this issue on github and this one for more alternative solutions, there are a couple of other ways to do it!
for e.g
const images = {
profile: {
    profile: require('./profile/profile.png'),
    comments: require('./profile/comments.png'),
},
   image1: require('./image1.jpg'),
   image2: require('./image2.jpg'),
};

export default images;

then
import Images from './img/index';

render() {
    <Image source={Images.profile.comments} />
}

from this answer

A: For anyone reading this that cannot work with the existing answers, I have an alternative.
First I'll explain my scenario.  We have a mono repo with a number of packages (large react-native app).  I want to dynamically import a bunch of locale files for i18n without having to keep a central registry in some magic file. There could be a number of teams working in the same monorepo and the DX we want is for package developers to be able to just add their local files in a known folder {{packageName}}/locales/en.json and have our core i18n functionality pick up their strings.
After several less than ideal solutions, I finally landed on https://github.com/kentcdodds/babel-plugin-preval as an ideal solution for us.  This is how I did it:
const packageEnFiles = preval`
  const fs = require('fs');
  const path = require('path');

  const paths = [];

  const pathToPackages = path.join(__dirname, '../../../../packages/');
fs.readdirSync(pathToPackages)
    .filter(name => fs.lstatSync(path.join(pathToPackages, name)).isDirectory())
    .forEach(dir => {
      if (fs.readdirSync(path.join(pathToPackages, dir)).find(name => name === 'locales')) {
        const rawContents = fs.readFileSync(path.join(pathToPackages, dir, 'locales/en.json'), 'utf8');
        paths.push({
          name: dir,
          contents: JSON.parse(rawContents),
        });
      }
    });

  module.exports = paths;
`;

Then I can just iterate over this list and add the local files to i18next:
packageEnFiles.forEach(file => {
  i18n.addResourceBundle('en', file.name, file.contents);
});

A: If you need to switch between multiple locally stored images, you can also use this way:
        var titleImg;
        var textColor;
        switch (this.props.data.title) {
        case 'Футбол':
            titleImg = require('../res/soccer.png');
            textColor = '#76a963';
            break;
        case 'Баскетбол':
            titleImg = require('../res/basketball.png');
            textColor = '#d47b19';
            break;
        case 'Хоккей':
            titleImg = require('../res/hockey.png');
            textColor = '#3381d0';
            break;
        case 'Теннис':
            titleImg = require('../res/tennis.png');
            textColor = '#d6b031';
            break;
        }

In this snippet I change variables titleImg and textColor depending of the prop. I have put this snippet directly in render() method.

A: I have found that a dynamic path for require() works when it starts with a static string. For example require("./" + path) works, whereas require(path) doesn't.

A: Here is my solution.
Setup
File structure:
app
  |--src
    |--assets
      |--images
        |--logos
          |--small_kl_logo.png
          |--small_a1_logo.png
          |--small_kc_logo.png
          |--small_nv_logo.png
          |--small_other_logo.png

        |--index.js
    |--SearchableList.js

In index.js, I have this:
const images = {
  logos: {
    kl: require('./logos/small_kl_logo.png'),
    a1: require('./logos/small_a1_logo.png'),
    kc: require('./logos/small_kc_logo.png'),
    nv: require('./logos/small_nv_logo.png'),
    other: require('./logos/small_other_logo.png'),
  }
};

export default images;

In my SearchableList.js component, I then imported the Images component like this:
import Images from './assets/images';

I then created a new function imageSelect in my component:
imageSelect = network => {
  if (network === null) {
    return Images.logos.other;
  }

  const networkArray = {
    'KL': Images.logos.kl,
    'A1': Images.logos.a1,
    'KC': Images.logos.kc,
    'NV': Images.logos.nv,
    'Other': Images.logos.other,
  };

  return networkArray[network];
};

Then in my components render function I call this new imageSelect function to dynamically assign the desired Image based on the value in the this.state.network:
render() {
  <Image source={this.imageSelect(this.state.network)} />
}

The value passed into the imageSelect function could be any dynamic string. I just chose to have it set in the state first and then passed in.
I hope this answer helps. :)

A: Simple to dynamic images (using require)
Example array(into state)
this.state={
       newimage: require('../../../src/assets/group/kids_room.png'),
       randomImages=[
         {
            image:require('../../../src/assets/group/kids_room.png')
          },
         {
            image:require('../../../src/assets/group/kids_room2.png')
          }
        ,
         {
            image:require('../../../src/assets/group/kids_room3.png')
          }

        ]

}

Trigger image( like when press button(i select image random number betwenn 0-2))
let setImage=>(){

this.setState({newimage:this.state.randomImages[Math.floor(Math.random() * 3)];
})
}

view
<Image
        style={{  width: 30, height: 30 ,zIndex: 500 }}

        source={this.state.newimage}
      />

A: Hey lads I rounded another way to require It's ugly but works. Images dynamically. Instead of storing your URL in the state you store the entire JSX. For an example:
state = {
  image: []
};

Instead of
let imageURL = `'../assets/myImage.png'`
this.state.image = imageURL

You use
let greatImage = (<Image source={require(../assets/myImage.png)}></Image>)
this.state.image = greatImage

To render in the JSX
{this.state.image}

You can style your image in the variable too. I had to use some if statements to render some images dynamically and after break my head for 2 hours this was the way that solved my problem. Like I said It's ugly and probably wrong.

A: Are you using a module bundler like webpack?
If so, you can try require.ensure()
See: https://webpack.js.org/guides/code-splitting/#dynamic-imports

A: Reading through the docs, I've found a working answer and I'm able to use dynamic images, in the docs they refer to it as Network Images here
https://facebook.github.io/react-native/docs/images#network-images
Not sure if this can be applied to other file types, but as they list require with non image types
You would need to use the uri: call
data = {uri: urlName}

For me I got images working dynamically with this
<Image source={{uri: image}} />

A: Try the solution mentioned in this thread for Android. This solves the issue but unfortunately, it's only for android.
But make sure to run react-native run-android after every update. Else, the added images won't appear in the app.

A: This seems to work  :

const {
      messages,
    } = require(`../${dynamicPath}/messages.specific`);