问:
write to a html file and display on iphone
i have a local html file that i can display on UIWebview now  is there a way like i can pass my string value to that html page and display the content???

this is how i am loading html

```<code>NSString *urlAddress = [[NSBundle mainBundle] pathForResource:@"index4" ofType:@"html"];

    NSURL   *instructionsURLd = [[NSURL alloc] initFileURLWithPath:urlAddress];

    [webView loadRequest:[NSURLRequest requestWithURL:instructionsURLd]];
</code>```

now index4.html content is

```<code><html>
<body>
testing hhhhhhhhhhhhhhhhhhhhhhhhhhhhh
<a href="index200.html">index1</a>
<TD><INPUT TYPE=BUTTON OnClick="Circle_calc(this.form);" VALUE="calculate"></TD>

</body>
</html>
</code>```

//

now lets say i have NSString s=@"hello"

now can i add this value to the  tag of html and show in UIwebview??

答:
You cannot store mutable (changing) objects in your application bundle. However, you can put them there before building you app, open them when the app is executing, and write them to disk, and modify them whenever you want, after that.

Your code

NSString *s;
    s = @"hello";

```<code>NSString *urlAddress = [[NSBundle mainBundle] pathForResource:@"index4" ofType:@"html"];
NSURL   *instructionsURLd = [[NSURL alloc] initFileURLWithPath:urlAddress];
NSError *error;
</code>```

When your starts for the first time only Grab the resource and store it into a string

```<code>NSString *myHTML = [NSString stringWithContentsOfURL:instructionsURLd encoding:NSASCIIEncoding error:&error];
</code>```

Immediately write the data to disk

```<code>NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSData *myData = [NSData dataWithBytes:[myHTML UTF8String] length:[myHTML lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"index4.html"];
[myData writeToFile:appFile atomically:YES];
</code>```

Then, load it when you need it

```<code>NSArray *paths2 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory2 = [paths2 objectAtIndex:0];
NSString *appFile2 = [documentsDirectory2 stringByAppendingPathComponent:@"index4.html"];
NSData *mySavedData = [[[NSData alloc] initWithContentsOfFile:appFile2] autorelease];
NSString *myNewHTML = [[NSString alloc] initWithData:mySavedData encoding:NSUTF8StringEncoding];
</code>```

Insert s into the HTML document

```<code>myNewHTML = [myHTML stringByReplacingOccurrencesOfString:@"<body>" withString:[NSString stringWithFormat:@"<body> %@",s]];
</code>```

Write everything back to the file

```<code>NSArray *paths3 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory3 = [paths objectAtIndex:0];
NSMutableData *myData3 = [NSData dataWithBytes:[myNewHTML UTF8String] length:[myNewHTML lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
NSString *appFile3 = [documentsDirectory3 stringByAppendingPathComponent:@"index4.html"];
NSData *myNewData = [NSData dataWithBytes:[myNewHTML UTF8String] length:[myNewHTML lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
[myNewData writeToFile:appFile3 atomically:YES];
</code>```

Body:
i have a local html file that i can display on UIWebview now  is there a way like i can pass my string value to that html page and display the content???

this is how i am loading html

NSString *urlAddress = [[NSBundle mainBundle] pathForResource:@"index4" ofType:@"html"];

    NSURL   *instructionsURLd = [[NSURL alloc] initFileURLWithPath:urlAddress];

    [webView loadRequest:[NSURLRequest requestWithURL:instructionsURLd]];

now index4.html content is

testing hhhhhhhhhhhhhhhhhhhhhhhhhhhhh
index1
<INPUT TYPE=BUTTON OnClick="Circle_calc(this.form);" VALUE="calculate">

//

now lets say i have NSString s=@"hello"

now can i add this value to the  tag of html and show in UIwebview??

Body:
You cannot store mutable (changing) objects in your application bundle. However, you can put them there before building you app, open them when the app is executing, and write them to disk, and modify them whenever you want, after that.

Your code

NSString *s;
    s = @"hello";

NSString *urlAddress = [[NSBundle mainBundle] pathForResource:@"index4" ofType:@"html"];
NSURL   *instructionsURLd = [[NSURL alloc] initFileURLWithPath:urlAddress];
NSError *error;

When your starts for the first time only Grab the resource and store it into a string

NSString *myHTML = [NSString stringWithContentsOfURL:instructionsURLd encoding:NSASCIIEncoding error:&error];

