text:
Q: how to layout with right position i have a screen and it is

i want the buttons to put under each other and the text view under each over , my code is
<LinearLayout
                        android:id="@+id/LL1"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:gravity="center_vertical"
                        android:orientation="horizontal" >

                        <TextView
                            android:id="@+id/tvTab1Ask"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="ask for new question" />

                        <Button
                            android:id="@+id/bMainTabsGetQuestion"
                            android:layout_width="116dp"
                            android:layout_height="33dp"
                            android:text="Get Question"
                            android:textSize="15px" />
                    </LinearLayout>

                    <LinearLayout
                        android:id="@+id/LL2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:gravity="center_vertical"
                        android:orientation="horizontal" >

                        <TextView
                            android:id="@+id/tvTab1Join"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="Join New Competition" />

                        <Button
                            android:id="@+id/bMainTabsJoin"
                            android:layout_width="wrap_content"
                            android:layout_height="30dp"
                            android:text="Join"
                            android:textSize="15px" />
                    </LinearLayout>

                    <LinearLayout
                        android:id="@+id/LL3"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:gravity="center_vertical"
                        android:orientation="horizontal" >

                        <TextView
                            android:id="@+id/tvTab1Signout"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="or you can signout" />

                        <Button
                            android:id="@+id/bMainTabsSignout"
                            android:layout_width="wrap_content"
                            android:layout_height="30dp"
                            android:text="Sign out"
                            android:textSize="15px" />
                    </LinearLayout>

i mean each button have to start vertically at the same point

A: I think that when you will make it with <TableLayout> it will works how you want.

A: Try followin XML:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tableLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TableRow
        android:id="@+id/row1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="5dip"
        android:weightSum="2" >

        <TextView
            android:id="@+id/tv1"
            android:layout_column="0"
            android:text="Ask for new Question"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:layout_weight="1" />

        <Button
            android:id="@+id/btn1"
            android:text="Get Questiopn"
            android:layout_column="1"
            android:layout_weight="1" />
    </TableRow>

    <TableRow
        android:id="@+id/row2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="5dip"
        android:weightSum="2" >

        <TextView
            android:id="@+id/tv2"
            android:layout_column="0"
            android:text="Join new Competition"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:layout_weight="1" />

        <Button
            android:id="@+id/btn2"
            android:text="Join"
            android:layout_column="1"
            android:layout_weight="1" />
    </TableRow>

    <TableRow
        android:id="@+id/row3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="5dip"
        android:weightSum="2" >

        <TextView
            android:id="@+id/tv3"
            android:layout_column="0"
            android:text="Or you can Signout"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:layout_weight="1" />

        <Button
            android:id="@+id/btn3"
            android:text="Sign Out"
            android:layout_column="1"
            android:layout_weight="1" />
    </TableRow>

</TableLayout>

It is perfectly working, see followin

A: Why don't you try to change orientation to vertical(something like android:orientation="vertical") of each linear layout if you want to set the buttons and texts vertically ?

A: Use RelativeLayout instead of LinearLayout
and use parameters like android:layout_alignLeft=""
                            android:layout_alignBottom="" to align it according to your designs.


text:
Q: Receiving XML postbacks I'm a pretty seasoned PHP developer, and have integrated APIs before with platforms like PayPal and Authorize.Net after finding classes to work with... It's just that now I have to implement with limelight network's API and I have to start from scratch... Here's what I want to do after receiving a callback, posted to a PHP page I make:
Grab the XML in its raw form and send it to myself in an email so I can analyze what I'm working with.
No code yet, just an email function... the question is: how can I extract the XML from the post?  I'm sure I would need to make a handler, but I'm not certain where to start. Please advise.  Thanks!

A: Depending on your server configuration, you can usually get raw posted XML either from $HTTP_RAW_POST_DATA global or from file_get_contents('php://input');. I am not going to bother a seasoned PHP developer with the details of how to email something;)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mocha synchronous "before all" hook timeout I have a Mocha test suite that intermittently fails with the following message:
  1) "before all" hook

  0 passing (2s)
  1 failing

  1) "before all" hook:
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

The slimmed down code looks like this:
const rewiremock      = require("rewiremock").default;
const sinon           = require("sinon");

// Some more imports

let readFileSync;
let serverConfiguration;
let testingModule;

before(
  function ()
  {
    // Some mocking of the form:

    rewiremock(
      "fs"
    ).by(
      (
        mock
      ) =>
      {
        const realFs  = mock.requireActual("fs");
        readFileSync = sinon.spy(realFs, "readFileSync");

        return realFs;
      }
    );

    const originalModule = require("./path/to/my/mod");

    const fakeModule = {
      myMethod() {
        // Some behaviour-altering code and then:
        originalModule.myMethod();
      }
    };

    testingModule = rewiremock.proxy(
      "./path/to/testing/module",
      {
        "./path/to/my/mod"  : fakeHttpUiServerFactory
      }
    );

    console.log("one");

    // Some more mocking

    console.log("two");

    // Aaaand more mocking

    console.log("three");

    // Initialization of a configuration object

    serverConfiguration = {
        "nothing" : "special here"
    };

    console.log("four");
  }
);

The hook is synchronous; it does not have a done parameter (as shown), nor does the code return anything. I added some logs to try to see where the function stops before it times out, but every log is printed. It seems to execute the function just fine, but then it stops long enough for the timeout to occur.
Is there anything else I can try to add to help debug this issue when it happens? Again, this happens intermittently, so it is hard to give proper reproduction steps besides "I run this code". If the full version of the code would help, I can provide it (kind of, it is proprietary so you will see a lot of myThis and myThat, but the structure itself would remain the same).

A: Inside your before function, you can set this.timeout = xxxx and increase the time. I usually set it to 10000. There might be a better solution, but this is how I fix this issue for me.


text:
Q: "No installed components were detected" error on toggling AppBarButton visibility with Visual States In my UWP application, I am having a CommandBar with few AppBarButtons whose visibility I am toggling using Visual State. Whenever I apply any Visual State as VisualStateManager.GoToState(this, nameof(State1), false);
I get the following error:

No installed components were detected. The target object with name
'Button8' could not be resolved for a Setter.

The button (button8) is not null.
XAML:
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <CommandBar x:Name="ActionsCommandBar"
                    MaxWidth="640"
                    HorizontalAlignment="Left"
                    Background="Transparent"
                    ClosedDisplayMode="Compact"
                    DefaultLabelPosition="Right"
                    IsDynamicOverflowEnabled="True"
                    OverflowButtonVisibility="Auto"
                    Style="{StaticResource CommandBarWithoutRevealStyle}">
            <CommandBar.PrimaryCommands>
                <AppBarButton x:Name="Button1" Label="Button 1" />
                <AppBarButton x:Name="Button2" Label="Button 2" />
                <AppBarButton x:Name="Button3" Label="Button 3" />
                <AppBarButton x:Name="Button4" Label="Button 4" />
                <AppBarButton x:Name="Button5" Label="Button 5" />
                <AppBarButton x:Name="Button6" Label="Button 6" />
                <AppBarButton x:Name="Button7" Label="Button 7" />
                <AppBarButton x:Name="Button8" Label="Button 8" />
                <AppBarButton x:Name="Button9" Label="Button 9" />
            </CommandBar.PrimaryCommands>
        </CommandBar>
        <StackPanel Grid.Row="1" Orientation="Vertical" Margin="20">
            <Button Content="Visual State 1" Click="Button_Click"/>
            <Button Content="Visual State 2" Click="Button_Click1"/>
        </StackPanel>

        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="FolderStates">
                <VisualState x:Name="State1" >
                    <VisualState.Setters>
                        <Setter Target="Button1.Visibility" Value="Visible" />
                        <Setter Target="Button2.Visibility" Value="Visible" />
                        <Setter Target="Button7.Visibility" Value="Visible" />
                        <Setter Target="Button8.Visibility" Value="Visible" />
                        <Setter Target="Button9.Visibility" Value="Visible" />
                        <Setter Target="Button4.Visibility" Value="Visible" />
                    </VisualState.Setters>
                </VisualState>
                <VisualState x:Name="State2">
                    <VisualState.Setters>
                        <Setter Target="Button1.Visibility" Value="Visible" />
                        <Setter Target="Button2.Visibility" Value="Collapsed" />
                        <Setter Target="Button7.Visibility" Value="Collapsed" />
                        <Setter Target="Button8.Visibility" Value="Collapsed" />
                        <Setter Target="Button9.Visibility" Value="Collapsed" />
                        <Setter Target="Button4.Visibility" Value="Collapsed" />
                    </VisualState.Setters>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
    </Grid>

C# :
 private void Button_Click(object sender, RoutedEventArgs e)
 {
    try
    {
        VisualStateManager.GoToState(this, nameof(State1), false);
    }
    catch (Exception ex)
    {
        //No installed components were detected exception here
    }
 }

 private void Button_Click1(object sender, RoutedEventArgs e)
 {
    try
    {
        VisualStateManager.GoToState(this, nameof(State2), false);
    }
    catch (Exception ex)
    {
        //No installed components were detected exception here
    }
 }

A: I got the answer from another source. It is because when the page is rendered, Button8 is actually in OverflowFlyout. This means that Button8 is not added to the visualization tree. (The real-time visualization tree can be opened in Debug mode to confirm this).
The switching of VisualState is based on the current visual tree. If the element is not rendered, VisualState will encounter an error when switching.
So i decided to handle it in code behind.


text:
Q: How to Pass a Object to NextViewController in iOS? I am Parsing the RESTKIT Values.I am Having a Entity called EY_Connections with attributes.Just am Parsing the Values using RKMappingOperation in ViewController.m and i stored the Values of mappingOperation to object of EY_Connections.
ViewController.m
@interface NewConnectionViewController()
{
DataAccessHandler *dataAccess;
RKMappingResult *savedMappingResult;
EY_Connections *connect;
}

-(void)requestConnectionData
{
NSString *requestPath = @"user_history/consumer/data.json";
[[RKObjectManager sharedManager]
 getObjectsAtPath:requestPath
 parameters:nil
 success: ^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
     NSLog(@"result arrray us: %@",mappingResult);
     savedMappingResult = mappingResult;
     connect = ((EY_Connections *)savedMappingResult.firstObject);
 }
 failure: ^(RKObjectRequestOperation *operation, NSError *error) {
     RKLogError(@"Load failed with error: %@", error);
 }
 ];
}

