text:
Q: maxheap method of heapSort with index 0 and not index 1 I have this code for heapSort which works fine. I also understand how the algorithm works when the start index is 1 and not 0. My question is that the maxheap method by itself below works for all indices greater than zero, but not at index 0. however the Sort method calls with index 0 and the array gets sorted. when index i = 0, the call to maxheap will have left=2*i=0 and right=2*i+1=1, which leads to i and left being same at 0 and right at index 1, meaning that the the root and left are same and  has only right tree. this  is confusing to me. Here is the code:
public class HeapSort
{
    private static int heapSize;

    /* Sort Function */
    public static void sort(int arr[])
    {
        heapify(arr);
        System.out.println("arrays is "+Arrays.toString(arr));
        for (int i = heapSize; i > 0; i--)
        {
            swap(arr,0, i);
            heapSize = heapSize-1;
            maxheap(arr, 0);
        }
    }

    /* Function to build a heap */
    public static void heapify(int arr[])
    {
        heapSize = arr.length-1;
        for (int i = heapSize/2; i >= 0; i--)
            maxheap(arr, i);
        System.out.println("finished maxheap");
    }

    /* Function to swap largest element in heap */
    public static void maxheap(int arr[], int i)
    {
       //heapSize = arr.length-1;// comment this out if you use sort method since `heapSize` is defined at heapfy method
        int left = 2*i ;
        int right = 2*i + 1;
        int max = i;
        if (left <= heapSize && arr[left] > arr[i])
            max = left;
        if (right <= heapSize && arr[right] > arr[max])
            max = right;
        //System.out.printf("i is %s; left is %s; right is %s; max is %s%n",i,left,right,max);
        if (max != i)
        {
            swap(arr, i, max);
            maxheap(arr, max);
        }
    }

    /* Function to swap two numbers in an array */
    public static void swap(int arr[], int i, int j)
    {
        //System.out.println("called");
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }

    /* Main method */

    public static void main(String[] args)
    {
        System.out.println("Heap Sort Test\n");
        /* Call method sort */
       int[] arr = {34,5,6,712,90};
        sort(arr);
       System.out.println("\nElements after sorting ");
       System.out.println(Arrays.toString(arr));

     /* Call method maxheap; make sure you comment in heapSize=arr.length in the method */
        int[] arr2 = {2,1,3};
        maxheap(arr2, 1);
       //maxheap(arr2,0) will not work, i.e gives same arr2 as output
        System.out.println(Arrays.toString(arr2));
    }

}

EDIT:
These two blogs uses the same code:
sanfoundry.com/java-program-implement-heap-sort,
sciencetechpedia.blogspot.com/2012/11/heap-sort-using-java.html

A: If your start index = 0 of your array, the method to calculate the left child index and the right child index should like this:
private static int getLeftCh (int index) {
    return index * 2 + 1;
}
private static int getRightCh (int index) {
    return index * 2 + 2;
}

[My Heapsort like this]

public class HeapSort {

// Heap sort the givenArray.
// Time complexity = O(nlgn).
// From max to min.
private static int getLeftCh (int index) {
    return index * 2 + 1;
}
private static int getRightCh (int index) {
    return index * 2 + 2;
}
private static void exchange (int[] givenArray, int firstIndex, int secondIndex) {
    int tempElem = givenArray[firstIndex];
    givenArray[firstIndex] = givenArray[secondIndex];
    givenArray[secondIndex] = tempElem;
}
private static void minHeapify (int[] givenArray, int size, int index) {
    int left = getLeftCh(index);
    int right = getRightCh(index);
    int minIndex = index;
    if (left < size && givenArray[left] <= givenArray[index]) minIndex = left;
    else minIndex = index;
    if (right < size && givenArray[right] < givenArray[minIndex]) minIndex = right;
    if (index != minIndex) {
        // Exchange the givenArray[index] and the givenArray[minIndex].
        exchange(givenArray, index, minIndex);
        // Do recrusion on from minIndex.
        minHeapify (givenArray, size, minIndex);
    }
}
private static void buildMinHeap (int[] givenArray) {
    int size = givenArray.length;
    for (int i = (size / 2 - 1); i >= 0; i --) {
        // Do min-heapify on the i.
        minHeapify (givenArray, size, i);
    }
}
public static void heapSortFromMaxToMin (int[] givenArray) {
    int size = givenArray.length;
    // Build the max heap.
    buildMinHeap(givenArray);

    // Do the max-heapify on the remaining part of the minheap.
    for (int i = size - 1; i >= 0; i --) {
        // Move the current first elem back to the last one among the current scope.
        exchange (givenArray, 0, size - 1);
        // Do minHeapify on the remaining part of the heap from the index = 0.
        minHeapify (givenArray, (-- size), 0);
    }
}

// Show array.
public static void showArray (int[] givenArray) {
    int size = givenArray.length;
    for (int i = 0; i < size; i ++)
        System.out.print(String.format("%-6d", givenArray[i]));
    System.out.println();
}

// Main method to test.
public static void main (String[] args) {
    // Test data: {5, 4, 8, 0, 2, -5, 8, 0}.
    int[] givenArray = {5, 4, 8, 0, 2, -5, 8, 0};

    // Test the heap sort on the givenArray, from max to min.
    heapSortFromMaxToMin (givenArray);
    showArray(givenArray);
}
}

A: When your array is 0-based, the child nodes are at (2*i)+1 and (2*i)+2.
To generalize, child nodes are at (2*i)+1-array_base and (2*i)+2-array_base.


text:
Q: c++ stucts cant be accessed outside the if statement The goal is to have the user input some movie information for two movies.
Then two functions output the movies data
The problem is when I try to use the functions outside the if statements they cant be accssed anymore.
#include <iostream>
#include <string>
using namespace std;

struct MovieData // the stuct
{
    string Title,  // required varibles
        Director;
    int yearReleased,
        runTime;

    MovieData(string TITLE, string  DIRECTOR, int YearReleased, int RunTime)  // constructors
    {
        Title = TITLE;
        Director = DIRECTOR;
        yearReleased = YearReleased;
        runTime = RunTime;
    }
    string getTitle() // getters
    { return Title; }
    string getDirector()
    { return Director; }
    int getYear()
    { return yearReleased; }
    int getLength()
    { return runTime; }
};

void printMovie1(MovieData movieprint1) // fucntion that outputs movie 1
{
    cout << "Title of movie " << movieprint1.getTitle() << endl;
    cout << "Director is " << movieprint1.getDirector()<< endl;
    cout << "Movie release year " << movieprint1.getYear()<< endl;
    cout << "Movie length " << movieprint1.getLength() << endl;
}

void printMovie2(MovieData movieprint2) // function that outputs movie 2
{
    cout << "Title of movie " << movieprint2.getTitle() << endl;
    cout << "Director is " << movieprint2.getDirector() << endl;
    cout << "Movie release year " << movieprint2.getYear() << endl;
    cout << "Movie length " << movieprint2.getLength() << endl;
}

int main()
{
    string Title, // local varibles
        Director;
    int yearReleased,
        runTime;

    for (int i = 0; i < 2; i++) // forward loop to enter movie info
    {
        cout << "Please enter the movie " << (i + 1) << " title ";
        getline(cin, Title);

        cout << "Now the director ";
        getline(cin, Director);

        cout << "What year was " << Title << " releasted ";
        cin >> yearReleased;

        cout << "Lastly the length ";
        cin >> runTime;
        cin.ignore();

        if (i == 0)
        {
            MovieData movie1(Title, Director, yearReleased, runTime);
            // I know function works when placed here
            // printMovie1(movie1);
        }
        else if (i == 1)
        {
          MovieData  movie2(Title, Director, yearReleased, runTime);
         // I know function works when placed here
          // printMovie2(movie2);
        }
    }
    // these functions now dont work
    enter code hereprintMovie1(movie1);
    printMovie2(movie2);
    return 0;
}

A: You're having a scope issue
When you write :
  if (i == 0)
        {
            MovieData movie1(Title, Director, yearReleased, runTime);
            // movie1 starts living

        } // Aaand he's dead.

Your movie1 lives only inside thoses brackets. That's exactly why you must declare movie1 in the same scope you want to print them.
Another thing, since it's c++, try looking up how class work, i think in your overall approch to the problem class would do a much better work than struct.
And by the way, why not put the function printMovie1() inside your struct ?
Oh, and you don't need 2 print function, since they do the exact same job.
Try for example to call :
printMovie1(movie1);
printMovie1(movie2);

See ? it'll be the same output. Keep up the work, you're getting close to a good thing !

A: It has to do with the scope of obects. You have declared both the objects inside their if statements. To put it simply, an object always exists only inside the immediate block (think { and }) that it is declared in.
In your case :
if (i == 0)
    {
        MovieData movie1(Title, Director, yearReleased, runTime);
        //movie1 exists only inside this if statement.
    }
  //no movie1 from here on

So yo gotta do something like :
MovieData movie1;

if (i == 0)
    {
       movie1 = MovieData(Title, Director, yearReleased, runTime);

    }
//movie1 is accessible here. yay

A: Your MovieData lives only inside the scope of the brackets. Once you exit the outer scope, you can't access it anymore.
You could fix it declaring your variable outside the scope.
    MovieData  movie; //default construction
    if (i == 0)
    {
        movie = MovieData(Title, Director, yearReleased, runTime);
        // I know function works when placed here
        // printMovie1(movie1);
    }
    else if (i == 1)
    {
      movie= MovieData(Title, Director, yearReleased, runTime);
     // I know function works when placed here
      // printMovie2(movie2);

    }
    //you can now use movie

A: C/C++ uses block-local variables. For the sake of interest, this is not universal among programming languages; R and JavaScript are notable languages that use function-local variables. In other words, in R and JavaScript, when you declare (in JavaScript) or assign (in R) a local variable, it becomes part of the function's "activation object" (in JavaScript) or "evaluation environment" (in R). Subsequently it can be accessed from anywhere inside the function, even outside the scope of the declaration/assignment that created it.
Since you're using C++, you have to be careful about your blocks. You can't declare a variable inside a block and then access it outside of the block. This is enforced by the compiler. Thus, to solve your problem, you have to move your declarations of movie1 and movie2 out of the heavily nested blocks and into the outermost block inside which those variables will be accessed. You're going to have to define a nullary constructor and assignment method to allow this to work (since you have to branch on the assignment), or alternatively you could allocate dynamically (i.e. with new) inside the if-branches, in which case you would call the constructor at that time.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to Repair Ubuntu boot I have hard disk contain Windows 7 and Ubuntu 11 so I cloned it to new one but when I replaced it no OS working just dell mark appearing then restart by itself.
In the past started up by Ubuntu menu to select Windows or Ubuntu so now how can I fix Ubuntu boot to avoid reinstall everything.
Thank you in advance.

A: This sounds like your BIOS doesn't see the disk at all. Can you check that in the BIOS POST phase the hard disk is actually recognized?