Immediately write the data to disk

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSData *myData = [NSData dataWithBytes:[myHTML UTF8String] length:[myHTML lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"index4.html"];
[myData writeToFile:appFile atomically:YES];

Then, load it when you need it

NSArray *paths2 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory2 = [paths2 objectAtIndex:0];
NSString *appFile2 = [documentsDirectory2 stringByAppendingPathComponent:@"index4.html"];
NSData *mySavedData = [[[NSData alloc] initWithContentsOfFile:appFile2] autorelease];
NSString *myNewHTML = [[NSString alloc] initWithData:mySavedData encoding:NSUTF8StringEncoding];

Insert s into the HTML document

myNewHTML = [myHTML stringByReplacingOccurrencesOfString:@"<body>" withString:[NSString stringWithFormat:@"<body> %@",s]];

Write everything back to the file

NSArray *paths3 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory3 = [paths objectAtIndex:0];
NSMutableData *myData3 = [NSData dataWithBytes:[myNewHTML UTF8String] length:[myNewHTML lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
NSString *appFile3 = [documentsDirectory3 stringByAppendingPathComponent:@"index4.html"];
NSData *myNewData = [NSData dataWithBytes:[myNewHTML UTF8String] length:[myNewHTML lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
[myNewData writeToFile:appFile3 atomically:YES];


来源: stackexchange

问:
Xamarin Android Exception while loading assemblies: System.IO.FileNotFoundException: Could not load assembly 'Xamarin.Android.Support.Compat'
I am working on Xamarin.Forms project for my company and we plan to release our app on IOS and Android (Using Visual Studio Community Edition on Macbook pro). So far everything seemed to be OK. And then suddenly I cannot build debug or release on Android project. I am getting this error:

```<code>/Library/Frameworks/Mono.framework/External/xbuild/Xamarin/Android/Xamarin.Android.Common.targets(2,2): Error: Exception while loading assemblies: System.IO.FileNotFoundException: Could not load assembly 'Xamarin.Android.Support.Compat, Version=1.0.0.0, Culture=neutral, PublicKeyToken='. Perhaps it doesn't exist in the Mono for Android profile?
File name: 'Xamarin.Android.Support.Compat.dll'
  at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve (Mono.Cecil.AssemblyNameReference reference, Mono.Cecil.ReaderParameters parameters) [0x00099] in /Users/builder/data/lanes/5147/c2a33d8e/source/xamarin-android/external/Java.Interop/src/Java.Interop.Tools.Cecil/Java.Interop.Tools.Cecil/DirectoryAssemblyResolver.cs:220
  at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve (Mono.Cecil.AssemblyNameReference reference) [0x00000] in /Users/builder/data/lanes/5147/c2a33d8e/source/xamarin-android/external/Java.Interop/src/Java.Interop.Tools.Cecil/Java.Interop.Tools.Cecil/DirectoryAssemblyResolver.cs:170
  at Xamarin.Android.Tasks.ResolveAssemblies.AddAssemblyReferences (Java.Interop.Tools.Cecil.DirectoryAssemblyResolver resolver, System.Collections.Generic.ICollection`1[T] assemblies, Mono.Cecil.AssemblyDefinition assembly, System.Boolean topLevel) [0x0015c] in <593a6fd557984367bb21e275d0fa0659>:0
  at Xamarin.Android.Tasks.ResolveAssemblies.Execute (Java.Interop.Tools.Cecil.DirectoryAssemblyResolver resolver) [0x0019c] in <593a6fd557984367bb21e275d0fa0659>:0
</code>```

I am pretty sure I haven't changed any source files, it was building up until now..
The only App Compat I use is "Xamarin.Android.Support.v7.Compat".

The things I tried:

Removing all packages and adding them again.

Creating fresh Xamarin.Forms project and pulling code from git - same error

Installing Xamarin.Android.Support.Compat - Error I got:

You are trying to install this package into a project that targets
  'MonoAndroid,Version=v6.0', but the package does not contain any
  assembly references or content files that are compatible with that
  framework.

Made sure my target framework is same as target version (Use API 23) and my minimum target version is API 19.

Deleting Bin and Obj directories, restarting solution and building again.

I am using Xamarin.Forms 2.4.0.38779. I tried removing all packages and updating for the newest Forms - still got same error.

This is packages.config for Droid project:

```<code><?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="modernhttpclient" version="2.4.2"
   targetFramework="monoandroid60" />
 <package id="Plugin.PushNotification" version="1.1.2"
   targetFramework="monoandroid60" />
 <package id="Rg.Plugins.Popup" version="1.0.4"
   targetFramework="monoandroid60" />
 <package id="Xam.Plugin.DeviceInfo" version="3.0.2"
   targetFramework="monoandroid60" />
 <package id="Xam.Plugins.Settings" version="3.1.1"
   targetFramework="monoandroid60" />
 <package id="Xamarin.Android.Support.Animated.Vector.Drawable"
   version="23.3.0" targetFramework="monoandroid60" />
 <package id="Xamarin.Android.Support.Design" version="23.3.0"
   targetFramework="monoandroid60" />
 <package id="Xamarin.Android.Support.v4" version="23.3.0"
   targetFramework="monoandroid60" />
 <package id="Xamarin.Android.Support.v7.AppCompat" version="23.3.0"
    targetFramework="monoandroid60" />
 <package id="Xamarin.Android.Support.v7.CardView" version="23.3.0"
    targetFramework="monoandroid60" />
 <package id="Xamarin.Android.Support.v7.MediaRouter" version="23.3.0"
   targetFramework="monoandroid60" />
 <package id="Xamarin.Android.Support.v7.RecyclerView" version="23.3.0"
    targetFramework="monoandroid60" />
 <package id="Xamarin.Android.Support.Vector.Drawable"
    version="23.3.0"
    targetFramework="monoandroid60" />
 <package id="Xamarin.Forms" version="2.4.0.38779"
    targetFramework="monoandroid60" />
</packages>
</code>```

I will provide any logs, if needed.

答:
So after enabling detailed build output I found the issue!

Xamarin is really bad with it's error description, and by investigating into Build Log I found out that this missing dll was required by Plugin.PushNotification NuGet package I use for both iOS and Android. After removing all references to this package from Android project, it started building again!

ContentLicense: CC BY-SA 3.0

Body:
I am working on Xamarin.Forms project for my company and we plan to release our app on IOS and Android (Using Visual Studio Community Edition on Macbook pro). So far everything seemed to be OK. And then suddenly I cannot build debug or release on Android project. I am getting this error:

/Library/Frameworks/Mono.framework/External/xbuild/Xamarin/Android/Xamarin.Android.Common.targets(2,2): Error: Exception while loading assemblies: System.IO.FileNotFoundException: Could not load assembly 'Xamarin.Android.Support.Compat, Version=1.0.0.0, Culture=neutral, PublicKeyToken='. Perhaps it doesn't exist in the Mono for Android profile?
File name: 'Xamarin.Android.Support.Compat.dll'
  at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve (Mono.Cecil.AssemblyNameReference reference, Mono.Cecil.ReaderParameters parameters) [0x00099] in /Users/builder/data/lanes/5147/c2a33d8e/source/xamarin-android/external/Java.Interop/src/Java.Interop.Tools.Cecil/Java.Interop.Tools.Cecil/DirectoryAssemblyResolver.cs:220
  at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve (Mono.Cecil.AssemblyNameReference reference) [0x00000] in /Users/builder/data/lanes/5147/c2a33d8e/source/xamarin-android/external/Java.Interop/src/Java.Interop.Tools.Cecil/Java.Interop.Tools.Cecil/DirectoryAssemblyResolver.cs:170
  at Xamarin.Android.Tasks.ResolveAssemblies.AddAssemblyReferences (Java.Interop.Tools.Cecil.DirectoryAssemblyResolver resolver, System.Collections.Generic.ICollection`1[T] assemblies, Mono.Cecil.AssemblyDefinition assembly, System.Boolean topLevel) [0x0015c] in <593a6fd557984367bb21e275d0fa0659>:0
  at Xamarin.Android.Tasks.ResolveAssemblies.Execute (Java.Interop.Tools.Cecil.DirectoryAssemblyResolver resolver) [0x0019c] in <593a6fd557984367bb21e275d0fa0659>:0

I am pretty sure I haven't changed any source files, it was building up until now..
The only App Compat I use is "Xamarin.Android.Support.v7.Compat".

The things I tried:

Removing all packages and adding them again.

Creating fresh Xamarin.Forms project and pulling code from git - same error

Installing Xamarin.Android.Support.Compat - Error I got:

You are trying to install this package into a project that targets
  'MonoAndroid,Version=v6.0', but the package does not contain any
  assembly references or content files that are compatible with that
  framework.

Made sure my target framework is same as target version (Use API 23) and my minimum target version is API 19.

Deleting Bin and Obj directories, restarting solution and building again.

I am using Xamarin.Forms 2.4.0.38779. I tried removing all packages and updating for the newest Forms - still got same error.

This is packages.config for Droid project:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="modernhttpclient" version="2.4.2"
   targetFramework="monoandroid60" />
 <package id="Plugin.PushNotification" version="1.1.2"
   targetFramework="monoandroid60" />
 <package id="Rg.Plugins.Popup" version="1.0.4"
   targetFramework="monoandroid60" />
 <package id="Xam.Plugin.DeviceInfo" version="3.0.2"
   targetFramework="monoandroid60" />
 <package id="Xam.Plugins.Settings" version="3.1.1"
   targetFramework="monoandroid60" />
 <package id="Xamarin.Android.Support.Animated.Vector.Drawable"
   version="23.3.0" targetFramework="monoandroid60" />
 <package id="Xamarin.Android.Support.Design" version="23.3.0"
   targetFramework="monoandroid60" />
 <package id="Xamarin.Android.Support.v4" version="23.3.0"
   targetFramework="monoandroid60" />
 <package id="Xamarin.Android.Support.v7.AppCompat" version="23.3.0"
    targetFramework="monoandroid60" />
 <package id="Xamarin.Android.Support.v7.CardView" version="23.3.0"
    targetFramework="monoandroid60" />
 <package id="Xamarin.Android.Support.v7.MediaRouter" version="23.3.0"
   targetFramework="monoandroid60" />
 <package id="Xamarin.Android.Support.v7.RecyclerView" version="23.3.0"
    targetFramework="monoandroid60" />
 <package id="Xamarin.Android.Support.Vector.Drawable"
    version="23.3.0"
    targetFramework="monoandroid60" />
 <package id="Xamarin.Forms" version="2.4.0.38779"
    targetFramework="monoandroid60" />
</packages>

I will provide any logs, if needed.


问:
How do I edit a WPF button at runtime

So I was using Expression Blend to design my button. I created a new button, edited the template of the button by removing everything within it. Then I added a grid into it and named it "grid". Inside the grid i added a textblock and called it "textBlock". Then i saved the template under Applications.

This is the content in the app.xaml file.

```<code><Style x:Key="CustomButtonStyle" TargetType="{x:Type Button}">
        <Setter Property="FocusVisualStyle" Value="{StaticResource FocusVisual}"/>
        <Setter Property="Background" Value="{StaticResource Button.Static.Background}"/>
        <Setter Property="BorderBrush" Value="{StaticResource Button.Static.Border}"/>
        <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
        <Setter Property="BorderThickness" Value="1"/>
        <Setter Property="HorizontalContentAlignment" Value="Center"/>
        <Setter Property="VerticalContentAlignment" Value="Center"/>
        <Setter Property="Padding" Value="1"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Grid x:Name="grid" HorizontalAlignment="Left" Height="40" VerticalAlignment="Top" Width="90">
                        <TextBlock x:Name="textBlock" HorizontalAlignment="Left" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Margin="5,5,0,0" Height="25" Width="75" FontSize="17.333"/>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsDefaulted" Value="true"/>
                        <Trigger Property="IsMouseOver" Value="true"/>
                        <Trigger Property="IsPressed" Value="true"/>
                        <Trigger Property="IsEnabled" Value="false"/>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</code>```

Basically what I am intending to do is to create a button at runtime, apply this style to the button, go to the template of the button, and change the text property of the textblock in the template of the button.

So for starters, instead of creating a button at runtime, i created one at compile time and named it "customButton". Then I tried to edit the text property of the button's templates' textblock but ran into exceptions.

```<code>TextBlock tb = this.customButton.Template.FindName("textBlock", customButton) as TextBlock;
tb.Text = "ASDDDQWEQWEQWE";
</code>```

Please advise thanks!

答:
I want to create a button to represent a company stock info like
  Company name, image, and the % increase in stock price all in one
  single button. So at runtime, ill get the top 10 stocks from an
  external API and create 10 buttons at runtime with the information and
  add it to a stackpanel in my main window.

You need use ListBox and ItemTempate for this kind of scenarios.
Try the below code.

```<code> <ListBox x:Name="lstBox">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Button>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding CompanyName}" Margin="0,0,10,0"/>
                        <TextBlock Text="{Binding Percent}" />
                    </StackPanel>
                </Button>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        ObservableCollection<CompanyModel> companies = new ObservableCollection<CompanyModel>();
        for (int i = 0; i < 10; i++)
        {
            CompanyModel companyModel = new CompanyModel()
            {
                Percent = i,
                CompanyName = "Name" + i
            };
            companies.Add(companyModel);
        }
        lstBox.ItemsSource = companies;
    }
}

class CompanyModel
    {
        public int Percent { get; set; }
        public string CompanyName { get; set; }
    }
</code>```

Title: How do I edit a WPF button at runtime

Body:
So I was using Expression Blend to design my button. I created a new button, edited the template of the button by removing everything within it. Then I added a grid into it and named it "grid". Inside the grid i added a textblock and called it "textBlock". Then i saved the template under Applications.

This is the content in the app.xaml file.

Basically what I am intending to do is to create a button at runtime, apply this style to the button, go to the template of the button, and change the text property of the textblock in the template of the button.

So for starters, instead of creating a button at runtime, i created one at compile time and named it "customButton". Then I tried to edit the text property of the button's templates' textblock but ran into exceptions.

TextBlock tb = this.customButton.Template.FindName("textBlock", customButton) as TextBlock;
tb.Text = "ASDDDQWEQWEQWE";

Please advise thanks!

Body:
I want to create a button to represent a company stock info like
  Company name, image, and the % increase in stock price all in one
  single button. So at runtime, ill get the top 10 stocks from an
  external API and create 10 buttons at runtime with the information and
  add it to a stackpanel in my main window.

You need use ListBox and ItemTempate for this kind of scenarios.
Try the below code.

 <ListBox x:Name="lstBox">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Button>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding CompanyName}" Margin="0,0,10,0"/>
                        <TextBlock Text="{Binding Percent}" />
                    </StackPanel>
                </Button>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        ObservableCollection<CompanyModel> companies = new ObservableCollection<CompanyModel>();
        for (int i = 0; i < 10; i++)
        {
            CompanyModel companyModel = new CompanyModel()
            {
                Percent = i,
                CompanyName = "Name" + i
            };
            companies.Add(companyModel);
        }
        lstBox.ItemsSource = companies;
    }
}

class CompanyModel
    {
        public int Percent { get; set; }
        public string CompanyName { get; set; }
    }


问:
How to cut up a webpage in header, footer, ...?
I have developed a website with 13 webpages. The majority of them have the same header, footer, right aside, ... I know that I can place a HTML or JSP file that contains the code for the header or footer and include it in all my pages so I do not have to write the same code in all my wepages. This is an example of what I will like to place in file called header.html which I would include in all my webpages:

```<code><header>
  <hr id="barraCabecera11">
  <hr id="barraCabecera12">
  <h1 id="nombreBarberia"> The Notorius Barbershop </h1>
  <nav>
    <ul>
      <li id="indexN"><a href="index.html">Inicio</a></li>
      <li id="seccion1N" onmouseover="ver(1)" onmouseout="ocultar(1)">
        <p id="conocenosN">Conocenos</p>
        <div id="subseccion1">
          <p><a href="Subpaginas/Conocenos/historia.html">Historia</a></p>
          <p><a href="Subpaginas/Conocenos/filosofia.html">Filosofía</a></p>
          <p><a href="Subpaginas/Conocenos/plantilla.html">Barberos/Peluqueros</a></p>
        </div>
      </li>
      <li id="seccion2N" onmouseover="ver(2)" onmouseout="ocultar(2)">
        <p id="eventosN">Eventos</p>
        <div id="subseccion2">
          <p><a href="Subpaginas/Eventos/reservar.html">Reservar</a></p>
          <p><a href="Subpaginas/Eventos/contratar.html">Contratar</a></p>
        </div>
      </li>
      <li id="hairstyleN"><a href="Subpaginas/hairstyle.html">Hairstyle</a></li>
      <li id="notbarN"><a href="Subpaginas/notbar.html">The NotBar</a></li>
      <li id="cursosN"><a href="Subpaginas/cursos.jsp">Cursos</a></li>
      <li id="contactanosN"><a href="Subpaginas/contactanos.html">Contáctanos</a></li>
    </ul>
    <div class="borrar"></div>
  </nav>
</header>
</code>```

The problem is that I have different relative links in the nav of this header, so I cannot include a file with the same content in all my webpages. Is there a standard way of changing these relative links depending on which webpage the header is included?
Please, let me know if I am not explaining myself well.