If i Click a Save Button means,It should Pass All the Attribute Values of Connect Object into HomeViewController.How To pass These Values.This Is My button Action
-(IBAction)Save:(id)sender
{
//Please Update the Code To Pass the Connect Object to HomeViewController.

}

A: Link your view controllers in storyboard with segue and give that segue a name. Then:
-(IBAction)Save:(id)sender
{
    [self perfromSegueWithIdentifier:@"MySegue" sender:self];

}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Make sure your segue name in storyboard is the same as this line
    if ([[segue identifier] isEqualToString:@"MySegue"])
    {
        // Get reference to the destination view controller
        YourViewController *vc = [segue destinationViewController];

        // Pass any objects to the view controller here, like...
        [vc setMyObjectHere:object];
        // or maybe
        vc.savedMappingResult = savedMappingResult;
    }
}

Maybe your view controller is somewhere else - different storyboard:
-(IBAction)Save:(id)sender
{
    UIStoryboard * story = [UIStoryboard storyboardWithName:@"WhereIsIt" bundle:nil];
    YourViewController *vc = [story instantiateInitialViewController];
    // add values
    you could use instantiateViewControllerWithIdentifier as well
}

Since it is a bit unclear is your view controller coming after or you should save values and return to previous controller here is an implementation with delegate:
Create delegate in NewViewController.h
@protocol NewViewControllerDelegate
    -(void) saveMyData:(EY_Connections*)connections;
@end

When calling NewViewController set delegate to homeviewcontroller like so:
NewViewController *nvc = // instantiate it somehow
nvc.delegate = self;

Then in HomeViewController implement this method for saving:
-(void) saveMyData:(EY_Connections*)connections{
    // save your data here into variabels in the home view controller
}

and then, in your method call:
-(IBAction)Save:(id)sender
{
    [delegate saveMyData:connect];
}

To have it covered, you can use unwind segue as well and reuse prepare for segue we had down there.
If you are using present view controller you can:
a) use delegate as shown above
b) cast presentingViewController into HomeViewController and assign it there.
Here is explanation about delegates:
https://developer.apple.com/library/ios/documentation/General/Conceptual/CocoaEncyclopedia/DelegatesandDataSources/DelegatesandDataSources.html


text:
Q: "A non numeric value encountered" on a line with just a number I don't know what I changed but suddenly I'm getting an error on the code that worked before:

Warning: A non-numeric value encountered in C:\xampp\htdocs.apps\DeSplinterRekenen\Code\addAnswer.php on line 32

These are line 31, 32 and 33, I put the 1 in a seperate line to point out that the error is actually pointed on the 1:
header("Location: assignment.php?assign=" . $_SESSION['activeAssign'] . "&question=" . $_SESSION['activeQuestion'] +
    1
);

Why is php saying a literal 1 is non-numeric?
I've tried this and it worked, but it just seems weird I have to do it this way:
$var = $_SESSION['activeQuestion'] + 1;
header("Location: assignment.php?assign=" . $_SESSION['activeAssign'] . "&question=" . $var);
exit();

A: + and . have the same precedence, and they're left-associative. So ($a . $b + $c) is equivalent to ($a . $b) + $c, not $a . ($b + $c).
In your case, the concatenations don't produce a number, so when you try to add 1 to it, you get an error. You can use parentheses to specify the desired grouping.
header("Location: assignment.php?assign=" . $_SESSION['activeAssign'] . "&question=" . ($_SESSION['activeQuestion'] + 1));


text:
Q: How to download files to the Documents Folder in iOS 8 on iPhone/iPad? In my App I download some files and save them in the Documents Folder.
This worked under iOS 7 without any problems.
But now under iOS8 the files seam not to be saved anymore.
Here is the old method which worked unter iOS 7:
-(void)downloadMediaFile: (NSString*)url{
NSURL *fileUrl = [[NSURL alloc]initWithString:url];
NSString *theFilename = [fileUrl lastPathComponent];
NSLog(@"FILE NAME IS %@",theFilename);
NSData *mediaData = [[NSData alloc]initWithContentsOfURL:fileUrl];
NSString *resourceDocPath = [[NSString alloc]initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"]];
NSString *filePath = [resourceDocPath stringByAppendingPathComponent:theFilename];

[mediaData writeToFile:filePath atomically:YES];
NSLog(@"FINAL PATH %@",filePath);
}

I tried something different in iOS8 but without success:
NSString *resourceDocPath = [utilities applicationDocumentsDirectory];

-(NSString *)applicationDocumentsDirectory
{
NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentationDirectory inDomains:NSUserDomainMask] lastObject];
NSString *urlString = [url absoluteString];
return urlString;
}


text:
Q: Taylor Polynomials My question is this,
Compute $T_2(x)\ $ at $x=0.8$ for $y=e^x$
I have figured out at that $T_2(x)$ equals:
$$e^{0.8}+e^{0.8}(x-0.8)+\frac{e^{0.8}((x-0.8)^2)}{2}$$
The second part of the question asks to compute the error,
$\big|\ e^x\ -T_2(x)\big|$ at $ x=-0.3 $
This is where I have trouble... Can anyone offer some assistance with computing the error? Thank you!

A: By the Taylor remainder formula, the Lagrange form of the remainder gives:
$$ R_2(x) = \frac{\exp(0.3)}{6} (x-0.8)^{3}\approx 0.225(x^3-2.4x^2+1.92x-0.512)\\
\implies \boxed{R_2(x)=0.225x^3-0.54x^2+0.432x-0.1152}$$