A: Make sure you are booting from the correct device. If its a grub issue, you can use an ubuntu CD to recover it.


text:
Q: Getting .map() not a function when trying to pass JSON to Vue I have created a api on my backend and have the result in JSON on http://localhost:5000/result. I figured out that I need a .js file that will handle the api and allow me to use the data in my Vue components. This is the solution I found:
import axios from 'axios';

const url = "http://localhost:5000/result";

class WeatherService {
    static getWeather() {
        return new Promise((resolve, reject) => {
            axios.get(url).then((res) => {
                try {
                    const data = res.data;
                    resolve(
                        data.map(weather => ({
                            ...weather
                        }))
                    );
                } catch (error) {
                    reject(error);
                }
            })
        })
    }
}

export default WeatherService;

My Vue component
<script>
import WeatherService from '../WeatherService';

export default {
  name: 'Result',
  data(){
    return {
      weather: [],
      error: ''
    }
  },
  async created() {
    try {
      this.weather = await WeatherService.getWeather();
    } catch (error) {
      this.error = error.message;
    }
  }
}
</script>

Once I start up both, I get data.map is not a function and am not able to utilize any of the data.
Edit: I'm realizing now that .map() is used on arrays, and I'm trying to use it on JSON data. What would be a comparable solution?
Edit 2: Json data
{
  "coord": {
    "lon": -97.7431,
    "lat": 30.2672
  },
  "weather": [
    {
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 82.15,
    "feels_like": 81.23,
    "temp_min": 80.01,
    "temp_max": 84.2,
    "pressure": 1015,
    "humidity": 37
  },
  "visibility": 10000,
  "wind": {
    "speed": 3.44,
    "deg": 0
  },
  "clouds": {
    "all": 1
  },
  "dt": 1614206313,
  "sys": {
    "type": 1,
    "id": 3344,
    "country": "US",
    "sunrise": 1614171738,
    "sunset": 1614212779
  },
  "timezone": -21600,
  "id": 4671654,
  "name": "Austin",
  "cod": 200
}

A: The data you need doesn't require any mapping, so the Axios callback should just resolve the API response as-is:
class WeatherService {
    static getWeather() {
        return new Promise((resolve, reject) => {
            axios.get(url).then((res) => {
                resolve(res.data);
            })
        })
    }
}

Note that axios.get() already returns a Promise, so you could just return that without wrapping it:
class WeatherService {
    static getWeather() {
        return axios.get(url).then(res => res.data)
    }
}


text:
Q: Is the free product $\mathbb{Z}*\mathbb{Z}/n\mathbb{Z}$ linear over $\mathbb{Z}$? Let $H:=\mathbb{Z}*\mathbb{Z}/n\mathbb{Z}=\langle p,q| q^n=1\rangle.$ I want to know if $H$ is a ($\mathbb{Z}$)linear group that is to say is there an injective homomorphism $f: H\to GL_m(\mathbb{Z})$ for $m\geq n.$
I asked the question on Math Stack Exchange (https://math.stackexchange.com/questions/1430677/is-the-free-product-mathbbz-mathbbz-n-mathbbz-a-linear-group) and Derek Holt suggested me to also ask it here.
By advance thank you.

A: The group $Z*Z/n$ is virtually free: the kernel $K$ of the projection to $Z/n$ is free of index $n$ (say by the Kurosh theorem and since each finite order element is conjugate to an element of $Z/n$). Since a free group has a faithful representation over $Z$ of degree 2, the induced representation of this representation gives a faithful representation over $Z$ of your group of degree $2n$.


text:
Q: Is there a way to prevent Clang from treating va_list as __va_list_tag? For some reason, when I declare variables and functions with va_list types in them, the Clang AST treats them as __va_list_tag internally. This is problematic since the latter is a builtin definition that isn't included in stdarg.h. Is there a way to tell Clang not to replace this?
Here's some example code:
#include <cstdarg>
typedef int (*process_args)(va_list args);
void useless_func() {
  process_args useless_fp;
}

When I replace the types of declarations with their canonical types, I get the following:
#include <cstdarg>
typedef int (*process_args)(va_list args);
void useless_func() {
  int (*useless_fp)(__va_list_tag *);
}

I'd ideally like the __va_list_tag * part to be replaced with va_list so the resulting code can be compiled as C++ code.


text:
Q: How do ARCore or ARKit produce real-time augmentations of live video? So a while back about a year ago I was interested in building my own barebones augmented reality (AR) library. My goal was to be able to take a video of something (anything really) and then be able to place augmentations (3D objects that weren't really there) in the video. So for example I might take a video of my living room and then, through this AR library/tool, I'd be able to add in maybe a 3D avatar of a monster sitting on top of my coffee table. So, knowing absolutely nothing about the subject or computer vision in general, I had settled for the following strategy:

*

*Use 3D reconstruction tools/techniques (Structure from Motion, or SfM) to build up a 3D model of everything in the video (e.g. a 3D model of my living room)

*Analyze that 3D model (really a 3D pointcloud to be exact) for flat surfaces

*Add my own logic to determine what objects (3D models such as Blender files, etc.) to place in what area of the video's 3D model (e.g. monster standing on top of the coffee table)

*The hardest part: inferring the camera orientation in each frame of the video, and then figuring out how to orient the augmentation (e.g. monster) correctly based on what the camera is pointed at, and then "merging" the augmentation's 3D model into the main video 3D model. This means that as the camera moves around my living room, the monster appears to remain standing in the same place on my coffee table. I never figured out a good solution for this but figured if I could get to this 4th step that I'd find some solution.

After several difficult weeks (computer vision is hard!) I got the following pipeline of tools to work with mixed success:

*

*I was able to feed sample frames of a video (e.g. a video taken while walking around my living room) into OpenMVG and produce a sparse pointcloud PLY file/model of it

*Then I was able to feed that PLY file into MVE and produce a dense pointcloud (again PLY file) of it

*Then I fed the dense pointcloud and the original frames into mvs-texturing to produce a textured 3D model of my video

About 30% of the time, this pipeline worked amazing! Here's the model of the front of my house. You can see my 3D front yard, my son's 3D playhouse and even kinda/sorta make out windows and doors!

About 70% of the time the pipelined failed with indecipherable errors, or produced something that looked like an abstract painting. Additionally, even with automated scripting involved, it took the tooling about 30 mins to produce the final 3D textured model...so pretty slow.

Well, looks like Google ARCode and Apple ARKit beat me to the punch! These frameworks can take live video feeds from your smartphone and accomplish exactly what I had been trying to accomplish about a year ago: real-time 3D AR. Very, very similar (but much more advanced & interactive) as Pokemon Go. Take a video of your living room, and voila, an animated monster is sitting on your coffee table, and you can interact with it. Very, very, very cool stuff.
My question
I'm jealous! Of course, Google and Apple can hire some best-in-show CV/3D recon folks, but I'm still jealous!!! I'm curious if there are any hardcore AR/CV/3D recon gurus out there that either have insider knowledge or just know the AR landscape so well that they can speak to what kind of tooling/pipeline/technology is going on behind the scenes here with ARCode or ARKit. Because I practically broke my brain trying to figure this out on my own, and I failed spectacularly.

*

*Was my strategy (explained above) ballpark-accurate, or way off base? (Again: 3D recon of video -> surface analysis -> frame-by-frame camera analysis, model merge)?

*What kind of tooling/libraries/techniques are at play here?

*How do they accomplish this in real-time whereas, if my 3D recon even worked, it took 30+ mins to be processed & generated?

Thanks in advance!

A: I understand your jealousy and as a Computer Vision engineer I have it experienced many times before :-).
The key for AR on mobile devices is the fusion of computer vision and inertial tracking (the phone's gyroscope).
Quote from Apple's ARKit docu:

ARKit uses a technique called visual-inertial odometry. This process
  combines information from the iOS device's motion sensing hardware
  with computer vision analysis of the scene visible to the device's
  camera.

Quote from Google's ARCore docu:

The visual information is combined with inertial measurements from the
  device's IMU to estimate the pose (position and orientation) of the
  camera relative to the world over time.

The problem with this approach is that you have to know every single detail about your camera and IMU sensor. They have to be calibrated and synced together. No wonder it is easier for Apple than for the common developer. And this is also the reason why Google only supports a couple of phones for the ARCore preview.


text:
Q: filter not executing on static content request I'm trying to implement making gwt apps crawlable, but the CrawlFilter isn't being executed, ever. What am I doing wrong? Is static content not subject to filters?
<web-app>
  <!-- Crawling servlet filter -->
  <filter>
    <filter-name>AjaxCrawlFilter</filter-name>
    <filter-class>com.bitdual.server.CrawlServlet</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>AjaxCrawlFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!-- Default page to serve -->
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>

</web-app>

A: Static content is served from an entirely different infrastructure (like a CDN) so I wouldn't be surprised if filters are not executed on content hosted statically.


text:
Q: Binding values to pass to a on:click callback (anchor tag) I am building a sidebar component that updates the active link when clicking on one of the sidebar items. Therefore, I need to pass down the current sidebar item object to enable its active state.
Question: how do I pass values to a callback after an on:click event? Here is how I do it on regular javascript:

//HTML

    {#each items as item}

            {item.text}

    {/each}

I have checked the API and tried to use the bind:xxxx directives without success.
I expect the code to be able to update the current active sidebar item after clicking on it.

A: You need to pass the item to your handler:

    {#each items as item}

         onItemClick(item)}
          href={item.url}
        >{item.text}

    {/each}


text:
Q: Auto mounting an SDHC card on Ubuntu during boot I have the following entry in my /etc/fstab file:
/dev/mmcblk1 /home ext3   default 0 2

Now my problem is that the device at /dev/mmcblk1 changes its location periodically. When I set up the mount on boot, it was at location /dev/mmcblk0.
Is there a way to predetermine where the dive is going to be?

A: You could mount by UUID rather than location:

*

*Run sudo blkid and note down your device's UUID. The line should look something like /dev/mmcblk1: UUID="053b91eb-19c4-4684-be81-ee758579f034" TYPE="ext3", where 053b91eb-19c4-4684-be81-ee758579f034 would be the UUID.

*Replace the location in FStab with the UUID. The FStab line should now look something like UUID=053b91eb-19c4-4684-be81-ee758579f034 /home ext3   default 0 2
Note: according to mount(8), the options field (the fourth field on the line)
should be defaults rather than default.
This should recognize your card regardless of location.

A: I'd suggest using PySDM if you aren't looking to manually edit configuration files.

PySDM is a Storage Device Manager that
  allows full customization of hard disk
  mountpoints without manually access to
  fstab. It also allows the creation of
  udev rules for dynamic configuration
  of storage devices.

In Ubuntu, it can be installed by searching the Ubuntu Software Center for "pysdm". Once installed, it is available under the System --> Administration --> Storage Device Manager.

A: You will have to write a udev rule for your device, check this article for examples, its just a one liner.


text:
Q: Want to add popup entry in Allow popup option of firefox using javascript I want to add popup blocker entry for the specific site in htmlunit webclient
we can do it manually by clicking to edit popup blocker entry option in browser but how
to do it in htmlunit
is it possible ?
if yes ......how?
I want to do this in htmlunit
Thanks

A: Ofcourse this has to be done manual, that's the whole point. The user controls the browser, not you. Why not use a lightbox with text support or something?


text:
Q: Why is drawInContext so slow here? I'm using the QuartzImage class in one of the demo projects and what I'm was trying to achieve was a simple frame display unit that basically draws an image (320x480) every 1/10th of sec. So my "frame rate" should be 10 frames per sec.
In the QuartzImage demo class, there is a drawInContext method and in this method, it's basically drawing a CGImageRef using the CGContextDrawImage(), I measured the time it took to finish complete and it's taking on average around ~200ms.
2011-03-24 11:12:33.350 QuartzDemo[3159:207] drawInContext took 0.19105 secs

-(void)drawInContext:(CGContextRef)context
{
    CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
    CGRect imageRect;
    imageRect.origin = CGPointMake(0.0, 0.0);
    imageRect.size = CGSizeMake(320.0f, 480.0f);
    CGContextDrawImage(context, imageRect, image);
    CFAbsoluteTime end = CFAbsoluteTimeGetCurrent();
    NSLog(@"drawInContext took %2.5f secs", end - start);
}

Can anyone explain why it's taking that long and if there is any other way of improving the performance? 200ms just seems much more longer than it should have taken.
UPDATES
I tried @Brad-Larson's suggestion but not seeing a lot of performance improvement.
So the updated version is I got my own class
@interface FDisplay : UIView {
    CALayer *imgFrame;
    NSInteger frameNum;
}
end

So in my Class implementation
- (id)initWithFrame:(CGRect)frame {
    ............

    frameNum = 0;
    NSString *file = [NSString stringWithFormat:@"frame%d",frameNum];
    UIImage *img = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:file ofType:@"jpg"]];
    imgFrame = [CALayer layer];
    CGFloat     nativeWidth = CGImageGetWidth(img.CGImage);
    CGFloat     nativeHeight = CGImageGetHeight(img.CGImage);
    CGRect      startFrame = CGRectMake(0.0, 0.0, nativeWidth, nativeHeight);
    imgFrame.contents = (id)img.CGImage;
    imgFrame.frame = startFrame;
    CALayer *l = [self layer];
    [l addSublayer:imgFrame];
}

I have a NSTimer going at 0.1f calling my refresh method
NSString *file = [NSString stringWithFormat:@"frame%d",frameNum];
UIImage *img = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:file ofType:@"jpg"]];
frameNum++;
if (frameNum>100)
    frameNum = 0;