答:
I'm not sure if this is standard but I would change the href of the elements on each page by altering it in javascript after the page is loaded.

Edit: An example would be,given the following anchor tag:

```<code><a href="google.com" id="anchorTest">
</code>```

You would do:

```<code>document.getElementById('anchorTest').href = 'youtube.com';
</code>```

Body:
I have developed a website with 13 webpages. The majority of them have the same header, footer, right aside, ... I know that I can place a HTML or JSP file that contains the code for the header or footer and include it in all my pages so I do not have to write the same code in all my wepages. This is an example of what I will like to place in file called header.html which I would include in all my webpages:

 The Notorius Barbershop

Inicio

Conocenos

Historia

Filosofía

Barberos/Peluqueros

Eventos

Reservar

Contratar

Hairstyle

The NotBar

Cursos

Contáctanos

The problem is that I have different relative links in the nav of this header, so I cannot include a file with the same content in all my webpages. Is there a standard way of changing these relative links depending on which webpage the header is included?
Please, let me know if I am not explaining myself well.

Body:
I'm not sure if this is standard but I would change the href of the elements on each page by altering it in javascript after the page is loaded.

Edit: An example would be,given the following anchor tag:

<a href="google.com" id="anchorTest">

You would do:

document.getElementById('anchorTest').href = 'youtube.com';


问:
How to include the Google Cloud's JSON Project Key file in a Google Cloud Function?
I have a Google Cloud Function that works well and I want, once executed before the callback, to connect to Firestore to add a document to my Notifications collection.

```<code>const Firestore = require('@google-cloud/firestore');

const firestore = new Firestore({
  projectId: 'my-firebase-project',
  keyFilename: 'thekey.json',
});

var fsDocument = {
    'username': 'theuser',
    'organization': 'theorg',
    'attr': [
        {k:'key1', v:'val1'},
        {k:'key2', v:'val2'}
    ]
};

firestore.collection('Notifications').add(fsDocument).then(documentReference => {
    console.log('Added document with name' + documentReference.id);
});
</code>```

How can I include the key file to my google cloud function? So far, I am creating them in console.cloud.google.com.

答:
All files in your functions directory will be sent to Cloud Functions when you deploy.  You could put your credentials in a file under functions, then refer to it with a relative path like this:

```<code>const firestore = new Firestore({
  projectId: 'my-firebase-project',
  keyFilename: './thekey.json',
});
</code>```

You should only do this if your credentials are for a project different from the one running your Cloud Function.  If you're trying to access Firestore in the same project as the one running your function, just use the default credentials using the Admin SDK.  There are lots of examples of this in functions-samples.

Body:
I have a Google Cloud Function that works well and I want, once executed before the callback, to connect to Firestore to add a document to my Notifications collection.

const Firestore = require('@google-cloud/firestore');

const firestore = new Firestore({
  projectId: 'my-firebase-project',
  keyFilename: 'thekey.json',
});

var fsDocument = {
    'username': 'theuser',
    'organization': 'theorg',
    'attr': [
        {k:'key1', v:'val1'},
        {k:'key2', v:'val2'}
    ]
};

firestore.collection('Notifications').add(fsDocument).then(documentReference => {
    console.log('Added document with name' + documentReference.id);
});

How can I include the key file to my google cloud function? So far, I am creating them in console.cloud.google.com.

Body:
All files in your functions directory will be sent to Cloud Functions when you deploy.  You could put your credentials in a file under functions, then refer to it with a relative path like this:

const firestore = new Firestore({
  projectId: 'my-firebase-project',
  keyFilename: './thekey.json',
});

You should only do this if your credentials are for a project different from the one running your Cloud Function.  If you're trying to access Firestore in the same project as the one running your function, just use the default credentials using the Admin SDK.  There are lots of examples of this in functions-samples.


问:
My php Scripts is very slow at server
i'm testing an app hosted at: app.promls.net, but there is some mistake on the script execution, on localhost
takes only -> timer: 0.12875008583069 seconds. .
in the execution when is just plain text that are created via php.
and when content is created dinamically and cames from mysql database:
timer: 0.44203495979309 seconds.  /timer: 0.65762710571289 seconds. / timer: 0.48272085189819 seconds.
the times are diferent on the server. takes like 8 seconds on execution.

does anyone could give me a recomendation of how test and optimize my php execution.
i was optimizing the mysql database, cause some querys returns a tons of rows for a simple search, using describe and explain.
but know i have finished, and i would like to explore some new options for php execution.
i know that adding compression to html helps, but it only help on time of trasportation between server and final host when returns an html response. know i want to optimize php execution and if there are some tricks on mysql that could be implemented to help me improve the time response better.

note: i have thinking in use the hiphop for php and memcache or cassandra. but i guess those thinks are not re result for problem, cause i have no activities( means user actions) and no much information on my app.

thanks in advance i'm available for any comments or suggestions.

答:
First, off, try doing the following to your MYSQL DB:

Run  "OPTIMIZE TABLE mytable" on all of your tables

Run "ANALYZE TABLE mytable" on all of your tables.

Add indexes to the table fields that you are using

Be sure to substitute each table name for "mytable" in the above statements.

See if doing the first two makes a difference, then add the indexes.

Title: My php Scripts is very slow at server

ContentLicense: CC BY-SA 2.5


问:
Remove border around sprite image in Chrome
First time using this technique, seems that regardless what attributes I try to assign the border will not go away in Chrome. Other browsers are fine. I've tried outline:none, border:0; etc, etc. Also tried adding a colored border around the image, and noticed the the black border was still there within the colored border. Doesn't seem to want to go away.

Work-around's or advice much appreciated.

```<code>.share-link {
display: block;
width: 41px;
height: 32px;
text-decoration: none;
background: url("link-icon.png");
}

.share-link:hover {
background-position: -41px 0;
}

<a title="Share this Link" href="#"><img class="share-link"></a>
</code>```

答:
My base64 embedded images kept showing a grey line around it no matter what I did. Using
 instead of  worked for me.

BEFORE (wrong) I used:

in HTML:

```<code><img class='message-bubble-small'>
</code>```

in CSS:

```<code>img.message-bubble-small {
  background-image: url(data:image/png;base64,...);
  background-size: 16px 16px;
  width: 16px;
  height: 16px;
  float: left;
}
</code>```

AFTER I used:

in HTML:

```<code><div id='message-bubble-small'>
</code>```

in CSS:

```<code>#message-bubble-small {
  background-image: url(data:image/png;base64,...);
  background-size: 16px 16px;
  width: 16px;
  height: 16px;
  float: left;
}
</code>```

With the last example I have no more grey lines in Chrome.

Body:
First time using this technique, seems that regardless what attributes I try to assign the border will not go away in Chrome. Other browsers are fine. I've tried outline:none, border:0; etc, etc. Also tried adding a colored border around the image, and noticed the the black border was still there within the colored border. Doesn't seem to want to go away.

Work-around's or advice much appreciated.

.share-link {
display: block;
width: 41px;
height: 32px;
text-decoration: none;
background: url("link-icon.png");
}

.share-link:hover {
background-position: -41px 0;
}

Body:
My base64 embedded images kept showing a grey line around it no matter what I did. Using <div> instead of <img> worked for me.

BEFORE (wrong) I used:

in HTML:

<img class='message-bubble-small'>

in CSS:

img.message-bubble-small {
  background-image: url(data:image/png;base64,...);
  background-size: 16px 16px;
  width: 16px;
  height: 16px;
  float: left;
}

AFTER I used:

in HTML:

<div id='message-bubble-small'>

in CSS:

#message-bubble-small {
  background-image: url(data:image/png;base64,...);
  background-size: 16px 16px;
  width: 16px;
  height: 16px;
  float: left;
}

With the last example I have no more grey lines in Chrome.


问:
GWT & Java EE SessionScoped bean not persisting
I'm playing w/ EE and want to persist a user session state. I have the session bean here:

```<code>@Stateful(mappedName = "UserSessionState")
@Named("UserSessionState")
@SessionScoped
@StatefulTimeout(value = 5, unit = TimeUnit.MINUTES)
public class UserSessionState implements Serializable
{
    private boolean hasPlayerId = false;
    private String playerId = "";

    public void setRandomPlayerId()
    {
        playerId = UUID.uuid();
        hasPlayerId = true;
    }

    public boolean hasPlayerId()
    {
        return hasPlayerId;
    }

    public String getPlayerId()
    {
        return playerId;
    }
}
</code>```

And a servlet here (GameState is an Application Scoped bean that is working as expected, CustomExtendedHttpServlet is just a simple extension of HttpServlet)

```<code>public class NewUserJoined extends CustomExtendedHttpServlet
{
    @Inject
    protected GameState gameState;

    @Inject
    protected UserSessionState user;

    @Override
    protected String doGetImpl(HttpServletRequest request, HttpServletResponse response, UserContext userLoginContext)
    {
        if (!user.hasPlayerId())
        {
            user.setRandomPlayerId();
        }
        String userId = user.getPlayerId();

        if (!gameState.hasUser(userId))
        {
            gameState.addUser(userId, user);
            return "Hi, your ID is: " + user.getPlayerId() + ", there are " + gameState.getUserCount() + " other players here";
        }
        else
        {
            return user.getPlayerId() + " you're already in the game, there are: " + gameState.getUserCount() + " other players here";
        }
    }
}
</code>```

I'm not sure what's going on, but whenever I call the New User Joined servlet from the same HTTP session, I get this response on the first call (as expected):

"Hi, your ID is: , there are 1 other players here"

Repeating the same servlet call in the same session gives me the same message:
"Hi, your ID is: , there are 2 other players here"
...

It looks like a new instance of User Session State is getting created over and over. Am I doing this correctly?

EDIT 1: Here the code I use to send a request. It appears I'm getting a new session ID with each request, what could cause that?

```<code>RequestCallback callback = new RequestCallback()
{
    @Override
    public void onResponseReceived(Request request, Response response)
    {
        log(response.getText());
    }

    @Override
    public void onError(Request request, Throwable exception)
    {
        log(
            "Response Error | "
            + "Exception: " + exception);
    }
};

RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, SERVLET_URL);
rb.setCallback(callback);

try
{
    rb.send();
}
catch (RequestException e)
{
    log("Response Error | "
        + "Exception: " + e);
}
</code>```

答:
Figured out the issue,

Turns out I had an old workaround in the GWT client that was changing the host to get around a CORS issue. Because the response didn't match up to the origin, the cookie wasn't getting sent with future servlet GET calls.

Body:
I'm playing w/ EE and want to persist a user session state. I have the session bean here:

@Stateful(mappedName = "UserSessionState")
@Named("UserSessionState")
@SessionScoped
@StatefulTimeout(value = 5, unit = TimeUnit.MINUTES)
public class UserSessionState implements Serializable
{
    private boolean hasPlayerId = false;
    private String playerId = "";