text:
Q: Why do I get an error with ProGuard obfuscation, but not without the obfuscation? NPE - http://pastebin.com/gzuf3x1k (This comes up when I execute the obfuscated file). (StackTrace with LineNumbers: http://pastebin.com/ddY3Ei9G)
(The obfuscated stacktrace: http://pastebin.com/svipdakN)
addRefreshedVersionsListener(VersionManager.java):
public void addRefreshedVersionsListener(RefreshedVersionsListener listener){
    this.refreshedVersionsListeners.add(listener);
}

getResourceFiles(VersionManager.java):
private Set<Downloadable> getResourceFiles(Proxy proxy, File baseDirectory, CompleteVersion version)
    {
        Set result = new HashSet();
        InputStream inputStream = null;
        File assets = new File(baseDirectory, "assets");
        File objectsFolder = new File(assets, "objects");
        File indexesFolder = new File(assets, "indexes");
        String indexName = version.getAssets();
        long start = System.nanoTime();
        if (indexName == null) {
            indexName = "legacy";
        }
        File indexFile = new File(indexesFolder, indexName + ".json");
        try
        {
            URL indexUrl = new URL("https://s3.amazonaws.com/Minecraft.Download/indexes/" + indexName + ".json");
            inputStream = indexUrl.openConnection(proxy).getInputStream();
            String json = IOUtils.toString(inputStream);
            FileUtils.writeStringToFile(indexFile, json);
            AssetIndex index = (AssetIndex)this.gson.fromJson(json, AssetIndex.class);
            for (AssetIndex.AssetObject object : index.getUniqueObjects())
            {
                String filename = object.getHash().substring(0, 2) + "/" + object.getHash();
                File file = new File(objectsFolder, filename);
                if ((!file.isFile()) || (FileUtils.sizeOf(file) != object.getSize()))
                {
                    Downloadable downloadable = new AssetDownloadable(proxy, new URL("http://resources.download.minecraft.net/" + filename), file, false, object.getHash(), object.getSize());
                    downloadable.setExpectedSize(object.getSize());
                    result.add(downloadable);
                }
            }
            long end = System.nanoTime();
            long delta = end - start;
            Launcher.getInstance().println("Delta time to compare resources: " + delta / 1000000L + " ms ");
        }
        catch (IOException|JsonSyntaxException ex)
        {
            Launcher.getInstance().println("Couldn't download resources", ex);
        }
        finally
        {
            IOUtils.closeQuietly(inputStream);
        }
        return result;
    }

& The first cause [at net.minecraft.launcher.updater.VersionManager.refreshVersions(VersionManager.java)]
   public void refreshVersions() throws IOException {
      this.clearCache();
      File[] files = this.baseVersionsDir.listFiles();
      if(files != null) {
         File[] i$ = files;
         int version = files.length;

         for(int type = 0; type < version; ++type) {
            File directory = i$[type];
            String id = directory.getName();
            File jsonFile = new File(directory, id + ".json");
            if(directory.isDirectory() && jsonFile.exists()) {
               try {
                  String ex = "versions/" + id + "/" + id + ".json";
                  CompleteVersion version1 = (CompleteVersion)this.gson.fromJson(this.getContent(ex), CompleteVersion.class);
                  if(version1.getId().equals(id)) {
                     this.addVersion(version1);
                  } else if(Launcher.getInstance() != null) {
                     Launcher.getInstance().println("Ignoring: " + ex + "; it contains id: \'" + version1.getId() + "\' expected \'" + id + "\'");
                  }
               } catch (RuntimeException var10) {
                  if(Launcher.getInstance() == null) {
                     throw new JsonSyntaxException("Loading file: " + jsonFile.toString(), var10);
                  }
                  Launcher.getInstance().println("Couldn\'t load local version " + jsonFile.getAbsolutePath(), var10);
               }
            }
         }

Location of the cause on stacktrace:
CompleteVersion version1 = (CompleteVersion)this.gson.fromJson(this.getContent(ex), CompleteVersion.class);
                  if(version1.getId().equals(id)) {
                     this.addVersion(version1);
                  } else if(Launcher.getInstance() != null) {
                     Launcher.getInstance().println("Ignoring: " + ex + "; it contains id: \'" + version1.getId() + "\' expected \'" + id + "\'");
                  }

For some odd reason, this ALWAYS occurs with the fromJson method from GSON API (when executed after obfuscation).
CompleteVersion Class : http://pastebin.com/dF6aXCjS

A: I'm guessing that this is because when GSON tries to parse the JSON, it uses the property names in the CompleteVersion class. If those names are mangled, GSON won't find the property names in the JSON, so the properties will simply be null.
Another StackOverflow question appears to have several solutions to this problem. I've never used ProGuard personally, but it looks like you can try adding something like -keep class net.minecraft.launcher.versions.CompleteVersion { *; } to proguard.cfg so that the CompleteVersion class won't be touched by ProGuard.


text:
Q: Update observable list in ionic page I have just started to learn this ionic/angular. So, I have a ionic page which shows a list of observable items fetched through a service. On clicking any item, a popover is opened by passing item id to it.
This item id is used to fetch and show item details inside the popover. Lastly inside the popover, there is this submit button which updates the item status to 1.
MainPage.html
<div *ngFor="let bill of Bills$ | async">
  <ion-label>{{bill.Name}}</ion-label>
  {{bill.Description}}
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-button (click)="openBill(bill.Id)">Draft Bill</ion-button>
    </ion-buttons>
  </ion-toolbar>
</div>

MainPage.component.ts
  Bills$: Observable<Bill[]>;

  openBill(ev:any){
    console.log("Bill Id: "+ev);
    this.presentPopover(ev);
  }

  async presentPopover(ev: any) {
    const popover = await this.popoverController.create({
      component: DraftbillPage,
      componentProps: {
        "BillId": ev
      },
      cssClass: 'my-custom-class',
      event: ev,
      translucent: true
    });
    return await popover.present();
  }

  ngOnInit() {
    this.getBills();
  }

  getBills() {
    this.Bills$ = this.userService.getBills();
  }

UserService.ts
export class UserService {
  user: User;
  Bills$: Observable<Bill[]>;

  constructor() {
    this.user = new User();
    this.user.Bills = Bills;
    this.Bills$ = of(this.user.Bills);
  }

  //Method called through popover update item status from 0 to 1
  DraftBill(Id: number) {
    this.user.Bills.filter(b => b.Id == Id)[0].Status = 1;
  }

  //Method called through main page to fetch list of items with status 0
  getBills(): Observable<Bill[]> {
    return this.Bills$.pipe(
      map(bills => bills.filter(b => b.Status == 0))
    );
  }

  //Method called through popover to item details
  getBill(Id: number): Observable<Bill> {
    return this.Bills$.pipe(
      map(bills => bills.filter(b => b.Id == Id)[0])
    );
  }
}

The issue is my list in the main page is not getting updated after changing item status. I want to update my list in main page with only items having status as 0. I am not sure if my approach is correct.

A: Based on your code you do create Observable 'of' this.user.Bills initially, but then you modify the source array in this code below and not the array subscribers are getting via your Observable:
DraftBill(Id: number) {
    this.user.Bills.filter(b => b.Id == Id)[0].Status = 1;
}

Your observable is a stream of the emitted array. So your Observable<Bill[]>is not an array that's being observed by some observer, it's actually a stream of emitted Bill[] array. So you can't update the emitted value as it already has been emitted, but what you want is for your observable to emit another value, an updated array of Bills.
Seems like you need a Subject, an object that is both Observable and Observer (it inherits from both Observer and Observable interfaces). And in your specific case you might need a BehaviorSubject which emits initial value to any subscriber:
Bills$: BehaviorSubject<Bill[]> = new BehaviorSubject( here is the original array );

Now to modify its value you could:
this.Bills$.next( new array with updated values )

Now all templates subscribed to this BehaviorSubject will propagate new values.
If you could share the full code that you have at stackblitz, it should be easy to modify what you have.
So your service could be like:
import { Injectable } from '@angular/core';

import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable({ providedIn: 'root' })
export class UserService {

  user: User;
  Bills$: BehaviorSubject<any[]> = new BehaviorSubject([]);

  constructor() {
    this.user = new User();
    this.user.Bills = Bills;
    this.Bills$ = new BehaviorSubject(this.user.Bills);
  }

  DraftBill(Id: number) {
      this.user.Bills.filter(b => b.Id == Id)[0].Status = 1;
      this.Bills$.next(this.user.Bills);
  }

  getBills(): Observable<Bill[]> {
    return this.Bills$.pipe(
      map(bills => bills.filter(b => b.Status == 0))
    );
  }

  getBill(Id: number): Observable<Bill> {
    return this.Bills$.pipe(
      map(bills => bills.filter(b => b.Id == Id)[0])
    );
  }
}


text:
Q: Understanding reference counting and metaclasses I'm trying to do some things with metaclasses and I don't understand the result of this my python code.
import sys

class Meta(type):
    a = None
    b = None

    def __call__(cls, *args, **kwargs):
        name = args[0]
        if getattr(cls, name) is None:
            setattr(cls, name, super(Meta, cls).__call__(*args, **kwargs))
        return getattr(cls, name)

class A:
    __metaclass__ = Meta

    def __init__(self, name, in_a = None):
        self.a = None
        if in_a:
            self.a = in_a

a = A("a")

print sys.getrefcount(a) - 2  # 1

b = A("b", a)

print sys.getrefcount(a) - 2  # 2

b = None

print sys.getrefcount(a) - 2  # 2?

I have two reference on a, one of them is an attribute of b.
When I remove the reference b (or set to None), the count of refences on a is still 2.
Now, when I don't use metaclasses, it works well :
class A:
    def __init__(self, in_a = None):
        self.a = None
        if in_a is not None:
            self.a = in_a

a = A()

print sys.getrefcount(a) - 1  # 1

b = A(a)

print sys.getrefcount(a) - 1  # 2

b = None

print sys.getrefcount(a) - 1  # 1

Can you explain the difference?

A: With your code, b is also stored as A.b, so just setting the global b to None doesn't trigger collection of this instance - because there's still a ref to it - so the refcount stay constants. IOW, you forgot to check the refcount on b ;-)
Just add A.b = None and you will see the refcount go down.
Note that it has nothing to do with metaclasses (not sure what you're trying to do here actually but there's probably a much simpler/obvious solution).


text:
Q: False display of special characters like "TM" symbol in wordpress, when cache plugin is enabled When the WP Fastest Cache plugin is enabled it significantly improves the speed of my pages but somehow causes an error.
When I load the page the first time, the special characters like "TM" and "`" are correctly displayed. On mobile it works fine too.
However, when visiting or reloading the same page in the same browser the special characters are displayed as UTF-8 codes (as far as I know) and the "TM" symbol looks something like this: â"¢
I looked at my wp_config.php file and the charset is already UTF-8. it has something to do with the cache plugin but disabling it is not an option too since I really need the improved page speed.
Is there a way to fix the problem and let special characters display normally even after reloading the page?
Thanks in advance!
Deziox

A: Update: Found the solution myself.
Just copy the following line in your .htaccess file:
AddDefaultCharset utf-8


text:
Q: Open 10 tabs on one click I am new in Javascript. I try to open 10 new tabs with the same link but when I run the code and click on the button it opens only one tab with this url. Please tell me how to do that in js.
Here is the code:
<button
  onclick="virus()"
  type="button"
  name="button"
>Start your Magic!</button>

<script>
  function virus() {
    for(var i = 0; i < 10; i++) {
      window.open("https://www.w3schools.com/js/js_jquery_selectors.asp");
    }
  }
</script>

A: This is discussed extensively in this stackoverflow thread: Open multiple links in Chrome at once as new tabs
The long and short of it is that modern browsers don't seem to allow this.

A: First make sure you allow "Pop-ups and redirects" from chrome like the attached image.
Second try to wrap the code in a timeout like:
    for (var i = 0; i < 10; i++) {
        setTimeout(() => {
           window.open("https://www.w3schools.com/js/js_jquery_selectors.asp"  );
        }, 200);
    }

A: window.open() accepts a second parameter as windowName. So if there is no browsing context with a particular name, a new browsing context is created.
So since you haven't passed the second argument, all other window.open calls after the first one, will not create a new browsing context and won't open new windows/tabs.
So for a fix, you can try using the below code -
<button onclick="virus()" type="button" name="button"> Start your Magic!</button>
   <script>
       function virus(){
         for(var i=0;i<10;i++){
        window.open("https://www.w3schools.com/js/js_jquery_selectors.asp", i.toString());
         }
       }

I have passed a second argument as well to the window.open() which would help create a new browsing context every time the method is called.


text:
Q: Symfony: How to get request url in form extension Does it have any solution to get current url in form extension in symfony?
I've found this link, but it doesn't clear enough.
For example, i have this url "someurl/customer/update/1"
So i need to get this url, or at least, i need to get the customer_id="1" in that url.
Thanks for reading, have a good day
EDIT 1:
I'm trying to use requestStack solution, and got this error:

too few arguments to function
  MyCode\Bundle\CustomerBundle\Form\Extension\AdminCustomerUserUpdateTypeExtension::__construct(),
  0 passed in
  /home/www/g2/directo/var/cache/dev/ContainerXjfz6hz/getForm_ExtensionService.php
  on line 1502 and exactly 1 expected

Here is my code:

MyCode\Bundle\CustomerBundle\Form\Extension\AdminCustomerUserUpdateTypeExtension

class AdminCustomerUserUpdateTypeExtension extends AbstractTypeExtension
{
    protected $requestStack;

    public function __construct(RequestStack $requestStack)
    {
        $this->requestStack = $requestStack;
    }

    /**
     * {@inheritDoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $request = $this->requestStack->getCurrentRequest();
        var_dump($request); exit;
    }
}

services.yml

directo.form.extension.admin_customer_user_update_extension:
      class: Directo\Bundle\CustomerBundle\Form\Extension\AdminCustomerUserUpdateTypeExtension
      tags:
          - { name: form.type_extension, extended_type: 'Oro\Bundle\CustomerBundle\Form\Type\CustomerUserType' }

I think it has to use call some arguments into this services.yml
For example:
directo.form.extension.admin_customer_user_update_extension:
      class: Directo\Bundle\CustomerBundle\Form\Extension\AdminCustomerUserUpdateTypeExtension
arguments:
          - '@oro_customer_user.manager'
      tags:
          - { name: form.type_extension, extended_type: 'Oro\Bundle\CustomerBundle\Form\Type\CustomerUserType' }

May i know what arguments that i need to import? thanks.

A: Inject the RequestStack into your formtype like this:
protected $requestStack;

public function __construct(RequestStack $requestStack)
{
    $this->requestStack = $requestStack;
}

And to get the current request you can use this:
$request = $this->requestStack->getCurrentRequest();

You can read more about it in the symfony docs:
https://symfony.com/doc/current/service_container/request.html

A: Your referred link says you can define your form extension as a service, like that:
# config/services.yaml
services:
    App\Form\Extension\SampleTypeExtension:
        tags:
            - { name: form.type_extension }

via that definition, you are able to inject RequestStack to your service.

Not: If you are using autowiring enable than you don't need to pass it
  as an argument in your service. If not you should pass it.

Sample Form Extension:
namespace App\Form\Extension;

use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\HttpFoundation\RequestStack;

class SampleTypeExtension extends AbstractTypeExtension
{
    /** @var RequestStack */
    private $requestStack;

    public function __construct(RequestStack $requestStack) {
        $this->requestStack = $requestStack;
    }
}

You can do it what you want with $this->requestStack.
good luck.
Reference Link: https://symfony.com/doc/current/form/create_form_type_extension.html#registering-your-form-type-extension-as-a-service

A: Rather than URL, I would get the route name, more reliable, you will be able to handle many conditions more easily.
Controller
public function newAction(Request $request, ExtraFunctionService $extraFunction) {
    $route=$request->attributes->get('_route');
    $form=$this->createForm(UtilisateurType::class, $utilisateur, array(
        'action'=>$this->generateUrl($route),
        'method'=>'POST',
        'data_route'=>$route, //Send route information to form
    ));
}

FormType
public function buildForm(FormBuilderInterface $builder, array $options) {
    $dataRoute=$option['data_route'];
    $builder->add();
    if($dataRoute == 'route_name_a')) {
        $builder->add();
    } else if($dataRoute == 'route_name_b') {
        $builder->add();
    } else if($dataRoute == 'route_name_c') {
        $builder->add();
    }
}

public function configureOptions(OptionsResolver $resolver) {
    $resolver->setDefaults(array(
        'data_class'=>'AppBundle\Entity\EntityName',
        'data_route'=>null, //Set default to null in case param is not passed
    ));
}


text:
Q: How to list all undefined variables in JavaScript? Consider the following well-known situation:
var x = 1;
function f () {
  console.log(x);
  var x = 3;
  console.log(x);
}
f();

In this case the output will be:
undefined
3

So I would like to list all the 'undefined' variables that are read before they received any value. Is it possible to do somehow?

A: Maybe Resharper could help inspect undefined variable?

A: My answer gives not a program generated list of all undefined variables, but helps to detect this situation:
Use http://www.jslint.com/ or http://www.javascriptlint.com/ to analyze your program(fragment). It gives you hints about un- or wrongdeclared variables and helps you producing code of higher quality (see also  Douglas Crockford: JavaScript The Good Parts)


text:
Q: TreeMap Iterator behaviour not consistent upon removal Today when tying to discover a bug I found the TreeMap iterator behavior a little strange when removing objects. In fact has I tested different uses, in a simple example:
    TreeMap<String, String> map = new TreeMap<String, String>();
    map.put("1", "1");
    map.put("2", "2");
    map.put("3", "3");
    map.put("4", "4");
    map.put("5", "5");

    Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();

     while (iterator.hasNext()) {
        Map.Entry<String, String> entry = iterator.next();
        System.out.println("Before "+entry.getKey());
        iterator.remove();
        System.out.println("After " +entry.getKey());
    }

the result is:
Before 1
After 1
Before 2
After 2
Before 3
After 3
Before 4
After 4
Before 5
After 5

But if I change it to:
    TreeMap<String, String> map = new TreeMap<String, String>();
    map.put("1", "1");
    map.put("2", "2");
    map.put("3", "3");
    map.put("4", "4");
    map.put("5", "5");

    Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();

            String key = "4";

    while (iterator.hasNext()) {
        Map.Entry<String, String> entry = iterator.next();
        if(entry.getKey().equals(key)){
            iterator.remove();
            System.out.println(entry.getKey());
        }
    }

Then for key = 4 the result is 5 and for key = 5 the result is 5 due to the links being changed upon removal. But why are the behaviors different. JIT? Even if that is the answer, shouldn't they be uniform?

A: See the Javadoc for Map.Entry for getValue():

Returns the value corresponding to this entry. If the
  mapping has been removed from the backing map (by the iterator's
  remove operation), the results of this call are undefined.

The behaviour is undefined once you've removed the entry, hence that may explain why you are getting varying results.
NOTE: Another user, aix, posted a similar answer and I was going to comment on it, but it was deleted/removed for some reason.
EDIT: I'm not sure if this answer is correct, since I just noticed the OP was calling getKey() instead of getValue().
EDIT 2: Thanks to Ed Staub for this: I think the general idea still holds, since the Javadoc for Map.Entry states:

... more formally, the behavior of a map entry is undefined if the backing map has been modified after the entry was returned by the iterator, except through the setValue operation on the map entry.

A: To answer the question as to why this happens, the comment gives a hint
// If strictly internal, copy successor's element to p and then make p
// point to successor.

AFAIK, this is part of keeping the tree balanced.
What this means if you have only one child node (or none) the node itself is removed. If the node has two children, the node is replaced with its successor.
If you always remove from the start, that node is discarded which you can still use but it is not modified.  If you remove the right node from the middle of the tree, the entry is modified to balance the tree so using the entry after removing see the modified entry.

A: I personally wouldn't call this is a "strange" behaviour. It may just not be what you expected.
TreeMap internally implements a red-black tree. When removing a node, the tree get's rebalanced (see TreeMap.deleteEntry(Entry<K,V> p)) and there are several cases how this reblanacing is done which depend on the current tree respectively which node gets removed.


text:
Q: Rails 4 i18n on activerecord attributes I'm wondering about something with Rails 4 and i18n. I've set up some attributes like this:
en:
  activerecord:
    models:
      tutor: Tutor
    attributes:
      tutor:
        country: Country
        rate: Rate

ja:
  activerecord:
    models:
      tutor: チューター
    attributes:
      tutor:
        country: 国籍
        rate: 料金

In my view I am now doing the following:
<%= table_sort( t('activerecord.attributes.tutor.rate') ) %>

Is activerecord.attributes.tutor.rate correct or is there any shorter, better or preferred ways to translate table column names?
Cheers!

A: You can use the human_attribute_name method
Tutor.human_attribute_name :rate


text:
Q: Получение карточек после фетчинга и рендера. Как получить отрендеренные каточки? Фетчу данные, и на их основе рендерю карточки на странице.
Как мне при помощи querySelectorAll получить эти карточки после их рендера?
Вот функция запроса:
async function fetchingData(dataBase, parentSelector) {
   const res = await fetch(dataBase);
   const carsData = await res.json();
   document.querySelectorAll('.skeleton').forEach(item => item.remove());
   for (let i = 0; i < carsData.length; i++) {
      fillCard(carsData, i, parentSelector);
   }
}

Класс карточки:
class CarCard {
   constructor(src, alt, year, type, name, text, price, parentSelector) {
      this.src = src;
      this.alt = name;
      this.year = year;
      this.type = type;
      this.name = name;
      this.text = text;
      this.price = price;
      this.parentSelector = document.querySelector(parentSelector);
   }
   render() {
      const card = document.createElement('div');
      card.classList.add('catalog__item');
      card.innerHTML = `

                  ${this.year}
                  |
                  ${this.type}

                     ${this.name}

                     ${this.text}

                  <button class="catalog__item-btn btn">
                     Explore
                  </button>

                     $${this.price}

      `;
      this.parentSelector.append(card);
   }
}

Функция рендера:
function fillCard(arr, i, parentSelector) {
   new CarCard(
      arr[i].src,
      arr[i].alt,
      arr[i].year,
      arr[i].type,
      arr[i].name,
      arr[i].text,
      arr[i].price,
      parentSelector
   ).render();
}

A: Вариант в лоб, это получить коллекцию сразу после создания элементов:
document.querySelectorAll('.catalog__item');

Если нужна живая коллекция, то можно сделать так:
document.getElementsByClassName('catalog__item');

Это может быть представлено в виде:
async function fetchingData(dataBase, parentSelector) {
   const res = await fetch(dataBase);
   const carsData = await res.json();
   document.querySelectorAll('.skeleton').forEach(item => item.remove());
   for (let i = 0; i < carsData.length; i++) {
      fillCard(carsData, i, parentSelector);
   }
   return document.querySelectorAll('.catalog__item'); // или document.getElementsByClassName
}
fetchingData().then(res => { ... })

или
let elementsRender;
async function fetchingData(dataBase, parentSelector) {
   const res = await fetch(dataBase);
   const carsData = await res.json();
   document.querySelectorAll('.skeleton').forEach(item => item.remove());
   for (let i = 0; i < carsData.length; i++) {
      fillCard(carsData, i, parentSelector);
   }
   elementsRender = document.querySelectorAll('.catalog__item'); // или document.getElementsByClassName
}

Предложу еще один варимнт. Он вернет такую же коллекцию элементов в виде массива(Немного изменен код)
  class CarCard {
    constructor(src, alt, year, type, name, text, price, parentSelector) {
      this.src = src;
      this.alt = name;
      this.year = year;
      this.type = type;
      this.name = name;
      this.text = text;
      this.price = price;
      this.parentSelector = document.querySelector(parentSelector);
    }
    render() {
      const card = document.createElement('div');
      card.classList.add('catalog__item');
      card.innerHTML = `

                  ${this.year}
                  |
                  ${this.type}

                     ${this.name}

                     ${this.text}

                  <button class="catalog__item-btn btn">
                     Explore
                  </button>

                     $${this.price}

      `;
      this.parentSelector.append(card);
      return card; // Добавлен return
    }
  }

  function fillCard(element, parentSelector) { // Работаем с элементом
    new CarCard(
      element.src,
      element.alt,
      element.year,
      element.type,
      element.name,
      element.text,
      element.price,
      parentSelector
    ).render();
  }

  async function fetchingData(dataBase, parentSelector) {
    const res = await fetch(dataBase);
    const carsData = await res.json();
    document.querySelectorAll('.skeleton').forEach(item => item.remove());
    return carsData.map(item => fillCard(item, parentSelector)); // Возвращаем результат
  }

В метод render() класса добавлен return, который возвращает созданный элемент.
В функцию и конструктор класса передается сам элемент возвращенного массива, а не сам массив


text:
Q: Which VGA to use for accelerated playback? I've got 2 VGAs in my laptop. (The question would be too localised, but people often have an Intel integrated card and a similar discrete card. So my guess would be that the question will help others who seek the same answer.)

*

*Intel MHD4500

*ATI HD3650 M

Intel is said to support ALL kind of media files (source), and ATI is known to have "UVD+".
Basically I'm thinking about switching to CoreAVC.
But which card should I use? ATI or Intel?

A: To save battery power with you laptop, I would recommend the Intel VGA, if everything runs fine with the Intel, you should always use it. If you face any problems with it (videos not playing smooth or something like that), then you should change to the ATI. The video file formats which can be played do not depend on your hardware, only the capability of using hardware acceleration does.
In a nutshell you could say: Use the intel VGA (for powersaving) unless you face problems with it. There is a bit trial and error involved here.

A: Later I found out, (suprisingly) Intel got a better support for DXVA. If you install a new ffdshow codec pack for your MPC-HC for example, you'll be able to decode your HD movies with DXVA.


text:
Q: Disabling autocommit in mysql hungs out the query I have a big (~5gb) sql dump, which I need to import, but after 2-4 stack queries (~1700 queries that take 0.5 - 1.5 sec) comes a stack query which exection takes for about a minute.
When I disable autocommit (SET autocommit = 0;), then all the queries go ok, but on some point mysql just hungs out and do nothing.
That issue comes out only when I set autocommit to zero.
What can be the problem and how can I solve it?


text:
Q: I recently ran updates now the terminal doesn't see installed packages I recently ran the system updater. At the time there was 400 updates. I installed them all and everything was peachy.
A few days later it showed that I had more updates. So, wanting to avoid getting to 400 updates again, I ran them. There was only 4 and they were all related to python libs.
These were all level 3 updates and I installed them the day after they came out (6/25/13).
I am a Ruby On Rails developer and the next day I came in and was working on a project, I went to run my rails server with the command rails s and I got this message:
rails is not currently installed please run apt-get install rails to install.

I then tried to run rake, cap -f deploy(capistrano), and even ruby -v and I got the same message for all of them.
RubyMine (my IDE) still sees that ruby on rails is installed, and I can run my dev server though that.This is not ideal however so:
How do I make my terminal see my ruby on rails installation again?


text:
Q: How to Sort items by row? In each cell of my column G, i have a list of elements like this :
['element1','element2','element3',...]

In some cells i have the same list, but not ordered in the same way:
For example, in G2 i have ['element1','element2','element3'] and in G250 i have ['element3','element1','element2'].
I did a script to order each list alphabetically (to compare if they are the same), but i want it to be automatic because the values come from an import range, and data can be added every day.
So i tried a formula : =trim(substitute(concatenate(transpose(sort(transpose(split(G2,"'"))))),",","")) that works for what i'm doing with it. The result looks like this : []element1element2element3.

Lists
Ordered List with basic formula in each cell
Ordered List with arrayformula

['element1','element2','element7','element8','element55']
[]element1element2element55element7element8
#VALUE!

['element6','element5','element3','element2']
[]element2element3element5element6

['element2','element3','element6','element5']
[]element2element3element5element6

['element9','element7','element4','element88']
[]element4element7element88element9

['element4','element88','element7','element9']
[]element4element7element88element9

['element4','element8','element9']
[]element4element8element9

But i cant use arrayformula =arrayformula(trim(substitute(concatenate(transpose(sort(transpose(split(G2:G,"'"))))),",","")))
I have an error

The textual result of CONCATENATE exceeds the allowed limit, which is 50000 characters.

After some research on internet, it seems that the error come from concatenate (i tried with join, and it doesnt work either).
There isn't 50k characters in my lists so i suppose that it's trying to concatenate all the cells of my array formula.

A: SORT each row after SPLITting using BYROW and CONCATENATE:
=BYROW(G2:G7,LAMBDA(row,CONCATENATE(SORT(TRANSPOSE(SPLIT(row, "[',']"))))))

Lists
Ordered List with arrayformula

['element1','element2','element7','element8','element55']
element1element2element55element7element8

['element6','element5','element3','element2']
element2element3element5element6

['element2','element3','element6','element5']
element2element3element5element6

['element9','element7','element4','element88']
element4element7element88element9

['element4','element88','element7','element9']
element4element7element88element9

['element4','element8','element9']
element4element8element9


text:
Q: file streamer crashes unity I am trying to save data for my app I am using this code:
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/inventorySave.gd");
bf.Serialize(file, toSave);
file.Close();

I also tried this code:
StreamWriter sw = new StreamWriter(Application.persistentDataPath + "/inventorySave.txt");
sw.WriteLine(toSave);
print("wrote line" + toSave);
sw.Flush();
sw.Close();

But none of them seem to work (my unity crashes and I don't get any errors in console). Saving is called inside a for loop, and I am trying to save string with less then 8 characters the code can be found here.

A: This is what I have found somewhere in your code:
for (int i = 0; i <= numbers.Length ; i++)
            {
                print("inside while class");
                switch (int.Parse(numbers[i--].ToString()))
                {
                    case 0:
                        finalString[i--] = "a".ToString(); break;
                    case 1:
                        finalString[i--] = "b".ToString(); break;
                    case 2:
                        finalString[i--] = "c".ToString(); break;
                    case 3:
                        finalString[0] = "d".ToString(); break;
                    case 4:
                        finalString[i--] = "e".ToString(); break;
                    case 5:
                        finalString[i--] = "f".ToString(); break;
                    case 6:
                        finalString[i--] = "g".ToString(); break;
                    case 7:
                        finalString[i--] = "h".ToString(); break;
                    case 8:
                        finalString[i--] = "i".ToString(); break;
                    case 9:
                        finalString[i--] = "j".ToString(); break;
                }

                i++;

In every iteration, this is what happens to variable i:

*

*int i = 0; // in start of for loop i is "0".

*switch (int.Parse(numbers[i--].ToString()))  // i = -1 here

*finalString[i--] = "a".ToString(); break; // in any of case statement, i = -2

*i++; // i = -1 here

*i++; // i = 0 here
Hence : value of i will always be 0 and will never be greater than numbers.Length so loop will not terminate.
Hence : infinite loop -> Unity Crashes


text:
Q: Removing rows with specific text My goal is to get the combinations of values of columns. For instance,
   UT    Fruit_1 Fruit_2 Fruit_3
0  I1      Apple  Orange   Peach
1  I2      Apple   Lemon     NaN
2  I3  Starfruit   Apple  Orange

in this dataframe, I want to combine values of Fruit_* columns. So, the results are (Apple, Orange), (Apple, Peach), (Orange, Peach)...
As you can see, the dataframe has NaN. So, after the combination work, I will delete rows with specific text: 'nan'. By reading some posts related to this task, I made the below code.
import pandas as pd
import numpy as np
from itertools import combinations

df = pd.DataFrame([['I1', 'Apple', 'Orange', 'Peach'],
                   ['I2', 'Apple', 'Lemon', np.NAN],
                   ['I3', 'Starfruit', 'Apple', 'Orange']],
                  columns=['UT', 'Fruit_1', 'Fruit_2', 'Fruit_3'])

temp1 = df.set_index ('UT')
temp2 = temp1.apply (lambda x: list (combinations (x, 2)), 1)
temp3 = temp2.apply (lambda x: pd.Series (x))
temp4 = temp3.stack ().reset_index (level = [0, 1])
del temp4['level_1']
temp4.columns = ['UT', 'pair']
temp4[~temp4.pair.str.contains('nan')]

But, after running this code, I got an error message:
TypeError: ufunc 'invert' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
How to solve this error?

A: For pandas 0.25 is possible use Series.explode with trick for remove NaNs in combinations by filter out them by list comprehension with filter, it working, because np.NaN != np.NaN by definition:
df = pd.DataFrame([['I1', 'Apple', 'Orange', 'Peach'],
                   ['I2', 'Apple', 'Lemon', np.NAN],
                   ['I3', 'Starfruit', 'Apple', 'Orange']],
                  columns=['UT', 'Fruit_1', 'Fruit_2', 'Fruit_3'])

temp4 = (df.set_index ('UT')
           .apply (lambda x: list (combinations ([y for y in x if y == y], 2)), 1)
           .explode()
           .reset_index(name='pair'))

print (temp2)
   UT                 pair
0  I1      (Apple, Orange)
1  I1       (Apple, Peach)
2  I1      (Orange, Peach)
3  I2       (Apple, Lemon)
4  I3   (Starfruit, Apple)
5  I3  (Starfruit, Orange)
6  I3      (Apple, Orange)

For oldier pandas versions:
temp4 = (df.set_index ('UT')
          .stack()
          .groupby(level=0)
          .apply(lambda x: pd.Series(list(combinations (x, 2))))
          .reset_index(level=1, drop=True)
          .reset_index(name='pair'))

print (temp4)
   UT                 pair
0  I1      (Apple, Orange)
1  I1       (Apple, Peach)
2  I1      (Orange, Peach)
3  I2       (Apple, Lemon)
4  I3   (Starfruit, Apple)
5  I3  (Starfruit, Orange)
6  I3      (Apple, Orange)


text:
Q: angular $compile link to controller does not load images I am trying to render a gallery in a bootstrap modal-box. I am compiling a template with an ng-init which contains the images. This works for the first page(it loads all the images and the caption). For the second page(in the plnkr click to the second page) it does not display the picture of the bear, but it does display the caption. I am already using the ng-src instead of src but this does not seem to work for images that are not loaded at the first page.
Plnkr test:
http://plnkr.co/edit/HuTimgo1GD21CEADh4kI?p=preview

A: Solved this by using preloading images from this guy http://www.bennadel.com/blog/2597-preloading-images-in-angularjs-with-promises.htm


text:
Q: Valid json giving json.decoder.JSONDecodeError: Expecting ',' delimiter I'm learning about how to handle json using python but it is giving me an error.
Here's my code
import json
people_string = """
{
"people": [
    {
        "name": "John Smith",
        "phone": 666-625-7263,
        "emails": ["john.smith@fakemail.com","johnsmith@workmail.com"],
        "has_license": false
    },
    {
        "name": "Jane Doe",
        "phone": 666-625-7263,
        "emails": null,
        "has_license": true
    }
  ]
}
"""
data = json.loads(people_string)

I'm getting the following error:
Traceback (most recent call last):
  File "c:/Users/Tanishq/Desktop/Tanishq-imp/python tutorials/json-35.py", line 20, in <module>
    data = json.loads(people_string) #https://docs.python.org/3/library/json.html#encoders-and-decoders
  File "C:\Users\Tanishq\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "C:\Users\Tanishq\AppData\Local\Programs\Python\Python38-32\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\Tanishq\AppData\Local\Programs\Python\Python38-32\lib\json\decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 6 column 21 (char 71)

A: Your error is in the json literal string, you defined the pair phone incorrectly...
You should do
....
    "phone": "666-625-7263",
....

I mean, the number must be between "" because it is a string, not a number (because of the - symbols)

A: wrap the phone value with double quote (" ")
import json
people_string = '''
{
"people": [
    {
        "name": "John Smith",
        "phone": "666-625-7263",
        "emails": ["john.smith@fakemail.com","johnsmith@workmail.com"],
        "has_license": false
    },
    {
        "name": "Jane Doe",
        "phone": "666-625-7263",
        "emails": null,
        "has_license": true
    }
  ]
}'''
data = json.loads(people_string)


text:
Q: disable connection of actual vertex on JGraphX I need to disable connection of actual vertex if edges of vertex >= 2
if(graph.getModel().getEdgeCount(cell)>=2){
       graphComp.setConnectable(false);    // but for actual cell, not for all vertexes
    }
How can I do that?

A: Instead of mxGraphComponent.setConnectable(false) you can disable the connection for one Cell by calling mxCell.setConnectable(false).
If you want it to be enabled again when the edgecount goes down again you can use:
int maxEdgeCount = 2;

cell.setConnectable(cell.getEdgeCount < maxEdgeCount);


text:
Q: Why this code does not trigger ConcurrentModificationException? I'm modifying same list from multiple threads, shouldn't it trigger
ConcurrentModificationException while iterating list?
What could be done to trigger this exception?
public class ConcurrentTest {

    static List<String> list = setupList();

    public static List<String> setupList() {
        System.out.println("setup predefined list");

        List<String> l = new ArrayList();
        for(int i = 0; i < 50;i++) {
            l.add("test" + i);
        }

        return l;
    }

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(50);

        for(int i = 0; i < 50; i++) {
            executorService.submit( () -> {
                list.add("key1");

                Thread currentThread = Thread.currentThread();
                System.out.println( Thread.currentThread().getName() + ", " + list.size() );

                for(String val: list) {
                    try {
                        Thread.sleep(25);
                    }
                    catch(Exception e) {

                    }
                }

            });
        }

        executorService.shutdown();
    }
}

A: The ConcurrentModificationException triggers when you modify a list while iterating on it. In your code qhen you iterate on the list, you only sleep the thread and do not modify it.This would trigger the exception:
for(String s: list) {
    list.add("something");
}

A: Have you check whether below block throwing exception or not.
try {
    list.add("key1");

    Thread currentThread = Thread.currentThread();
    System.out.println( Thread.currentThread().getName() + ", " + list.size() );

    for(String val: list) {
        try {
            Thread.sleep(25);
        }
        catch(Exception e) {

        }
    }
}catch (Exception e) {
    e.printStackTrace();
}

Please wrap around try...catch block and print() error message to check its throwing error or not.

A: Your code does (and can) produce a ConcurrentModificationException. You are not catching it to print it.
With the below, we can see that it indeed throws many ConcurrentModificationException.
try {
    for (String val : list) {
        try {
          Thread.sleep(25);
        } catch (Exception e) {
        }
    }
} catch (Exception e) {
    e.printStackTrace();
}

NOTE: From the javadoc,

Note that the fail-fast behavior of an iterator cannot be guaranteed
    as it is, generally speaking, impossible to make any hard guarantees in the
    presence of unsynchronized concurrent modification.  Fail-fast iterators
    throw {@code ConcurrentModificationException} on a best-effort basis.
    Therefore, it would be wrong to write a program that depended on this
    exception for its correctness:  the fail-fast behavior of iterators
    should be used only to detect bugs

Also see: java.util.ConcurrentModificationException not thrown when expected

Or, you could get the returned Future and collect them in a list. By doing that, you will get the exception when calling get on (atleast) one of the futures.


text:
Q: gcc preprocessor: how to escape quotes in an argument I am trying to use gcc preprocessor for its macro expansion capabilities (I'm not trying to produce code).
I have a macro — MY_MACRO — that needs to get an argument that has double quotes inside
As you can see, the preprocessor produces an error: unterminated argument list
Is there a way to escape the quotes?
#define MY_MACRO(X)
MY_MACRO(prefix"suffix)

For example:
$ gcc -E -P -w a.txt
error: unterminated argument list invoking macro "MY_MACRO"
$

A: The C preprocessor works on C source code. A lone " is not valid C, so the cpp rejects it. You can cpp for other purposes only if you're willing to stick to the C syntax rules.
m4 is a general-purpose macro-processor and standard installed on anything Unix-like, though nobody likes it. There aren't many alternatives.


text:
Q: Android layout: Some ViewPager fragments shall be covered by AppBar and some shall be below the AppBar I have a layout that contains an AppBarLayout with a Toolbar and TabLayout. Below that is a ViewPager that will show one of my fragments.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_height="wrap_content"
        android:layout_width="match_parent">

        <android.support.v7.widget.Toolbar android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:titleTextColor="@android:color/white"
            app:title="Titel">
        </android.support.v7.widget.Toolbar>

        <android.support.design.widget.TabLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/InfoViewTabs"
            app:tabTextColor="@color/colorTabNotSelected"
            app:tabSelectedTextColor="@color/colorTabSelected"
            android:background="?attr/colorPrimary">
        </android.support.design.widget.TabLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">
    </android.support.v4.view.ViewPager>
</android.support.design.widget.CoordinatorLayout>

Due to appbar_scrolling_view_behavior, the content of the view pager is below the toolbar (A). When I remove that behavior the ViewPager stretches over the complete layout and the AppBar will cover a part of it (B).

Normally I want behavior A, so the content of the ViewPagers fragment is fully visible. But now I have a fragment that shall be shown fullscreen (B) because the AppBar fades away via OnPageChangeListener.onPageScrolled.
My idea is to remove the behavior so the ViewPager will always be in fullscreen (B), and then move the fragments down somehow. But I don't want to put a top margin in the xml of those fragments, because what value would I choose. It is not possible to add the scrollbehavior to sub children of the view.
How can this be accomplished?
An example for such a layout is WhatsApp. Normally the tab layout is shown, but when you swipe to the camera, the toolbar fades and the camera below is in fullscreen.


text:
Q: Codeigniter, REST_Controller and Backbone.js not talking Using Phil Sturgeon's REST_Controller
Backbone.js Collection:
define([
    'jquery',
    'underscore',
    'backbone',
    'models/project/ProjectModel2'
], function($, _, Backbone, ProjectModel2){
    var ProjectsCollection2 = Backbone.Collection.extend({

        initialize: function() {
            this.on('all', function(e) { console.log("ProjectCollectiona: " + e); });
        },
        model: ProjectModel2,
        url: "http://subdomain.domain.com/index.php/test/index"

    });

    return ProjectsCollection2;
});

Codeigniter Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require(APPPATH'.libraries/REST_Controller.php');
class Test extends REST_Controller {

    public function index_get()
    {
        $this->response(array('success' => 'get'), 200);
    }

    public function index_post()
    {
        $this->response(array('success' => 'post'), 200);
    }
}

Headers output via Chrome Inspector:
Request URL:http://subdomain.domain.com/index.php/test/index
Request Method:GET
Status Code:500 Internal Server Error
Request Headersview source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Type:application/x-www-form-urlencoded
Cookie:__utma=218955780.1934049331.1355591749.1355591749.1355591749.1; __utmc=218955780; __utmz=218955780.1355591749.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); ci_session=a%3A5%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%22698c724d973d37b869d90ca059b326c5%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A119%3A%22Mozilla%2F5.0+%28Macintosh%3B+Intel+Mac+OS+X+10_7_5%29+AppleWebKit%2F537.17+%28KHTML%2C+like+Gecko%29+Chrome%2F24.0.1312.52+Safari%2F537.17%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1358311296%3Bs%3A9%3A%22user_data%22%3Bs%3A0%3A%22%22%3B%7D164f4b5137bde1a0f31c3db5cc6723bf
Host:subdomain.domain.com
Referer:http://subdomain.domain.com/
User-Agent:Using Chrome on Mac
X-Requested-With:XMLHttpRequest
Response Headersview source
Connection:close
Content-Encoding:gzip
Content-Length:20
Content-Type:text/html
Date:Wed, 16 Jan 2013 04:41:36 GMT
Server:Apache
Vary:Accept-Encoding

Two problems:
1st one is obvious, getting a 500 when defining the URL for the Codeigniter controller.  Am I defining the URL incorrectly?
2nd one is perplexing, I tried to autoload REST_Controller.php from the library and when I ran the above code I get a blank browser, nothing at all in Chrome inspector as well.
Any guidance is greatly appreciated.


text:
Q: Order of a center of a group is prime order
Question :
  Suppose that $G$ is a non-abelian group of order $p^{3}$ where $p$ is prime and
  $Z (G) \neq \{e\}$.
  Prove that $|Z (G)| =p$.

Any useful hint to this question is appreciated.
Thanks in advance.

A: Since the center is non trivial his order can be $p,p^2$ or $p^3$. But $G$ is non abelian, so $|Z (G)|\neq p^3$.
Also if $|Z (G)|=p^2$, then $|G/Z|=p$, so $G/Z$ is cyclic, so $G$ is abelian (proof here).
Finally $|Z (G)|=p$.


text:
Q: Forms con Post independientes Estimados tengo la siguiente duda es posible realizar el siguiente código? he tratado de varias formas poder generar una especie de post recursivo, es decir, necesito consultar en la misma pagina si el rut esta o no en una tabla y después guardar la información en otra tabla, no se si sera posible de esta forma, agradecería cualquier comentario
                  <form id='form_feed_buscar' name="form_feed_buscar" action='ayuda_buen_pagador.php'  method="POST">
                       Rut:
                      <input type="text" name="rut" id="rut" title="INGRESE RUT SIN GUION" />
                      <input type="submit" value="Buscar" class="btn btn-info" name="btn2">

                          <?php
                          if(isset($_POST['btn2'])){
                            $rut = $_POST['rut'];
                            $where="";
                            $existe = 0;
                            $where="where rut = '".$rut."'";

                            $sql=$db->prepare("select * from buen_pagador $where ");
                            $sql->execute();
                            while($row = $sql->fetch()){
                              $existe++;
                            }
                            if($existe==0) {echo "
  NO SE ENCONTRARON COINCIDENCIAS CON LOS DATOS INGRESADOS
";}

                            if ($existe>0) {
                              ?>

Formulario de activación

                                <form id='form_feed_guardarr' name="form_feed_guardarr" action='guardar_buen_pagador.php' method="POST" >

                                        Rut
                                        <?php echo $rut ?>

                                              Indique linea a reactivar
                                              <input type="text" id="primera_linea" name="primera_linea" class="form-control" placeholder=""   />

                                              segunda linea a reactivar
                                              <input type="text" id="segunda_linea" name="segunda_linea" class="form-control" placeholder="" />

                                              tercera linea a reactivar
                                              <input type="text" id="tercera_linea" name="tercera_linea" class="form-control" placeholder="" />

                                              cuarta linea a reactivar
                                              <input type="text" id="cuarta_linea" name="cuarta_linea" class="form-control" placeholder="" />

                                              motivo que lo solicita
                                              <select class="form-control select" id="motivo" name="motivo" >
                                                  <option value=""> </option>
                                                  <option value="pago_no_reflejado">Pago no reflejado</option>
                                                  <option value="No_puedo_pagar_hoy_pago_manana">No puedo pagar hoy pago mañana</option>
                                                  <option value="problemas_economicos">Problemas económicos</option>
                                              </select>

                                  <button class="btn btn-primary pull-right" type="submit" name="guardar" style="margin-right: 45px;">Guardar</button>

                                </form>

                              <?php
                            }
                          }
                          ?>

                    </form>

o como seria posible ejecutar dos post en haciendo llamado a actions distintas?, uno seria la consulta del rut y el otro el guardar información que dentro de la base, en base a que si se encuentra el rut dentro de la primera consulta, estaré atento a cualquier apoyo o comentario

A: No es posible utilizar un <form> dentro de otro. Deben estar totalmente separados y no anidados.

Flow content, but with no form element descendants.
https://html.spec.whatwg.org/multipage/forms.html#the-form-element

Debes considerar reorganizar los formularios para que no se traslapen. De esta manera tambien pueden actuar totalmente independientes, con action distintos. Dependiendo de lo que deseas lograr, puedes simplemente finalizar el primer formulario antes:
<form id='form_feed_buscar' name="form_feed_buscar" action='ayuda_buen_pagador.php' method="POST">
     Rut:
    <input type="text" name="rut" id="rut" title="INGRESE RUT SIN GUION" />
    <input type="submit" value="Buscar" class="btn btn-info" name="btn2">
</form>

        <?php
        if(isset($_POST['btn2'])){
          $rut = $_POST['rut'];
          $where="";
          $existe = 0;
          $where="where rut = '".$rut."'";

          $sql=$db->prepare("select * from buen_pagador $where ");
          $sql->execute();
          while($row = $sql->fetch()){
            $existe++;
          }
          if($existe==0) {echo "
  NO SE ENCONTRARON COINCIDENCIAS CON LOS DATOS INGRESADOS
";}

          if ($existe>0) {
            ?>

Formulario de activación

        <form id='form_feed_guardarr' name="form_feed_guardarr" action='guardar_buen_pagador.php' method="POST">

                        Rut
                        <?php echo $rut ?>

                        Indique linea a reactivar
                        <input type="text" id="primera_linea" name="primera_linea" class="form-control"
                            placeholder="" />

                        segunda linea a reactivar
                        <input type="text" id="segunda_linea" name="segunda_linea" class="form-control"
                            placeholder="" />

                        tercera linea a reactivar
                        <input type="text" id="tercera_linea" name="tercera_linea" class="form-control"
                            placeholder="" />

                        cuarta linea a reactivar
                        <input type="text" id="cuarta_linea" name="cuarta_linea" class="form-control" placeholder="" />

                        motivo que lo solicita
                        <select class="form-control select" id="motivo" name="motivo">
                            <option value=""> </option>
                            <option value="pago_no_reflejado">Pago no reflejado</option>
                            <option value="No_puedo_pagar_hoy_pago_manana">No puedo pagar hoy pago mañana</option>
                            <option value="problemas_economicos">Problemas económicos</option>
                        </select>

            <button class="btn btn-primary pull-right" type="submit" name="guardar"
                style="margin-right: 45px;">Guardar</button>

        </form>

        <?php
          }
        }
        ?>


text:
Q: How can I populate a 3rd column result on intersections of 1st and 2nd columns all from the same table that are selected by the user on dropdown? I have a column vehicle_name and I would like 2 dropdown lists of my 2 other columns namely, vehicle_type and vehicle_color.
When these 2 dropdown values are selected and submitted, I would like their intersection to print out the values from vehicle_name. So far my code only generates a dropdown list for vehicle_type, I would need another dropdown for vehicle_colour. Which on submissions populates the intersected values for the vehicle_name. How can I achieve this?
<!DOCTYPE html>

<?php
echo "
";
echo "
";
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";

$db = new mysqli($servername, $username, $password, $dbname);

if (!$db) {
    exit('Connect Error (' . mysqli_connect_errno() . ') '
        . mysqli_connect_error());
}
?>

Select vehicle type:

<select name="payment_method">
    <option value = "">---Select---</option>
<?php
$queryusers = "SELECT DISTINCT vehicle_type FROM orders";
$db = mysqli_query($db, $queryusers);
while ($d=mysqli_fetch_assoc($db)) {
    echo "<option value='{".$d['vehicle_type']."}'>".$d['vehicle_type']."</option>";
}

?>
</select>

Select color:

<select name="vehicle_color">
    <option value = "">---Select---</option>

<?php
$query_for_color = "SELECT DISTINCT vehicle_color FROM orders";
$db = mysqli_query($db, $query_for_date);
while ($a=mysqli_fetch_assoc($db)) {
    echo "<option value='{".$a['vehicle_color']."}'>".$a['vehicle_color']."</option>";
}

?>
</select>

<button class="go-btn" type="submit">Go</button>

A: As I don't see any AJAX / client-side code in your above example I assume that this is  a pure backend-side filtering you are performing. Your code is currently missing parts of the required elements we would need but let's try to figure this out together:
1. Form around your inputs
Add a <form method="POST" target="path-to-your-script.php"> where "path-to-your-script.php" has to be changed to your PHP file name or rewritten URL path. This has to be around the <select> boxes.
You may also use PHP_SELF to set this automatically, this should work in most cases. I used html_entities($var) to avoid any code injections via manipulated URL.
<form name="test" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">

2. Check for POST'ed variable 'vehicle_type'
In your form, check if a search for available colors has been performed:
<?php
  $query_for_color = "SELECT DISTINCT vehicle_color FROM orders";

  // check if the form variable 'vehicle_type' is available; if so, filter entries.
  if (isset($_POST['vehicle_type'])) {
    $vType= filter_var($_POST['vehicle_type'], FILTER_SANITIZE_STRING);
    $query_for_colors .= ' WHERE vehicle_type = \''.$vType.'\'';
  }
  $db = mysqli_query($db, $query_for_date);
  while ($a=mysqli_fetch_assoc($db)) {
      echo "<option value='{".$a['vehicle_color']."}'>".$a['vehicle_color']."</option>";
  }
?>

Edit:
As pointed out by one user in the comment, filter_var($var, FILTER_SANITIZE_STRING) won't be enough to avoid potential SQL injections. This was just a recommendation and was not part of the question at all. If you have to work with user data, do more than using filter_var(), instead use either prepared statements or properly escape the user data. There are many tutorials like this one out there that will guide you to safe queries.


text:
Q: Tell AFJSONRequestSerializer (or other serializers) to log serialized data to console I couldn't find this information in the docs.
How to I tell an AFJSONRequestSerializer (or any other serializer) to log the generated JSON to the console.

A: The easiest way would be to listen for either AFNetworkingTaskDidResumeNotification or AFNetworkingOperationDidStartNotification notifications, and log the request of the task or operation from that.
Alternatively, you could either add a log statement in an method overridden by an HTTP manager subclass, or even swizzle AFHTTPRequestSerialization -requestBySerializingRequest:....


text:
Q: Mysql update if one of fields is a duplicate My DB has table ip(address, count) and I want to update the 'count' value if address is found in DB, else add a new record. I do this:
INSERT INTO ip(address,count)
VALUES('0.0.0.1', 3)
ON DUPLICATE KEY UPDATE count=count+VALUES(count);

But as a result a have this table:
+----+---------+-------+
| id | address | count |
+----+---------+-------+
|  1 | 0.0.0.1 | 3     |
|  2 | 0.0.0.1 | 3     |
|  3 | 0.0.0.1 | 3     |
+----+---------+-------+

  `id` int(50) NOT NULL AUTO_INCREMENT,
  `address` varchar(40) DEFAULT NULL,
  `count` varchar(10) DEFAULT NULL,
   PRIMARY KEY (`id`)

Why doesn't it sum 'count' , but makes a new record always ? How do I change primary key ?

A: Have you actually created the unique key on the address column? If you haven't then the ON DUPLICATE KEY UPDATE clause will never run and so rows will keep being created.
Could you update your question to include the schema for the table?

A: You need to mark ADDRESS as UNIQUE key for this to work.
Quoting from documentation

If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that
  would cause a duplicate value in a UNIQUE index or PRIMARY KEY, an
  UPDATE of the old row is performed

A: create your table using following query
CREATE TABLE `ip` (
    `id` INT(50) NOT NULL AUTO_INCREMENT,
    `address` VARCHAR(40) NULL DEFAULT NULL,
    `count` VARCHAR(10) NULL DEFAULT NULL,
    PRIMARY KEY (`id`),
    UNIQUE INDEX `address` (`address`)
)

Then use following query to insert
INSERT INTO ip(address,`count`) VALUES('0.0.0.1', 3)
  ON DUPLICATE KEY UPDATE `count`=`count`+1;

In this case if table already contain that ip, then count will be incremented by one.
Please note that column address  should be either UNIQUE index or PRIMARY KEY, otherwise this wont work. In my create table query i set address as unique.


text:
Q: Implementing a Pipe in C++ I am having trouble implementing my pipe. It reads Unix terminal commands from a text file for commands such as "ls|wc" where it opens a pipe so that the output of ls can be used for wc.
I have implemented it to parse program names ("ls", "wc") and store them in two separate arrays (arguments and arguments2), fork a child process, then have that child fork another child process, then the second child process calls the execvp() command and passes the first program to be executed.
The output from ("ls") is then written to the pipe by changing the standard output. The former child process then execvp()'s the other process ("wc") and reads from the pipe by changing the standard input.
However, wc loops indefinitely and does not seem to count the number of words from ls. Ls executes in a directory where there are words to be counted.
Any tips? Thank you so much and sorry for the long explanation.
Here is a simpler example: It forks, creates a pipe, and implements "ls" and writes its output to the pipe, goes back to the parent and reads from the pipe the output of "ls". It still seems to be reading forever or not working right.
//
//  main.cpp
//  Pipe_Test
//
//  Created by Dillon Sheffield on 9/28/15.
//  Copyright © 2015 Dillon Sheffield. All rights reserved.
//

#include <iostream>
using namespace std;

int main()
{
    char* arguments[2];
    char* programArguments[1];
    int fd[2];

    arguments[0] = new char[2];
    arguments[1] = new char[2];
    programArguments[0] = new char[1];
    programArguments[0][0] = '\0';
    string ls = "ls";
    string wc = "wc";
    for (int i = 0; i < 1; i++) {
        arguments[0] = &ls.at(i);
        arguments[1] = &wc.at(i);
    }

    pid_t pid = fork();
    pipe(fd);

    if (pid < 0) {
        perror("Failed.\n");
    } else if (pid == 0) {
        dup2(fd[1], STDOUT_FILENO);

        execvp(arguments[0], programArguments);
    }

    wait(NULL);

    dup2(fd[0], STDIN_FILENO);
    execvp(arguments[1], programArguments);

    close(0);
    close(1);

    return 0;
}

Here is my original code:
//
//  main.cpp
//  homework2
//
//  Created by Dillon Sheffield on 9/19/15.
//  Copyright © 2015 Dillon Sheffield. All rights reserved.
//

#include <iostream>
#include <fstream>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
using namespace std;

// Global Variable(s)
const short inputLineSize = 10; // Size of programName, arguments, and argument name.
char *arguments[inputLineSize];
char *arguments2[inputLineSize];
ifstream inputFile;
char* input;

void readLine()
{
    // Create new char array(s)
    input = new char[inputLineSize];

    // Initialize the char array(s)
    for (int i = 0; i < inputLineSize; i++)
    {
        input[i] = '\0';
    }

    // Read a line and skip tabs, spaces, and new line characters
    for (int i = 0; !inputFile.eof() && inputFile.peek() != '\n'; i++)
    {
        while (inputFile.peek() == '\n' || inputFile.peek() == '\t' || inputFile.peek() == ' ') inputFile.get();
        inputFile.get(input[i]);
    }

    // If the file is multi-spaced, keep reading new line char(s) to clear them
    while (inputFile.peek() == '\n') inputFile.get();
}

void parseTokens()
{
    //----------Parse the read line into tokens--------------------------------------------//

    // Get the program name
    for (int i = 0; i < inputLineSize; i++)
    {
        arguments[i] = new char[inputLineSize];
        for (int j = 0; j < inputLineSize; j++)
            arguments[i][j] = '\0';
    }

    int i = 0;
    int j = 0;
    while (input[i] != '\0' && input[i] != '-' && input[i] != '|')
    {
        arguments[j][i] = input[i];
        i++;
    }

    // Tokenize arguments if supplied
    j++;
    int k;
    while (input[i] == '-')
    {
        k = 0;
        arguments[j][k] = input[i];
        i++;
        k++;

        while (input[i] != '-' && input[i] != '\0')
        {
            arguments[j][k] = input[i];
            i++;
            k++;
        }
        j++;
    }

    // Delete unused arguments
    while (j < inputLineSize)
    {
        delete arguments[j];
        arguments[j] = NULL;
        j++;
    }

    // Check if the pipe command '|' is supplied
    if (input[i] == '|')
    {
        i++;

        // Get the other program name
        for (int x = 0; x < inputLineSize; x++)
        {
            arguments2[x] = new char[inputLineSize];
            for (int y = 0; y < inputLineSize; y++)
                arguments2[x][y] = '\0';
        }

        int x = 0;
        int j = 0;
        while (input[i] != '\0' && input[i] != '-' && input[i] != '|')
        {
            arguments2[j][x] = input[i];
            i++;
            x++;
        }

        // Tokenize arguments if supplied
        j++;
        int k;
        while (input[i] == '-')
        {
            k = 0;
            arguments2[j][k] = input[i];
            i++;
            k++;

            while (input[i] != '-' && input[i] != '\0')
            {
                arguments2[j][k] = input[i];
                i++;
                k++;
            }
            j++;
        }

        // Delete unused arguments
        while (j < inputLineSize)
        {
            delete arguments2[j];
            arguments2[j] = NULL;
            j++;
        }
    }
}

int main()
{
    // Variable(s)
    pid_t pid;
    pid_t pid2;
    int fd[2];

//--Open the file named "input"-------------------------------------------------------//

    inputFile.open("input", ios::in);

    // Check if opening the file was successful
    if (inputFile.is_open())
    {
        // Read until the file has reached the end
        while (!inputFile.eof())
        {
            // Read a line and parse tokens
            readLine();
            parseTokens();

//----------Now create a new process with parsed Program Name and Arguments-----------//

            // Create a pipe
            pipe(fd);

            // Fork
            pid = fork();
            if (pid < 0)
            {
                perror("Fork failed.\n");
                return -2;
            }
            else if (pid == 0)
            {
                // Fork again
                pid2 = fork();

                if (pid2 < 0)
                {
                    perror("Fork failed.\n");
                    return -2;
                }
                else if (pid2 == 0)
                {
                    // Change standard output
                    if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO) perror("dup2 error to stdout.\n");

                    // Execute the given program
                    execvp(arguments[0], arguments);
                }

                // Change the standard input to the pipe
                if (dup2(fd[0], STDIN_FILENO) != STDIN_FILENO) perror("dup2 error to stdin.\n");

                int returnValue = execvp(arguments2[0], arguments2);
                if (returnValue == -1) perror("Error has occurred.\n");

                // Close the pipe and exit
                close(fd[0]);
                close(fd[1]);
                exit(0);
            }

            // Wait for the child so it doesn't become a Zombie
            wait(NULL);

//----------Clean up-----------------------------------------------------------------//
            delete input;
            input = NULL;
            int i = 0;
            while (arguments[i] != NULL)
            {
                delete arguments[i];
                arguments[i] = NULL;
                i++;
            }
            i = 0;
        }
    }
    else perror("Cannot open file.\n");

    inputFile.close();
    return 0;
}

A: You first execute a pipe(), then you execute a fork(), and the child process, with some additional work, executes your commands.
The problem here is that the pipe()d file descriptors, both of them, remain open in the original parent process. Both the read-side of the pipe, and, more importantly, the write-side of the pipe. These file descriptors do, from all appearances, get correctly set up for your child processes, but because the file descriptors also remain open in the parent process, the pipe never closes, even after the process that writes to the write side of the pipe terminates.
Since the write side of the pipe remains open, in the parent process, the child process that's reading the read side of the pipe will continue reading. Forever.
What you need to do is that after the fork, in the parent process, close both the read and the write side of the pipe. Once the initial process gets forked, the parent process does not need the pipe, and its open file descriptors get in the way.


text:
Q: What are the TV/movie Discworld adaptations? So... I've seen the Hogfather and Colour of Magic/Light Fantastic via YouTube... think they were pretty good, but the video/audio quality was poor.  And I understand Going Postal is out there as well (gonna hunt it down shortly... I hope).  I've also seen some cartoon versions of Wyrd Sisters, etc.
So... how many adaptations are there, both live action and animated? Where were they released?

A: According to the Discworld wiki, there are a few more titles than offered in the search proposed by DJClayworth's post.
The link here Discworld Adaptations gives all titles, including those, but not limited to the titles you have already seen.
Should anyone not be able to access the link, the adaptations are

*

*Truckers, 1992, an animated series by Cosgrove Hall.

*Johnny and the Dead, a TV serial by ITV, 1995.

*Soul Music, 1997, an animated series by Cosgrove Hall.

*Wyrd Sisters, 1997, an animated series by Cosgrove Hall.

*Johnny and the Bomb, 2006, a three-part TV series on the BBC.

*Hogfather, aired by Sky One, Christmas 2006 as TV film.

*The Colour of Magic, aired by Sky One, Easter 2008 as TV film.

*Going Postal, aired by Sky One, Easter 2010 as TV film.

A: Going to IMDB and entering Terry Pratchett's name will get you a list of everything - existing and proposed - that he has written. You've listed most of them.
British DVDs will not play on most North American players. It's not about the region locking, it's about the TV format (PAL vs NTSC). You can buy players that will play if you look.
Fortunately most of PTerry's works are available in North American format in the usual online stores.


text:
Q: Migrating log4j 1.2.17 from JBoss AS 7.1.1 Final to JBoss EAP 6.2 I am migrating my application server from JBoss AS 7.1.1 Final to JBoss EAP 6.2. However, I am having some issues with the Apache log4j 1.2.17 and EAP 6.2.
In AS 7.1.1 I didn't have to do anything other than have the log4j.jar in the build path of the project I was working on in Eclipse. The logs I wanted were defined within the JBoss standalone.xml and were created whenever I started the server. I am using JAR files, not WAR or EAR files for the deployment of my applications.
Now when migrating to EAP 6.2 I am trying to make everything local in my Eclipse structure.
I set the per-deployment setting in the standalone.conf to false as shown below:
JAVA_OPTS="$JAVA_OPTS -Dorg.jboss.as.logging.per-deployment=false"

I created a META-INF folder in my project src folder with the file jboss-deployment-structure.xml with the following:
<jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.2">
<deployment>
    <dependencies>
        <module name="com.log4j.mylog4j" export="true" />
    </dependencies>
    <exclusions>
        <module name="org.apache.log4j" />
    </exclusions>
</deployment>

I also placed the log4j.properties in the src folder with the definition of rootlogger and all of the individual loggers.
However, whenever I try to log anything within my application I get the warning:
log4j:WARN No appenders could be found for logger
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

Any help would be greatly appreciated.

A: I figured out my problem. I have multiple projects in eclipse one being a logging project with a program the controls all of my logging. So I set up my META-INF in the logging project. However, all the logging calls were made in another project with many other programs. I had to set up the META-INF in this other project NOT the logging project. Not sure why but it got rid of this error.


text:
Q: Pointlabels not displaying when data point is at maximum I have the following graph: http://synicworld.com/media/graph.png
Is there a way to get the pointlabel to show on the bars that have maximum value?

A: pointLabels {
    edgeTolerance: 100
}

Looks like it's just edgeTolerance, which I had tried before, but not with a value high enough.

A: pointLabels {
    edgeTolerance: -20
}
This will allow rendering of point labels even if they're too close to the edge.  The negative value means there might be overlap onto the chart.


text:
Q: BIRT - execute sql query under getDefaultValueList Method of a parameter I'm wondering if I could use a DataSet or a SQL query in getDefaultValueList method?
I want to do something like shown below, but the below code doesnt work as the datasets are executed after the parameter form is displayed.
if (dataSetRow["customerId"] == reportContext.getHttpServletRequest().getParameter("customerId"))
{
  reportContext.getDesignHandle().findParameter("SomeParameter").hidden = true;
}

A: If I understand you correctly, you want to hide or display SomeParameter based on the value of the parameter customerId?
Since all parameters are "loaded" into the form at the same time, such a direct connection isn't possible. You could, however, look into cascading parameters and see whether you can adapt your problem to their functionality.