[CATransaction begin];
[CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
[imgFrame setContents:(id)img.CGImage];
[CATransaction commit];
end = CFAbsoluteTimeGetCurrent();
NSLog(@"(%d)refresh took %2.5f secs", [[self subviews] count],end - start);

I think I got everything right but the frame rate is still way low,
refresh took 0.15960 secs

A: Using Quartz to draw out images is about the slowest way you could do this, due to the way that content is presented to the screen.
As a step up, you could use a UIImageView and swap out its hosting image for each frame.  An even faster approach might be to use a CALayer and set its contents property to a CGImageRef representing each image frame.  You may need to disable implicit animations using a CATransaction for this to be as fast as it can be.  If I recall, I was able to get 320x480 images to be drawn at over 15 FPS on an original iPhone using the latter method.
Finally, for optimal performance you could set up an OpenGL ES display with a rectangle that filled the screen and supply the images as textures to be rendered on that rectangle.  This would require significantly more code, but it would be extremely fast.

A: I have been porting my game from Android to iPhone and I was shocked by the performance of Quartz.
The same code on Android is 10x faster than on iPhone. I have a few DrawImages, and a bunch of line draws and beziers.
It's so slow on iOS, specially iPhone 4, where the processor struggles to keep up with the retina display resolution.
My game performed perfectly at 60fps in almost ANY android device.
I tried several approaches for rendering (always avoiding OpenGL). I started by drawing everything at every frame. Then I started rendering as much as I could before the game loop, by using UIImage's. Now I'm trying to go with CALayers. Although I can see the game at steady 60FPS on iPhone 3GS and 4S, the most I can get on the iPhone 4 is 45 FPS.


text:
Q: dynamic options for selected item in previous option list I am writing an html which should contain two select tags. to make it clear, the first select tag includes name of continents and user should choose one of them. the second select tag should dynamically shows the name of countries for the selected continent in the first select tags.
could anyone please help me to understand how I should implement it by JavaScript function? what event should be set on the first select tag? should the event be set on the options or on the select tag?

<meta cahrset="utf-8">
    <title>Java Script Question Exam</title>

    <form id="form1">

            Select your Continent

              <select id="continent" size="1" onchange='ContinentFun("country")'>
                <option>Latin America</option>
                <option>Asia</option>
                <option>Eroupa</option>
                <option>Africa</option>
              </select>

                Select Country

                    <select id="country" size="1" width="15">
                    </select>

               <input type="button" name="Send" value="Send" onclick='PrintInfo("continent","country","t1")' />

    <textarea id="t1">
    </textarea>
</form>

it now works as well as I wanted.....

A: HTML
<select id='continentSelector'>
    <option>Africa</option>
    <option>Antarctica</option>
    <option>Asia</option>
    <option>Australia</option>
    <option>Europe</option>
    <option>North America</option>
    <option>South America</option>
</select>

Javascript
var selector = document.getElementById('continentSelector');
selector.addEventListener("change",function() {
     alert(this.value); // that will alert 'Africa' / 'Europe' .. etc

     // you can do your logic for the second selector here
     // eg. getCountriesByContinent(this.value);
},false);

A: On the first select box you'll want to bind to the onchange event. Your event handler would then make an AJAX call back to the server (supplying the selected continent) which would return the list of countries (prob as JSON).
You can then use that list to populate the options of your second select box.


text:
Q: Nautilus - file does not open as admin I run an ubuntu server and I installed nautilus in gnome to get the possibility to open a textfile as administrator. But when I right-click on the file and select "open as administrator" I get prompted with the admin password - when I enter it and click "ok", nothing happens... Do I have to select a standard textedit or something like this?
Additionally is it possible to run the terminal in a window in the gnome gui?
Thanks!

A: You can use gnome-terminal or xterm package, to open virtual terminal in GUI.
About nautlius, here I found answer which should help you


text:
Q: Show decimal point number in PHP I hold decimals in a database using DECIMAL(10,5)
I would like to format these numbers according to a few rules:

*

*A zero decimal should display as 0

*Show a long decimal (no trailing zero's) with all of it's numbers

*When possible, I would like to only show up to 2 decimal places (when there are trailing zeros)

Here are some examples:

*

*The left side corresponds to how the number is stored in database.

*The right number is how I would like to display the number in my application.

0.00000 => 0
0.51231 => 0.51231
0.12000 => 0.12
0.40000 => 0.40
0.67800 => 0.678
12.10000 => 12.10

A: This will work for you:
function format($x){
    if(!(int)substr_replace($x, '', $dpos = strpos($x, '.'), 1))
        return 0;
    else
        return str_pad((rtrim($x, '0')), $dpos + 3, '0');
}

Example

A: I would utilize the number_format function in php to actually do the formatting after you determine the amount of decimal places to the number has.
Source:
http://php.net/manual/en/function.number-format.php
Example Usage:
$number = 1234.56;

// english notation (default)
$english_format_number = number_format($number);
// 1,235

// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56

$number = 1234.5678;

// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57

A: Well here's one way (I haven't tested it yet so there may be minor errors):
$pattern = '/([0-9]+)\\.{0,1}([0-9]*?)0*$/';
$subject = 12.10000;
$matches = array();
$result = preg_match ($pattern, $subject, $matches);
$number = $matches[1];
if ($matches[2] != 0) {
    $number .= '.'.$matches[2];
    if ($matches[2] < 10) {
        $number .= '0';
    }
}
echo $number;

And here's another way (probably a little faster):
$x = 1.000;
$result = (int)$x;

$trimmed = rtrim($x, 0);
if ($trimmed[strlen($trimmed) - 1] != '.') {
    if ($trimmed[strlen($trimmed) - 2] == '.') {
        $result = $trimmed.'0';
    } else {
        $result = $trimmed;
    }
}
echo $result;

A: I haven't used it myself, but theres the NumberFormatter class: http://php.net/manual/class.numberformatter.php as part of the Internationalization Functions for this stuff. Using that is a little more involved i think though.

A: I know this is an old question, but the following quick function I wrote for my own project might help someone looking for this.
function number_format_least_dp($number, $decimal_point = '.', $thousand_seperator = ','){
    if (floatval($number) == (int)$number){
        $number = number_format($number, 0, $decimal_point, $thousand_seperator);
    } else {
        $number = rtrim($number, '.0');
        $number = number_format($number, strlen(substr(strrchr($number, '.'), 1)), $decimal_point, $thousand_seperator);
    }
    return $number;
}


text:
Q: variable changing despite of copy I've written code for a sudoku-solver and chase the bugs right now. There is a function "insert" that should copy the dictionary "mglwerte" and change it. But the function changes not only the copy but the original dictionary, despite using copy at the beginning of the function. Here is the call of the function:
    print(ebene, ": 748: ", mglwerte["748"], " / 779: ", mglwerte["779"])
    sudokuneu, mglwerteneu, geklappt = insert(int(var[0]), int(var[1]), wert, sudoku, mglwerte)
    print(ebene, ": 748: ", mglwerte["748"], " / 779: ", mglwerte["779"])

And the function itself:
def insert(z,s,v,sudokualt,mglwertealt):
    sudoku = sudokualt.copy()
    mglwerte = mglwertealt.copy()
    geschafft = True
    q = 3*int((z-1)/3) + int((s-1)/3) + 1
    keyfull = str(z) + str(s) + str(q)

    if v not in mglwerte[keyfull]:
        print(v, "not in ", keyfull)
        return None, None, False

    sudoku[keyfull] = v
    mglwerte[keyfull] = {}

    for key,value in mglwerte.items():
        if len(value) > 0:
            if str(key[0]) == str(z) or str(key[1]) == str(s) or str(key[2]) == str(q):
                value.discard(v)
                mglwerte[key] = value
                if len(value) < 1:
                    geschafft = False
    return sudoku, mglwerte, geschafft

The print-statements in the first piece of code show me, that "mglwerte" is changed after the call of the function. How can I change this?


text:
Q: why do we shift bits while checking ip address I have a range of ip addresses ,and I need to check that my client which accesses my application falls in that range. I went thru few articles, and they shift bits after splitting the IP
for instance 127.0.0.1 is splitted after the '. ' and after splitting we get an array of 4 elements, and each of it is shifted
element 1 >> 24;

etc .... and summed up together to check.
May I know why we  use the shift operator here ?

A: The code should probably be something like that (I haven't run it so you might need to fix small issues like small compilation errors or overflow handling):
uint GetIpValue(uint[] values)
{
  return (values[0] << 24) +
         (values[1] << 16) +
         (values[2] << 8) +
         (values[3]);
}

This is create a uint value that is bigger if the left part of the IP is bigger, which is how IP comparison is usally defined.
You can now calculate each such IP Value to see if it's lower or bigger than another IP Value.
Example:
bool IsIpInRange(uint[] ip, uint[] ipStart, uint[] ipEnd)
{
  uint ipValue = GetIpValue(ip);
  return ipValue >= GetIpValue(ipStart) && ipValue <= GetIpValue(ipEnd);
}

A: I'm not sure exactly what you're referring to, but I would hazard a guess that you are using a mask?
i.e. If you want to check that your range is 127.XXX.XXX.XXX then your mask would be /8, meaning you're only keeping 8 bits of the 32. You would then need to shift over 24 bits so you can look at the 127.
127.0.0.1 = 0111 1111 . 0000 0000 . 0000 0000 . 0000 0001
127.0.0.1 & 255.0.0.0 = 0111 1111 . 0000 0000 . 0000 0000 . 0000 0000 = 127.0.0.0
127.0.0.1 & 255.0.0.0 >> 24 = 0111 1111 = 127

A: Each octet of an IP address is 8 bits, so the whole address is 32 bits and fits in an integer. I'm guessing they're converting the string representation of an IP address to an integer by pulling out the four octets and bit shifting them to the four words in an int

A: Just guessing here but it seems perfectly logical that since IPv4 addresses fits in integer (4 bytes both of them), checking range can be done through normal < and > operators. All you do is packing your IPv4 address in to integer (127.0.0.1 -> 0x7F000001) and check if it is in range of two previously packed edges of interval, just as if you are simply checking if 5 is in 1...10 interval.
It is also much easier to finding out if IP address you have belongs to that masked IP address you are checking against. Pack it to integer, shift both of them to the number of bits that are zeroed in mask and just compare them to each other by simple equality operation. (127.0.0.1/8 -> 0x7F000001 >> 8 -> 0x7F0000 == (0x7F000005 >> 8) <- 127.0.0.5)


text:
Q: How to Hide/Show Form Fields on Add and Edit Item Pages via Jquery I am creating an inventory application for an intranet. I used a Property Agent module & DotNetNuke application to prepare my form.
Because of many form fields; I want to hide most of the form fields by default and display them when corresponding select value is selected from related dropdowns.
I have succeed to hide/display form fields when adding a new item to Inventory; however I couldn't unhide filled form fields on product edit form. I am not skilled at Jquery so, I tried to use topics here to get desired results with no luck.
My page url for adding an item is:  intranetApp/tabid/121/personel/EditProperty/language/tr-TR/Default.aspx
[Show hide works at the page above]
My page url for editing an item is:
intranetApp/tabid/121/personel/EditProperty/kayitNo/{propertyid}/language/tr-TR/Default.aspx
[Although I want rows of filled boxes + selected items displayed; they are hidden by default and I need to switch between values of Cihaz Tipi in order to display hidden rows.
I think with your help I can adjust the script and get correct results.
      $(document).ready(function() {
      $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_5').hide(); //Varsayılan                olarak Cihaz Markası alanini sakla
      $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_6').hide(); //Varsayılan olarak Diğer Marka alanini sakla
      $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_7').hide(); //Varsayılan olarak Model alanini sakla
      $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_10').hide(); //Varsayılan olarak Anakart Markası alanini sakla
      $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_11').hide(); //Varsayılan olarak Anakart Modeli alanini sakla
      $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_12').hide(); //Varsayılan olarak Anakart Seri No alanini sakla
      $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_13').hide(); //Varsayılan olarak İşlemci markası alanini sakla
      $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_14').hide(); //Varsayılan olarak İşlemci modeli ve frekansı alanini sakla
      $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_15').hide(); //Varsayılan olarak sistemdeki ram miktarı alanini sakla
      $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_16').hide(); //Varsayılan olarak Ana Bellek Türü alanini sakla
      $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_17').hide(); //Varsayılan olarak Ana Bellek Modül Sayısı alanını sakla
      $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_18').hide(); //Varsayılan olarak Hard Disk türü alanını sakla
      $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_19').hide(); //Varsayılan olarak Hard Disk Kapasitesi alanını sakla
      $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_20').hide(); //Varsayılan olarak Hard Disk Seri No alanını sakla
      $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_21').hide(); //Varsayılan olarak Cihaza Takılı Kartlar alanını sakla
      $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_22').hide(); //Varsayılan olarak Cihaza Takılı Sürücüler alanını sakla
      $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_23').hide(); //Varsayılan olarak Monitör markası alanını sakla
      $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_24').hide(); //Varsayılan olarak Monitör tipi alanını sakla
      $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_25').hide(); //Varsayılan olarak Monitör boyutu alanını sakla
      $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_26').hide(); //Varsayılan olarak Monitör seri no alanını sakla
      $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_27').hide(); //Varsayılan olarak Yazici Renk Secimi alanini sakla
      $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_28').hide(); //Varsayılan olarak Yazicida Kulllanilan Kagit Tipi alanini sakla
      $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_29').hide(); //Varsayılan olarak Veri Iletisim Agina Baglanti Sekli alanini sakla

      $('#dnn_ctr499_Default_EditProperty_rptDetails_21_3').bind('change', function() { //Cihaz tipi alanindan yapilacak secime gore
var optionValue = $("#dnn_ctr499_Default_EditProperty_rptDetails_21_3").val();

switch (optionValue)
{
  case 'Masaüstü Bilgisayar': // Cihaz tipi listeden masaüstü bilgisayar olarak secildiginde

    $("#dnn_ctr499_Default_EditProperty_rptDetails_trItem_5").show(); //Cihaz Markası secimini goster
    $("#dnn_ctr499_Default_EditProperty_rptDetails_trItem_6").hide(); //Diğer Marka seçimini goster
    $("#dnn_ctr499_Default_EditProperty_rptDetails_trItem_7").show(); //Cihaz Modeli seçimini goster
    $("#dnn_ctr499_Default_EditProperty_rptDetails_trItem_10").show(); //Anakart Markası secimini goster
    $("#dnn_ctr499_Default_EditProperty_rptDetails_trItem_11").show(); //Anakart Modeli secimini goster
    $("#dnn_ctr499_Default_EditProperty_rptDetails_trItem_12").show(); //Anakart Seri No secimini goster
    $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_13').show(); //İşlemci Markası seçimini göster
    $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_14').show(); //İşlemci modeli ve frekansı seçimini göster
    $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_15').show(); //Sistemdeki ram miktarı alanını göster
    $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_16').show(); //Ana Bellek Türü alanını göster
    $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_17').show(); //Ana Bellek modül sayısı alanını göster
    $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_18').show(); //Hard Disk Türü alanını göster
    $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_19').show(); //Hard Disk Kapasitesi alanını göster
    $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_20').show(); //Hard Disk seri no alanını göster
    $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_21').show(); //Cihaza Takılı Kartlar alanını göster
    $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_22').show(); //Cihaza Takılı Sürücüler alanını göster
    $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_23').show(); //Monitör markası alanını göster
    $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_24').show(); //Monitör tipi alanını göster
    $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_25').show(); //Monitör boyutu alanını göster
    $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_26').show(); //Monitör seri no alanını göster

    break;
    case 'Dizüstü Bilgisayar': // Cihaz tipi listeden dizüstü bilgisayar olarak secildiginde
    $("#dnn_ctr499_Default_EditProperty_rptDetails_trItem_5").show(); //Cihaz Markası seçimini göster
    $("#dnn_ctr499_Default_EditProperty_rptDetails_trItem_6").show(); //Diğer Marka seçimini göster
    $("#dnn_ctr499_Default_EditProperty_rptDetails_trItem_7").show(); //Cihaz Modeli seçimini göster
    $("#dnn_ctr499_Default_EditProperty_rptDetails_trItem_10").hide(); //Anakart Markası secimini sakla
    $("#dnn_ctr499_Default_EditProperty_rptDetails_trItem_11").hide(); //Anakart Modeli secimini sakla
    $("#dnn_ctr499_Default_EditProperty_rptDetails_trItem_12").hide(); //Anakart Seri No secimini sakla
    $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_13').hide(); //İşlemci Markası seçimini sakla
    $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_14').hide(); //İşlemci modeli ve frekansı seçimini sakla
    $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_15').hide(); //Sistemdeki ram miktarı alanını sakla
    $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_16').hide(); //Ana Bellek Türü alanını sakla
    $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_17').hide(); //Ana Bellek modül sayısı alanını sakla
    $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_20').hide(); //Hard Disk seri no alanını sakla
    $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_23').hide(); //Monitör markası alanını sakla
    $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_24').hide(); //Monitör tipi alanını sakla
    $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_25').hide(); //Monitör boyutu alanını sakla
    $('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_26').hide(); //Monitör seri no alanını sakla

    break;
  case 'Laser Yazıcı':
  case 'Inkjet Yazıcı':
  case 'Dot Matrix Yazıcı':
    $("#dnn_ctr499_Default_EditProperty_rptDetails_trItem_27").show(); //Yazici Renk Secimi secimini goster
    $("#dnn_ctr499_Default_EditProperty_rptDetails_trItem_28").show(); //Yazicida Kulllanilan Kagit Tipi secimini goster
    $("#dnn_ctr499_Default_EditProperty_rptDetails_trItem_29").show(); //Veri Iletisim Agina Baglanti Sekli  secimini goster

  default:
    $("#dnn_ctr499_Default_EditProperty_rptDetails_trItem_10").hide();
    //$('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_11').hide();
    //$('#dnn_ctr499_Default_EditProperty_rptDetails_trItem_12').hide();
    break;
    }
    });
    });

MY HTML is located at:
https://gist.github.com/anonymous/5362300

A: One option, may not be the most robust, but will work adequately with not too many fields. You can also loop the if statement if other fields are put into an array.
Theory: Use onblur handle with if statement, then run  function and pass arguments based on answer.
If cannot add html code, use .bind() from jquery
IE

function checkValues (elementId) {
var checkThis = $(elementId).val();

if (checkThis==/*Enter what you are looking for*/) {
    $("/*SHOW THIS ID*/").show();
    //hide original form element if needed
    $(elementId).hide();
    return;
}
//repeat if statements as necessary

    alert("entry not found");
};

}


text:
Q: How to find folder id of Skydrive folder How do i find the folder id of a Skydrive folder using the folder name. Or Is it possible to delete a folder in Skydrive without its folder id.
Am using Windows Phone 8 - LiveConnectClient
-Thanks

A: I don't think there is a search API but you can do it yourself.
This code is for 5.2 SDK but you get the idea. List the folders in the root folder. If needed list the subfolders till you find the directory.
This is to list the root:
clientFolder.GetAsync("me/skydrive/files");

And to get the ids:
        foreach (IDictionary<string, object> album in data)
        {
            SkydriveAlbum albumItem = new SkydriveAlbum();
            albumItem.ID = (string)album["id"];
        }

Full code:
/// <summary>
/// Gets the root dirs from SkyDrive
/// </summary>
public void ListSkyDriveRootAlbums()
{
    List<SkydriveAlbum> albums = new List<SkydriveAlbum>();
    LiveConnectClient clientFolder = new LiveConnectClient(App.Session);
    clientFolder.GetCompleted += (sender, e) =>
    {
        if (e.Error == null)
        {
            List<object> data = (List<object>)e.Result["data"];
            foreach (IDictionary<string, object> album in data)
            {
                SkydriveAlbum albumItem = new SkydriveAlbum();
                albumItem.Title = (string)album["name"];
                albumItem.Description = (string)album["description"];
                albumItem.ID = (string)album["id"];
                albums.Add(albumItem);
            }

            if (ListAlbumsCompleted != null)
            {
                ListAlbumsCompleted(albums.ToArray(), e.Error);
            }
        }
        else if (ListAlbumsCompleted != null)
        {
            ListAlbumsCompleted(null, e.Error);
        }
    };

    clientFolder.GetAsync("me/skydrive/files");
}


text:
Q: Angular : Access variable outside of function and api call Super new to  Angular and JS, running version 10, how on earth do you get the array data after the service calls? Any tips on how to do this would be appreciated. Arrays are intact inside the calls but never outside. How can I get it so I can use the array in my html template?
// PROBLEM, as noted where undefined below.

selectScript(s_id, r_id, prompts: Prompt, scripts: Script){
  this.apiService.readScript(s_id).subscribe((scripts: Script[])=>{
    this.scripts = scripts;
   // console.log(scripts); // Array OK
  });
  this.apiService.readPrompts(r_id).subscribe((prompts: Prompt[])=>{
    this.prompts = prompts;
    //console.log(prompts); // Array OK
  });
  console.log(this.scripts); // Undefined! How to get array here?
  this.ud = true;
  this.ngOnInit();
}


text:
Q: Cannot create a breakpoint in a file using gdb gdb GNU gdb (GDB) Red Hat Enterprise Linux (7.0.1-32.el5_6.2)
g++ (GCC) 4.1.2 20080704 (Red Hat 4.1.2-50)

Compiling with the following cflags:
CFLAGS = -Wall -Wextra -Wunreachable-code -ggdb -O0

I have also tried using just -g as well, but that didn't work either.
I have a file call demo.cpp and I am trying to create a break point in that file.
My executable target is called demo_app. I run gdb using the following:
gdb demo_app

I try and create the break point
b demo.cpp:997

gdb returns the following message:
No source file named demo.cpp.
Make breakpoint pending on future shared library load? (y or [n]) n

The executable file properties:
ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), for GNU/Linux 2.6.9, dynamically linked (uses shared libs), for GNU/Linux 2.6.9, not stripped

However, I have another file called video.cpp and I can create break points in that file.
Many thanks for any advice,
================== UPDATE
I have done the following:
(gdb) start
Temporary breakpoint 1 at 0x804ba44
Starting program: /home/user/video_demo/demo
warning: .dynamic section for "/lib/libc.so.6" is not at the expected address
warning: difference appears to be caused by prelink, adjusting expectations
warning: .dynamic section for "/lib/libuuid.so.1" is not at the expected address
warning: difference appears to be caused by prelink, adjusting expectations
[Thread debugging using libthread_db enabled]
[New Thread 0x1ab7b90 (LWP 5123)]

(gdb) b demo.cpp:1038
No source file named demo.cpp.
Make breakpoint pending on future shared library load? (y or [n]) n

================= MAKEFILE ========
OBJECT_FILES = demo.o video.o
CFLAGS = -Wall -Wextra -Wunreachable-code -ggdb -O0
CC = g++ -m32
TARGET = demo

# Include path
INC_PATH = -I /usr/network/inc
INC_PATH+= -I sdp/inc

# Library path
LIB_PATH = -L /usr/network/lib
LIB_PATH+= -L sdp/lib

# Libraries to include
LIBS = -lnetwork -lsdpAPI -lpthread

# Linker run-time path
LDFLAGS = -Wl,-rpath=/usr/network/lib
LDFLAGS+= -Wl,-rpath=sdp/lib

$(TARGET): $(OBJECT_FILES)
    $(CC) $(CFLAGS) $(LDFLAGS) $(INC_PATH) $(OBJECT_FILES) $(LIB_PATH) $(LIBS) -o $(TARGET)

demo.o: demo.cpp video.cpp
    $(CC) $(CLFAGS) $(INC_PATH) $(LIB_PATH) $(SDP_LIB) -c demo.cpp

video.o: video.cpp
    $(CC) $(CFLAGS) $(INC_PATH) $(LIB_PATH) -c video.cpp

clean:
    rm -f $(OBJECT_FILES) $(TARGET) *~

A: There's a mistake in your makefile - CLFAGS instead of CFLAGS in the recipe for demo.o.
You should be able to catch that if you watch the output when you run make - you'll see missing compiler options when building just that one object, since CLFAGS is an empty variable.
And of course, there's something to be said for taking advantage of the built-in recipes. If you store all your options in the variables make expects by default, you won't have to rewrite recipes and have that chance for typos. For example, append $(INC_PATH) to CPPFLAGS. (And you shouldn't need to pass any linker flags to compile-only steps like you're doing.)

A: There are several possible explanations:

*

*The most likely one is that demo.o (result of compiling demo.cpp) is not linked into the final executable. This could happen if you put demo.o into an archive library, and your main.o doesn't reference any symbols from demo.o

*Your demo.o is really not built with the -ggdb flag

*There is a bug in your GCC or your GDB

To confirm or refute 1, run nm demo.o, then nm demo_app, and verify that symbols from demo.o are present in the final executable.
To confirm or refute 2, run make clean && make all > make.log 2>&1, then see what command line was actually used to build demo.o
If you can refute both 1 and 2, then 3 is the only possibility I can think of at the moment. You can use readelf -w demo_app, and see whether it has references to demo.cpp. If it does not, the bug is in GCC. If it does, the bug could be in either GCC or GDB.
EDIT: Thank you for providing the Makefile. You are building an executable called demo. You claim to debug demo_app. PEBKAC?

A: Say start as your first gdb command.  Let the program load.  Then try setting the breakpoint.  It should then not prompt you regarding future library loading.  Assuming the breakpoint is set as it should be, then do continue.


text:
Q: Вывод данных с БД MySQL У меня есть кусок кода
 $query = "SELECT id, name, lastname, bykva FROM uchenik WHERE bykva='$bykva' AND class=$class";
$result = mysql_query($query) or die(mysql_error()); $users = array();
while($row=mysql_fetch_array($result)){
    $uc = $row["lastname"] ." ". $row["name"];
    $id = $row["id"];
    $users[] = "$uc";
}

Если взять $row=mysql_fetch_array($result) без цикла и вывести, то он выводит тех учеников, которых надо. Пример:
Array ( [0] => 1 [id] => 1 [1] => Анель [name] => Анель [2] => Абылкасымова [lastname] => Абылкасымова [3] => Б [bykva] => Б )

Но вот в цикле он делает 2 массива, в 1 тех учеников, которые мне нужны, а во 2 уже остальных. И уже присваивает моему массиву $users всех учеников, а не тех которых мне нужно. Пример:
Array ( [0] => 1 [id] => 1 [1] => Анель [name] => Анель [2] => Абылкасымова [lastname] => Абылкасымова [3] => Б [bykva] => Б ) Array ( [0] => 2 [id] => 2 [1] => Мади [name] => Мади [2] => Рымкулов [lastname] => Рымкулов [3] => А [bykva] => А )

Как мне сделать, чтобы в цикле он делал только тех ученикв, которые мне нужны
A: Измените
$row=mysql_fetch_array($result)

на
$row=mysql_fetch_assoc($result)

уберите $users[] = "$uc";

P.S.
Непонятно, зачем вы в запрос передаете переменную $bykva и букву получаете запросом.
A: Правильно оформить SQL запрос, в соответствии с тем, что именно Вам нужно получить на выходе.


text:
Q: How to create multiple columns in Pandas Dataframe? I have data as you can see in the terminal. I need it to be converted to the Excel sheet format as you can see in the Excel sheet file by creating multi-levels in columns.
I researched this and reached many different things but cannot achieve my goal then, I reached "transpose", and it gave me the shape that I need but unfortunately that it did reshape from a column to a row instead where I got the wrong data ordering.
Current result:

Desired result:

What can I try next?

A: This can be done with unstack after setting player__number as index. You have to reorder the Multiindex columns and fill missing values/delete duplicates though:
import pandas as pd

data = {"player__number": [2, 10 , 2, 10, 2, 10],
        "cel1": [0, 2, 0, 1, 0, 1],
        "cel2": [0, 5, 0, 1, 0, 2],
        "cel3": [1, 3, 0, 1, 0, 1],
}

df = pd.DataFrame(data).set_index('player__number', append=True)
df = df.unstack('player__number').reorder_levels([1, 0], axis=1).sort_index(axis=1) # unstacking, reordering and sorting columns
df = df.ffill().iloc[1::2].reset_index(drop=True) # filling values and keeping only every two rows
df.to_excel('output.xlsx')

Output:

A: You can use pivot() function and reorder multi-column levels.
Before that, index/group data for repeated iterations/rounds:
data=[
    (2,0,0,1),
    (10,2,5,3),
    (2,0,0,0),
    (10,1,1,1),
    (2,0,0,0),
    (10,1,2,1),
]

columns = ["player_number", "cel1", "cel2", "cel3"]

df = pd.DataFrame(data=data, columns=columns)

df_nbr_plr = df[["player_number"]].groupby("player_number").agg(cnt=("player_number","count"))
df["round"] = list(itertools.chain.from_iterable(itertools.repeat(x, df_nbr_plr.shape[0]) for x in range(df_nbr_plr.iloc[0,0])))

[Out]:
   player_number  cel1  cel2  cel3  round
0              2     0     0     1      0
1             10     2     5     3      0
2              2     0     0     0      1
3             10     1     1     1      1
4              2     0     0     0      2
5             10     1     2     1      2

Now, pivot and reorder the colums levels:
df = df.pivot(index="round", columns="player_number").reorder_levels([1,0], axis=1).sort_index(axis=1)

[Out]:
player_number   2              10
              cel1 cel2 cel3 cel1 cel2 cel3
round
0                0    0    1    2    5    3
1                0    0    0    1    1    1
2                0    0    0    1    2    1


text:
Q: Why does running the whole file cause an error but line by line works? I want to click a hover menu option using selenium. When i run the whole file, it encounters an error stating "element is not attached to page document", but when I run the specific section that setups the proper location and that hovers (line 28-41) line by line, it has no probems hovering then clicking the desired link.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager

url = "https://usmon.com/db/index.jsp"
username = "000"
password = "000"

#Sets correct path for selinium to find chrome if chrome not in default location
options = webdriver.ChromeOptions()
options.binary_location = r"C:\Program Files\Google\Chrome Beta\Application\chrome.exe"
chrome_driver_binary = r"C:\Users\karln\.wdm\drivers\chromedriver\win32\108.0.5359\chromedriver.exe"
driver = webdriver.Chrome(chrome_driver_binary, chrome_options=options)

#launch URL
start = driver.get(url)

driver.find_element_by_id("username").send_keys(username)
driver.find_element_by_id("password").send_keys(password)

#Used xpath because element did not have a class or ID. To find xpath in chrome, inspect element, then copy html line in inspect tool, and you'll get options for which type to copy, and you can click on xpath
driver.find_element_by_xpath('//*[@id="primary-home-area"]/div[1]/div/div[2]/div[2]/form/table/tbody/tr[4]/td[2]/button').click()

#Switching view to San Antonio or it wont find my cases
#chg_vw = driver.find_element_by_xpath('//*[@id="main_Child_web_id"]').click()
san_an = driver.find_element_by_xpath('//*[@id="main_Child_web_id"]/option[1]').click()

#Identifying element to hover over
pt_records = driver.find_element_by_xpath('//*[@id="main_ui"]/li[1]/a/span[1]')

#Hover over element
hover = ActionChains(driver)
hover.move_to_element(pt_records).perform()

#Identify element to click in hover menu and click it
cl_cases = driver.find_element_by_xpath('//*[@id="main_ui"]/li[1]/ul/li[4]/a')
hover.move_to_element(cl_cases).click().perform()

I have tried to add an implicit wait times, since that was I saw recommended multiple times but to avail.


text:
Q: ORMlite connect to an existing Sqlite Table Android Is there a way to open a pre populated sqlite database using ORMLite. I am sure there is but then my next question is should I be using the following line of codes?
/**
 * This is called when the database is first created. Usually you should call createTable statements here to create
 * the tables that will store your data.
 */
@Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
    try {
        Log.i(DatabaseHelper.class.getName(), "onCreate");
        TableUtils.createTable(connectionSource, Comment.class);
        TableUtils.createTable(connectionSource , Words.class);
    } catch (SQLException e) {
        Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
        throw new RuntimeException(e);
    }

Any help would be appreciated.

A:
Is there a way to open a pre populated sqlite database using ORMLite.

To use existing databases, you will need to match your current schema precisely for it to work.  You could also increase your database version and use the onUpgrade(...) method to tweak the database to have it match your ORMLite entities.

I am sure there is but then my next question is should I be using the following line of codes?

The onCreate(...) method is called to create new tables if they don't yet exist. To open up existing database (like your subject mentions), the onCreate(...) method will not be called.


text:
Q: Deploying Application that use SWI-Prolog without installing SWI-Prolog I create a VS-Package application (.vsix) that uses SWI-Prolog inside it.
My question is: how can I deploy my VS-Package application (VS 2012) without requiring the user the run the SWI-Prolog installer? Is it possible for me to just create a folder in my client computer and copy some SWI-Prolog libraries in there?
Thanks

A: According to the docs it's a case of saving the state and passing the emulator in:

swipl -o mystate --stand_alone=true -c myload.pl

The --Options are passed to qsave_program/2, so the possible values are discussed in the link if you need more customisation. A docs example, also worth a read


text:
Q: Make global config available to react component My scenario is as follows:
I have a component <PasswordInput> that has a prop hide that toggles whether the input fields type is set to text or password.
Now I have several products defined that define for each product if that prop should be set to true|false.
/products
  /prodA
    config.js
  /prodB
    config.js
  /prodC
    config.js

Each of those config.js files would contain similar:
export default {
  FEATURES: {
    hidePasswordByDefault: true,
  }
}

// or

export default {
  FEATURES: {
    hidePasswordByDefault: false,
  }
}

With a special webpack config I alias the current compiled product via process.env so one can include the current product config via
import Product from "product/config"
Then I could, in theory, import the config in parent component that renders the <PasswordInput> component:
import Product from "product/config"

const SignIn = (props) => (
  <div>
    <PasswordInput hide={Product.FEATURES.hidePasswordByDefault}/>
  </div>
)
export default SignIn

But that seems like bad style.
Another option would be to use React context to propagate it down from a root <Product> component. But usage of context is not recommended I understood.
The last option I could think of, would be to pass down the product via props from a root Product component. But how can I make sure the prop is passed down to very last child?
Another reason why I don't want to include the product config at component level is that it could very easily create circular references in my particular webpack config.


text:
Q: Nhibernate Validation Annotation not generating valid schema I am generating schema using nhibnernate, but its not generating it is not considering the constraints:
 public class Person
    {
        public virtual int Id { get; set; }

        [NotNull]
        public virtual string name { get; set; }
    }

public class PersonMap : ClassMapping<Person>
    {
        public PersonMap()
        {
            Id(x => x.Id);
            Property(x => x.name);
        }
    }

public class PersonVal : ValidationDef<Person>
    {
        public PersonVal()
        {
            Define(x => x.name).NotNullable();
        }
    }

I am attaching the validation to configuration as follows:
    public static void SetupNHibernateValidator(Configuration config)
            {
                var nhvConfiguration = new FluentConfiguration();

                nhvConfiguration
                    .SetDefaultValidatorMode(ValidatorMode.UseAttribute)
                    .Register(Assembly.Load("ClassLibrary2").ValidationDefinitions());

                nhvConfiguration
                    .IntegrateWithNHibernate
                    .ApplyingDDLConstraints()
                    .RegisteringListeners();

                //nhvConfiguration.Register(new [] { typeof(Person) });
                nhvConfiguration.Register(new [] { typeof(PersonVal) });

                ValidationEngine = new ValidatorEngine();
                ValidationEngine.Configure(nhvConfiguration);

                ValidatorInitializer.Initialize(config, ValidationEngine);
            }

        public static ISessionFactory BuildSessionFactory()
        {
            const string ConnectionString = @"XYZ";

            _nhConfiguration = new Configuration( db =>
db.Dialect<MsSql2008Dialect>();
                db.Driver<SqlClientDriver>();
                db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                db.IsolationLevel = IsolationLevel.ReadCommitted;
                db.ConnectionString = connection;
                db.Timeout = 10;);

            ValidationProvider.SetupNHibernateValidator(_nhConfiguration);
            var mapping = GetMappings();
            _nhConfiguration.AddDeserializedMapping(mapping, "ClassLibrary2");
            return _sessionFactory = _nhConfiguration.BuildSessionFactory();
        }

and the output generated is:
create table Person (
        Id INT not null,
       name NVARCHAR(255) null,
       primary key (Id)
    )

what can be the problem??
the NAME field is still defined as NULL, it should have been NOT NULL.
Sorry guys, i know its too much code...
Thanks for help...
EDIT
i am using mapping by code
using NHibernate.Validator.Cfg.Loquacious;
    public class PersonVal : ValidationDef<Person>

using NHibernate.Mapping.ByCode.Conformist;
        public class PersonMap : ClassMapping<Person>

using NHibernate.Validator.Constraints;
            public class Person

A: The issue was with line:
Register(Assembly.Load("ClassLibrary2").ValidationDefinitions()

I have replaced it with:
Register(Assembly.Assembly.GetExecutingAssembly().ValidationDefinitions())


text:
Q: Tibco dataloss remote daemon did not satisfy our retransmission request I am having some real problems now with TIBCO RV, at the exact same time two machines reported dataloss on INBOUND. The 3rd machine, the remote daemon, did not report any unusual errors. This is happening too often, even though I've manually changed the rx/tx buffer size on network cards. I am not using CDM. Any ideas? Thanks
Machine 1
2013-01-08 12:58:21 /usr/tibco/tibrv/bin/realrvd64: TIB/Rendezvous Error: {ADV_CLASS="ERROR" ADV_SOURCE="SYSTEM" ADV_NAME="DATALOSS.INBOUND.BCAST" ADV_DESC="dataloss: remote daemon did not satisfy our retransmission request(s)" host="Machine 3" lost=3 scid=13001}
Machine 2
2013-01-08 12:58:21 /usr/tibco/tibrv/bin/realrvd64: TIB/Rendezvous Error: {ADV_CLASS="ERROR" ADV_SOURCE="SYSTEM" ADV_NAME="DATALOSS.INBOUND.BCAST" ADV_DESC="dataloss: remote daemon did not satisfy our retransmission request(s)" host="Machine 3" lost=3 scid=13001}


text:
Q: PowerDNS: setup/configuration help needed Hope some can give me some help.
I have several network storage devices (from QNAP) and a few other network device like printers and so.
I have successfully installed PowerDNS on one of the QNAP (TS-269 Pro) and want to test this DNS application and use it to RESOLVE my internal devices.
So i am looking for some guidance in how to configure PowerDNS, and have my Linux/Mac/Windows clients use this DNS, so that external and internal request will be resolved.
Thanx in advance. for any help/guidance!

A: You will likely be wanting to install PowerDNS recursor, not PowerDNS Server. The Server is for authoritative Nameservers and does not 'resolve' any domain name for you but just what you configure it to serve. The Recursor on the other hand serves that purpose but can also serve some static zones and data from /etc/hosts when given the configuration flag export-etc-hosts=yes. Its configuration file usually resides in /etc/powerdns/recursor.conf but depending on your distribution that may vary.
For general documentation please have a look at http://doc.powerdns.com/html/index.html .
For the recursor it also pays to limit max-cache-entries to a resonable value because if not set it could happily consume all available memory depending on the amount and diversity of queries received.
A few years back 1000000 entries amounted to around 700MB of memory usage (RSS) on an amd64 cpu architecture. Something like 10000 may however be sufficient for single computer personal use.


text:
Q: Double Quotes issue in VBA vbNewLine Code :
var1 = "Hello"
var2 = "Dear"
var3 = var1 & vbNewLine & var2

Sheets("sheet_name").Cells(1, 1).Value = var3

If we take cell value in text file it looks like..
"Hello
Dear"
I do not want double quotes surrounding the text.Could anyone suggest me for this issue.


text:
Q: The method 'map' was called on null. & Tried calling: map(Closure: (String) => Answer) Error:
The following NoSuchMethodError was thrown building MyApp(dirty, state: _MyAppState#ad714):

  The method 'map' was called on null.
  Receiver: null
  Tried calling: map<Answer>(Closure: (String) => Answer)

my code:
import 'package:flutter/material.dart';

import './qestion.dart';
import 'answer.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  var _questionIndex = 0;

  void _answerQuestion() {
    setState(() {
      _questionIndex = _questionIndex + 1;
    });
    print(_questionIndex);
    //print('Answer choosen');
  }

  Widget build(BuildContext context) {
    var questions = [
      {
        'questionText': 'what\'s your favorite color?',
        'answers': ['red', 'black', 'brown'],
      },
      {
        'questionText': 'what\s your favorite animal ?',
        'answers': ['lion', 'horse'],
      },
    ];

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('My First Application'),
        ),
        body: Column(
          children: [
            Question(
              questions[_questionIndex]['questionText'],
            ),

            ...(questions[_questionIndex]['answer'] as List<String>)
                    . map((answer) {
                  return Answer(_answerQuestion, answer);
                }).toList()
                [],
            // RaisedButton(
            //   child: Text('Answer 2'),
            //   onPressed: () => {print('it is a =anonymus ans')},
            // ),
          ],
        ),
      ),
    );
  }
}