    public void setRandomPlayerId()
    {
        playerId = UUID.uuid();
        hasPlayerId = true;
    }

    public boolean hasPlayerId()
    {
        return hasPlayerId;
    }

    public String getPlayerId()
    {
        return playerId;
    }
}

And a servlet here (GameState is an Application Scoped bean that is working as expected, CustomExtendedHttpServlet is just a simple extension of HttpServlet)

public class NewUserJoined extends CustomExtendedHttpServlet
{
    @Inject
    protected GameState gameState;

    @Inject
    protected UserSessionState user;

    @Override
    protected String doGetImpl(HttpServletRequest request, HttpServletResponse response, UserContext userLoginContext)
    {
        if (!user.hasPlayerId())
        {
            user.setRandomPlayerId();
        }
        String userId = user.getPlayerId();

        if (!gameState.hasUser(userId))
        {
            gameState.addUser(userId, user);
            return "Hi, your ID is: " + user.getPlayerId() + ", there are " + gameState.getUserCount() + " other players here";
        }
        else
        {
            return user.getPlayerId() + " you're already in the game, there are: " + gameState.getUserCount() + " other players here";
        }
    }
}

I'm not sure what's going on, but whenever I call the New User Joined servlet from the same HTTP session, I get this response on the first call (as expected):

"Hi, your ID is: , there are 1 other players here"

Repeating the same servlet call in the same session gives me the same message:
"Hi, your ID is: , there are 2 other players here"
...

It looks like a new instance of User Session State is getting created over and over. Am I doing this correctly?

EDIT 1: Here the code I use to send a request. It appears I'm getting a new session ID with each request, what could cause that?

RequestCallback callback = new RequestCallback()
{
    @Override
    public void onResponseReceived(Request request, Response response)
    {
        log(response.getText());
    }

    @Override
    public void onError(Request request, Throwable exception)
    {
        log(
            "Response Error | "
            + "Exception: " + exception);
    }
};

RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, SERVLET_URL);
rb.setCallback(callback);

try
{
    rb.send();
}
catch (RequestException e)
{
    log("Response Error | "
        + "Exception: " + e);
}


问:
The code is not indented
a program to display the numbers indivisible by 5 but not 7

```<code> for i in range(2000,3201):
if i%5!=0 and i%7==0:
    print i

else:
    continue
</code>```

Identationerror: unindent does not match any outer indentation level
specifically on line 5, the else statement

答:
Try something like this:</p>

```<code>for i in range(2000,3201):
  if i%5!=0 and i%7==0:
    print i
  else:
    continue
</code>```

Title: The code is not indented

Body:
a program to display the numbers indivisible by 5 but not 7

 for i in range(2000,3201):
if i%5!=0 and i%7==0:
    print i

else:
    continue

Identationerror: unindent does not match any outer indentation level
specifically on line 5, the else statement

Body:
Try something like this:

for i in range(2000,3201):
  if i%5!=0 and i%7==0:
    print i
  else:
    continue


问:
Using MobX observable decorators with create-react-app
The MobX docs tell me I must "use the transform plugin transform-decorators-legacy and make sure it is first in the plugins list", in order for the decorators to work. The MobX boilerplate project suggests I need a .babelrc like:

```<code>{
  "presets": [
    "react",
    "es2015",
    "stage-1"
  ],
  "plugins": ["transform-decorators-legacy", "react-hot-loader/babel"]
}
</code>```

How do I do that with a create-react-app generated project? Any attempt to use @ decorators errors. There is no .babelrc even after the project is 'ejected'.

答:
This is the best solution I've found without ejecting. Replace create-react-scripts.

https://www.npmjs.com/package/custom-react-scripts

If you have a new project start by using this in your terminal:

```<code>create-react-app my-app --scripts-version custom-react-scripts
</code>```

Then cd into my-app directory and create a .env file. Edit the .env file to this:

```<code>REACT_APP_BABEL_STAGE_0=true
REACT_APP_DECORATORS=true
</code>```

Your app will now support decorators.

If you have an existing app and want to add this. Add the .env like above then:

```<code>npm i custom-react-scripts --save
</code>```

remove react-scripts in your package.json. Do not change the scripts from react-scripts start to create-react-scripts start. Leave the scripts as is.

now add your mobx stuff with decorators and enjoy less boilerplate code.

my final package.json

