问:
AngularJS copy to clipboard
Is there a way to make a copy button with a copy function that will copy all the contents of a modal and you can paste it to notepad</p>

答:
document.execCommand is now deprecated. Instead you can do:

HTML:

```<code><i class="fa fa-copy" ng-click="copyToClipboard('some text to copy')"></i>
</code>```

Controller:

```<code>$scope.copyToClipboard = function(string) {
    navigator.clipboard.writeText(string)
        .then(console.log('copied!'));
}
</code>```

Title: AngularJS copy to clipboard

Body:
document.execCommand is now deprecated. Instead you can do:

HTML:

<i class="fa fa-copy" ng-click="copyToClipboard('some text to copy')"></i>

Controller:

$scope.copyToClipboard = function(string) {
    navigator.clipboard.writeText(string)
        .then(console.log('copied!'));
}


来源: stackexchange

问:
Serialize an object to XML
I have a C# class that I have inherited. I have successfully "built" the object. But I need to serialize the object to XML. Is there an easy way to do it?

It looks like the class has been set up for serialization, but I'm not sure how to get the XML representation. My class definition looks like this:

```<code>[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.domain.com/test")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.domain.com/test", IsNullable = false)]
public partial class MyObject
{
  ...
}
</code>```

Here is what I thought I could do, but it doesn't work:

```<code>MyObject o = new MyObject();
// Set o properties
string xml = o.ToString();
</code>```

How do I get the XML representation of this object?

答:
It might be too late to party but there is serialization with only user defined Namespaces:

```<code>public static string XmlSerialize<T>(this T obj) where T : class
        {
            Type serialType = typeof(T);
            var xsSubmit = new XmlSerializer(serialType);

            XmlWriterSettings xws = new XmlWriterSettings() { OmitXmlDeclaration = true, Indent = true };

            var Namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
            new XmlQualifiedName(string.Empty,  GetXmlNameSpace(serialType) ?? string.Empty )

        });
 private static string GetXmlNameSpace(Type target)
        {
            XmlRootAttribute attribute = (XmlRootAttribute)Attribute.GetCustomAttribute(target, typeof(XmlRootAttribute));
            return attribute == null ? null : attribute.Namespace;
        }
</code>```

And defined namespace in the custom class

```<code> [XmlRoot("IdentityTerminal",Namespace = "http://my-name-space/XMLSchema")]

    public class IdentityTerminal
    {
    }
</code>```

This code allows to user only user defined namespaces and omit default ones.

ContentLicense: CC BY-SA 3.0

Title: Serialize an object to XML

Body:
I have a C# class that I have inherited. I have successfully "built" the object. But I need to serialize the object to XML. Is there an easy way to do it?

It looks like the class has been set up for serialization, but I'm not sure how to get the XML representation. My class definition looks like this:

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.domain.com/test")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.domain.com/test", IsNullable = false)]
public partial class MyObject
{
  ...
}

Here is what I thought I could do, but it doesn't work:

MyObject o = new MyObject();
// Set o properties
string xml = o.ToString();

How do I get the XML representation of this object?

Body:
It might be too late to party but there is serialization with only user defined Namespaces:

public static string XmlSerialize<T>(this T obj) where T : class
        {
            Type serialType = typeof(T);
            var xsSubmit = new XmlSerializer(serialType);

            XmlWriterSettings xws = new XmlWriterSettings() { OmitXmlDeclaration = true, Indent = true };

            var Namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
            new XmlQualifiedName(string.Empty,  GetXmlNameSpace(serialType) ?? string.Empty )

        });
 private static string GetXmlNameSpace(Type target)
        {
            XmlRootAttribute attribute = (XmlRootAttribute)Attribute.GetCustomAttribute(target, typeof(XmlRootAttribute));
            return attribute == null ? null : attribute.Namespace;
        }

And defined namespace in the custom class

 [XmlRoot("IdentityTerminal",Namespace = "http://my-name-space/XMLSchema")]

    public class IdentityTerminal
    {
    }

This code allows to user only user defined namespaces and omit default ones.

ContentLicense: CC BY-SA 4.0


问:
dash load up with an empty table
I am making my first dash application. I am creating a layout which will contain a dash_table however at load up time the table will be empty as the table will populate once the user selects an option.

I have tried setting the dash table to {} & none but when I do this the page will not load. How can I have an empty table as part of my layout when loading the page?

答:
You need to provide a dictionary of column names at least to create an empty datatable. You can leave the data attribute as empty, here is a minimally working example:

from dash import Dash, dash_table, html

app = Dash(__name__)

app.layout = html.Div([
    dash_table.DataTable(id="table_infos",
        columns=[
            {'id': "Intitulé", 'name': "Intitulé"},
            {'id': "Donnée", 'name': "Donnée"}
        ]
    )
])

if __name__ == '__main__':
    app.run_server(debug=True)
```

Title: dash load up with an empty table


问:
Typescript. Can I define conditional types?
Imagine I have the following type

```<code>type BannerConditions = {
    publication_id?: number;
    product_id?: number;
    resource?: string;
    type: string;
  };
</code>```

But publication_id and product_id can only exist if resource exists. Can I define it somehow?

答:
Keep it simple: merge them as required properties in a separate optional object:

```<code>type BannerConditions = {
  type: string;
  resource?: {
    publication_id: number;
    product_id: number;
    type: string;
  };
};
</code>```

I changed resource to type since resource.resource seems to be a bit odd. BannerConditions could also be an interface rather than a type.

Body:
Imagine I have the following type

type BannerConditions = {
    publication_id?: number;
    product_id?: number;
    resource?: string;
    type: string;
  };

But publication_id and product_id can only exist if resource exists. Can I define it somehow?

Body:
Keep it simple: merge them as required properties in a separate optional object:

type BannerConditions = {
  type: string;
  resource?: {
    publication_id: number;
    product_id: number;
    type: string;
  };
};

I changed resource to type since resource.resource seems to be a bit odd. BannerConditions could also be an interface rather than a type.


问:
MySQL SELECT with PK as key of result set
Is it possible to use SELECT statement in MySQL such that key of the result-set rows is the actual PK of table rows?

result set = PHP associative arrays

PK is auto-increment

答:
There is no native function to do that.

But you can quite easily iterate that resultset and set keys by your own.

```<code>$data = array();
while ($row = mysql_fetch_assoc($result)) {
    $data[ $row['id'] ] = $row;
}
</code>```

Body:
There is no native function to do that.

But you can quite easily iterate that resultset and set keys by your own.

$data = array();
while ($row = mysql_fetch_assoc($result)) {
    $data[ $row['id'] ] = $row;
}


问:
Looking for an UWP Grid that has ItemsSource
I am looking for a control that can handle ItemsSource, like a ListVIew, but at the same time handles automatic column width.

Grid doesn't seem to handle ItemsSource, so dynamically adding rows would mean a lot of column definitions.

ListView doesn't understand a mix of Auto and * columns, so gives strange results.

DataGrid seems to be the closest possible thing, but has many features that I don't want. Like row selection and focus items.

I tried to use the DataGrid, but there are just too many features. Are there any DataGrid implementations or other controls available in UWP that simply let me fill a grid with ItemsSource that are only used for layout? Or should I continue on this path and try to disable as many features as I can via styles?

<tkControls:DataGrid
    AllowFocusOnInteraction="False"
    AutoGenerateColumns="False"
    CanUserReorderColumns="False"
    CanUserResizeColumns="False"
    CanUserSortColumns="False"
    GridLinesVisibility="None"
    ItemsSource="{x:Bind _viewModel.Modes, Mode=OneWay}">
    <tkControls:DataGrid.Columns>
        <tkControls:DataGridTextColumn
            Width="*"
            Binding="{Binding Name, Mode=OneWay}" />
        <tkControls:DataGridTemplateColumn Header="Record">
            <tkControls:DataGridTemplateColumn.CellTemplate>
                <DataTemplate x:DataType="model:IModeViewModel">
                    <CheckBox
                        IsChecked="{x:Bind IsRecordEnabled}"
                        IsEnabled="{x:Bind IsStrongestMode, Converter={StaticResource BoolNegationConverter}, Mode=OneWay}" />
                </DataTemplate>
            </tkControls:DataGridTemplateColumn.CellTemplate>
        </tkControls:DataGridTemplateColumn>
        <tkControls:DataGridTemplateColumn Width="150">
            <tkControls:DataGridTemplateColumn.CellTemplate>
                <DataTemplate x:DataType="model:IModeViewModel">
                    <controls:QuantityBox
                        IsEnabled="{x:Bind IsGainEditEnabled, Mode=OneWay}"
                        PropertySettings="{x:Bind GainPropertySettings, Mode=OneWay}"
                        Quantity="{x:Bind Gain}" />
                </DataTemplate>
            </tkControls:DataGridTemplateColumn.CellTemplate>
        </tkControls:DataGridTemplateColumn>
        <tkControls:DataGridTemplateColumn Header="View">
            <tkControls:DataGridTemplateColumn.CellTemplate>
                <DataTemplate x:DataType="model:IModeViewModel">
                    <CheckBox
                        IsChecked="{x:Bind IsVisible}"
                        IsEnabled="{x:Bind IsRecordEnabled, Mode=OneWay}" />
                </DataTemplate>
            </tkControls:DataGridTemplateColumn.CellTemplate>
        </tkControls:DataGridTemplateColumn>
    </tkControls:DataGrid.Columns>
</tkControls:DataGrid>
```

答:
I'd say you can't have too many features, they trend to be useful someday ...

Stating that, you are on the right track. Use the datagrid and disable/style anything you need. For the selection and focusing you may use

```<code><DataGrid>
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="IsHitTestVisible" Value="False"/>
        </Style>
    </DataGrid.RowStyle>
    <!--Other DataGrid items-->
</DataGrid>
</code>```

Body:
I'd say you can't have too many features, they trend to be useful someday ...

Stating that, you are on the right track. Use the datagrid and disable/style anything you need. For the selection and focusing you may use

<DataGrid>
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="IsHitTestVisible" Value="False"/>
        </Style>
    </DataGrid.RowStyle>
    <!--Other DataGrid items-->
</DataGrid>


问:
Align single item left when Column crossAxisAlignment is center
Most contents in my column is centre so i preferred to choose crossAxisAlignment: CrossAxisAlignment.center but one top most content i want to be left aligned. How can i achieve this?

```<code>return Scaffold(
  body: Column(
    crossAxisAlignment: CrossAxisAlignment.center,
    children: <Widget>[
      Text('Left'), // It must be left aligned
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),

    ],
  ),
);
</code>```