Problematic part may be:
        ...(questions[_questionIndex]['answer'] as List<String>)
                . map((answer) {
              return Answer(_answerQuestion, answer);
            }).toList()

Question.dart:
import 'package:flutter/material.dart';

class Question extends StatelessWidget {
  // const Question({ Key? key }) : super(key: key);
  final String questionText;
  Question(this.questionText);

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.all(10),
      width: double.infinity,
      child: Text(
        questionText,
        style: TextStyle(fontSize: 25),
        textAlign: TextAlign.center,
      ),
    );
  }
}

Answer.dart
import 'package:flutter/material.dart';

class Answer extends StatelessWidget {
  //const Answer({ Key? key }) : super(key: key);
  final Function selectHandler;
  final String answerText;
  Answer(this.selectHandler, this.answerText);

  @override
  Widget build(BuildContext context) {
    return Container(
        width: double.infinity,
        child: RaisedButton(
          textColor: Colors.black,
          color: Colors.cyan,
          child: Text(answerText),
          onPressed: selectHandler,
        ));
  }
}

how can i solve this error in VScode editor?

A: You have typo. In place where you declare variable there is answers field, but you are accessing answer field.
Change following line and see again.
...(questions[_questionIndex]['answers'] as List<String>)
                    . map((answer) {
                  return Answer(_answerQuestion, answer);
                }).toList()