{
  "name": "mobx-test",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "custom-react-scripts": "^0.2.1",
    "mobx": "^3.4.0",
    "mobx-react": "^4.3.5",
    "react": "^16.2.0",
    "react-dom": "^16.2.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

oh and if you are using vscode you will want to hide the warnings about unsupported decorators. To do that add a tsconfig.json file to your project with this

{
    "compilerOptions": {
        "experimentalDecorators": true,
        "allowJs": true
    }
}

Body:
The MobX docs tell me I must "use the transform plugin transform-decorators-legacy and make sure it is first in the plugins list", in order for the decorators to work. The MobX boilerplate project suggests I need a .babelrc like:

{
  "presets": [
    "react",
    "es2015",
    "stage-1"
  ],
  "plugins": ["transform-decorators-legacy", "react-hot-loader/babel"]
}

How do I do that with a create-react-app generated project? Any attempt to use @ decorators errors. There is no .babelrc even after the project is 'ejected'.

Body:
This is the best solution I've found without ejecting. Replace create-react-scripts.

https://www.npmjs.com/package/custom-react-scripts

If you have a new project start by using this in your terminal:

create-react-app my-app --scripts-version custom-react-scripts

Then cd into my-app directory and create a .env file. Edit the .env file to this:

REACT_APP_BABEL_STAGE_0=true
REACT_APP_DECORATORS=true

Your app will now support decorators.

If you have an existing app and want to add this. Add the .env like above then:

npm i custom-react-scripts --save

remove react-scripts in your package.json. Do not change the scripts from react-scripts start to create-react-scripts start. Leave the scripts as is.

now add your mobx stuff with decorators and enjoy less boilerplate code.

my final package.json

{
  "name": "mobx-test",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "custom-react-scripts": "^0.2.1",
    "mobx": "^3.4.0",
    "mobx-react": "^4.3.5",
    "react": "^16.2.0",
    "react-dom": "^16.2.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

oh and if you are using vscode you will want to hide the warnings about unsupported decorators. To do that add a tsconfig.json file to your project with this

{
    "compilerOptions": {
        "experimentalDecorators": true,
        "allowJs": true
    }
}


问:
Break up GIT branches into separate directories
I've inherited a Git repo that has one directory and about 20 branches in it.  Each branch contains totally unique code - something with it's own make and source that would normally (if I set it up) be in separate subdirs.  It's very tough for me to work with as is.

How can I break up these 20+ branches into 20 directories, keeping the histories intact of each branch and establish a more traditional Git layout.

答:
You should:

create a temp folder

create folders for each branch in your temp folder

copy all contents of each branch in each folder

remove the contents in your branch master of your git repository if I understand what you want

move all contents of temp folder in your git repository

you can automate the process with a shell code thanks to git branch -a


问:
How do i toggleClass on img in Gridview?
Im trying to enlarge pictures in a ASP gridview with jquery like this.

```<code> <style>
  .enlargeImg{
   width:600px;
   height:600px;
 }

  </style>
  <script src="../Scripts/jquery-1.10.2.js"></script>

   <script type="text/javascript">
       $(document).ready(function () {
           $('.pageContainer').on('click','img', function () {
           $(this).toggleClass('.enlargeImg');
           });

        });
   </script>
</code>```

I hit the picture alright(can call an alert), but i can not get the toggleclass to work. Is it possible to do so?

答:
You dont need the extra dot when using toggleClass (.enlargeImg), just use enlargeImg.

p.s. I reduced the size of your image in css so that it fits inside the stack snippet.

$(document).ready(function() {
  $('.pageContainer').on('click', 'img', function() {
    $(this).toggleClass('enlargeImg');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.basicImage{
  width: 100px;
  height: 50px;
}

.enlargeImg {
  width: 200px;
  height: 150px;
}</code>```

```

Body:
Im trying to enlarge pictures in a ASP gridview with jquery like this.

I hit the picture alright(can call an alert), but i can not get the toggleclass to work. Is it possible to do so?

Body:
You dont need the extra dot when using toggleClass (.enlargeImg), just use enlargeImg.

p.s. I reduced the size of your image in css so that it fits inside the stack snippet.

$(document).ready(function() {
  $('.pageContainer').on('click', 'img', function() {
    $(this).toggleClass('enlargeImg');
  });
});

.basicImage{
  width: 100px;
  height: 50px;
}

.enlargeImg {
  width: 200px;
  height: 150px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='pageContainer'>
  <img src='https://kaggle2.blob.core.windows.net/datasets-images/152/327/43994ab64328703c9e656b04e6769947/dataset-original.jpg' class='basicImage' />
</div>


问:
CAAnimation on multiple SceneKit nodes simultaneously
I am creating an application wherein I am using SceneKit contents in AR app. I have multiple nodes which are being placed at different places in my scene. They may or may not be necessarily be inside one parent node. The user has to choose a correct node, as per challenge set by the application. If the user chooses correct node, the correct node goes through one kind of animation and incorrect ones (may be several) undergo another set of animation. I am accomplishing animations using CAAnimation directly, which is all good. Basically to accomplish this, I am creating an array of all nodes and using them for animation.

```<code>DispatchQueue.global(qos: .userInteractive).async { [weak self] in
    for node in (self?.nodesAddedInScene.keys)! {
        for index in 1...node.childNodes.count - 1 {
            if node.childNodes[index].childNodes.first?.name == "target" {
                self?.riseUpSpinAndFadeAnimation(on: node.childNodes[index])
            } else {
                self?.fadeAnimation(on: node.childNodes[index])
            }
        }
    }
}
</code>```

When user chooses "target" node, that node goes through one set of animation and others go through another set of animations.

RiseUpSpinAndFadeAnimation:

```<code>    private func riseUpSpinAndFadeAnimation(on shape: SCNNode) {
        let riseUpAnimation = CABasicAnimation(keyPath: "position")
        riseUpAnimation.fromValue = SCNVector3(shape.position.x, shape.position.y, shape.position.z)
        riseUpAnimation.toValue = SCNVector3(shape.position.x, shape.position.y + 0.5, shape.position.z)

        let spinAnimation = CABasicAnimation(keyPath: "eulerAngles.y")
        spinAnimation.toValue = shape.eulerAngles.y + 180.0
        spinAnimation.autoreverses = true

        let fadeAnimation = CABasicAnimation(keyPath: "opacity")
        fadeAnimation.toValue = 0.0

        let riseUpSpinAndFadeAnimation = CAAnimationGroup()
        riseUpSpinAndFadeAnimation.animations = [riseUpAnimation, fadeAnimation, spinAnimation]
        riseUpSpinAndFadeAnimation.duration = 1.0
        riseUpSpinAndFadeAnimation.fillMode = kCAFillModeForwards
        riseUpSpinAndFadeAnimation.isRemovedOnCompletion = false

        shape.addAnimation(riseUpSpinAndFadeAnimation, forKey: "riseUpSpinAndFade")
    }
</code>```

FadeAnimation:

```<code>private func fadeAnimation(on shape: SCNNode) {
    let fadeAnimation = CABasicAnimation(keyPath: "opacity")
    fadeAnimation.toValue = 0.0
    fadeAnimation.duration = 0.5
    fadeAnimation.fillMode = kCAFillModeForwards
    fadeAnimation.isRemovedOnCompletion = false
    shape.addAnimation(fadeAnimation, forKey: "fade")
}
</code>```

I expect animations to work out, which they are actually. However, the issue is since the nodes are in an array animation is not being done at the same time for all nodes. There are minute differences in start of animation which actually is leading to not so good UI.

What I am looking for is a logic wherein I can attach animations on all nodes and call these animations together later when let's say the user taps correct node. Arrays don't seem to be a wise choice to me. However, I am afraid if I make all of these nodes child nodes of an empty node and the run animation on that empty node, possibly it would be difficult to manage placement of these child nodes in the first place since they supposed to be kept at random distances and not necessarily close together. Given that this ultimately drives AR experience, it more so becomes a bummer.

Requesting some inputs whether there are methods to attach animation to multiple (selected out of those) object (even if sequentially) but RUN them together. I used shape.addAnimation(fadeAnimation, forKey: "fade") "forKey", can that be made of use in such use case? Any pointers appreciated.

答:
Manganese,

I am just taking a guess here or could spark an idea for you :-)

I am focusing on this part of your question:
"What I am looking for is a logic wherein I can attach animations on all nodes and call these animations together later when let's say the user taps correct node."

I wonder if SCNTransaction:
[https://developer.apple.com/documentation/scenekit/scntransaction][1]
might do the trick

or maybe dispatch.sync or async (totally guessing...but could help)
[https://developer.apple.com/documentation/dispatch][1]

or I am way off the mark :-)
just trying to help out....

We all learn by sharing what we know

RAD

Body:
I am creating an application wherein I am using SceneKit contents in AR app. I have multiple nodes which are being placed at different places in my scene. They may or may not be necessarily be inside one parent node. The user has to choose a correct node, as per challenge set by the application. If the user chooses correct node, the correct node goes through one kind of animation and incorrect ones (may be several) undergo another set of animation. I am accomplishing animations using CAAnimation directly, which is all good. Basically to accomplish this, I am creating an array of all nodes and using them for animation.

DispatchQueue.global(qos: .userInteractive).async { [weak self] in
    for node in (self?.nodesAddedInScene.keys)! {
        for index in 1...node.childNodes.count - 1 {
            if node.childNodes[index].childNodes.first?.name == "target" {
                self?.riseUpSpinAndFadeAnimation(on: node.childNodes[index])
            } else {
                self?.fadeAnimation(on: node.childNodes[index])
            }
        }
    }
}

When user chooses "target" node, that node goes through one set of animation and others go through another set of animations.

RiseUpSpinAndFadeAnimation:

    private func riseUpSpinAndFadeAnimation(on shape: SCNNode) {
        let riseUpAnimation = CABasicAnimation(keyPath: "position")
        riseUpAnimation.fromValue = SCNVector3(shape.position.x, shape.position.y, shape.position.z)
        riseUpAnimation.toValue = SCNVector3(shape.position.x, shape.position.y + 0.5, shape.position.z)

        let spinAnimation = CABasicAnimation(keyPath: "eulerAngles.y")
        spinAnimation.toValue = shape.eulerAngles.y + 180.0
        spinAnimation.autoreverses = true

        let fadeAnimation = CABasicAnimation(keyPath: "opacity")
        fadeAnimation.toValue = 0.0

        let riseUpSpinAndFadeAnimation = CAAnimationGroup()
        riseUpSpinAndFadeAnimation.animations = [riseUpAnimation, fadeAnimation, spinAnimation]
        riseUpSpinAndFadeAnimation.duration = 1.0
        riseUpSpinAndFadeAnimation.fillMode = kCAFillModeForwards
        riseUpSpinAndFadeAnimation.isRemovedOnCompletion = false

        shape.addAnimation(riseUpSpinAndFadeAnimation, forKey: "riseUpSpinAndFade")
    }

FadeAnimation:

private func fadeAnimation(on shape: SCNNode) {
    let fadeAnimation = CABasicAnimation(keyPath: "opacity")
    fadeAnimation.toValue = 0.0
    fadeAnimation.duration = 0.5
    fadeAnimation.fillMode = kCAFillModeForwards
    fadeAnimation.isRemovedOnCompletion = false
    shape.addAnimation(fadeAnimation, forKey: "fade")
}

I expect animations to work out, which they are actually. However, the issue is since the nodes are in an array animation is not being done at the same time for all nodes. There are minute differences in start of animation which actually is leading to not so good UI.

What I am looking for is a logic wherein I can attach animations on all nodes and call these animations together later when let's say the user taps correct node. Arrays don't seem to be a wise choice to me. However, I am afraid if I make all of these nodes child nodes of an empty node and the run animation on that empty node, possibly it would be difficult to manage placement of these child nodes in the first place since they supposed to be kept at random distances and not necessarily close together. Given that this ultimately drives AR experience, it more so becomes a bummer.

Requesting some inputs whether there are methods to attach animation to multiple (selected out of those) object (even if sequentially) but RUN them together. I used shape.addAnimation(fadeAnimation, forKey: "fade") "forKey", can that be made of use in such use case? Any pointers appreciated.


问:
How to add vertical grid line to my d3 chart
I would like to know what I'm doing wrong. I've followed some tutorials(Vertical gridSimple gridlines in d3js v4) about making gridlines in 3DJS V4, and I've tried to combine their code with my own.

My chart looks like this:

However I would like to have some vertical grid lines in the svg, so the chart will be easier to read.

My code:

```<code>function makeChart(desktopData,mobileData,tabletData){
    console.log(desktopData);
    var WIDTH = 1200,
        HEIGHT = 300,
        MARGINS = {
                top:20,
            right:20,
            bottom:20,
            left:50
        }
    var vis = d3.select("#visualisation"),
        WIDTH = 1200,
        HEIGHT = 300,
        MARGINS = {
            top: 20,
            right: 20,
            bottom: 20,
            left: 50
        },
        xScale = d3.scale.linear().range([MARGINS.left,WIDTH-MARGINS.right]).domain([00,23]),

        yScale = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([00,100]),

        xAxis = d3.svg.axis()
            .scale(xScale)

        yAxis = d3.svg.axis()
            .scale(yScale)
            .ticks(10)
            .tickPadding(20)
            .orient("left");

    vis.append("svg:g")
        .attr("class","axis")
        .attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")")
        .call(xAxis);

    vis.append("svg:g")
        .attr("class","axis")
        .attr("transform", "translate(" + (MARGINS.left) + ",0)")
        .call(yAxis);

    var lineGen = d3.svg.line()
        .x(function(d){
            return xScale(d.uur);
        })
        .y(function(d){
            return yScale(d.pageviews);
        });

    vis.append('svg:path')
        .attr('d', lineGen(desktopData))
        .attr('stroke','deepskyblue')
        .attr('stroke-width',2)
        .attr('fill','none');

    vis.append('svg:path')
        .attr('d', lineGen(mobileData))
        .attr('stroke','orange')
        .attr('stroke-width',2)
        .attr('fill','none');

    vis.append('svg:path')
        .attr('d', lineGen(tabletData))
        .attr('stroke','deeppink')
        .attr('stroke-width',2)
        .attr('fill','none');

// gridlines in y axis function
    function make_y_gridlines() {
        return d3.svg.axis(yScale)
    }

    // add the Y gridlines
    vis.append("g")
        .attr("class", "grid")
        .call(make_y_gridlines()
            .tickSize(-WIDTH)
            .tickFormat("")
        )

}
</code>```

My css:

```<code>.grid line {
  stroke: lightgrey;
  stroke-opacity: 0.7;
  shape-rendering: crispEdges;
}

.grid path {
  stroke-width: 0;
}
</code>```

答: If I'm not mistaken in your CSS your .grid path{stroke-width:0;} should read .grid path{stroke-width:0.5;} the 0.5 can be which ever number you would like. A stroke width of 0 effectively removes the lines.

Body:
I would like to know what I'm doing wrong. I've followed some tutorials(Vertical gridSimple gridlines in d3js v4) about making gridlines in 3DJS V4, and I've tried to combine their code with my own.

My chart looks like this:

However I would like to have some vertical grid lines in the svg, so the chart will be easier to read.

My code:

function makeChart(desktopData,mobileData,tabletData){
    console.log(desktopData);
    var WIDTH = 1200,
        HEIGHT = 300,
        MARGINS = {
                top:20,
            right:20,
            bottom:20,
            left:50
        }
    var vis = d3.select("#visualisation"),
        WIDTH = 1200,
        HEIGHT = 300,
        MARGINS = {
            top: 20,
            right: 20,
            bottom: 20,
            left: 50
        },
        xScale = d3.scale.linear().range([MARGINS.left,WIDTH-MARGINS.right]).domain([00,23]),

        yScale = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([00,100]),

        xAxis = d3.svg.axis()
            .scale(xScale)

        yAxis = d3.svg.axis()
            .scale(yScale)
            .ticks(10)
            .tickPadding(20)
            .orient("left");

    vis.append("svg:g")
        .attr("class","axis")
        .attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")")
        .call(xAxis);

    vis.append("svg:g")
        .attr("class","axis")
        .attr("transform", "translate(" + (MARGINS.left) + ",0)")
        .call(yAxis);

    var lineGen = d3.svg.line()
        .x(function(d){
            return xScale(d.uur);
        })
        .y(function(d){
            return yScale(d.pageviews);
        });

    vis.append('svg:path')
        .attr('d', lineGen(desktopData))
        .attr('stroke','deepskyblue')
        .attr('stroke-width',2)
        .attr('fill','none');

    vis.append('svg:path')
        .attr('d', lineGen(mobileData))
        .attr('stroke','orange')
        .attr('stroke-width',2)
        .attr('fill','none');

    vis.append('svg:path')
        .attr('d', lineGen(tabletData))
        .attr('stroke','deeppink')
        .attr('stroke-width',2)
        .attr('fill','none');

// gridlines in y axis function
    function make_y_gridlines() {
        return d3.svg.axis(yScale)
    }

    // add the Y gridlines
    vis.append("g")
        .attr("class", "grid")
        .call(make_y_gridlines()
            .tickSize(-WIDTH)
            .tickFormat("")
        )

}

My css:

.grid line {
  stroke: lightgrey;
  stroke-opacity: 0.7;
  shape-rendering: crispEdges;
}

.grid path {
  stroke-width: 0;
}


问:
Draw the border around particular part of text in label
I have attached a screen shot of label should show following contents.
Time stamp text appended by two images and again one text having white border.
    I've append images to label by using NSTextAttachment then i'm appending the text that has to show either at last or in between two images depends on condition. With one more label I can achieve this easily if text comes every time at the end but it won't.I saw so many tutorials to create the border for complete text of label.Is there any way to create border only for particular part of label text.<img src="https://i.stack.imgur.com/w7nJe.png" alt="enter image description here"> </p>

答:
You need to make an image with your needed text and attach to the text as NSTextAttachment here is the implementation for that

Objective-C Version
You can make your PG image like this

```<code>@implementation ImageHelper

+(UIImage*)imageForText:(NSString*)text{
        UILabel * lblBadge = [[UILabel alloc] initWithFrame:CGRectMake(0,0,16,16)];
        [lblBadge setTextAlignment:NSTextAlignmentCenter];
        [lblBadge setLineBreakMode:NSLineBreakByClipping];
        [lblBadge setTextColor:[UIColor darkGrayColor]];
        [lblBadge.layer setCornerRadius:2.0f];
        [lblBadge.layer setBorderWidth:1];
        [lblBadge setText:text];
        [lblBadge sizeToFit];
        [lblBadge setBounds:CGRectMake(0,0,lblBadge.bounds.size.width + 4,lblBadge.bounds.size.height)];

        UIGraphicsBeginImageContextWithOptions(lblBadge.bounds.size, NO, [UIScreen mainScreen].scale);
        [lblBadge.layer setAllowsEdgeAntialiasing:YES];
        [lblBadge.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return img;
}

@end
</code>```

example of Use

```<code>NSMutableAttributedString * normalNameString = [[NSMutableAttributedString alloc]initWithString:@"testing "];

NSTextAttachment * attachment = [[NSTextAttachment alloc] init];
attachment.image = [ImageHelper imageForText:@"PG-13"];
attachment.bounds = CGRectMake(0, -6, attachment.image.size.width, attachment.image.size.height);
[normalNameString appendAttributedString:[NSAttributedString attributedStringWithAttachment:attachment]];

self.lblText.attributedText = normalNameString;
</code>```

Swift Version

You can make your PG image like this

```<code>class imageHelper{
    static func pgImage(textValue:String) ->UIImage{
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: 15, height: 16))
        label.lineBreakMode = .byClipping
        label.textAlignment = .center
        label.textColor = UIColor.darkGray
        label.layer.borderColor = UIColor.darkGray.cgColor
        label.layer.borderWidth = 1
        label.layer.cornerRadius = 2
        label.text = textValue
        label.sizeToFit()
        label.bounds = CGRect(x: 0, y: 0, width: label.bounds.size.width + 4, height: label.bounds.size.height)

        UIGraphicsBeginImageContextWithOptions(label.bounds.size, false, UIScreen.main.scale)
        label.layer.allowsEdgeAntialiasing = true
        label.layer.render(in: UIGraphicsGetCurrentContext()!)

        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
}
</code>```

example of Use

```<code>        let normalNameString = NSMutableAttributedString.init(string: "testing ")

        let attachment = NSTextAttachment()
        attachment.image = imageHelper.pgImage(textValue: "PG-13")
        attachment.bounds = CGRect(x: 0, y: -6, width: (attachment.image?.size.width)!, height: (attachment.image?.size.height)!)
        normalNameString.append(NSAttributedString(attachment: attachment))

        self.lblText.attributedText = normalNameString
</code>```

RESULT

Body:
You need to make an image with your needed text and attach to the text as NSTextAttachment here is the implementation for that

Objective-C Version
You can make your PG image like this

@implementation ImageHelper

+(UIImage*)imageForText:(NSString*)text{
        UILabel * lblBadge = [[UILabel alloc] initWithFrame:CGRectMake(0,0,16,16)];
        [lblBadge setTextAlignment:NSTextAlignmentCenter];
        [lblBadge setLineBreakMode:NSLineBreakByClipping];
        [lblBadge setTextColor:[UIColor darkGrayColor]];
        [lblBadge.layer setCornerRadius:2.0f];
        [lblBadge.layer setBorderWidth:1];
        [lblBadge setText:text];
        [lblBadge sizeToFit];
        [lblBadge setBounds:CGRectMake(0,0,lblBadge.bounds.size.width + 4,lblBadge.bounds.size.height)];

        UIGraphicsBeginImageContextWithOptions(lblBadge.bounds.size, NO, [UIScreen mainScreen].scale);
        [lblBadge.layer setAllowsEdgeAntialiasing:YES];
        [lblBadge.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return img;
}

@end

example of Use

NSMutableAttributedString * normalNameString = [[NSMutableAttributedString alloc]initWithString:@"testing "];

NSTextAttachment * attachment = [[NSTextAttachment alloc] init];
attachment.image = [ImageHelper imageForText:@"PG-13"];
attachment.bounds = CGRectMake(0, -6, attachment.image.size.width, attachment.image.size.height);
[normalNameString appendAttributedString:[NSAttributedString attributedStringWithAttachment:attachment]];

self.lblText.attributedText = normalNameString;

Swift Version

You can make your PG image like this

class imageHelper{
    static func pgImage(textValue:String) ->UIImage{
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: 15, height: 16))
        label.lineBreakMode = .byClipping
        label.textAlignment = .center
        label.textColor = UIColor.darkGray
        label.layer.borderColor = UIColor.darkGray.cgColor
        label.layer.borderWidth = 1
        label.layer.cornerRadius = 2
        label.text = textValue
        label.sizeToFit()
        label.bounds = CGRect(x: 0, y: 0, width: label.bounds.size.width + 4, height: label.bounds.size.height)

        UIGraphicsBeginImageContextWithOptions(label.bounds.size, false, UIScreen.main.scale)
        label.layer.allowsEdgeAntialiasing = true
        label.layer.render(in: UIGraphicsGetCurrentContext()!)

        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
}

example of Use

        let normalNameString = NSMutableAttributedString.init(string: "testing ")

        let attachment = NSTextAttachment()
        attachment.image = imageHelper.pgImage(textValue: "PG-13")
        attachment.bounds = CGRect(x: 0, y: -6, width: (attachment.image?.size.width)!, height: (attachment.image?.size.height)!)
        normalNameString.append(NSAttributedString(attachment: attachment))

        self.lblText.attributedText = normalNameString

RESULT


问:
That A-Ha Moment for Understanding OO Design in C#
I've been studying C# for a couple of years, reading voraciously, even taking a few C# data access courses from Microsoft.  I've also been reading books on OOP.  I'm coding a web-based database application at work.  While my job title is not "programmer", I'm fortunate enough to be able to work on this as a side project.  I coded in Basic in the early 80's and was even good at utilizing pokes and peeks to manipulate the Apple ][ + and the TRS-80 to astound and amaze my friends.  But that was a very linear approach to coding.

All this being said, something is just not clicking with me.  I haven't had that a-ha moment with either C# or OOP that gives me the ability to sit down, open up VS2008, and start coding.  I have to study other people's code so much that it simply seems like I'm not doing anything on my own.  I'm getting discouraged.

It's not like I'm not capable of it.  I picked up t-sql really quickly.  Someone can tell me what information they want out of the database and I can code out the tsql in a matter of a few minutes to give them what they want.  SQL is something that I get.  This isn't happening for me with OOP or C#.  Granted, C# is inherently more complex, but at some point it has to click.  Right?

I read over stackoverflow and I'm overwhelmed at how infinitely smart you all are.

What was it for you that made it click?

Edited to add:
A lot of the answers here were outstanding.  However, one in particular seemed to have risen to the top and that's the one I marked as the "answer".  I also hate not marking my questions with the answer.

答:
The following didn't make OO click for me (it already had when I heard it), but I did find it a very nice nutshell description.

A collegue of mine is fond of quoting a statement from one of his college professors, which went something like this:

Write out a grid with the rows labeled by data types and the columns labeled by operations on the data. If you slice your implementation horizontally, you're doing object-oriented programming. If you slice it vertically, you're doing functional programming.

Try thinking of OO as a way to organize your code in which the implementation of an operation on a programmer-defined data type is bundled into the definition of the data.

OwnerDisplayName: GregD

LastEditorDisplayName: GregD


问:
Matplotlib: Plots in Loop appear again at end of Loop
I'm getting into Python and managed to create a Loop, which plots different data and is updating every loopcount.
But, after the loop end, all plots appear again at the bottom of the output.
So, it shows my plots at z=0,1,2,3,... and stops at the last z-value, then all plots for all z-values show below the final plot. I'm using python 3.6 with Jupyter.</p>

```<code>for k in range(0,size(z),50):
    figure()
    w=z[k]
    name = "file_%s.png" % k
    name2 = "z = %s, Index = %s" % (z[k],k)
    title(name2)
    imshow(I[:,:,k], cmap=plt.cm.YlGnBu_r)
    display.clear_output(wait=True)
    display.display(pl.gcf())
    savefig(name)
    time.sleep(0.1)

print('End of Loop')
</code>```

答:
Try using plt.show() instead of display.display(pl.gcf()).

You might have to add %matplotlib inline to the first row of your cell.

Also: It seems you're using iPython, please add that as a tag.
Plus by convention pyplot is imported as plt not as pl

Body:
I'm getting into Python and managed to create a Loop, which plots different data and is updating every loopcount.
But, after the loop end, all plots appear again at the bottom of the output.
So, it shows my plots at z=0,1,2,3,... and stops at the last z-value, then all plots for all z-values show below the final plot. I'm using python 3.6 with Jupyter.

for k in range(0,size(z),50):
    figure()
    w=z[k]
    name = "file_%s.png" % k
    name2 = "z = %s, Index = %s" % (z[k],k)
    title(name2)
    imshow(I[:,:,k], cmap=plt.cm.YlGnBu_r)
    display.clear_output(wait=True)
    display.display(pl.gcf())
    savefig(name)
    time.sleep(0.1)

print('End of Loop')


问:
When to use a pipe in Angular
Is there any rule, or best practice to tell when a pipe is best over a component method ?

Maybe something like, when something is purly a view logic and doesn't contain any domain logic

答:
Quote from Angular Best Practices — August 2017 Edition

One scenario is usually we subscribe to Observables and get the values when it is ready.

```<code>...
template: `
    {{myData | json}}
`)
export class XXXComponent {
    myData;
    constructor(http: HttpClient) {
        http.get('path/to/my/data/api.json')
        .subscribe(data => {
            this.myData = data;
        });
    }
}
</code>```

The better way is using async pip within template and let Angular manage the lifecycle for us. The Async pipe will cancel HTTP requests if the data is no longer needed, instead of completing, processing, and then doing nothing with it.

```<code>...
template: `
    {{data | async | json}}
`)
export class XXXComponent {
    data;
    constructor(http: HttpClient) {
        this.data = http.get('path/to/my/api.json');
    }
}
</code>```

Most cases pipe are used for transforming data, one of the advantages is it is simple AND it is chaining! You can do a lot of combinations based on your specific requirements and each pipe can be reused.

{{ myArray | slice:0:2 | json }}

Title: When to use a pipe in Angular

Body:
Quote from Angular Best Practices — August 2017 Edition

One scenario is usually we subscribe to Observables and get the values when it is ready.

...
template: `
    {{myData | json}}
`)
export class XXXComponent {
    myData;
    constructor(http: HttpClient) {
        http.get('path/to/my/data/api.json')
        .subscribe(data => {
            this.myData = data;
        });
    }
}

The better way is using async pip within template and let Angular manage the lifecycle for us. The Async pipe will cancel HTTP requests if the data is no longer needed, instead of completing, processing, and then doing nothing with it.

...
template: `
    {{data | async | json}}
`)
export class XXXComponent {
    data;
    constructor(http: HttpClient) {
        this.data = http.get('path/to/my/api.json');
    }
}

Most cases pipe are used for transforming data, one of the advantages is it is simple AND it is chaining! You can do a lot of combinations based on your specific requirements and each pipe can be reused.
<p>{{ myArray | slice:0:2 | json }}</p>


问:
Remove ArrayList duplicates in a text file - Java
I want to remove the duplicates of userNames in the ArrayList. I've tried to convert the ArrayList to an HashSet, but for some reason it doesn't work. The reason why I chose to convert the ArrayList into a HashSet is because it does not allow duplicated values, however, when I use it on my code, it only changes the order in the list:

My code output:

```<code>Choreography - Imran Sullivan
Goodfella - Khalil Person
DarknianIdeal - Sophia Jeffery
DarknianIdeal - Clyde Calderon
Frolicwas - Taylor Vargas
Reliable - Aryan Hess
DarknianIdeal - Liyah Navarro
Deservedness - Eadie Jefferson
Reliable - Angel Whitehouse
Choreography - Priya Oliver
</code>```

How the output should be:

```<code>Choreography - Imran Sullivan
Goodfella - Khalil Person
DarknianIdeal - Sophia Jeffery
Frolicwas - Taylor Vargas
Reliable - Aryan Hess
Deservedness - Eadie Jefferson
</code>```

This is the code. I've splitted the data into an Array so I can print out the data individually.

```<code>import java.util.*;
import java.io.*;

public class Task1 {
    public static void main(String[] args) {
        List<Person> personFile = new ArrayList<>();
        Set<Person> splitUserNameList = new HashSet<>(personFile);

        try {
            BufferedReader br = new BufferedReader(new FileReader("person-data.txt"));
            String fileRead = br.readLine();
            while (fileRead != null) {
                String[] personData = fileRead.split(":");
                String personName = personData[0];
                String userNameGenerator = personData[1];
                String[] userNameSplit = userNameGenerator.split(",");
                String newUserNameSplit = userNameSplit[0];
                Person personObj = new Person(personName, newUserNameSplit);
                splitUserNameList.add(personObj);
                fileRead = br.readLine();
            }
            br.close();
        }
        catch (FileNotFoundException ex) {
            System.out.println("File not found!");
        }
        catch (IOException ex) {
            System.out.println("An error has occured: " + ex.getMessage());
        }

        for (Person userNames: splitUserNameList) {
            System.out.println(userNames);
        }
    }
}

/* Person Class */

public class Person {
    private String personName;
    private String userNameGenerator;

    public Person(String personName, String userNameGenerator) {
        this.personName = personName;
        this.userNameGenerator = userNameGenerator;
    }

    public String getPersonName() {
        return personName;
    }

    public String getUserNameGenerator() {
        return userNameGenerator;
    }

    @Override
    public String toString() {
        return userNameGenerator + " - " + personName;
    }
}
</code>```

答:
You need to override the equals and hashCode methods on your Person object in order for Set to know which objects are considered the same.

It seems you want any two people with the same userNameGenerator field to be considered equal. In that case, the following will suit your needs:

```<code>public class Person {
    private String commonName;
    private String userNameGenerator;

    ...

    @Override
    public int hashCode()
    {
        return userNameGenerator.hashCode();
    }

    @Override
    public boolean equals(Object o)
    {
        if (this == o) return true;

        if (this.getClass() != o.getClass()) return false;

        final Person that = (Person) o;

        return this.userNameGenerator.equals(that.userNameGenerator);
    }
}
</code>```

Some important things to note:

In the case of duplicates, the Set will only allow in the first one
so insertion order becomes important.

Sets should not contain mutable elements because mutability destroys
their internal consistency. Your Person class is immutable (has no
setters) which is good but you may want to enforce this immutability even
further by declaring all of it's fields final.

Body:
I want to remove the duplicates of userNames in the ArrayList. I've tried to convert the ArrayList to an HashSet, but for some reason it doesn't work. The reason why I chose to convert the ArrayList into a HashSet is because it does not allow duplicated values, however, when I use it on my code, it only changes the order in the list:

My code output:

Choreography - Imran Sullivan
Goodfella - Khalil Person
DarknianIdeal - Sophia Jeffery
DarknianIdeal - Clyde Calderon
Frolicwas - Taylor Vargas
Reliable - Aryan Hess
DarknianIdeal - Liyah Navarro
Deservedness - Eadie Jefferson
Reliable - Angel Whitehouse
Choreography - Priya Oliver

How the output should be:

Choreography - Imran Sullivan
Goodfella - Khalil Person
DarknianIdeal - Sophia Jeffery
Frolicwas - Taylor Vargas
Reliable - Aryan Hess
Deservedness - Eadie Jefferson

This is the code. I've splitted the data into an Array so I can print out the data individually.

import java.util.*;
import java.io.*;

public class Task1 {
    public static void main(String[] args) {
        List<Person> personFile = new ArrayList<>();
        Set<Person> splitUserNameList = new HashSet<>(personFile);

        try {
            BufferedReader br = new BufferedReader(new FileReader("person-data.txt"));
            String fileRead = br.readLine();
            while (fileRead != null) {
                String[] personData = fileRead.split(":");
                String personName = personData[0];
                String userNameGenerator = personData[1];
                String[] userNameSplit = userNameGenerator.split(",");
                String newUserNameSplit = userNameSplit[0];
                Person personObj = new Person(personName, newUserNameSplit);
                splitUserNameList.add(personObj);
                fileRead = br.readLine();
            }
            br.close();
        }
        catch (FileNotFoundException ex) {
            System.out.println("File not found!");
        }
        catch (IOException ex) {
            System.out.println("An error has occured: " + ex.getMessage());
        }

        for (Person userNames: splitUserNameList) {
            System.out.println(userNames);
        }
    }
}

/* Person Class */

public class Person {
    private String personName;
    private String userNameGenerator;

    public Person(String personName, String userNameGenerator) {
        this.personName = personName;
        this.userNameGenerator = userNameGenerator;
    }

    public String getPersonName() {
        return personName;
    }

    public String getUserNameGenerator() {
        return userNameGenerator;
    }

    @Override
    public String toString() {
        return userNameGenerator + " - " + personName;
    }
}

Body:
You need to override the equals and hashCode methods on your Person object in order for Set to know which objects are considered the same.

It seems you want any two people with the same userNameGenerator field to be considered equal. In that case, the following will suit your needs:

public class Person {
    private String commonName;
    private String userNameGenerator;

    ...

    @Override
    public int hashCode()
    {
        return userNameGenerator.hashCode();
    }

    @Override
    public boolean equals(Object o)
    {
        if (this == o) return true;

        if (this.getClass() != o.getClass()) return false;

        final Person that = (Person) o;

        return this.userNameGenerator.equals(that.userNameGenerator);
    }
}

Some important things to note:

In the case of duplicates, the Set will only allow in the first one
so insertion order becomes important.

Sets should not contain mutable elements because mutability destroys
their internal consistency. Your Person class is immutable (has no
setters) which is good but you may want to enforce this immutability even
further by declaring all of it's fields final.


问:
WinForms ComboBox SelectedIndexChanged not firing when typing few chars followed by Alt+Down
In short

When I type a character in a ComboBox, press Alt+Down followed by Enter or Tab, the SelectedIndexChanged event doesn't fire, even though the SelectedIndex value does change!  Why doesn't the event fire?

Update
The same error occurs if you type a character, press Alt+Down and then type Esc. You would expect the Esc to cancel the change. However, the SelectedIndex does change, and the SelectedIndexChanged event doesn't fire.

What should happen if you just type Alt+Down, use the arrow keys to browse to an entry, and then type Esc? Should the selected index be set back to its original value?

Not so short

I have a WinForm application with a ComboBox on it. The ComboBox' SelectedIndexChanged event is wired up to a event handler that shows the SelectedItem in a Label control. The ComboBox' Items collection has three values: "One", "Two", and "Three".

When I select an item with the mouse, the event fires.

When I scroll the mouse, the event fires.

When I use Alt+Down to expand the combobox and walk through the items with Up and Down, the event fires.

But... When I type in the first character of a value, then press Alt+Down, followed by Enter or Tab, the value does get selected and is shown in the combobox, but the event doesn't fire.

I've also added a button that shows the SelectedIndex. It shows the SelectedIndex has changed. So even though the SelectedIndex does change, the SelectedIndexChanged event does not fire!

If I just type in a valid value like One the event doesn't fire either, but in that case a click on the button reveals the SelectedIndex indeed hasn't changed. So in that case the behavior is normal.

To reproduce, create a Form and add a ComboBox, a Label and a Button. Place the following code in the Form1.cs:

```<code>using System;
using System.Windows.Forms;

namespace ComboBoxSelectedIndexChanged
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            comboBox1.Items.AddRange(new object[] {
                "One",
                "Two",
                "Three"
            });
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            label1.Text = "Selected index: " + comboBox1.SelectedIndex;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Selected item: " + comboBox1.SelectedItem +
                "\nSelected index: " + comboBox1.SelectedIndex);
        }
    }
}
</code>```

答:
Correct me if I'm wrong. Here is code I've used.</p>

```<code>comboBox1.Items.AddRange(new object[] {
                "One",
                "Two",
                "Three"
});

comboBox1.SelectedIndexChanged+=(sa,ea)=>
 {
   label1.Text = "Selected index: " + comboBox1.SelectedIndex;
 };
comboBox1.TextChanged+= (sa, ea) =>
 {
 comboBox1.SelectedIndex = comboBox1.FindStringExact(comboBox1.Text);

 //OR
 //comboBox1.SelectedIndex = comboBox1.Items.IndexOf(comboBox1.Text);
  comboBox1.SelectionStart  = comboBox1.Text.Length;
};
</code>```

Body:
In short

When I type a character in a ComboBox, press Alt+Down followed by Enter or Tab, the SelectedIndexChanged event doesn't fire, even though the SelectedIndex value does change!  Why doesn't the event fire?

Update
The same error occurs if you type a character, press Alt+Down and then type Esc. You would expect the Esc to cancel the change. However, the SelectedIndex does change, and the SelectedIndexChanged event doesn't fire.

What should happen if you just type Alt+Down, use the arrow keys to browse to an entry, and then type Esc? Should the selected index be set back to its original value?

Not so short

I have a WinForm application with a ComboBox on it. The ComboBox' SelectedIndexChanged event is wired up to a event handler that shows the SelectedItem in a Label control. The ComboBox' Items collection has three values: "One", "Two", and "Three".

When I select an item with the mouse, the event fires.

When I scroll the mouse, the event fires.

When I use Alt+Down to expand the combobox and walk through the items with Up and Down, the event fires.

But... When I type in the first character of a value, then press Alt+Down, followed by Enter or Tab, the value does get selected and is shown in the combobox, but the event doesn't fire.

I've also added a button that shows the SelectedIndex. It shows the SelectedIndex has changed. So even though the SelectedIndex does change, the SelectedIndexChanged event does not fire!

If I just type in a valid value like One the event doesn't fire either, but in that case a click on the button reveals the SelectedIndex indeed hasn't changed. So in that case the behavior is normal.

To reproduce, create a Form and add a ComboBox, a Label and a Button. Place the following code in the Form1.cs:

using System;
using System.Windows.Forms;

namespace ComboBoxSelectedIndexChanged
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            comboBox1.Items.AddRange(new object[] {
                "One",
                "Two",
                "Three"
            });
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            label1.Text = "Selected index: " + comboBox1.SelectedIndex;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Selected item: " + comboBox1.SelectedItem +
                "\nSelected index: " + comboBox1.SelectedIndex);
        }
    }
}