答:
Wrap the widget you want with Align widget and set it to be left aligned.

```<code>Align(
  alignment: Alignment.centerLeft,
  child: Text('Left'),
),
</code>```

Body:
Most contents in my column is centre so i preferred to choose crossAxisAlignment: CrossAxisAlignment.center but one top most content i want to be left aligned. How can i achieve this?

return Scaffold(
  body: Column(
    crossAxisAlignment: CrossAxisAlignment.center,
    children: <Widget>[
      Text('Left'), // It must be left aligned
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),

    ],
  ),
);

Body:
Wrap the widget you want with Align widget and set it to be left aligned.

Align(
  alignment: Alignment.centerLeft,
  child: Text('Left'),
),


问:
Flutter Image Picker integration tests
I am trying the solution for e2e test for image_picker from this link How to test ImagePicker in Flutter Driver?

```<code> void main() {
      enableFlutterDriverExtension();

      const MethodChannel channel =
          MethodChannel('plugins.flutter.io/image_picker');

      setUp(() {
        channel.setMockMethodCallHandler((MethodCall methodCall) async {
          ByteData data = await rootBundle.load('images/sample.png');
          Uint8List bytes = data.buffer.asUint8List();
          Directory tempDir = await getTemporaryDirectory();
          File file = await File(
            '${tempDir.path}/tmp.tmp',
          ).writeAsBytes(bytes);
          print(file.path);
          return file.path;
        });
      });
      app.main();
    }
</code>```

My main file for test is exactly the same. The issue is that when I am using enableFlutterDriverExtension();
the test right after start, finished with the info that all test passed, without emulating steps on emulator and print all the info to console after every step. And in the console I am getting

```<code>[VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: 'package:flutter_driver/src/extension/extension.dart': Failed assertion: line 222 pos 10:
'WidgetsBinding.instance == null': is not true.
#0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:47:61)
#1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:36:5)
#2      enableFlutterDriverExtension (package:flutter_driver/src/extension/extension.dart:222:10)
#3      main
</code>```

Without enableFlutterDriverExtension(); test fail when I am trying to call image_picker. With error

```<code>flutter:   'package:flutter_test/src/binding.dart': Failed assertion: line 775 pos 14: '_pendingExceptionDetails != null': A test overrode FlutterError.onError
but either failed to return it to its original state, or had unexpected additional errors that it could not handle. Typically, this is caused by using expect()
before restoring FlutterError.onError.
flutter:   dart:core-patch/errors_patch.dart 47:61       _AssertionError._doThrowNew
</code>```

What exactly the enableFlutterDriverExtension(); do? Without testing image_picker and this enableFlutterDriverExtension() tests are working correctly. Is there any other solution for testing image_picker?

答:
The question How to test ImagePicker in Flutter Driver? is over 2 years old so it's not more actuel.

bevore you test it you need to implament it for a platform. you implement it for android like this:
Starting with version 0.8.1 the Android implementation support to pick (multiple) images on Android 4.3 or higher.

No configuration required - the plugin should work out of the box. It is however highly recommended to prepare for Android killing the application when low on memory. How to prepare for this is discussed in the Handling MainActivity destruction on Android section.

It is no longer required to add android:requestLegacyExternalStorage="true" as an attribute to the  tag in AndroidManifest.xml, as image_picker has been updated to make use of scoped storage.

Note: Images and videos picked using the camera are saved to your application's local cache, and should therefore be expected to only be around temporarily. If you require your picked image to be stored permanently, it is your responsibility to move it to a more permanent location.

then you can test it by checking if it works by doing this:

```<code>// it pick a image from gallery but you can change that to camera
final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
</code>```

you need to know that it gives you a XFile and not a normal file but you can convert it to an file like this:

```<code>final xFile = await ImagePicker().pickImage(source: ImageSource.gallery);

final String? path = xFile!.path;

//that's the File
final bytes = await File(path!).readAsBytes();
</code>```

Title: Flutter Image Picker integration tests

Body:
I am trying the solution for e2e test for image_picker from this link How to test ImagePicker in Flutter Driver?

 void main() {
      enableFlutterDriverExtension();

      const MethodChannel channel =
          MethodChannel('plugins.flutter.io/image_picker');

      setUp(() {
        channel.setMockMethodCallHandler((MethodCall methodCall) async {
          ByteData data = await rootBundle.load('images/sample.png');
          Uint8List bytes = data.buffer.asUint8List();
          Directory tempDir = await getTemporaryDirectory();
          File file = await File(
            '${tempDir.path}/tmp.tmp',
          ).writeAsBytes(bytes);
          print(file.path);
          return file.path;
        });
      });
      app.main();
    }

My main file for test is exactly the same. The issue is that when I am using enableFlutterDriverExtension();
the test right after start, finished with the info that all test passed, without emulating steps on emulator and print all the info to console after every step. And in the console I am getting

[VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: 'package:flutter_driver/src/extension/extension.dart': Failed assertion: line 222 pos 10:
'WidgetsBinding.instance == null': is not true.
#0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:47:61)
#1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:36:5)
#2      enableFlutterDriverExtension (package:flutter_driver/src/extension/extension.dart:222:10)
#3      main

Without enableFlutterDriverExtension(); test fail when I am trying to call image_picker. With error

flutter:   'package:flutter_test/src/binding.dart': Failed assertion: line 775 pos 14: '_pendingExceptionDetails != null': A test overrode FlutterError.onError
but either failed to return it to its original state, or had unexpected additional errors that it could not handle. Typically, this is caused by using expect()
before restoring FlutterError.onError.
flutter:   dart:core-patch/errors_patch.dart 47:61       _AssertionError._doThrowNew

What exactly the enableFlutterDriverExtension(); do? Without testing image_picker and this enableFlutterDriverExtension() tests are working correctly. Is there any other solution for testing image_picker?

Body:
The question How to test ImagePicker in Flutter Driver? is over 2 years old so it's not more actuel.

bevore you test it you need to implament it for a platform. you implement it for android like this:
Starting with version 0.8.1 the Android implementation support to pick (multiple) images on Android 4.3 or higher.

No configuration required - the plugin should work out of the box. It is however highly recommended to prepare for Android killing the application when low on memory. How to prepare for this is discussed in the Handling MainActivity destruction on Android section.

It is no longer required to add android:requestLegacyExternalStorage="true" as an attribute to the  tag in AndroidManifest.xml, as image_picker has been updated to make use of scoped storage.

Note: Images and videos picked using the camera are saved to your application's local cache, and should therefore be expected to only be around temporarily. If you require your picked image to be stored permanently, it is your responsibility to move it to a more permanent location.

then you can test it by checking if it works by doing this:

// it pick a image from gallery but you can change that to camera
final XFile? image = await _picker.pickImage(source: ImageSource.gallery);

you need to know that it gives you a XFile and not a normal file but you can convert it to an file like this:

final xFile = await ImagePicker().pickImage(source: ImageSource.gallery);

final String? path = xFile!.path;

//that's the File
final bytes = await File(path!).readAsBytes();


问:
Setting an attribute from a parents attribute
I have this HTML and i am trying to convert the href from photo.php to #photo etc for each

```<code><ul id="menu">
    <li id="home" class="tab_selected"><a href="home.php">Home</a></li>
    <li id="portfolio"><a href="portfolio.php">Portfolio</a></li>
    <li id="music"><a href="music.php">Music</a></li>
    <li id="video"><a href="video.php">Video</a></li>
    <li id="photo"><a href="photo.php">Photo</a></li>
</ul>
</code>```

I have been trying something like this:

```<code>$('#menu li a').attr('href', "#"+$(this).parent().attr('id'));
</code>```

But the href always comes out undefined.

I am storing the hash in the li#id but if i could not do this it would be even better.

Thanks.

答:
```<code>$('#menu li a').each(function(){
    var $this = $(this);
    $this.attr('href', "#"+$this.parent().attr('id'));
});
</code>```

Body:
I have this HTML and i am trying to convert the href from photo.php to #photo etc for each

Home

Portfolio

Music

Video

Photo

I have been trying something like this:

$('#menu li a').attr('href', "#"+$(this).parent().attr('id'));

But the href always comes out undefined.

I am storing the hash in the li#id but if i could not do this it would be even better.

Thanks.


问:
Loading Robot Resource files from Python package
I have a number of teams working in Robot in separate repositories, and want to make available a set of common Python and Robot code to avoid duplication. I've pulled out the .py and .robot files that I want to package, have built the package (making sure that the .robot files are present in the .tar.gz), and have published it to our local artifactory. When I go to use these files in Robot tests, however, I can successfully use the .py files with the

Library  package.module

syntax.

However using Robot resources with the

Resource  package.resource.robot

syntax fails. Is there some way to include and utilize .robot resources in a python package?

答:
Loading rf resource files from python packages is not supported by Robot Framework out of the box.

I wrote a blogpost about this few years ago: http://rasjani.github.io/2020/01/05/bundle-resources.html - and there's also a proof of concept library that's implementing the idea from the post here: https://github.com/rasjani/robotframework-importresource


问:
VBA For each loop, type mismatch
I have an issue where I get the type mismatch error when running my code, I'm trying to store an output of a calculation into an array using the 'For each' loop to loop through the range of cells that hold the value id like to multiply by a static value and then store.

How do I adjust the code to prevent the type mismatch error for the array GrossHS()?

```<code>Sub NetWeightDist()

Dim mltplier As Double
Dim SumGW As Long
Dim GrossHS() As Variant
Dim lngth As Long
Dim Netrng As Range
Dim NetCl As Range

lngth = Cells(Rows.Count, 9).End(xlUp).Row

SumGW = Application.WorksheetFunction.Sum(Range("L2:L1000"))
mltplier = Worksheets("Sheet1").Range("Q2").Value / SumGW

Set Netrng = Worksheets("Sheet1").Range("L2:L" & lngth)

ReDim GrossHS(1 To lngth)
For Each NetCl In Netrng

GrossHS() = mltplier * NetCl.Value
Next

End Sub
</code>```

答:
Put the column L values into an array and iterate that

Option Explicit
Sub NetWeightDist()

    Dim ws As Worksheet
    Dim mltplier As Double, lastrow As Long, i As Long
    Dim SumGW As Long, arGrossHS, arNet

    Set ws = ActiveSheet
    With ws
        lastrow = .Cells(.Rows.Count, "I").End(xlUp).Row
        arNet = .Range("L2:L" & lastrow).Value2
        ReDim arGrossHS(1 To UBound(arNet))

        SumGW = Application.WorksheetFunction.Sum(arNet)
        mltplier = Sheets("Sheet1").Range("Q2") / SumGW
        MsgBox "Items=" & UBound(arNet) & " Sum=" & SumGW & " Multiplier=" & mltplier

        For i = 1 To UBound(arNet)
             arGrossHS(i) = mltplier * arNet(i, 1)
        Next

    End With
End Sub
```

Title: VBA For each loop, type mismatch

Body:
I have an issue where I get the type mismatch error when running my code, I'm trying to store an output of a calculation into an array using the 'For each' loop to loop through the range of cells that hold the value id like to multiply by a static value and then store.

How do I adjust the code to prevent the type mismatch error for the array GrossHS()?

Sub NetWeightDist()

Dim mltplier As Double
Dim SumGW As Long
Dim GrossHS() As Variant
Dim lngth As Long
Dim Netrng As Range
Dim NetCl As Range

lngth = Cells(Rows.Count, 9).End(xlUp).Row

SumGW = Application.WorksheetFunction.Sum(Range("L2:L1000"))
mltplier = Worksheets("Sheet1").Range("Q2").Value / SumGW

Set Netrng = Worksheets("Sheet1").Range("L2:L" & lngth)

ReDim GrossHS(1 To lngth)
For Each NetCl In Netrng

GrossHS() = mltplier * NetCl.Value
Next

End Sub


问:
Print array of strings - Shell Script
Dears,

Simple question, I have a shell variable with the following values,

```<code>myarr=["Life","is","good","when","you","learning"]
</code>```

It is an array of strings ! Here is how I want to print it. Also, I need to do with a loop because each of these element would be passed to a function to process the string

Expected Output

```<code>Life \
is \
good \
when \
you \
learning
</code>```

答:
You can make a for loop to print all the elements of your array.

# declare your array variable
declare -a myarr=("Life","is","good","when","you","learning")

# get length of an array
length=${#myarr[@]}

for (( j=0; j<${length}; j++ ));
do
  printf "${myarr[$j]}\n"
done
```

Title: Print array of strings - Shell Script

Body:
Dears,

Simple question, I have a shell variable with the following values,

myarr=["Life","is","good","when","you","learning"]

It is an array of strings ! Here is how I want to print it. Also, I need to do with a loop because each of these element would be passed to a function to process the string

Expected Output

Life \
is \
good \
when \
you \
learning


问:
how to pass values using @Input()
enter image description here
How should I do so that my card can get data from another file?

OneProcessItemComponent.ts

```<code>export class OneProcessItemComponent {
  @Input() item = processItem;
}
</code>```

OneProcessItemComponent.html

```<code><div class="process__item">
  <div class="process__wrap">
    <img src="{{ item.image }}" alt="process" class="process__img">
    <div class="process__item-title">{{ item.title }}</div>
    <div class="process__item-subtitle">{{ item.subtitle }}</div>
  </div>
</div>
</code>```

processItem.ts

```<code>export const processItem: IProcessItem[] = [
  {
    title: `Buy Now`,
    subtitle: `Lock in a buy order now at the current
    spot price.`,
    image: `../../../../../../../assets/img/process-1.svg`,
  },
</code>```

答:
*ngFor required for IProcessItem[]. (Try to recreate the whole scenario.)

app.component.ts

```<code>import { IProcessItem, processItem } from "./processItem";

@Component({...})

export class AppComponent {
  public processItem: IProcessItem[] = processItem;
}
</code>```

app.component.html

```<code><app-one-process-item [item]="processItem"><app-one-process-item>
</code>```

processItem.ts

```<code>export interface IProcessItem {
    title: string;
    subtitle: string;
    image: string
}

export const processItem: IProcessItem[] = [{
    title: `Buy Now`,
    subtitle: `Lock in a buy order now at the current
      spot price.`,
    image: `../../../../../../../assets/img/process-1.svg`,
}];
</code>```

OneProcessItemComponent.ts

```<code>import { IProcessItem } from "../processItem";

@Component({...})
export class CombineThreeComponent implements OnInit {
  @Input() item: IProcessItem[];

  constructor() { }
  ngOnInit(): void { }
}
</code>```

OneProcessItemComponent.html

```<code><div class="process__item" *ngFor="let data of item">
    <div class="process__wrap">
        <img src="{{ data.image }}" alt="process" class="process__img">
        <div class="process__item-title">{{ data.title }}</div>
        <div class="process__item-subtitle">{{ data.subtitle }}</div>
    </div>
</div>
</code>```

Output -

Title: how to pass values using @Input()

Body:
enter image description here
How should I do so that my card can get data from another file?

OneProcessItemComponent.ts

export class OneProcessItemComponent {
  @Input() item = processItem;
}

OneProcessItemComponent.html

{{ item.title }}

{{ item.subtitle }}

processItem.ts

export const processItem: IProcessItem[] = [
  {
    title: `Buy Now`,
    subtitle: `Lock in a buy order now at the current
    spot price.`,
    image: `../../../../../../../assets/img/process-1.svg`,
  },

Body:
*ngFor required for IProcessItem[]. (Try to recreate the whole scenario.)

app.component.ts

import { IProcessItem, processItem } from "./processItem";

@Component({...})

export class AppComponent {
  public processItem: IProcessItem[] = processItem;
}

app.component.html

<app-one-process-item [item]="processItem"><app-one-process-item>

processItem.ts

export interface IProcessItem {
    title: string;
    subtitle: string;
    image: string
}

export const processItem: IProcessItem[] = [{
    title: `Buy Now`,
    subtitle: `Lock in a buy order now at the current
      spot price.`,
    image: `../../../../../../../assets/img/process-1.svg`,
}];

OneProcessItemComponent.ts

import { IProcessItem } from "../processItem";

@Component({...})
export class CombineThreeComponent implements OnInit {
  @Input() item: IProcessItem[];

  constructor() { }
  ngOnInit(): void { }
}

OneProcessItemComponent.html

<div class="process__item" *ngFor="let data of item">
    <div class="process__wrap">
        <img src="{{ data.image }}" alt="process" class="process__img">
        <div class="process__item-title">{{ data.title }}</div>
        <div class="process__item-subtitle">{{ data.subtitle }}</div>
    </div>
</div>

Output -


问:
removing punctuation from dataframe does not work Pyspark
I am new to Spark and text processing. Could someone give some suggestion on the following issue I have.
I want to remove all the punctuations in a column of a dataframe. I saw some posts online related to this topic, still cannot figure out why my code does not work.
If I remove a single punctuation, for example, period, that seems work

```<code>from pyspark.sql.functions import udf
commaRep = udf(lambda x: x.replace('.', ' '))
df=df.withColumn('RD',commaRep('DELAY_REASON'))
df.display()
</code>```

Before:
Late inbound FA crew from F_29. DD
After:
Late inbound FA crew from F_29  DD

However, if I do a loop for all the punctuations that I want to remove:

```<code>from pyspark.sql.functions import udf
punc = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
for ch in punc:
  commaRep = udf(lambda x: x.replace(ch, ' '))

df=df.withColumn('RD',commaRep('DELAY_REASON'))
df.display()
</code>```

Then none of the punctuations got removed. for example, string like:
Ramp headset not working. Had to get a new one. sh
remains the same, I wonder what was wrong with the loop.

thanks for any help!
Daisy

答:
Actually you don't need an UDF. You can use spark built-in regexp_replace:

from pyspark.sql.types import StringType
from pyspark.sql.functions import regexp_replace

df = spark.createDataFrame(
  ["a:;,|/dlk\\", "jnh'.-lk", "ldkc!o?@"],
  StringType()
).toDF("text")
df.show()

df.withColumn("no_punctuation", regexp_replace(
  "text",
  r"""[!\"#$%&'()*+,\-.\/:;<=>?@\[\\\]^_`{|}~]""",
  " "
)).show()
```

I had to escape a few characters so that they are correctly handled in the regex expression (like -, /, [, ]).

Body:
I am new to Spark and text processing. Could someone give some suggestion on the following issue I have.
I want to remove all the punctuations in a column of a dataframe. I saw some posts online related to this topic, still cannot figure out why my code does not work.
If I remove a single punctuation, for example, period, that seems work

from pyspark.sql.functions import udf
commaRep = udf(lambda x: x.replace('.', ' '))
df=df.withColumn('RD',commaRep('DELAY_REASON'))
df.display()

Before:
Late inbound FA crew from F_29. DD
After:
Late inbound FA crew from F_29  DD

However, if I do a loop for all the punctuations that I want to remove:

from pyspark.sql.functions import udf
punc = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
for ch in punc:
  commaRep = udf(lambda x: x.replace(ch, ' '))

df=df.withColumn('RD',commaRep('DELAY_REASON'))
df.display()

Then none of the punctuations got removed. for example, string like:
Ramp headset not working. Had to get a new one. sh
remains the same, I wonder what was wrong with the loop.

thanks for any help!
Daisy

Body:
Actually you don't need an UDF. You can use spark built-in regexp_replace:

from pyspark.sql.types import StringType
from pyspark.sql.functions import regexp_replace

df = spark.createDataFrame(
  ["a:;,|/dlk\\", "jnh'.-lk", "ldkc!o?@"],
  StringType()
).toDF("text")
df.show()

df.withColumn("no_punctuation", regexp_replace(
  "text",
  r"""[!\"#$%&'()*+,\-.\/:;<=>?@\[\\\]^_`{|}~]""",
  " "
)).show()

I had to escape a few characters so that they are correctly handled in the regex expression (like -, /, [, ]).


答:
```<code>   return Scaffold(
  body: Column(
    crossAxisAlignment: CrossAxisAlignment.center,
    children: <Widget>[
      Align(
         alignment: Alignment.topLeft,
         child :Text('Left')
      ), // It must be left aligned
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),

    ],
  ),
);
</code>```

Title: Align single item left when Column crossAxisAlignment is center


问:
GoLang project CMD command have strange behave
I'm working on a GoLang Project for Rosetta-API.
There is a implementation for exec.Command

Code:

```<code>    func StartBitcoind(ctx context.Context, configPath string, g *errgroup.Group) error {
    logger := utils.ExtractLogger(ctx, "eunod")
    cmd := exec.Command(
        "/app/eunod",
        fmt.Sprintf("--conf=%s", configPath),
    )

    stdout, err := cmd.StdoutPipe()
    if err != nil {
        return err
    }

    stderr, err := cmd.StderrPipe()
    if err != nil {
        return err
    }

    g.Go(func() error {
        return logPipe(ctx, stdout, bitcoindLogger)
    })

    g.Go(func() error {
        return logPipe(ctx, stderr, bitcoindStdErrLogger)
    })

    if err := cmd.Start(); err != nil {
        return fmt.Errorf("%w: unable to start eunod", err)
    }

    g.Go(func() error {
        <-ctx.Done()

        logger.Warnw("sending interrupt to eunod")
        return cmd.Process.Signal(os.Interrupt)
    })

    return cmd.Wait()
}
</code>```

From now i will linked to github.

On line: https://github.com/ScArFaCe2020/rosetta-euno/blob/master/bitcoin/node.go#L68-L71 is the exec.Command.

the fmt.Sprintf("--conf=%s", configPath), Works fine.
Now i need to add --daemon inside it.

But when i change this to

```<code>fmt.Sprintf("--daemon --conf=%s", configPath),
</code>```

It doesn't work.

Does anyone have a idea how i can add the --daemon?

答:
exec.Command takes variadic string arguments. Its signature looks like this.

func Command(name string, arg ...string) *Cmd
```
<p>Either pass a slice of stings followed by <code>...</code> or pass a number of strings as arguments.</p>
<p>In your case, you treat the whole string <code>--daemon --conf=/some/path</code> as a single argument, while you actually want to treat it as two distinct arguments.</p>
<p>The most simple way to solve this would be doing it like this.</p>
<pre class="lang-golang prettyprint-override"><code>cmd := exec.Command(
    "/app/eunod",
    "--daemon",
    fmt.Sprintf("--conf=%s", configPath),
)
</code>```

You can learn more about variadic arguments here https://golangdocs.com/variadic-functions-in-golang for example.

Body:
I'm working on a GoLang Project for Rosetta-API.
There is a implementation for exec.Command

Code:

    func StartBitcoind(ctx context.Context, configPath string, g *errgroup.Group) error {
    logger := utils.ExtractLogger(ctx, "eunod")
    cmd := exec.Command(
        "/app/eunod",
        fmt.Sprintf("--conf=%s", configPath),
    )

    stdout, err := cmd.StdoutPipe()
    if err != nil {
        return err
    }

    stderr, err := cmd.StderrPipe()
    if err != nil {
        return err
    }

    g.Go(func() error {
        return logPipe(ctx, stdout, bitcoindLogger)
    })

    g.Go(func() error {
        return logPipe(ctx, stderr, bitcoindStdErrLogger)
    })

    if err := cmd.Start(); err != nil {
        return fmt.Errorf("%w: unable to start eunod", err)
    }

    g.Go(func() error {
        <-ctx.Done()

        logger.Warnw("sending interrupt to eunod")
        return cmd.Process.Signal(os.Interrupt)
    })

    return cmd.Wait()
}

From now i will linked to github.

On line: https://github.com/ScArFaCe2020/rosetta-euno/blob/master/bitcoin/node.go#L68-L71 is the exec.Command.

the fmt.Sprintf("--conf=%s", configPath), Works fine.
Now i need to add --daemon inside it.

But when i change this to

fmt.Sprintf("--daemon --conf=%s", configPath),

It doesn't work.

Does anyone have a idea how i can add the --daemon?

Body:
exec.Command takes variadic string arguments. Its signature looks like this.

func Command(name string, arg ...string) *Cmd

Either pass a slice of stings followed by ... or pass a number of strings as arguments.

In your case, you treat the whole string --daemon --conf=/some/path as a single argument, while you actually want to treat it as two distinct arguments.

The most simple way to solve this would be doing it like this.

cmd := exec.Command(
    "/app/eunod",
    "--daemon",
    fmt.Sprintf("--conf=%s", configPath),
)

You can learn more about variadic arguments here https://golangdocs.com/variadic-functions-in-golang for example.


问:
Level system Discordjs
I am making a Level system for my bot. It's working perfectly, but there's one problem about the level system, It is when the bot making a restart, the current exp is resetting too. How can I stop it like that?

Here is my current code.

```<code>const db = require('quick.db');

if (!db[msg.author.id]) db[msg.author.id] = {
    xp: 0,
    level: 0
  };
db[msg.author.id].xp++;
let userInfo = db[msg.author.id];
if(userInfo.xp > 100) {
    userInfo.level++
    userInfo.xp = 0
    msg.reply("Congratulations, you level up")
}

if(msg.content.toLowerCase().startsWith(`${prefix}level`)) {
    let userInfo = db[msg.author.id];
    let member = msg.mentions.members.first();
    let embed = new MessageEmbed()
    .setTitle('Level Checking')
    .setDescription("<@" + msg.member.id + ">" + ` Your current level is: ${userInfo.level}`)
    .setColor('RANDOM')
    .addFields({name:"Level", value: `${userInfo.level}`})
    .addField("XP", userInfo.xp+"/100")
    .setTimestamp()
    .setFooter('Level | Reborn')
    if(!member) return msg.channel.send({embeds: [embed]})
    let memberInfo = db[member.id]
    let embed2 = new MessageEmbed()
    .setTitle('Level Checking')
    .setDescription("<@" + msg.member.id + ">" + ` Your current level is: ${memberInfo.level}`)
    .setColor('RANDOM')
    .addFields({name:"Level", value: `${memberInfo.level}`})
    .addField("XP", memberInfo.xp+"/100")
    .setTimestamp()
    .setFooter('Level | Reborn')
    msg.channel.sendEmbed({embeds: [embed2]})
}
</code>```

I'm using Discordjs v13

答:
You can use mongo db its a good database service, you can find a lot of documentation on internet and its easy to use

https://www.mongodb.com/, its free to use.
https://www.youtube.com/watch?v=8no3SktqagY, this video will explain you everything

I hope it will help

Title: Level system Discordjs

Body:
I am making a Level system for my bot. It's working perfectly, but there's one problem about the level system, It is when the bot making a restart, the current exp is resetting too. How can I stop it like that?

Here is my current code.

const db = require('quick.db');

if (!db[msg.author.id]) db[msg.author.id] = {
    xp: 0,
    level: 0
  };
db[msg.author.id].xp++;
let userInfo = db[msg.author.id];
if(userInfo.xp > 100) {
    userInfo.level++
    userInfo.xp = 0
    msg.reply("Congratulations, you level up")
}

if(msg.content.toLowerCase().startsWith(`${prefix}level`)) {
    let userInfo = db[msg.author.id];
    let member = msg.mentions.members.first();
    let embed = new MessageEmbed()
    .setTitle('Level Checking')
    .setDescription("<@" + msg.member.id + ">" + ` Your current level is: ${userInfo.level}`)
    .setColor('RANDOM')
    .addFields({name:"Level", value: `${userInfo.level}`})
    .addField("XP", userInfo.xp+"/100")
    .setTimestamp()
    .setFooter('Level | Reborn')
    if(!member) return msg.channel.send({embeds: [embed]})
    let memberInfo = db[member.id]
    let embed2 = new MessageEmbed()
    .setTitle('Level Checking')
    .setDescription("<@" + msg.member.id + ">" + ` Your current level is: ${memberInfo.level}`)
    .setColor('RANDOM')
    .addFields({name:"Level", value: `${memberInfo.level}`})
    .addField("XP", memberInfo.xp+"/100")
    .setTimestamp()
    .setFooter('Level | Reborn')
    msg.channel.sendEmbed({embeds: [embed2]})
}

I'm using Discordjs v13


问:
Quickblox voice calling / video calling
Does anyone know how I could use quickblox to make a voice calling/video calling? I'm making this app when the user clicks on the phone icon it starts the voice call between users and when they click on the video icon it opens them to video call? I just started working on it, I'm just wondering if anyone who tell me how to achieve the voice calling function. Thank you!</p>

答:
You can mute video stream when you start a call in order to simulate audio call (the guide is here - https://docs.quickblox.com/docs/android-video-calling-advanced#disable-video).

Then if you need to switch to video call you can unmute the video stream. You can find useful this video calling samples - https://docs.quickblox.com/docs/code-samples#video-calling-samples

Title: Quickblox voice calling / video calling


问:
Sending large data over sockets in java
I am working on client server architecture and i am just beginner in this thing. Here my server is of C and client is of Java and i want to send a binary/database (.db)/image file of size around 10 - 20 MB from C server to the Java client. But data is lost while implementing the following code:

Server side C code is:

```<code>int sockfd, newsockfd, portno, clilen;

struct sockaddr_in serv_addr, client_addr;

sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd < 0)
{
    strcpy(message,"Error opening socket");
    eFlag = 1;
    send_message(message);
}

bzero((char *)&serv_addr, sizeof(serv_addr));
portno = 6789;
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);

if(bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
    strcpy(message,"Error on binding");
    eFlag = 1;
    send_message(message);
}

listen(sockfd, 5);
clilen = sizeof(client_addr);
newsockfd = accept(sockfd, (struct sockaddr *)&client_addr, &clilen);

if(newsockfd < 0)
{
    strcpy(message,"Error on accept");
    eFlag = 1;
    send_message();
    exit(4);
}

void send_file()
{
    buffer = (char *)malloc(sizeof(char)*lSize);

    result = fread(buffer, sizeof(char), lSize, fp);
    printf("\n\n########## data read into buffer successfully #######");

    if(newsockfd)
    {
        n = send(newsockfd, buffer, lSize);
        printf("\n\n$$$$$$$$ Data sent successfully $$$$$");
        strcpy(message,"Data sent successfully");
        send_message(message);
    }

    else
    {
        strcpy(message, "Error writing on socket");
        send_message(message);
    }

    sleep(sleepTime);
    sleepTime = (int) (sleepTime*1.02);

    free(buffer);
}
</code>```

And, my client side Java code is:

```<code>                    final int PORT_NO = 6789;
        final String Server_name = "192.133.133.1";
        Socket m_socket = null;
        String str;
        int ch;

    try {
        if(m_socket == null)
            m_socket = new Socket(Server_name, PORT_NO);
        if(m_socket == null)
            System.out.println("Unable to open the socket");

    DataInputStream dis = new DataInputStream(m_socket.getInputStream());
    PrintStream ps = new PrintStream(m_socket.getOutputStream());

    DataInputStream ds = new DataInputStream(System.in);

    while(true)
    {
        System.out.println("1. Synchronize");
        System.out.println("2. Exit");
        System.out.println("Enter your choice...");
        str = ds.readLine();
        ch = Integer.parseInt(str);

        switch(ch)
        {
        case 1:
     ps.println("<message action='buttonpress' value='synchronize' />");
     System.out.println("avilable data to read is:"+dis.available());
     FileOutputStream fos = new FileOutputStream("mukul.db");

            byte data[] = new byte[102400]; //100 Kb byte array

                            dis.read(data);

            String str_data = new String(data);
            str_data = str_data.trim();
            data = str_data.getBytes();

            fos.write(data);
            fos.close();

            break;
</code>```

here only part of data is read i.e around 10 kb or less.

I am just a beginner to such posts and my code may be cumbersome, so please ignore all the mistakes in posting.

So please kindly tell me how can i receive 1 MB/10 MB of data in this client-server architecture without the loss of data.

What if i use "sendfile(out_fp, in_fp, pos, len)" method in C code instead of "send()". This method sends file handle. So what will be the corresponding function in Java to capture file handle.

Thank you in advance.

答:
Java side,</p>

```<code>int lent2 = 0;
int LengthToReceive = 102400;
char[] chTemp = new char[LengthToReceive];

while (true) {

    int readlength = bufferedreader.read(chTemp, lent2,LengthToReceive - lent2);
    if(readlength==-1){
        break;
    }

    lent2 += readlength;
    if (lent2 >= LengthToReceive) {
        flag = false;
        break;
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Sending large data over sockets in java

Body:
I am working on client server architecture and i am just beginner in this thing. Here my server is of C and client is of Java and i want to send a binary/database (.db)/image file of size around 10 - 20 MB from C server to the Java client. But data is lost while implementing the following code:

Server side C code is:

int sockfd, newsockfd, portno, clilen;

struct sockaddr_in serv_addr, client_addr;

sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd < 0)
{
    strcpy(message,"Error opening socket");
    eFlag = 1;
    send_message(message);
}

bzero((char *)&serv_addr, sizeof(serv_addr));
portno = 6789;
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);

if(bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
    strcpy(message,"Error on binding");
    eFlag = 1;
    send_message(message);
}

listen(sockfd, 5);
clilen = sizeof(client_addr);
newsockfd = accept(sockfd, (struct sockaddr *)&client_addr, &clilen);

if(newsockfd < 0)
{
    strcpy(message,"Error on accept");
    eFlag = 1;
    send_message();
    exit(4);
}

void send_file()
{
    buffer = (char *)malloc(sizeof(char)*lSize);

    result = fread(buffer, sizeof(char), lSize, fp);
    printf("\n\n########## data read into buffer successfully #######");

    if(newsockfd)
    {
        n = send(newsockfd, buffer, lSize);
        printf("\n\n$$$$$$$$ Data sent successfully $$$$$");
        strcpy(message,"Data sent successfully");
        send_message(message);
    }

    else
    {
        strcpy(message, "Error writing on socket");
        send_message(message);
    }

    sleep(sleepTime);
    sleepTime = (int) (sleepTime*1.02);

    free(buffer);
}

And, my client side Java code is:

                    final int PORT_NO = 6789;
        final String Server_name = "192.133.133.1";
        Socket m_socket = null;
        String str;
        int ch;

    try {
        if(m_socket == null)
            m_socket = new Socket(Server_name, PORT_NO);
        if(m_socket == null)
            System.out.println("Unable to open the socket");

    DataInputStream dis = new DataInputStream(m_socket.getInputStream());
    PrintStream ps = new PrintStream(m_socket.getOutputStream());

    DataInputStream ds = new DataInputStream(System.in);

    while(true)
    {
        System.out.println("1. Synchronize");
        System.out.println("2. Exit");
        System.out.println("Enter your choice...");
        str = ds.readLine();
        ch = Integer.parseInt(str);

        switch(ch)
        {
        case 1:
     ps.println("<message action='buttonpress' value='synchronize' />");
     System.out.println("avilable data to read is:"+dis.available());
     FileOutputStream fos = new FileOutputStream("mukul.db");

            byte data[] = new byte[102400]; //100 Kb byte array

                            dis.read(data);

            String str_data = new String(data);
            str_data = str_data.trim();
            data = str_data.getBytes();

            fos.write(data);
            fos.close();

            break;

here only part of data is read i.e around 10 kb or less.

I am just a beginner to such posts and my code may be cumbersome, so please ignore all the mistakes in posting.

So please kindly tell me how can i receive 1 MB/10 MB of data in this client-server architecture without the loss of data.

What if i use "sendfile(out_fp, in_fp, pos, len)" method in C code instead of "send()". This method sends file handle. So what will be the corresponding function in Java to capture file handle.

Thank you in advance.

Body:
Java side,

int lent2 = 0;
int LengthToReceive = 102400;
char[] chTemp = new char[LengthToReceive];

while (true) {

    int readlength = bufferedreader.read(chTemp, lent2,LengthToReceive - lent2);
    if(readlength==-1){
        break;
    }

    lent2 += readlength;
    if (lent2 >= LengthToReceive) {
        flag = false;
        break;
    }
}


问:
Difference on GraphQL endpoint between apollo-server and apollo-server-express
Due to the fact that I need to add a bit more configuration to my GraphQL server, I am switching from apollo-server to apollo-server-express (as recommended by the documentation).

This is my old index.ts:

```<code>import { env } from 'process'
import { ApolloServer } from 'apollo-server'
import { typeDefs } from '../graphql/schema'
import { context } from './context'
import resolvers from '../graphql/resolvers/'

const port = env.GRAPHQL_SERVER_PORT || 80

const server = new ApolloServer({
  typeDefs,
  resolvers,
  context
})

server.listen({ port: port }).then(({ url }) => {
  console.log(`Server ready at ${url}`)
})
</code>```

and this is what I'm trying to do now:

```<code>import { env } from 'process'
import { ApolloServer } from 'apollo-server-express';
import { ApolloServerPluginDrainHttpServer } from 'apollo-server-core';
import express from 'express';
import { forceDomain } from 'forcedomain'
import http from 'http';
import { typeDefs } from '../graphql/schema'
import { context } from './context'
import resolvers from '../graphql/resolvers/'

async function startApolloServer(typeDefs: any, resolvers: any, context: any) {
  const port = env.GRAPHQL_SERVER_PORT || 80
  const app = express();
  const httpServer = http.createServer(app);
  const plugins = [ApolloServerPluginDrainHttpServer({ httpServer })]

  const server = new ApolloServer({
    typeDefs,
    resolvers,
    context,
    plugins,
  });

  await server.start();

  app.use(function(req, res, next) {
    // some extra middleware configuration here
  })

  server.applyMiddleware({ app })

  await new Promise<void>(resolve => httpServer.listen({ port: port }, resolve))
  console.log(`Server ready at http://localhost:${port}${server.graphqlPath}`)
}

startApolloServer(typeDefs, resolvers, context)

</code>```

What I don't understand is that after switching to apollo-server-express, everything is working fine (and the added middleware does what I need it to do) but the GraphQL endpoint is moved to the /graphql route (I.E. http://localhost:4000/graphql, or https://my-devel-server.com/graphql) instead of being on the root as it was before (so just http://localhost:4000), when I was using apollo-server and the listen method.

Why is that, and how can I use apollo-server-express while keeping the endpoint on the root of the server?

答:
I'm not sure as to why the middleware work now without seeing how you implemented them, but "GraphQL Middleware" is quite different from "Express Middleware" so maybe it's the way they were structured.

About the routes, it's just a standard to make the base GraphQL route at /graphql, since in an Express App, you could potentially have other REST routes at the root.

To change this behaviour you could change the line server.applyMiddleware({ app }) to server.applyMiddleware({ app, path: '/' }) with the path you want GraphQL to start on.

Body:
Due to the fact that I need to add a bit more configuration to my GraphQL server, I am switching from apollo-server to apollo-server-express (as recommended by the documentation).

This is my old index.ts:

import { env } from 'process'
import { ApolloServer } from 'apollo-server'
import { typeDefs } from '../graphql/schema'
import { context } from './context'
import resolvers from '../graphql/resolvers/'

const port = env.GRAPHQL_SERVER_PORT || 80

const server = new ApolloServer({
  typeDefs,
  resolvers,
  context
})

server.listen({ port: port }).then(({ url }) => {
  console.log(`Server ready at ${url}`)
})

and this is what I'm trying to do now:

import { env } from 'process'
import { ApolloServer } from 'apollo-server-express';
import { ApolloServerPluginDrainHttpServer } from 'apollo-server-core';
import express from 'express';
import { forceDomain } from 'forcedomain'
import http from 'http';
import { typeDefs } from '../graphql/schema'
import { context } from './context'
import resolvers from '../graphql/resolvers/'

async function startApolloServer(typeDefs: any, resolvers: any, context: any) {
  const port = env.GRAPHQL_SERVER_PORT || 80
  const app = express();
  const httpServer = http.createServer(app);
  const plugins = [ApolloServerPluginDrainHttpServer({ httpServer })]

  const server = new ApolloServer({
    typeDefs,
    resolvers,
    context,
    plugins,
  });

  await server.start();

  app.use(function(req, res, next) {
    // some extra middleware configuration here
  })

  server.applyMiddleware({ app })

  await new Promise<void>(resolve => httpServer.listen({ port: port }, resolve))
  console.log(`Server ready at http://localhost:${port}${server.graphqlPath}`)
}

startApolloServer(typeDefs, resolvers, context)

What I don't understand is that after switching to apollo-server-express, everything is working fine (and the added middleware does what I need it to do) but the GraphQL endpoint is moved to the /graphql route (I.E. http://localhost:4000/graphql, or https://my-devel-server.com/graphql) instead of being on the root as it was before (so just http://localhost:4000), when I was using apollo-server and the listen method.

Why is that, and how can I use apollo-server-express while keeping the endpoint on the root of the server?


问:
The body of view to be destroyed gets called (but it shouldn't)
While verifying how binding invalidates a view (indirectly), I find an unexpected behavior.

If the view hierarchy is

```<code> list view -> detail view
</code>```

it works fine (as expected) to press a button in the detail view to delete the item.

However, if the view hierarchy is

```<code>list view -> detail view -> another detail view (containing the same item)
</code>```

it crashes when I press a button in the top-most detail view to delete the item. The crash occurs in the first detail view (the underlying one), because its body gets called.

To put it in another way, the behavior is:

If the detail view is the top-most view in the navigation stack, its body doesn't get called.

Otherwise, its body gets called.

I can't think out any reason for this behavior. My debugging showed below are what happened before the crash:

I pressed a button in top-most detail view to delete the item.

The ListView's body got called (as a result of ContentView body got called). It created only the detail view for the left item.

Then the first DetailView's body get called. This is what caused the crash. I can't think out why this occurred, because it certainly didn't occur for the top-most detail view.

Below is the code. Note the ListView and DetailView contains only binding and regular properties (they don't contain observable object or environment object, which I'm aware complicate the view invalidation behavior).

```<code>import SwiftUI

struct Foo: Identifiable {
    var id: Int
    var value: Int
}

// Note that I use forced unwrapping in data model's APIs. This is intentional. The rationale: the caller of data model API should make sure it passes a valid id.
extension Array where Element == Foo {
    func get(_ id: Int) -> Foo {
        return first(where: { $0.id == id })!
    }

    mutating func remove(_ id: Int) {
        let index = firstIndex(where: { $0.id == id })!
        remove(at: index)
    }
}

class DataModel: ObservableObject {
    @Published var foos: [Foo] = [Foo(id: 1, value: 1), Foo(id: 2, value: 2)]
}

struct ListView: View {
    @Binding var foos: [Foo]

    var body: some View {
        NavigationView {
            List {
                ForEach(foos) { foo in
                    NavigationLink {
                        DetailView(foos: $foos, fooID: foo.id, label: "First detail view")
                    } label: {
                        Text("\(foo.value)")
                    }
                }
            }
        }
    }
}

struct DetailView: View {
    @Binding var foos: [Foo]
    var fooID: Int
    var label: String

    var body: some View {
        // The two print() calls are for debugging only.
        print(Self._printChanges())
        print(label)
        print(fooID)

        return VStack {
            Text(label)
            Divider()
            Text("Value: \(foos.get(fooID).value)")
            NavigationLink {
                DetailView(foos: $foos, fooID: fooID, label: "Another detail view")
            } label: {
                Text("Create another detail view")
            }
            Button("Delete It") {
                foos.remove(fooID)
            }
        }
    }
}

struct ContentView: View {
    @StateObject var dataModel = DataModel()

    var body: some View {
        ListView(foos: $dataModel.foos)
    }
}
</code>```

Test 1: Start the app, click on an item in the list view to go to the detail view, then click on "Delete It" button. This works fine.

The view hierarchy: list view -> detail view

Test 2: Start the app, click on an item in the list view to go to the detail view, then click on "Create another detail view" to go to another detail view. Then click on "Delete It" button. The crashes the first detail view.

The view hierarchy: list view -> detail view -> another detail view

Could it be just another bug of @Binding? Is there any robust way to work around the issue?

答:
I think this is very much like Paul's approach. I just kept the Array extension with the force unwrap as in OP.</p>
```<code>struct Foo: Identifiable {
    var id: Int
    var value: Int
}

// Note that I use forced unwrapping in data model's APIs. This is intentional. The rationale: the caller of data model API should make sure it passes a valid id.
extension Array where Element == Foo {
    func get(_ id: Int) -> Foo {
        return first(where: { $0.id == id })!
    }

    mutating func remove(_ id: Int) {
        let index = firstIndex(where: { $0.id == id })!
        remove(at: index)
    }
}

class DataModel: ObservableObject {
    @Published var foos: [Foo] = [Foo(id: 1, value: 1), Foo(id: 2, value: 2), Foo(id: 3, value: 3)]
}

struct ListView: View {
    @EnvironmentObject var dataModel: DataModel

    var body: some View {
        NavigationView {
            List {
                ForEach(dataModel.foos) { foo in
                    NavigationLink {
                        DetailView(foo: foo, label: "First detail view")
                    } label: {
                        Text("\(foo.value)")
                    }
                }
            }
        }
    }
}

struct DetailView: View {
    @EnvironmentObject var dataModel: DataModel

    var foo: Foo
    var label: String

    var body: some View {
        // The two print() calls are for debugging only.
        print(Self._printChanges())
        print(label)
        print(foo.id)

        return VStack {
            Text(label)
            Divider()
            Text("Value: \(foo.value)")
            NavigationLink {
                DetailView(foo: foo, label: "Yet Another detail view")
            } label: {
                Text("Create another detail view")
            }
            Button("Delete It") {
                dataModel.foos.remove(foo.id)
            }
        }
    }
}

struct ContentView: View {
    @StateObject var dataModel = DataModel()

    var body: some View {
        ListView()
            .environmentObject(dataModel)
    }
}
</code>```

Body:
While verifying how binding invalidates a view (indirectly), I find an unexpected behavior.

If the view hierarchy is

 list view -> detail view

it works fine (as expected) to press a button in the detail view to delete the item.

However, if the view hierarchy is

list view -> detail view -> another detail view (containing the same item)

it crashes when I press a button in the top-most detail view to delete the item. The crash occurs in the first detail view (the underlying one), because its body gets called.

To put it in another way, the behavior is:

If the detail view is the top-most view in the navigation stack, its body doesn't get called.

Otherwise, its body gets called.

I can't think out any reason for this behavior. My debugging showed below are what happened before the crash:

I pressed a button in top-most detail view to delete the item.

The ListView's body got called (as a result of ContentView body got called). It created only the detail view for the left item.

Then the first DetailView's body get called. This is what caused the crash. I can't think out why this occurred, because it certainly didn't occur for the top-most detail view.

Below is the code. Note the ListView and DetailView contains only binding and regular properties (they don't contain observable object or environment object, which I'm aware complicate the view invalidation behavior).

import SwiftUI

struct Foo: Identifiable {
    var id: Int
    var value: Int
}

// Note that I use forced unwrapping in data model's APIs. This is intentional. The rationale: the caller of data model API should make sure it passes a valid id.
extension Array where Element == Foo {
    func get(_ id: Int) -> Foo {
        return first(where: { $0.id == id })!
    }

    mutating func remove(_ id: Int) {
        let index = firstIndex(where: { $0.id == id })!
        remove(at: index)
    }
}

class DataModel: ObservableObject {
    @Published var foos: [Foo] = [Foo(id: 1, value: 1), Foo(id: 2, value: 2)]
}

struct ListView: View {
    @Binding var foos: [Foo]

    var body: some View {
        NavigationView {
            List {
                ForEach(foos) { foo in
                    NavigationLink {
                        DetailView(foos: $foos, fooID: foo.id, label: "First detail view")
                    } label: {
                        Text("\(foo.value)")
                    }
                }
            }
        }
    }
}

struct DetailView: View {
    @Binding var foos: [Foo]
    var fooID: Int
    var label: String

    var body: some View {
        // The two print() calls are for debugging only.
        print(Self._printChanges())
        print(label)
        print(fooID)

        return VStack {
            Text(label)
            Divider()
            Text("Value: \(foos.get(fooID).value)")
            NavigationLink {
                DetailView(foos: $foos, fooID: fooID, label: "Another detail view")
            } label: {
                Text("Create another detail view")
            }
            Button("Delete It") {
                foos.remove(fooID)
            }
        }
    }
}

struct ContentView: View {
    @StateObject var dataModel = DataModel()

    var body: some View {
        ListView(foos: $dataModel.foos)
    }
}

Test 1: Start the app, click on an item in the list view to go to the detail view, then click on "Delete It" button. This works fine.

The view hierarchy: list view -> detail view

Test 2: Start the app, click on an item in the list view to go to the detail view, then click on "Create another detail view" to go to another detail view. Then click on "Delete It" button. The crashes the first detail view.

The view hierarchy: list view -> detail view -> another detail view

Could it be just another bug of @Binding? Is there any robust way to work around the issue?

Body:
I think this is very much like Paul's approach. I just kept the Array extension with the force unwrap as in OP.

struct Foo: Identifiable {
    var id: Int
    var value: Int
}

// Note that I use forced unwrapping in data model's APIs. This is intentional. The rationale: the caller of data model API should make sure it passes a valid id.
extension Array where Element == Foo {
    func get(_ id: Int) -> Foo {
        return first(where: { $0.id == id })!
    }

    mutating func remove(_ id: Int) {
        let index = firstIndex(where: { $0.id == id })!
        remove(at: index)
    }
}

class DataModel: ObservableObject {
    @Published var foos: [Foo] = [Foo(id: 1, value: 1), Foo(id: 2, value: 2), Foo(id: 3, value: 3)]
}

struct ListView: View {
    @EnvironmentObject var dataModel: DataModel

    var body: some View {
        NavigationView {
            List {
                ForEach(dataModel.foos) { foo in
                    NavigationLink {
                        DetailView(foo: foo, label: "First detail view")
                    } label: {
                        Text("\(foo.value)")
                    }
                }
            }
        }
    }
}

struct DetailView: View {
    @EnvironmentObject var dataModel: DataModel

    var foo: Foo
    var label: String

    var body: some View {
        // The two print() calls are for debugging only.
        print(Self._printChanges())
        print(label)
        print(foo.id)

        return VStack {
            Text(label)
            Divider()
            Text("Value: \(foo.value)")
            NavigationLink {
                DetailView(foo: foo, label: "Yet Another detail view")
            } label: {
                Text("Create another detail view")
            }
            Button("Delete It") {
                dataModel.foos.remove(foo.id)
            }
        }
    }
}

struct ContentView: View {
    @StateObject var dataModel = DataModel()

    var body: some View {
        ListView()
            .environmentObject(dataModel)
    }
}


问:
Powershell script to show file extensions in File Explorer
I'm fairly new to the world of Powershell and currently I'm trying to push a Powershell script via Intune to the company devices (all Windows 10 21H2 machines) that will show the file extensions in File Explorer.

So far, I've found this:

```<code>Set-Itemproperty -path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced' -Name 'HideFileExt' -value 0
</code>```

The PS script is pushed via Intune to a test device and the monitor tells me the policy is applied successfuly but the file extensions are still not visible.

Is there something wrong with the line of code?

答:
This was the solution:

"The script works fine. I am positive that it is not applied successfully, despite Intune telling you it did. While it is not part of that question, I suppose you should check the user context in which the script is applied and if the eventvwr or any other possible source tells you why the script did not apply correctly. Also, after trying the script locally for myself, you need to refresh the explorer tab via f5 for the change to apply"  –
Bowshock

Body:
I'm fairly new to the world of Powershell and currently I'm trying to push a Powershell script via Intune to the company devices (all Windows 10 21H2 machines) that will show the file extensions in File Explorer.

So far, I've found this:

Set-Itemproperty -path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced' -Name 'HideFileExt' -value 0

The PS script is pushed via Intune to a test device and the monitor tells me the policy is applied successfuly but the file extensions are still not visible.

Is there something wrong with the line of code?


问:
How can I process this array more efficiently
I have an array of names that looks like the following.
["John Doe", "Mary Blog"]

What I want to do is process this array and return an array with the initials like the following.

["JD", "MB"]

I have already done this but my code is ugly and inefficient (nested loops).
It's probably fine for a small array like in my example.

How can I process my array more efficiently?

```<code>       let contacts = ["John Doe", "Mary Blog"]
       var initalsArray: [String] = []
       let names = contacts.map {$0}

            for name in names {
                var initals: String = ""
                let fullname = name.components(separatedBy: " ")
                for part in fullname {
                    if part.count > 0 {
                        initals += part[0]
                    }
                }
                initalsArray.append(initals)
            }
</code>```

答:
Actually this answer though similar may be a bit quicker

```<code>let contacts = ["John Doe", "Mary Blog"]
let result = contacts.map { $0.components(separatedBy: .whitespacesAndNewlines).reduce("") { $0 + String($1.prefix(1)) } }
print(result)
</code>```

Instated of constructing inner arrays and then joining them I just added it to the string of previous first letters

Body:
I have an array of names that looks like the following.
["John Doe", "Mary Blog"]

What I want to do is process this array and return an array with the initials like the following.

["JD", "MB"]

I have already done this but my code is ugly and inefficient (nested loops).
It's probably fine for a small array like in my example.

How can I process my array more efficiently?

       let contacts = ["John Doe", "Mary Blog"]
       var initalsArray: [String] = []
       let names = contacts.map {$0}

            for name in names {
                var initals: String = ""
                let fullname = name.components(separatedBy: " ")
                for part in fullname {
                    if part.count > 0 {
                        initals += part[0]
                    }
                }
                initalsArray.append(initals)
            }

Body:
Actually this answer though similar may be a bit quicker

let contacts = ["John Doe", "Mary Blog"]
let result = contacts.map { $0.components(separatedBy: .whitespacesAndNewlines).reduce("") { $0 + String($1.prefix(1)) } }
print(result)

Instated of constructing inner arrays and then joining them I just added it to the string of previous first letters


问:
How to push docker image in artifactory with token authentication via Jenkins?
We operate artifactory and jenkins for CI process. Now we use standard username/password credentials for login to artifactory. Want to use token for login. I generated token in artifactory and add it to Jenkins.
Part of code Jenkins pipeline:

```<code>// Build a Docker image
stage ('Build a Docker image') {
        docker.withRegistry("https://${params.DOCKER_REGISTRY}", params.DOCKER_REGISTRY_CREDS) {
        def img = docker.build("${docker_tag}:${build_version}", "--build-arg VERSION=${params.DOCKER_BUILD_VERSION} -f ${dockerfile} ." )
        try {
                img.push()
                docker_push_rmi(img, docker_tag, "${params.DOCKER_BUILD_VERSION}.latest")
                docker_push_rmi(img, docker_tag, "latest")
        } finally {
            sh "docker rmi ${docker_tag}:${build_version}"
        }
        }
}
</code>```

where DOCKER_REGISTRY_CREDS - username/password for artifactory login.

How I can convert it to token access?

答: Try using the token as a password and use the username of whoever created the token.</p>

Body:
We operate artifactory and jenkins for CI process. Now we use standard username/password credentials for login to artifactory. Want to use token for login. I generated token in artifactory and add it to Jenkins.
Part of code Jenkins pipeline:

// Build a Docker image
stage ('Build a Docker image') {
        docker.withRegistry("https://${params.DOCKER_REGISTRY}", params.DOCKER_REGISTRY_CREDS) {
        def img = docker.build("${docker_tag}:${build_version}", "--build-arg VERSION=${params.DOCKER_BUILD_VERSION} -f ${dockerfile} ." )
        try {
                img.push()
                docker_push_rmi(img, docker_tag, "${params.DOCKER_BUILD_VERSION}.latest")
                docker_push_rmi(img, docker_tag, "latest")
        } finally {
            sh "docker rmi ${docker_tag}:${build_version}"
        }
        }
}

where DOCKER_REGISTRY_CREDS - username/password for artifactory login.

How I can convert it to token access?


问:
Checking time-stamps if they are from today in MySQL
I have a database with several tables. Each of these tables has a column 'created' which contains time-stamps of when that particular row was created in the database.

Now, I want to create a MySQL script that checks once every week if there is data coming into these tables. So, there should be data coming everyday. How do I create a MySQL script that allows me to do this for all the tables in the database?

Note: Remember I want to do this for all the tables in the database with a single script. That's the main thing I want to know.

答:
i use this approach for a table called call, with a column of timestamp type called systemdate:

```<code>SELECT * FROM `call` WHERE DATE(`systemdate`) = DATE(NOW());
</code>```

mysql DATE() statement gets the datepart of a datetime or timestamp field.

Sorry, just noticed that you want to check if atleast there is an entry for each of the days in the previous week.

you can use this query to check the prevous days individually:

yesterday:

```<code>SELECT * FROM `call` WHERE DATE(`systemdate`) = DATE(NOW()) - 1;
</code>```

before yesterday:

```<code>SELECT * FROM `call` WHERE DATE(`systemdate`) = DATE(NOW()) - 2;
</code>```

Or you can check the whole week at once:

```<code>SELECT * FROM `call` WHERE DATE(`systemdate`) > DATE_SUB(CURDATE(), INTERVAL 7 DAY)  GROUP BY DATE(`systemdate`);
</code>```

This will return one result for each day, so if you have 7 results you'll know at least an entry was made on each day.

Body:
i use this approach for a table called call, with a column of timestamp type called systemdate:

SELECT * FROM `call` WHERE DATE(`systemdate`) = DATE(NOW());

mysql DATE() statement gets the datepart of a datetime or timestamp field.

Sorry, just noticed that you want to check if atleast there is an entry for each of the days in the previous week.

you can use this query to check the prevous days individually:

yesterday:

SELECT * FROM `call` WHERE DATE(`systemdate`) = DATE(NOW()) - 1;

before yesterday:

SELECT * FROM `call` WHERE DATE(`systemdate`) = DATE(NOW()) - 2;

Or you can check the whole week at once:

SELECT * FROM `call` WHERE DATE(`systemdate`) > DATE_SUB(CURDATE(), INTERVAL 7 DAY)  GROUP BY DATE(`systemdate`);

This will return one result for each day, so if you have 7 results you'll know at least an entry was made on each day.


问:
Class AMSupportURLConnectionDelegate is implemented in both
I'm trying to build a flutter app on M1 mac and getting the following error.

```<code>$ flutter build ios --release
Building XXX for device (ios-release)...
Automatically signing iOS for device deployment using specified development team in Xcode project: XXX
Running pod install...                                             13.2s
Running Xcode build...
Xcode build done.                                            6.7s
Failed to build iOS app
Error output from Xcode build:
↳
    objc[65074]: Class AMSupportURLConnectionDelegate is implemented in both ?? (0x1f66de518) and ?? (0x1160d82b8). One
    of the two will be used. Which one is undefined.
    objc[65074]: Class AMSupportURLSession is implemented in both ?? (0x1f66de568) and ?? (0x1160d8308). One of the two
    will be used. Which one is undefined.
    ** BUILD FAILED **

Xcode's output:
↳
    note: Using new build system
    note: Building targets in parallel
    note: Planning build
    note: Constructing build description
    error: The linked framework 'Pods_Runner.framework' is missing one or more architectures required by this target:
    armv7. (in target 'Runner' from project 'Runner')

Encountered error while building for device.
</code>```

Here is my flutter doctor -v

```<code>flutter doctor -v
[✓] Flutter (Channel stable, 1.22.4, on macOS 11.0 20A2411 darwin-arm, locale en-AU)
    • Flutter version 1.22.4 at /Users/mlee/development/flutter
    • Framework revision 1aafb3a8b9 (3 weeks ago), 2020-11-13 09:59:28 -0800
    • Engine revision 2c956a31c0
    • Dart version 2.10.4

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
    • Android SDK at /Users/mlee/Library/Android/sdk
    • Platform android-30, build-tools 30.0.2
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 12.2)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 12.2, Build version 12B45b
    • CocoaPods version 1.10.0

[!] Android Studio (version 4.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    ✗ Flutter plugin not installed; this adds Flutter specific functionality.
    ✗ Dart plugin not installed; this adds Dart specific functionality.
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)

[✓] VS Code (version 1.51.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.16.0

[✓] Connected device (2 available)

! Doctor found issues in 1 category.
</code>```

答:
I try all the answer mention here but none of them work for me.
what work for me is going to pubspec.yaml and click pub upgrade and then re run the app and it work for me. also make sure to check the dart analysis tab after click pub upgraded as some of the package will throw error you need to updated the code for that in my case only one package which was flag showing error after pub upgrade which is fixed by looking at the updated documentation in the pub.dev of that package.

thanks have a nice day I hope this help.

Body:
I'm trying to build a flutter app on M1 mac and getting the following error.

$ flutter build ios --release
Building XXX for device (ios-release)...
Automatically signing iOS for device deployment using specified development team in Xcode project: XXX
Running pod install...                                             13.2s
Running Xcode build...
Xcode build done.                                            6.7s
Failed to build iOS app
Error output from Xcode build:
↳
    objc[65074]: Class AMSupportURLConnectionDelegate is implemented in both ?? (0x1f66de518) and ?? (0x1160d82b8). One
    of the two will be used. Which one is undefined.
    objc[65074]: Class AMSupportURLSession is implemented in both ?? (0x1f66de568) and ?? (0x1160d8308). One of the two
    will be used. Which one is undefined.
    ** BUILD FAILED **

Xcode's output:
↳
    note: Using new build system
    note: Building targets in parallel
    note: Planning build
    note: Constructing build description
    error: The linked framework 'Pods_Runner.framework' is missing one or more architectures required by this target:
    armv7. (in target 'Runner' from project 'Runner')

Encountered error while building for device.

Here is my flutter doctor -v

flutter doctor -v
[✓] Flutter (Channel stable, 1.22.4, on macOS 11.0 20A2411 darwin-arm, locale en-AU)
    • Flutter version 1.22.4 at /Users/mlee/development/flutter
    • Framework revision 1aafb3a8b9 (3 weeks ago), 2020-11-13 09:59:28 -0800
    • Engine revision 2c956a31c0
    • Dart version 2.10.4

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
    • Android SDK at /Users/mlee/Library/Android/sdk
    • Platform android-30, build-tools 30.0.2
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 12.2)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 12.2, Build version 12B45b
    • CocoaPods version 1.10.0

[!] Android Studio (version 4.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    ✗ Flutter plugin not installed; this adds Flutter specific functionality.
    ✗ Dart plugin not installed; this adds Dart specific functionality.
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)

[✓] VS Code (version 1.51.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.16.0

[✓] Connected device (2 available)

! Doctor found issues in 1 category.


问:
Center Image in UIWebView
Does anybody know a possibility to center simple pictures within a UIWebview without using hmtl/css?
Thanks in Advance.</p>

答:
Swift
First action = webView.navigationDelegate = self

and

```<code>func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {

        let cssString = "html,body { height: 100%; display: flex; align-items: center; justify-content: center; }"
        let jsString = "var style = document.createElement('style'); style.innerHTML = '\(cssString)'; document.head.appendChild(style);"
        webView.evaluateJavaScript(jsString, completionHandler: nil)

}
</code>```

Title: Center Image in UIWebView

Body:
Swift
First action = webView.navigationDelegate = self

and

func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {

        let cssString = "html,body { height: 100%; display: flex; align-items: center; justify-content: center; }"
        let jsString = "var style = document.createElement('style'); style.innerHTML = '\(cssString)'; document.head.appendChild(style);"
        webView.evaluateJavaScript(jsString, completionHandler: nil)

}


问:
Oracle SQLDeveloper on MacOS won't open after installation of correct Java
I downloaded the Oracle SQLDeveloper, but when I opened it, it said that it requires a minimum of Java 8 and gave me the website for the download. I went on and downloaded Java 10.0.1, but when I went back on to open SQL, it continued saying it required a minimum of Java 8.

I checked that the Java 10.0.1 had installed correctly, and I'm pretty sure it has. It shows up in System Preferences and when clicked, it opens the Java Control Panel fine.

I'm on a MacOS X El Captain 10.11.6.

答:
Sqldeveloper works only with jre 8

A) install

```<code>brew tap AdoptOpenJDK/openjdk
brew install adoptopenjdk8
</code>```

A.1) Optional - add the following to .zshrc

```<code>jdk() {
      version=$1
      unset JAVA_HOME;
      export JAVA_HOME=$(/usr/libexec/java_home -v"$version");
      java -version
}
</code>```

Thanks to - Mac OS X and multiple Java versions

B) permissions

```<code>chmod +x /Applications/SQLDeveloper.app/Contents/Resources/sqldeveloper/sqldeveloper.sh
</code>```

C) create a sqldeveloper.zsh as below

```<code>#!/bin/zsh
source ~/.zshrc
jdk 1.8.0_291
/Applications/SQLDeveloper.app/Contents/Resources/sqldeveloper/sqldeveloper.sh
</code>```

Body:
Sqldeveloper works only with jre 8

A) install

brew tap AdoptOpenJDK/openjdk
brew install adoptopenjdk8

A.1) Optional - add the following to .zshrc

jdk() {
      version=$1
      unset JAVA_HOME;
      export JAVA_HOME=$(/usr/libexec/java_home -v"$version");
      java -version
}

Thanks to - Mac OS X and multiple Java versions

B) permissions

chmod +x /Applications/SQLDeveloper.app/Contents/Resources/sqldeveloper/sqldeveloper.sh

C) create a sqldeveloper.zsh as below

#!/bin/zsh
source ~/.zshrc
jdk 1.8.0_291
/Applications/SQLDeveloper.app/Contents/Resources/sqldeveloper/sqldeveloper.sh


问:
Spring - import jpa repositories from another module
I have two gradle modules: common and app

The common module contains a JpaRepository named OutboxJpaMessageRepository.

The app module contains another JpaRepository named RentRepository.

The common has the following configuration class, which is auto-imported by the other module (using a spring.factories file):

@Configuration
@EntityScan("path.to.common.module")
@EnableJpaRepositories("path.to.common.module")
@ComponentScan("path.to.common.module")
public class OutboxMessagingAutoConfig {
}
```

The problem is that @EnableJpaRepositories("path.to.common.module") overrides the default auto-configuration of the application, and the app can't find RentRepository (different package).

Can a library exports jpa repositories without override the default configuration of the client?

I don't want to re-configure all apps which use the common module

答:
Two solutions I can think of:

1: @EnableJpaRepositories accepts an array as parameter, pass it path.to.app.module.

2: Use @EnableAutoConfiguration and spare yourself a lot of trouble.

Body:
I have two gradle modules: common and app

The common module contains a JpaRepository named OutboxJpaMessageRepository.

The app module contains another JpaRepository named RentRepository.

The common has the following configuration class, which is auto-imported by the other module (using a spring.factories file):

@Configuration
@EntityScan("path.to.common.module")
@EnableJpaRepositories("path.to.common.module")
@ComponentScan("path.to.common.module")
public class OutboxMessagingAutoConfig {
}

The problem is that @EnableJpaRepositories("path.to.common.module") overrides the default auto-configuration of the application, and the app can't find RentRepository (different package).

Can a library exports jpa repositories without override the default configuration of the client?

I don't want to re-configure all apps which use the common module


问:
Find columns where week row and year row matches values given in another cell range
I have a matrix in excel where the 2 top rows are "Year" and "Week".

As you probably could imagine there is a lot of columns in this matrix as time goes by. Therefore I would like a button that simply sends the user to the column with year and week matching the 2 "search cells"

To illustrate:

What I want is just to select the column or Year-Week range that matches the criterias in cell B1 and B2.

So that it would select column C or range("C4:C5") with the criterias given in the picture.

I simply cant wrap my head around it atm, so I hope you can help me.

Thanks in advance!

答:
here example:

```<code>Sub test()

Dim criteria1$, criteria2$
Dim cl As Range, data As Range

criteria1 = [B1].Value
criteria2 = [B2].Value

Set data = [B4:G5]

For Each cl In data
    If cl.Value = criteria1 And cl.Offset(1, 0).Value = criteria2 Then
        Range(cl, cl.Offset(1, 0)).Select
    End If
Next cl

End Sub
</code>```

you can assign this Sub to button/shape/picture ...

Body:
here example:

Sub test()

Dim criteria1$, criteria2$
Dim cl As Range, data As Range

criteria1 = [B1].Value
criteria2 = [B2].Value

Set data = [B4:G5]

For Each cl In data
    If cl.Value = criteria1 And cl.Offset(1, 0).Value = criteria2 Then
        Range(cl, cl.Offset(1, 0)).Select
    End If
Next cl

End Sub

you can assign this Sub to button/shape/picture ...


问:
"Dotting" in JSON using Gson on Android
I'm trying to parse a JSON feed using Gson in Android. I know the JSON is valid. I suspect that it is because the format is like this:

```<code> "Info":[
 {

"Id":"",
"Name":"",
"Description":"",
"Date":""
 }
</code>```

In order to parse this I need to "dot" in. Ex: Info.Name

How can I do this in a serialized DTO?

```<code>@SerializedName("Name")
public String name;

@SerializedName("Description")
public String desc;

@SerializedName("Date")
public String date;
</code>```

I tried to put "Info." in front of each serializedName but that didn't work either. I also know my JSON parsing method works properly, because it's used somewhere else with a different DTO. But in that parsing, I don't have to "dotting" issue.

Can anyone help?

EDIT: I have tried everything you guys posted, and nothing works. The error says:

```<code>The JsonDeserializer failed to deserialize json object {"Info":[{".......
</code>```

SECOND EDIT:
I was able to get rid of the error, but now it returns null. Haha, getting pretty damn frustrated right about now!

答:
The Info object is a list because of the []. You have to use the following code to deserialze it:

EDIT:

```<code>public class Info {
    // as in your question
    public String name;
    ...
}
public class Data {
    @SerializedName("Info")
    public List<Info> info;
}
</code>```

Then just use the data class to deserialize your json.

Title: "Dotting" in JSON using Gson on Android

Body:
I'm trying to parse a JSON feed using Gson in Android. I know the JSON is valid. I suspect that it is because the format is like this:

 "Info":[
 {

"Id":"",
"Name":"",
"Description":"",
"Date":""
 }

In order to parse this I need to "dot" in. Ex: Info.Name

How can I do this in a serialized DTO?

@SerializedName("Name")
public String name;

@SerializedName("Description")
public String desc;

@SerializedName("Date")
public String date;

I tried to put "Info." in front of each serializedName but that didn't work either. I also know my JSON parsing method works properly, because it's used somewhere else with a different DTO. But in that parsing, I don't have to "dotting" issue.

Can anyone help?

EDIT: I have tried everything you guys posted, and nothing works. The error says:

The JsonDeserializer failed to deserialize json object {"Info":[{".......

SECOND EDIT:
I was able to get rid of the error, but now it returns null. Haha, getting pretty damn frustrated right about now!

Body:
The Info object is a list because of the []. You have to use the following code to deserialze it:

EDIT:

public class Info {
    // as in your question
    public String name;
    ...
}
public class Data {
    @SerializedName("Info")
    public List<Info> info;
}

Then just use the data class to deserialize your json.


问:
What is the output format of datefield to us it in strptime?
I need to display three upcoming college fests in homepage, so I need to compare start_date of each fest with today's date and display it if it's equal or greater than today's date

The code I need this for is(here start_date is of type DateField)

```<code>def home(request):
    context={
        'fests':Fest.objects.all().filter(datetime.strptime('start_date',"%b %d ")>=date.today()).order_by('-start_date')[:3]
    }
    return render(request,'webpage/home.html',context)
</code>```

The output of start_date is in str form, so I can't compare it with date.today(). To use strptime() I need to input the format of the string. So what is the format needed?

答:
It has no format, it is simply a date object, so you filter with:

```<code>def home(request):
    context={
        'fests': Fest.objects.filter(<strong>start_date__gte=date.today()</strong>).order_by('-start_date')[:3]
    }
    return render(request,'webpage/home.html',context)</code>```

Body:
I need to display three upcoming college fests in homepage, so I need to compare start_date of each fest with today's date and display it if it's equal or greater than today's date

The code I need this for is(here start_date is of type DateField)

def home(request):
    context={
        'fests':Fest.objects.all().filter(datetime.strptime('start_date',"%b %d ")>=date.today()).order_by('-start_date')[:3]
    }
    return render(request,'webpage/home.html',context)

The output of start_date is in str form, so I can't compare it with date.today(). To use strptime() I need to input the format of the string. So what is the format needed?

Body:
It has no format, it is simply a date object, so you filter with:

def home(request):
    context={
        'fests': Fest.objects.filter(start_date__gte=date.today()).order_by('-start_date')[:3]
    }
    return render(request,'webpage/home.html',context)