A: Let's talk about the main part, to generate Answer widgets.
questions[_questionIndex]['answers'] provides us the answers per question. and by mapping this we can generate the List<Answer> widgets. It will be long expression to handle(for me and failed), therefore I am using inline function to generate Answer widgets.
...() {
  final List<String?>? answers =
      questions[_questionIndex]['answers'] as List<String?>?;

  return answers == null
      ? [
          Text("could not find any answer"),
        ]
      : answers
          .map(
            (e) => Answer(
              selectHandler: _answerQuestion,
              answerText: e ?? "failed to get answer",
            ),
          )
          .toList();
}()

Another common issue is

Fuction can't be assing....void Function....

We can simply use VoidCallback instead of Function, else we need to use anonymous function to handle this.
Small issue like adding @override, moving data to widget level, key constructor fixed on full snippet, and I prefer and suggest using named Constructor.  You can search and learn more about those keywords.
Remember to handle range error and page navigation, I stop the _questionIndex increment  on end of list.
Run on dartPad
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  var _questionIndex = 0;
  var questions = [
    {
      'questionText': 'what\'s your favorite color?',
      'answers': ['red', 'black', 'brown'],
    },
    {
      'questionText': 'what\s your favorite animal ?',
      'answers': ['lion', 'horse'],
    },
    {
      'questionText': 'what\s your favorite animal ?',
    },
  ];
  void _answerQuestion() {
    setState(() {
      /// handle range error,
      if (_questionIndex < questions.length - 1) {
        _questionIndex += 1;
      }
    });
    print(_questionIndex);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('My First Application'),
        ),
        body: Column(
          children: [
            Question(
              questionText: questions[_questionIndex]['questionText'] as String,
            ),
            ...() {
              final List<String?>? answers =
                  questions[_questionIndex]['answers'] as List<String?>?;

              return answers == null
                  ? [
                      Text("could not find any answer"),
                    ]
                  : answers
                      .map(
                        (e) => Answer(
                          selectHandler: _answerQuestion,
                          answerText: e ?? "failed to get answer",
                        ),
                      )
                      .toList();
            }()
          ],
        ),
      ),
    );
  }
}