Body:
Correct me if I'm wrong. Here is code I've used.

comboBox1.Items.AddRange(new object[] {
                "One",
                "Two",
                "Three"
});

comboBox1.SelectedIndexChanged+=(sa,ea)=>
 {
   label1.Text = "Selected index: " + comboBox1.SelectedIndex;
 };
comboBox1.TextChanged+= (sa, ea) =>
 {
 comboBox1.SelectedIndex = comboBox1.FindStringExact(comboBox1.Text);

 //OR
 //comboBox1.SelectedIndex = comboBox1.Items.IndexOf(comboBox1.Text);
  comboBox1.SelectionStart  = comboBox1.Text.Length;
};


问:
Efficient way to copy or merge two ArrayList containing same objects
I have an Object like below

```<code>Product {

String name;

boolean isFiltered;

}
</code>```

We have two lists - masterProductList and filteredProductList containing product.

We have to copy values of filteredProductList(this list has property isFiltered set) to masterProductList.

I can do it with following approches -

Approach 1

```<code>for (Product filterProduct: filteredPL) {
    for (Product masterProduct: masterPL) {
        if (filterProduct.equals(masterProduct)) {
            // Copy Values
            masterProduct.setIsFiltered(filterProduct.getIsFiltered());
        }
    }
}
</code>```

Approach 2

```<code>for (Product filterProduct: filteredPL) {
    for (Product masterProduct: masterPL) {
        //Delete the old product having old values
        masterProduct.remove(filterProduct);
        //Add product with new values
        masterProduct.add(filterProduct);
    }
}
</code>```

Both of these approaches have n square complexity.

Is there any other better way to do this so that we can reduce the complexity?

答:
try this</p>

```<code>Set<Product> masterPLHS = new HashSet<Product>(masterPL);

for (Product filterProduct: filteredPL) {
      masterPLHS.add(filterProduct);
}
</code>```

Body:
I have an Object like below

Product {

String name;

boolean isFiltered;

}

We have two lists - masterProductList and filteredProductList containing product.

We have to copy values of filteredProductList(this list has property isFiltered set) to masterProductList.

I can do it with following approches -

Approach 1

for (Product filterProduct: filteredPL) {
    for (Product masterProduct: masterPL) {
        if (filterProduct.equals(masterProduct)) {
            // Copy Values
            masterProduct.setIsFiltered(filterProduct.getIsFiltered());
        }
    }
}

Approach 2

for (Product filterProduct: filteredPL) {
    for (Product masterProduct: masterPL) {
        //Delete the old product having old values
        masterProduct.remove(filterProduct);
        //Add product with new values
        masterProduct.add(filterProduct);
    }
}