class Question extends StatelessWidget {
  // const Question({ Key? key }) : super(key: key);
  final String questionText;
  const Question({
    Key? key,
    required this.questionText,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.all(10),
      width: double.infinity,
      child: Text(
        questionText,
        style: const TextStyle(fontSize: 25),
        textAlign: TextAlign.center,
      ),
    );
  }
}

class Answer extends StatelessWidget {
  final VoidCallback selectHandler;
  final String answerText;

  const Answer({
    Key? key,
    required this.selectHandler,
    required this.answerText,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SizedBox(
        width: double.infinity,
        child: ElevatedButton(
          child: Text(answerText),
          onPressed: selectHandler,
        ));
  }
}


text:
Q: Firebase Admin Node.js SDK doesn't have firebase.firestore.FieldValue.increment. Should I use Firebase JavaScript SDK (Client)? My app engine is using Firebase Admin Node.js SDK to use Firebase.firestore (and other products). I want to use firebase.firestore.FieldValue.increment to implement a counter.
But it doesn't seem Firebase Admin Node.js SDK has firebase.firestore.FieldValue.increment.
Should I use Firebase Javascript Client SDK for it? If so, I have to use both Firebase Javascript Client SDK and Firebase Admin Node.js SDK. Is it OK?
I am using Node.js 8 and "firebase-admin": "^7.0.0".

A: admin.firestore.FieldValue is just an alias to this type defined in the @google-cloud/firestore package: https://cloud.google.com/nodejs/docs/reference/firestore/1.3.x/FieldValue
So anything available in that type is readily available in admin.firestore.FieldValue as well. That includes increment(). The documentation is just out of date.


text:
Q: Changing Fancy Sliding Form active tab on page load I am using Fancy Sliding Form.
(Source website: http://tympanus.net/codrops/2010/06/07/fancy-sliding-form-with-jquery/
Demo: http://tympanus.net/Tutorials/FancySlidingForm/)
I put a popup window in my second tab, there I made a postback to save my inputs from popup window but when I do this, the page refreshes and I lose the current active tab, it goes to the first tab.
I see in the js file:
    /*  current position of fieldset / navigation link    */
var current     = 1;

But how can I change the beginning tab. I want activate another tab on page load.

A: you can set javascript variable as bellow and use it for your script.
sample code with php ,
<?php
    $active_tab_from_php = 2 // you should change this, for testing you can hard code
    echo '<script> var active_tab = "'. $active_tab_from_php . '";</script>';
?>

now you can use this active_tab variable with your script as below,
var current    = active_tab;


text:
Q: getting Ceil() of Decimal in python? Is there a way to get the ceil of a high precision Decimal in python?
>>> import decimal;
>>> decimal.Decimal(800000000000000000001)/100000000000000000000
Decimal('8.00000000000000000001')
>>> math.ceil(decimal.Decimal(800000000000000000001)/100000000000000000000)
8.0

math rounds the value and returns non precise value

A: x = decimal.Decimal('8.00000000000000000000001')
with decimal.localcontext() as ctx:
    ctx.prec=100000000000000000
    ctx.rounding=decimal.ROUND_CEILING
    y = x.to_integral_exact()

A: You can do this using the precision and rounding mode option of the Context constructor.
ctx = decimal.Context(prec=1, rounding=decimal.ROUND_CEILING)
ctx.divide(decimal.Decimal(800000000000000000001), decimal.Decimal(100000000000000000000))

EDIT:  You should consider changing the accepted answer..  Although the prec can be increased as needed, to_integral_exact is a simpler solution.

A: The most direct way to take the ceiling of a Decimal instance x is to use x.to_integral_exact(rounding=ROUND_CEILING).  There's no need to mess with the context here.  Note that this sets the Inexact and Rounded flags where appropriate;  if you don't want the flags touched, use x.to_integral_value(rounding=ROUND_CEILING) instead.  Example:
>>> from decimal import Decimal, ROUND_CEILING
>>> x = Decimal('-123.456')
>>> x.to_integral_exact(rounding=ROUND_CEILING)
Decimal('-123')

Unlike most of the Decimal methods, the to_integral_exact and to_integral_value methods aren't affected by the precision of the current context, so you don't have to worry about changing precision:
>>> from decimal import getcontext
>>> getcontext().prec = 2
>>> x.to_integral_exact(rounding=ROUND_CEILING)
Decimal('-123')

By the way, in Python 3.x, math.ceil works exactly as you want it to, except that it returns an int rather than a Decimal instance.  That works because math.ceil is overloadable for custom types in Python 3.  In Python 2, math.ceil simply converts the Decimal instance to a float first, potentially losing information in the process, so you can end up with incorrect results.

A: >>> decimal.Context(rounding=decimal.ROUND_CEILING).quantize(
...   decimal.Decimal(800000000000000000001)/100000000000000000000, 0)
Decimal('9')

A: def decimal_ceil(x):
    int_x = int(x)
    if x - int_x == 0:
        return int_x
    return int_x + 1

A: Just use potency to make this.
import math
def lo_ceil(num, potency=0): # Use 0 for multiples of 1, 1 for multiples of 10, 2 for 100 ...
      n = num / (10.0 ** potency)
      c = math.ceil(n)
      return c * (10.0 ** potency)

lo_ceil(8.0000001, 1) # return 10


text:
Q: Is it possible to connect MetaMask or other wallet, to a Xamarin app? I want to sell NFT's from mobile game, based on Xamarin. I was wondering that connecting to MetaMask would be the first step. But how to do that?

A: You can search nuget package in you nuget package manager, rightclick your solution, and choose manage your nuget package, and search for the walletconnect
and install it to enable it in your project.


text:
Q: Improve the way feature requests are made and acted upon Short version:
Surface significant pending features as a first-class entity within the Stack Exchange network with mechanisms for community input and collaborative decision making.  One form this could take is a "uservoice-like" site where the items are those that have gained traction in meta or are proposed by the team (i.e., user suggestions aren't directly allowed), with related chat rooms and/or meta questions and up/down voting.
Long version:
Let me describe a scenario that I think happens too frequently on Stack Overflow.  A feature appears, seemingly out of nowhere; lots of people flock to meta to complain about the change; people who frequent meta a lot say "what are you whining about, it was discussed in question blah, blah, blah"; you navigate to question "blah, blah, blah" and you find a feature request to which @Jeff has responded (as often as not, not having the most upvotes) and, therein, you see the origin of the feature that just appeared.
From the outside two things appear clear.  First, users are genuinely surprised by new features and changed behaviors.  Second, the team is genuinely surprised that people (who care) aren't aware of these things.  I attribute this to the difference between the way normal users use meta and the way the team does.  Normal users don't spend a lot of time in meta; maybe we come here each day and browse around, but we're not driven to dive deep into the question pool and participate - if you're not on the team and you do this, you're left to draw your own conclusions about your normality :).  For team members (and mods), meta is much more important and they do use both tools and searches to dig into meta issues and to expose ideas to the meta audience.  The audience those requests finds probably depends on the time of day and, likely, the amount of attention those users give to meta (see previous aside on normality).
Additionally, feature requests are mixed in with, on meta, a vast array of other types of posts, including complaints about previous requests, support issues, bug reports, requests for features that will never see the light of day, duplicate requests for the same feature, etc.  Unless you take the time to highlight or search for feature requests AND wade through the resulting morass of responses, it's easy to miss a feature request.  If you don't log on to meta regularly, you have no chance - for one thing, features sometimes seem to appear within hours or a couple of days of the request being made.
My suggestion is to elevate feature requests into their own site, not as a regular Stack Exchange site, but one with a different mode of operation.  Once upon a time we had UserVoice and, while it worked pretty well for certain types of questions, it failed at being an all-around support site for SO.  It suffered from some the same problems I describe above.  With a few tweaks, though, such a site or something similar could be made to work better as a way to collaboratively give input on the direction of the Stack Exchange platform.  The key features that would be necessary are:

*

*An intake mechanism from a larger, freeform suggestion forum (meta)

*A winnowing process, perhaps within the team, from proposed to tentatively accepted features

*A related space to take discussion out of the way, i.e., we want it to be easy to see, navigate, and vote on the collection of tentative features

*Voting (unlimited? limited by rep?) on tentative features.  On UserVoice we had 10 chits we could hand out.  I think people ought to be able to vote up or down on each item, but I'd be open to ideas that tied the number of votes to participation.

*A means of exposing which features have been accepted.  Knowing the roadmap for implementation would be nice as well.

Additionally, there would be no ability to add items (except for the team), no editing of existing items (except for the team), no answers (just voting), and no inline comment streams (just a ballot with links to offline comments).
Exposing feature requests in this way would give people who are interested (passionate) about the direction of Stack Exchange a more convenient way of participating in its direction.  By letting users continue to propose features on meta, we don't place any artificial barriers to input.  By only putting the realistic feature requests in the tool, we make it easy to find and give input to features that might actually have a life.  Using voting (up and down) we can both provide guidance into the relative importance of said features and whether the features actually make sense, perhaps leading to more refinement.  Moving discussion completely out of the way (into chat or a related meta question), we keep the browsing and voting interface clean.

A: Short version
I certainly think that significant new features should be surfaced to the community for comments and review. That seems to not be happening lately. But I don't necessarily think we need a new website for that. All we need is a (moderator only) [feature-review] or [new-feature] tag on meta.
That said, I think there's a reluctance by the development team to surface new features until they are already completed, when any feedback on their design would be less useful.
Long version
Your question assumes that new features are actually driven by ideas from the user community. They may be, indirectly, but...
Let me make an analogy. Compare and contrast the design process of the C# language with that of the Java language. In C#'s case, you have one prominent company with a small language team led by a very smart benevolent dictator. In Java's case, you have a consortium driven by several large players in the Java space, each of which has a vote; design by committee, if you will.
Which process works better?
On the one hand, Java is arguably more "industry-standard," since it demands a high degree of consensus to get new features. But getting new features into the language takes a long time; the consensus-developing process is extremely slow, and features tend to be hobbled by compromise (e.g. generics via type erasure). As the language gets progressively more complex, the process must necessarily slow down as well, to make sure that new features are being integrated properly into the language, and all of the edge cases are being considered.
On the other hand, C# is a "defacto-standard" (although Microsoft has mitigated this by allowing the specification to be ECMA certified). Because the team that proposes and develops new features is small, and can be placed into a single room around a conference table for immediate discussion, new features get proposed and adopted rather quickly. The result is that the C# language evolves much faster than Java does.
In the early days of Stack Overflow, I believe that the process was more community-driven than it is now. But the community was much smaller then, and it consisted of early adopters: very smart people who understood the concept and were willing to put the hard work into making it successful. In that sense, it was a lot like C#; even though it was technically "design by committee," it was a small committee.
But Stack Overflow grew up, and then it became Stack Exchange, and it got some new stakeholders. Now the community is much larger, and that "design by committee" process no longer scales. As each new user comes in who doesn't understand why he can't do anything he wants on a Stack Exchange site, and how un-democratic the process seems to be, we have to (once again) explain to him that many of these decisions were made a long time ago, by community consensus, and that it is counterproductive to continue to rehash them.
In summary, I think as the community has grown, the development process for new features has shifted from Java style to C# style. Adding a "feature requests" website doesn't necessarily change that fundamental dynamic.


text:
Q: Text must be rendered within  Component While looking around at other questions, I still seemed to not be able to solve my issue. It still believes that there is text somewhere and I just need to know if I am completely overlooking something. I am new to React Native and React.js as a whole.
``
<View style={styles.body}>
  {restaurantData.length ? (
      <Text>{restaurantData.length}</Text>
   ) : null}
  {restaurantData ? (
      <View>
            {restaurantData.map((restaurant) => (
                  <Cards restaurantData={restaurant} />
            ))}
      </View>
   ) : null}
   <Button onPress={getData} title="Get Data" />
   <Divider style={{backgroundColor: 'blue'}} />;
   <Button onPress={refreshData} title="Get Next 20 Restaurants" />
</View>

``

A: there's a ';' at the end of this link. Try removing it to see if that resolves your problem. If think I would check to see if there's extra spaces around your code. Sometimes React native doesn't like trailing spaces or spaces around your tags.
<Divider style={{backgroundColor: 'blue'}} />;


text:
Q: How to delete on-demand files on onedrive for mac without having to download them first? If I delete a file from onedrive for mac with files on-demand turned on and that file has not downloaded to my computer, it has to first download it and then move it to trash. This is rather annoying and a behavior that does not exist on onedrive windows or ios version.

*

*How can I just delete that file from the remote server without having to download it on my hard drive first?

*Is this a bug or a designed behavior of Microsoft? Or the apple finder extension api just does not support this?

*Dose similar issue exist on Google Drive or Dropbox app for mac?


text:
Q: phantomjs page.sendEvent not working I'm scraping Instagram which is built with React, so i'm trying to comment on a post which will be only posted by pressing the enter key in the textarea. Which will trigger the onkeypress event of React. i have tried to trigger the keypress event with page.sendEvent but it doesn't do anything.
                    page.evaluate(function(mimicKeyPress, _$) {
                        mimicKeyPress(_$("._bilrf"), "my Comment")
                    },mimicKeyPress, _$)

                    page.sendEvent("keypress", page.event.key.ENTER)

                    setTimeout(function() {
                        page.render("a.jpg"); phantom.exit()
                    }, 5000)


text:
Q: How to get Tensorflow RNN to respect time I am trying to set up a RNN to solve a Rubik's cube from any legitimate scramble. I have generated the data the network is being trained on so I know that it is correct. I believe that I have set up both the data pipeline and the network but I have included it below just to incase. I am using tensorflow version 2.8.0 but I am willing to change version.
I set up the data pipeline as such:
def process_path(file_path):
    data_out = tf.py_function(
        func=lambda path: np.load(path.numpy().decode("utf-8")),inp=[file_path],Tout=tf.float32)
    feature = data_out[0,:,:]
    feature = tf.expand_dims(feature, axis=0)
    feature = tf.expand_dims(feature, axis=-1)
    label = data_out[1:,:,:]
    label = tf.expand_dims(label, axis=-1)
    return feature/6, label/6
r = 2
list_ds = tf.data.Dataset.list_files(str('../data/*r_'+str(r)+'_*.npy'),shuffle=False)
labeled_ds = list_ds.map(process_path)
data_dirpathname = '../data/'
data_dir = pathlib.Path(data_dirpathname)
data_count = len(list(data_dir.glob('*r_'+str(r)+'_*.npy')))
print(data_count)
val_size = int(data_count * splt)
train_ds = list_ds.skip(val_size)
val_ds = list_ds.take(val_size)
train_ds = train_ds.map(process_path)
val_ds = val_ds.map(process_path)

batch_size = 300
def configure_for_performance(ds):
    ds = ds.cache()
    ds = ds.shuffle(buffer_size=1000)
    ds = ds.batch(batch_size)
    ds = ds.prefetch(buffer_size=tf.data.AUTOTUNE)
    return ds

train_ds = configure_for_performance(train_ds)
val_ds = configure_for_performance(val_ds)

I then test that the features and labels are made correctly by ploting out the cross display of the cube using a personal function called plotCube that takes the value and turns it into the right colors.
for feature, label in labeled_ds.take(1):
    plt.figure(figsize=(90,30))
    print(feature.shape)
    one = feature[0,:,:,0]
    ax = plt.subplot(131)
    plotCube(one*6,ax)
    print(label.shape)
    for i in range(label.shape[0]):
        one = label[i,:,:,0]
        ax = plt.subplot(1,3,i+2)
        plotCube(one*6,ax)

Plot output
The output of the plot shows that the feature is the scramble of the cube and the labels are the states taken to solve it in order. This proves that the data is set up right
The network was made using the following code:
inp = layers.Input(shape=(1,9,12,1))
x = layers.Rescaling(1./6)(inp)
x = layers.ConvLSTM2D(filters=64,kernel_size=(5,5),padding="same",return_sequences=True,activation="relu",)(x)
x = layers.BatchNormalization()(x)
x = layers.ConvLSTM2D(filters=64,kernel_size=(3, 3),padding="same",return_sequences=True,activation="relu",)(x)
x = layers.BatchNormalization()(x)
x = layers.ConvLSTM2D(filters=64,kernel_size=(1, 1),padding="same",return_sequences=True,activation="relu",)(x)
x = layers.Conv3D(filters=1,kernel_size=(3, 3, 3),padding="same",activation="sigmoid",)(x)

model = keras.models.Model(inp, x)
model.compile(loss=keras.losses.binary_crossentropy, optimizer=keras.optimizers.Adam(),)

After the model is trained on 7500 data sets the prediction looks as if time is not being respected and the average of the moves is being returned. When I test the model on a data set that it has never seen before and get this result. The left column is the data set and the right column is what the model predicts. The model is given the first cube cross from the data set. Each row represents the current state, so the top row is first state and the bottom row is the last state.
frames_prediction = model.predict(np.expand_dims(np.expand_dims(data[0,0,:,:,:], axis=0), axis=0))
print(frames_prediction.shape)
fig = plt.figure(figsize=(10,data.shape[1]*10))
for i in range(data.shape[1]):
    ax = plt.subplot(data.shape[1]+4,2,i*2+1)
    plotCube(np.round(data[0,i,:,:,:]*6),ax)
    if i<(data.shape[1]-1):
        ax = plt.subplot(data.shape[1]+4,2,i*2+4)
        plotCube(np.round(frames_prediction[0,i,:,:,0]*6),ax)

It is clear to see that the output is just the average of the second and third state. I have also trained this exact model architecture on 20 moves, 10 moves, and 5 moves. All of these models give worse results than the 2 move model shown. Is there any way to force the network to respect the order that the model is trained on so the output at each state can be unique?