Both of these approaches have n square complexity.

Is there any other better way to do this so that we can reduce the complexity?

Body:
try this

Set<Product> masterPLHS = new HashSet<Product>(masterPL);

for (Product filterProduct: filteredPL) {
      masterPLHS.add(filterProduct);
}


问:
Tracking Google Analytics Page Views in Angular2
I have built a new site using Angular 2 as the front-end. As everything is done via push state, there are no page loads which typically trigger the Google Analytics code to send a page view to Google's servers.

How can I manually send page view events to Google so that I can track what users of my site are viewing?

答:
If you are running into this issue after August 2017 then you most probably should use gtag.js (Google Universal Analytics Global Site Tag) instead of the old analytics.js. I suggest you to check the difference between the both in Migrate from analytics.js to gtag.js page, as well as How gtag.js works in Single page applications before continuing.

When you get your code snippet from Google Analytics it looks like this:

```<code><!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=<%= GOOGLE_ANALYTICS_ID %>"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', '<%= GOOGLE_ANALYTICS_ID %>'); <!-- Remove that one -->
</script>
</code>```

You need to remove the last line of the script and add the rest to your index.html.

Then you have to add the line you deleted from the script above to your code and add the page to track. Basically it's almost the same as the guys above suggested for analytics.js but now you use the gtag.js function.

For example if you want to track all pages you open here is the sample code:

```<code>import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import 'rxjs/add/operator/distinctUntilChanged';

// This still has to be declared
declare var gtag: Function;

@Component({
    moduleId: module.id,
    selector: 'my-app',
    templateUrl: 'app.component.html',
    styleUrls: ['app.component.css'],
})
export class AppComponent implements OnInit {

    constructor(private router: Router) { }

    ngOnInit() {
        this.router.events.distinctUntilChanged((previous: any, current: any) => {
            // Subscribe to any `NavigationEnd` events where the url has changed
            if(current instanceof NavigationEnd) {
                return previous.url === current.url;
            }
            return true;
        }).subscribe((x: any) => {
            gtag('config', '<%= GOOGLE_ANALYTICS_ID %>', {'page_path': x.url});
        });
    }
}
</code>```

If you've read the documentation for the gtag.js then you know that there could be tons of tracking options, but I focus on the most basic usage here.

Body:
If you are running into this issue after August 2017 then you most probably should use gtag.js (Google Universal Analytics Global Site Tag) instead of the old analytics.js. I suggest you to check the difference between the both in Migrate from analytics.js to gtag.js page, as well as How gtag.js works in Single page applications before continuing.

When you get your code snippet from Google Analytics it looks like this:

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=<%= GOOGLE_ANALYTICS_ID %>"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', '<%= GOOGLE_ANALYTICS_ID %>'); <!-- Remove that one -->
</script>

You need to remove the last line of the script and add the rest to your index.html.

Then you have to add the line you deleted from the script above to your code and add the page to track. Basically it's almost the same as the guys above suggested for analytics.js but now you use the gtag.js function.

For example if you want to track all pages you open here is the sample code:

import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import 'rxjs/add/operator/distinctUntilChanged';

// This still has to be declared
declare var gtag: Function;

@Component({
    moduleId: module.id,
    selector: 'my-app',
    templateUrl: 'app.component.html',
    styleUrls: ['app.component.css'],
})
export class AppComponent implements OnInit {

    constructor(private router: Router) { }

    ngOnInit() {
        this.router.events.distinctUntilChanged((previous: any, current: any) => {
            // Subscribe to any `NavigationEnd` events where the url has changed
            if(current instanceof NavigationEnd) {
                return previous.url === current.url;
            }
            return true;
        }).subscribe((x: any) => {
            gtag('config', '<%= GOOGLE_ANALYTICS_ID %>', {'page_path': x.url});
        });
    }
}

If you've read the documentation for the gtag.js then you know that there could be tons of tracking options, but I focus on the most basic usage here.


问:
PHP string date + 1 day equals?
I have a date which is saved in a regular string.

```<code>// format = DD-MM-YYYY
$date = "10-12-2011";
</code>```

How can I get the date-string +1 day so: 11-12-2011?

答:
if you want today +$i day

```<code>$today = date('Y-m-d');
$tomorrow = strtotime($today." +".$i." day");
</code>```

ContentLicense: CC BY-SA 4.0

Title: PHP string date + 1 day equals?

Body:
I have a date which is saved in a regular string.

// format = DD-MM-YYYY
$date = "10-12-2011";

How can I get the date-string +1 day so: 11-12-2011?

Body:
if you want today +$i day

$today = date('Y-m-d');
$tomorrow = strtotime($today." +".$i." day");


答:
Basically you should consider using pipe when some data requires some transformation in your template and you don't want to have a "dirty logic" in your component code.

For example, imagine you getting some html string from server or whatever. And you need to display this string in your template, but you want to display it as a plan text (simple string) without any html tags.

In this case this would be a good to create a pipe for that:

```<code>import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
    name: 'htmlToPlanText'
})
export class HtmlToPlanTextPipe implements PipeTransform {
    transform(value: string) {
        let html = new String(value);
        return html.replace(/(\<(\/?[^>]+)>)/g, '');
    }
}
</code>```

end next you can use it in your template code in this way:

```<code><span>{{yourHtmlString | htmlToPlanText}}</span>
</code>```

This will transform your html string to plan text.

Please note, this will note change your original variable in component controller. It will just transform value when rendering your component template.

Title: When to use a pipe in Angular

Body:
Is there any rule, or best practice to tell when a pipe is best over a component method ?

Maybe something like, when something is purly a view logic and doesn't contain any domain logic

Body:
Basically you should consider using pipe when some data requires some transformation in your template and you don't want to have a "dirty logic" in your component code.

For example, imagine you getting some html string from server or whatever. And you need to display this string in your template, but you want to display it as a plan text (simple string) without any html tags.

In this case this would be a good to create a pipe for that:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
    name: 'htmlToPlanText'
})
export class HtmlToPlanTextPipe implements PipeTransform {
    transform(value: string) {
        let html = new String(value);
        return html.replace(/(\<(\/?[^>]+)>)/g, '');
    }
}

end next you can use it in your template code in this way:

<span>{{yourHtmlString | htmlToPlanText}}</span>

This will transform your html string to plan text.

Please note, this will note change your original variable in component controller. It will just transform value when rendering your component template.