问:
Is there a way use a wildcard operator(*) in the File.ReadAllLines method?
I am trying to do a multiple convert of multiple CSV file to XML, based on this tutorial from Microsoft:

```<code>// Create the text file.
string csvString = @"GREAL,Great Lakes Food Market,Howard Snyder,Marketing Manager,(503) 555-7555,2732 Baker Blvd.,Eugene,OR,97403,USA
HUNGC,Hungry Coyote Import Store,Yoshi Latimer,Sales Representative,(503) 555-6874,City Center Plaza 516 Main St.,Elgin,OR,97827,USA
LAZYK,Lazy K Kountry Store,John Steel,Marketing Manager,(509) 555-7969,12 Orchestra Terrace,Walla Walla,WA,99362,USA
LETSS,Let's Stop N Shop,Jaime Yorres,Owner,(415) 555-5938,87 Polk St. Suite 5,San Francisco,CA,94117,USA";
File.WriteAllText("cust.csv", csvString);

// Read into an array of strings.
string[] source = File.ReadAllLines("cust.csv");
XElement cust = new XElement("Root",
    from str in source
    let fields = str.Split(',')
    select new XElement("Customer",
        new XAttribute("CustomerID", fields[0]),
        new XElement("CompanyName", fields[1]),
        new XElement("ContactName", fields[2]),
        new XElement("ContactTitle", fields[3]),
        new XElement("Phone", fields[4]),
        new XElement("FullAddress",
            new XElement("Address", fields[5]),
            new XElement("City", fields[6]),
            new XElement("Region", fields[7]),
            new XElement("PostalCode", fields[8]),
            new XElement("Country", fields[9])
        )
    )
);
Console.WriteLine(cust);

</code>```

I was planning to use a foreach loop to loop through all the CSV files in the directory that needed to be converted, though I have come to a snag.

In the line:

```<code>string[] source = File.ReadAllLines("cust.csv");
</code>```

Would there be a way to replace cust.csv with like a wildcard operator(*.csv) so that it takes all the CSV files it runs such as:

```<code>string[] source = File.ReadAllLines("*.csv");
</code>```

I know the above does not work since ReadAllLines does not support the "*", but what would be the logic for this so that it loops through all CSV files, then applies the logic conversion to them?

答:
but what would be the logic for this so that it loops through all CSV files, then applies the logic conversion to them?

You'd first use Directory.GetFiles or Directory.EnumerateFiles to list the relevant files in the directory. Both of those do support wildcards.

Once you have the files you want to operate on, you can read each of those in turn.

Body:
I am trying to do a multiple convert of multiple CSV file to XML, based on this tutorial from Microsoft:

// Create the text file.
string csvString = @"GREAL,Great Lakes Food Market,Howard Snyder,Marketing Manager,(503) 555-7555,2732 Baker Blvd.,Eugene,OR,97403,USA
HUNGC,Hungry Coyote Import Store,Yoshi Latimer,Sales Representative,(503) 555-6874,City Center Plaza 516 Main St.,Elgin,OR,97827,USA
LAZYK,Lazy K Kountry Store,John Steel,Marketing Manager,(509) 555-7969,12 Orchestra Terrace,Walla Walla,WA,99362,USA
LETSS,Let's Stop N Shop,Jaime Yorres,Owner,(415) 555-5938,87 Polk St. Suite 5,San Francisco,CA,94117,USA";
File.WriteAllText("cust.csv", csvString);

// Read into an array of strings.
string[] source = File.ReadAllLines("cust.csv");
XElement cust = new XElement("Root",
    from str in source
    let fields = str.Split(',')
    select new XElement("Customer",
        new XAttribute("CustomerID", fields[0]),
        new XElement("CompanyName", fields[1]),
        new XElement("ContactName", fields[2]),
        new XElement("ContactTitle", fields[3]),
        new XElement("Phone", fields[4]),
        new XElement("FullAddress",
            new XElement("Address", fields[5]),
            new XElement("City", fields[6]),
            new XElement("Region", fields[7]),
            new XElement("PostalCode", fields[8]),
            new XElement("Country", fields[9])
        )
    )
);
Console.WriteLine(cust);

I was planning to use a foreach loop to loop through all the CSV files in the directory that needed to be converted, though I have come to a snag.

In the line:

string[] source = File.ReadAllLines("cust.csv");

Would there be a way to replace cust.csv with like a wildcard operator(*.csv) so that it takes all the CSV files it runs such as:

string[] source = File.ReadAllLines("*.csv");

I know the above does not work since ReadAllLines does not support the "*", but what would be the logic for this so that it loops through all CSV files, then applies the logic conversion to them?


来源: stackexchange

问:
Enumerate windows like alt-tab does
I'm creating an alt-tab replacement for Vista but I have some problems listing all active programs.

I'm using EnumWindows to get a list of Windows, but this list is huge. It contains about 400 items when I only have 10 windows open. It seems to be a hwnd for every single control and a lot of other stuff.

So I have to filter this list somehow, but I can't manage to do it exactly as alt-tab does.

This is the code I use to filter the list right now. It works pretty well, but I get some  unwanted windows like detached tool-windows in Visual Studio and I also miss windows like iTunes and Warcraft3.

```<code>private bool ShouldWindowBeDisplayed(IntPtr window)
{
    uint windowStyles = Win32.GetWindowLong(window, GWL.GWL_STYLE);

    if (((uint)WindowStyles.WS_VISIBLE & windowStyles) != (uint)WindowStyles.WS_VISIBLE ||
        ((uint)WindowExStyles.WS_EX_APPWINDOW & windowStyles) != (uint)WindowExStyles.WS_EX_APPWINDOW)
    {
        return true;
    }
    return false;
}
</code>```

答:
Good work vhanla.  My Pascal is a bit rusty, but your solution was a great help.  I'm new to this, so please excuse my code and/or way of expressing things.  The answer is relatively simple.

To make the list of Alt-Tab Windows, it appears you need three criteria

1) The Window must be visible - using GetWindowVisible

2) The Window must not be a Tool bar Window - using GetWindowInfo

3) The Window must not be cloaked - using DwmGetWindowAttribute

I don't believe that you need to look at class names.  I think the WS_EX_APPWINDOW flag often fails the test (e.g. Chrome) - even when used in conjunction with the WS_EX_TOOLWINDOW.  Also ... I don't think you need to look at the parent Window if you are enumerating Windows at the top level.

```<code>    public static bool IsAltTabWindow(IntPtr hWnd)
    {
        const uint WS_EX_TOOLWINDOW = 0x00000080;
        const uint DWMWA_CLOAKED = 14;

        //  It must be a visible Window
        if (!IsWindowVisible(hWnd)) return false;

        //  It must not be a Tool bar window
        WINDOWINFO winInfo = new WINDOWINFO(true);
        GetWindowInfo(hWnd, ref winInfo);
        if ((winInfo.dwExStyle & WS_EX_TOOLWINDOW) != 0) return false;

        //  It must not be a cloaked window
        uint CloakedVal;
        DwmGetWindowAttribute(hWnd, DWMWA_CLOAKED, out CloakedVal, sizeof(uint));
        return CloakedVal == 0;
    }
</code>```

OwnerDisplayName: taby

ContentLicense: CC BY-SA 2.5

Title: Enumerate windows like alt-tab does

Body:
I'm creating an alt-tab replacement for Vista but I have some problems listing all active programs.

I'm using EnumWindows to get a list of Windows, but this list is huge. It contains about 400 items when I only have 10 windows open. It seems to be a hwnd for every single control and a lot of other stuff.

So I have to filter this list somehow, but I can't manage to do it exactly as alt-tab does.

This is the code I use to filter the list right now. It works pretty well, but I get some  unwanted windows like detached tool-windows in Visual Studio and I also miss windows like iTunes and Warcraft3.

private bool ShouldWindowBeDisplayed(IntPtr window)
{
    uint windowStyles = Win32.GetWindowLong(window, GWL.GWL_STYLE);

    if (((uint)WindowStyles.WS_VISIBLE & windowStyles) != (uint)WindowStyles.WS_VISIBLE ||
        ((uint)WindowExStyles.WS_EX_APPWINDOW & windowStyles) != (uint)WindowExStyles.WS_EX_APPWINDOW)
    {
        return true;
    }
    return false;
}

Body:
Good work vhanla.  My Pascal is a bit rusty, but your solution was a great help.  I'm new to this, so please excuse my code and/or way of expressing things.  The answer is relatively simple.

To make the list of Alt-Tab Windows, it appears you need three criteria

1) The Window must be visible - using GetWindowVisible

2) The Window must not be a Tool bar Window - using GetWindowInfo

3) The Window must not be cloaked - using DwmGetWindowAttribute

I don't believe that you need to look at class names.  I think the WS_EX_APPWINDOW flag often fails the test (e.g. Chrome) - even when used in conjunction with the WS_EX_TOOLWINDOW.  Also ... I don't think you need to look at the parent Window if you are enumerating Windows at the top level.

    public static bool IsAltTabWindow(IntPtr hWnd)
    {
        const uint WS_EX_TOOLWINDOW = 0x00000080;
        const uint DWMWA_CLOAKED = 14;

        //  It must be a visible Window
        if (!IsWindowVisible(hWnd)) return false;

        //  It must not be a Tool bar window
        WINDOWINFO winInfo = new WINDOWINFO(true);
        GetWindowInfo(hWnd, ref winInfo);
        if ((winInfo.dwExStyle & WS_EX_TOOLWINDOW) != 0) return false;

        //  It must not be a cloaked window
        uint CloakedVal;
        DwmGetWindowAttribute(hWnd, DWMWA_CLOAKED, out CloakedVal, sizeof(uint));
        return CloakedVal == 0;
    }

ContentLicense: CC BY-SA 4.0


问:
Android application Toast.makeText -error
I have problem due to the fact that my Android Studio
flags between  word

context and this -; expected
text and "Messages" ; expected
before .show ; expected and unexpected token I suppose .show

That does not make sense as the code is working perfectly in the tutorial but it is made in 2018 I wonder what could be issue or what more important what is the solutions?
Thanks you for all the answers :)

```<code>private void UserMenuSelector(MenuItem item)
    {
        switch (item.getItemId())
        {
            Context context;
            Object text;
            case R.id.nav_profile:
                Toast.makeText(context this, text "Profile",Toast.LENGTH_SHORT.show();
                break;

            case R.id.nav_home:
                Toast.makeText(context this, text "Home",Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_friends:
                Toast.makeText(context this, text "Friend List", Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_find_friends:
                Toast.makeText(context this, text "Find Friends", Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_messages:
                Toast.makeText(context this, text "Messages", Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_settings:
                Toast.makeText(context this, text "Settings", Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_Logout:
                Toast.makeText(context this, text "Logout", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    private void show() {

    }
}
</code>```

答:
Instead of:

```<code>Toast.makeText(context this, text "Profile",Toast.LENGTH_SHORT.show();
</code>```

Remove context and text from the arguments of the toast.

```<code>Toast.makeText(this, "Profile", Toast.LENGTH_SHORT).show();
</code>```

Do this for all the toasts.

Body:
I have problem due to the fact that my Android Studio
flags between  word

context and this -; expected
text and "Messages" ; expected
before .show ; expected and unexpected token I suppose .show

That does not make sense as the code is working perfectly in the tutorial but it is made in 2018 I wonder what could be issue or what more important what is the solutions?
Thanks you for all the answers :)

private void UserMenuSelector(MenuItem item)
    {
        switch (item.getItemId())
        {
            Context context;
            Object text;
            case R.id.nav_profile:
                Toast.makeText(context this, text "Profile",Toast.LENGTH_SHORT.show();
                break;

            case R.id.nav_home:
                Toast.makeText(context this, text "Home",Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_friends:
                Toast.makeText(context this, text "Friend List", Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_find_friends:
                Toast.makeText(context this, text "Find Friends", Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_messages:
                Toast.makeText(context this, text "Messages", Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_settings:
                Toast.makeText(context this, text "Settings", Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_Logout:
                Toast.makeText(context this, text "Logout", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    private void show() {

    }
}

Body:
Instead of:

Toast.makeText(context this, text "Profile",Toast.LENGTH_SHORT.show();

Remove context and text from the arguments of the toast.

Toast.makeText(this, "Profile", Toast.LENGTH_SHORT).show();

Do this for all the toasts.


问:
In angular js application how to make other codes wait until some code are done?
In angular js application, if have to send a request to the database, and until response comes no other actions should be done, Now I am not able to do that

```<code>function checkStep() {
  if (currenctStep == 1 && checkBalance()) { // request database to check balance
    alert('balance is not enough');
  } else if (currentStep == 2) {
    goToNextStep();
  } else if (currentStep == 3) {
    validateAll();
  }
 // ... some actions should wait until above codes are executed,
 // here some codes that do some actions and should change current step after
 // checkBalance() respose comes
}
</code>```

What can I do in order to make all other codes wait until the response comes in checkBalance()

答:
checkBalance is a async call, ti should return a promise.

Something like:

```<code>function checkStep() {
  if (currenctStep == 1) { // request database to check balance

   checkBalance().then(function (response) {
       // parse response data
       if (currentStep == 2) {
         goToNextStep();
        } else if (currentStep == 3) {
        validateAll();
      }
   }, function (error) {
       // failed to call DB
   });
  }
 // ... some actions
}
</code>```

where checkBalance can be:

```<code>function checkBalance() {
     // some call DB here
    return $http({method: 'GET', url:URL}).then(function (result) {
       return result;
    }, function (error) {
         console.error(error);
          return $q.reject(error);
    });
  };
</code>```

Body:
In angular js application, if have to send a request to the database, and until response comes no other actions should be done, Now I am not able to do that

function checkStep() {
  if (currenctStep == 1 && checkBalance()) { // request database to check balance
    alert('balance is not enough');
  } else if (currentStep == 2) {
    goToNextStep();
  } else if (currentStep == 3) {
    validateAll();
  }
 // ... some actions should wait until above codes are executed,
 // here some codes that do some actions and should change current step after
 // checkBalance() respose comes
}

What can I do in order to make all other codes wait until the response comes in checkBalance()

Body:
checkBalance is a async call, ti should return a promise.

Something like:

function checkStep() {
  if (currenctStep == 1) { // request database to check balance

   checkBalance().then(function (response) {
       // parse response data
       if (currentStep == 2) {
         goToNextStep();
        } else if (currentStep == 3) {
        validateAll();
      }
   }, function (error) {
       // failed to call DB
   });
  }
 // ... some actions
}

where checkBalance can be:

function checkBalance() {
     // some call DB here
    return $http({method: 'GET', url:URL}).then(function (result) {
       return result;
    }, function (error) {
         console.error(error);
          return $q.reject(error);
    });
  };


问:
Youtube api v3 error "SSL is required to perform this operation"
Looking for some insight into how to get video information using youtube's v3 api.

When passing the url, the json response I get is:

```<code>{"error":{"errors":[{"domain":"global","reason":"sslRequired","message":"SSL is required to perform this operation."}],"code":403,"message":"SSL is required to perform this operation."}}
</code>```

All I'm trying to do is get basic information (title, description, etc) so I used "snippet" for the part.

Here's a sample url i'm using:

```<code>http://www.googleapis.com/youtube/v3/videos?id=Ho4XgLj40Ss&part=snippet
</code>```

I have tried creating an API Key and adding &key={my_api_key} to the end of that url.

If the environment matters, I'm using a jquery getJSON request in a custom Wordpress theme.

I should mention that in the "try it now" section in the documentation, it returns a nice json object - with the OAuth off.

答:
Adding to @Xavier's answer, if you are using this API in a Flutter environment, then you can change your

```<code>Uri.http(baseUrl, endPointUrl, parameters);
</code>```

to

```<code>Uri.https(baseUrl, endPointUrl, parameters);
</code>```

Notice the https above.

ContentLicense: CC BY-SA 3.0

Body:
Looking for some insight into how to get video information using youtube's v3 api.

When passing the url, the json response I get is:

{"error":{"errors":[{"domain":"global","reason":"sslRequired","message":"SSL is required to perform this operation."}],"code":403,"message":"SSL is required to perform this operation."}}

All I'm trying to do is get basic information (title, description, etc) so I used "snippet" for the part.

Here's a sample url i'm using:

http://www.googleapis.com/youtube/v3/videos?id=Ho4XgLj40Ss&part=snippet

I have tried creating an API Key and adding &key={my_api_key} to the end of that url.

If the environment matters, I'm using a jquery getJSON request in a custom Wordpress theme.

I should mention that in the "try it now" section in the documentation, it returns a nice json object - with the OAuth off.

Body:
Adding to @Xavier's answer, if you are using this API in a Flutter environment, then you can change your

Uri.http(baseUrl, endPointUrl, parameters);

to

Uri.https(baseUrl, endPointUrl, parameters);

Notice the https above.


问:
Bundler cant find gem installed on system
I'm having a problem with one of my gems and I need to test my code with a rails app, I usually do this by adding a symlink in vendor/plugins but I think what I want to do needs it to be required as a gem not a plugin.

I've used bundler in the gem so I can build it with rake build, or install it using rake install, I've done a rake install and I get a lovely green text message saying that my gem has been installed. So I swapped over to my Rails app and added gem 'gemname', '1.0.0pre' to my Gemfile (matching the version I just installed) and ran a bundle install and it just hangs and then throws up and error saying it cant find the gem in any of my sources.

I've already run through making sure that I was using the right rvm ruby when installing the gem etc... and I'm at a loss as to why this wont work. Bundler normally has no problems with gems I already have installed.

答:
Bundler only knows about gems from sources specified in the Gemfile.

Put your gem in vendor/gems and then specify the location in your Gemfile like this:

```<code>gem "yourgem", :path => "vendor/yourgem"
</code>```

Your gem must have a yourgem.gemspec or bundler still won't find it.

Alternatively, you can reference a git project.
e.g.

```<code>gem "rails", :git => "git://github.com/rails/rails.git"
</code>```

Then run bundle install.

Body:
Bundler only knows about gems from sources specified in the Gemfile.

Put your gem in vendor/gems and then specify the location in your Gemfile like this:

gem "yourgem", :path => "vendor/yourgem"

Your gem must have a yourgem.gemspec or bundler still won't find it.

Alternatively, you can reference a git project.
e.g.

gem "rails", :git => "git://github.com/rails/rails.git"

Then run bundle install.


问:
How to pass enum to values to a dropdown in template [Angular]
I've recently started with typescript. I've created a dropdown using select and option tags in the template.

```<code><select [(ngModel)]="primaryMode" (ngModelChange)="primaryModeChangeHandler($event)">
  <option *ngFor="let mode of modes" [value]="mode">{{mode}}</option>
</select>
</code>```

and in typescript I was having an array:

```<code>modes= ['Calendar Year', 'Year-to-date', 'Rolling Year', 'Custom'];
</code>```

But my tech lead said that I've to use enum instead of array. Here's my code now:

```<code>import { Component, OnInit, ... } from '@angular/core';

export enum presetRange {
    CalendarYear,
    YearToDate,
    RollingYear,
    CustomRange
}

@Component({
  selector: 'app-timeselector',
  templateUrl: './timeselector.component.html',
  styleUrls: ['./timeselector.component.css']
})
export class TimeselectorComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  primaryMode;

  primaryModeChangeHandler(event) {
    console.log(this.primaryMode);
  }
}
</code>```

But the problem is that I don't know how to bind dropdown to an enum. I tried few things but I failed. Here's the stackblitz. Please correct me where I'm wrong.

答:
String enums require a key and a value. And enums are used to create named constants, they don't produce a list. So you still need an array, but created from the values of the enum.

Controller

enum PresetRange {
  CalendarYear = 'Calendar Year',
  YearToDate = 'Year-to-date',
  RollingYear = 'Rolling Year',
  CustomRange = 'Custom'
}

@Component({
  selector: 'app-timeselector',
  templateUrl: './timeselector.component.html',
  styleUrls: ['./timeselector.component.css']
})
export class TimeselectorComponent implements OnInit {
  primaryMode: any;
  modesLabels = [                        // <-- you still need the array
    PresetRange.CalendarYear,
    PresetRange.YearToDate,
    PresetRange.RollingYear,
    PresetRange.CustomRange
  ];

  constructor() { }

  ngOnInit() {
  }

  primaryModeChangeHandler(event) {
    console.log(this.primaryMode);
  }
}
```

<p>Template</p>

<pre class="lang-html prettyprint-override"><code><select [(ngModel)]="primaryMode" (ngModelChange)="primaryModeChangeHandler($event)">
  <option *ngFor="let label of modesLabels" [value]="label">{{label}}</option>
</select>
</code>```

I've modified your Stackblitz

Body:
I've recently started with typescript. I've created a dropdown using select and option tags in the template.

<select [(ngModel)]="primaryMode" (ngModelChange)="primaryModeChangeHandler($event)">
  <option *ngFor="let mode of modes" [value]="mode">{{mode}}</option>
</select>

and in typescript I was having an array:

modes= ['Calendar Year', 'Year-to-date', 'Rolling Year', 'Custom'];

But my tech lead said that I've to use enum instead of array. Here's my code now:

import { Component, OnInit, ... } from '@angular/core';

export enum presetRange {
    CalendarYear,
    YearToDate,
    RollingYear,
    CustomRange
}

@Component({
  selector: 'app-timeselector',
  templateUrl: './timeselector.component.html',
  styleUrls: ['./timeselector.component.css']
})
export class TimeselectorComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  primaryMode;

  primaryModeChangeHandler(event) {
    console.log(this.primaryMode);
  }
}

But the problem is that I don't know how to bind dropdown to an enum. I tried few things but I failed. Here's the stackblitz. Please correct me where I'm wrong.

Body:
String enums require a key and a value. And enums are used to create named constants, they don't produce a list. So you still need an array, but created from the values of the enum.

Controller

enum PresetRange {
  CalendarYear = 'Calendar Year',
  YearToDate = 'Year-to-date',
  RollingYear = 'Rolling Year',
  CustomRange = 'Custom'
}

@Component({
  selector: 'app-timeselector',
  templateUrl: './timeselector.component.html',
  styleUrls: ['./timeselector.component.css']
})
export class TimeselectorComponent implements OnInit {
  primaryMode: any;
  modesLabels = [                        // <-- you still need the array
    PresetRange.CalendarYear,
    PresetRange.YearToDate,
    PresetRange.RollingYear,
    PresetRange.CustomRange
  ];

  constructor() { }

  ngOnInit() {
  }

  primaryModeChangeHandler(event) {
    console.log(this.primaryMode);
  }
}

Template

<select [(ngModel)]="primaryMode" (ngModelChange)="primaryModeChangeHandler($event)">
  <option *ngFor="let label of modesLabels" [value]="label">{{label}}</option>
</select>

I've modified your Stackblitz


问:
F# Downcasting arrays without reflection
I am working on a program where the user can send me all sort of objects at runtime, and I do not know their type in advance (at compile time). When the object can be down-cast to an (F#) array, of any element type, I would like to perform some usual operations on the underlying array. E.g. Array.Length,  Array.sub...

The objects I can get from the users will be of things like box [| 1; 2; 3 |] or box [| "a"; "b"; "c" |], or any 'a[], but I do not know 'a at compile time.

The following does not work :

```<code>let arrCount (oarr: obj) : int =
    match oarr with
    | :? array<_> as a -> a.Length
    | :? (obj[]) as a -> a.Length
 // | :? (int[]) as a -> a.Length     // not an option for me here
 // | :? (string[]) as a -> a.Length  // not an option for me here
 // | ...
    | _ -> failwith "Cannot recognize an array"
</code>```

E.g both arrCount (box [| 1; 2; 3 |]) and arrCount (box [| "a"; "b"; "c" |]) fail here.

The only solution I found so far is to use reflection, e.g. :

```<code>type ArrayOps =
     static member count<'a> (arr: 'a[]) : int = arr.Length
     static member sub<'a> (arr: 'a[]) start len : 'a[] = Array.sub arr start len
     // ...

let tryCount (oarr: obj) =
    let ty = oarr.GetType()
    if ty.HasElementType  && ty.BaseType = typeof<System.Array> then
        let ety = ty.GetElementType()
        let meth = typeof<ArrayOps>.GetMethod("count").MakeGenericMethod([| ety |])
        let count = meth.Invoke(null, [| oarr |]) :?> int
        Some count
    else
        None
</code>```

My question: is there a way to use functions such as Array.count, Array.sub, etc... on arguments of the form box [| some elements of some unknown type |] without using reflection?

答:
Curiously, this is a non-issue in languages like C# and VB, while you may have to do some extra work for F#. You can't do this in general, because F# doesn't have co-variant types.

Vote for that feature here!.

But we do have flexible types which give us rather limited contra-variance, which we can work with.

```<code>let anyLength (arr : #obj[]) =
    arr |> Array.length
</code>```

And,

```<code>let iarr = [| 1; 2; 3|]
let sarr = [|"a"; "b" |]

anyLength iarr // 3
anyLength sarr // 2
</code>```

Body:
I am working on a program where the user can send me all sort of objects at runtime, and I do not know their type in advance (at compile time). When the object can be down-cast to an (F#) array, of any element type, I would like to perform some usual operations on the underlying array. E.g. Array.Length,  Array.sub...

The objects I can get from the users will be of things like box [| 1; 2; 3 |] or box [| "a"; "b"; "c" |], or any 'a[], but I do not know 'a at compile time.

The following does not work :

let arrCount (oarr: obj) : int =
    match oarr with
    | :? array<_> as a -> a.Length
    | :? (obj[]) as a -> a.Length
 // | :? (int[]) as a -> a.Length     // not an option for me here
 // | :? (string[]) as a -> a.Length  // not an option for me here
 // | ...
    | _ -> failwith "Cannot recognize an array"

E.g both arrCount (box [| 1; 2; 3 |]) and arrCount (box [| "a"; "b"; "c" |]) fail here.

The only solution I found so far is to use reflection, e.g. :

type ArrayOps =
     static member count<'a> (arr: 'a[]) : int = arr.Length
     static member sub<'a> (arr: 'a[]) start len : 'a[] = Array.sub arr start len
     // ...

let tryCount (oarr: obj) =
    let ty = oarr.GetType()
    if ty.HasElementType  && ty.BaseType = typeof<System.Array> then
        let ety = ty.GetElementType()
        let meth = typeof<ArrayOps>.GetMethod("count").MakeGenericMethod([| ety |])
        let count = meth.Invoke(null, [| oarr |]) :?> int
        Some count
    else
        None

My question: is there a way to use functions such as Array.count, Array.sub, etc... on arguments of the form box [| some elements of some unknown type |] without using reflection?

Body:
Curiously, this is a non-issue in languages like C# and VB, while you may have to do some extra work for F#. You can't do this in general, because F# doesn't have co-variant types.

Vote for that feature here!.

But we do have flexible types which give us rather limited contra-variance, which we can work with.

let anyLength (arr : #obj[]) =
    arr |> Array.length

And,

let iarr = [| 1; 2; 3|]
let sarr = [|"a"; "b" |]

anyLength iarr // 3
anyLength sarr // 2


答:
```<code>private void UserMenuSelector(MenuItem item)
    {
        switch (item.getItemId())
        {
            Context context;
            Object text;
            case R.id.nav_profile:
                Toast.makeText(this, text "Profile",Toast.LENGTH_SHORT.show();
                break;

            case R.id.nav_home:
                Toast.makeText(this, text "Home",Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_friends:
                Toast.makeText(this, text "Friend List", Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_find_friends:
                Toast.makeText(this, text "Find Friends", Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_messages:
                Toast.makeText(this, text "Messages", Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_settings:
                Toast.makeText(this, text "Settings", Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_Logout:
                Toast.makeText(this, text "Logout", Toast.LENGTH_SHORT).show();
                break;
        }
</code>```

Title: Android application Toast.makeText -error


问:
What kind of encoding is this: \x3Cb\x3E\x3C?
I'm receiving data from an AJAX request, and it's really weird. I thought it was unicode, but unicode's codes are like \u00E7 (ç).

```<code>\x3Cb\x3E\x3C
</code>```

What do you think this is? And how can I convert it to normal text with Java?

答:
html entities it is. So you have html content embedded in your ajax hash.
what language you are using? there should be several encode/decode anyway. RoR has it for sure, in .NET is use the JSON.NET lib to decode.</p>

Body:
I'm receiving data from an AJAX request, and it's really weird. I thought it was unicode, but unicode's codes are like \u00E7 (ç).

\x3Cb\x3E\x3C

What do you think this is? And how can I convert it to normal text with Java?


问:
Rust doesn't accept input from stdin from native messaging - firefox
I am making a native messaging application, with the web API, from firefox. The extension is supposed to call an application that parses stdin and then calls my other rust app, based on some of the data it parsed, but for no apparent reason, the rust app doesn't accept input from firefox (it works when I do it manually).
This is the code of the extension:

/*
On a click on the browser action, send the app a message.
*/
browser.browserAction.onClicked.addListener(() => {
  console.log("Sending:  ping");
  var sending = browser.runtime.sendNativeMessage(
    "themefox_manager",
    "ping");
  sending.then(onResponse, onError);
});

function onResponse(response) {
  console.log("Received " + response);
}

function onError(error) {
  console.log(`Error: ${error}`);
}
```

<p>and this the code of the rust app:</p>

<pre class="lang-rust prettyprint-override"><code>use std::fs;
use std::io;
use std::io::prelude::*;

fn main() {
    let stdin = io::stdin();
    for line in stdin.lock().lines() {
        let mut file = fs::File::create("/home/user/filename.txt").unwrap();
        //
        if line.unwrap() == "ping" {
            file.write_all(b"TEST").expect("Error");
        }
    }
}

</code>```

The weird thing is, that the text file in my home dir first appears, when I close firefox, not when the app gets started. And it also doen't have the text TEST.

Thanks for any help!

Cheers

答:
I managed to make my own solution, taking a bit from this crate.

Quick note: "If you want to skip all of the code and immeditly want to start coding from a template repo, scoll to the bottom of this solution, and you should be able to find more info there."

The code, which reads the input, and then returns it, is the following:

pub fn read_input<R: Read>(mut input: R) -> io::Result<serde_json::Value> {
    let length = input.read_u32::<NativeEndian>().unwrap();
    let mut buffer = vec![0; length as usize];
    input.read_exact(&mut buffer)?;
    let json_val: serde_json::Value = serde_json::from_slice(&buffer).unwrap();
    Ok(json_val)
}
```

<p>What the code does, is read the input, which is being passed as a parameter to the function, and then it reads it parses it in a json var and returns the sucess/err value of it. </p>

<p>That code is being used in the main.rs file like this:</p>

<pre class="lang-rust prettyprint-override"><code>let json_val = match lib::read_input(io::stdin()) {
    Err(why) => panic!("{}", why.to_string()),
    Ok(json_val) => json_val,
};
</code>```

Here the input is being passed as a parameter to the read_input function.

And to send the code i used the following function:

```<code>pub fn write_output<W: Write>(mut output: W, value: &serde_json::Value) -> io::Result<()> {
    let msg = serde_json::to_string(value)?;
    let len = msg.len();
    // Chrome won't accept a message larger than 1MB
    if len > 1024 * 1024 {
        panic!("Message was too large", length: {}, len)
    }
    output.write_u32::<NativeEndian>(len as u32)?;
    output.write_all(msg.as_bytes())?;
    output.flush()?;
    Ok(())
}
</code>```

Which gets the stdout and the message passed as parameters. The function then writes the message to the output (normally stdout, could also be a file for debugging purposes).

The code which calls the function write_output is the following:

```<code>
    let response = serde_json::json!({ "msg": "pong" });
    match lib::write_output(io::stdout(), &response) {
        Err(why) => panic!("{}", why.to_string()),
        Ok(_) => (),
    };

</code>```

The project uses these dependencies, so make sure to add them to Cargo.toml

```<code>    "byteorder" = "*"
    "serde_json" = "*"
</code>```

The imports for the main.rs file are:

```<code>mod lib;
use std::io;
</code>```

and for the lib.rs file, in which both functions reside:

```<code>extern crate serde_json;
use byteorder::{NativeEndian, ReadBytesExt, WriteBytesExt};
use std::error::Error;
use std::fs;
use std::io;
use std::io::{Read, Write};
</code>```

I also created a git template repo, so that you can start really quick, you can find it here.

Body:
I am making a native messaging application, with the web API, from firefox. The extension is supposed to call an application that parses stdin and then calls my other rust app, based on some of the data it parsed, but for no apparent reason, the rust app doesn't accept input from firefox (it works when I do it manually).
This is the code of the extension:

/*
On a click on the browser action, send the app a message.
*/
browser.browserAction.onClicked.addListener(() => {
  console.log("Sending:  ping");
  var sending = browser.runtime.sendNativeMessage(
    "themefox_manager",
    "ping");
  sending.then(onResponse, onError);
});

function onResponse(response) {
  console.log("Received " + response);
}

function onError(error) {
  console.log(`Error: ${error}`);
}

and this the code of the rust app:

use std::fs;
use std::io;
use std::io::prelude::*;

fn main() {
    let stdin = io::stdin();
    for line in stdin.lock().lines() {
        let mut file = fs::File::create("/home/user/filename.txt").unwrap();
        //
        if line.unwrap() == "ping" {
            file.write_all(b"TEST").expect("Error");
        }
    }
}

The weird thing is, that the text file in my home dir first appears, when I close firefox, not when the app gets started. And it also doen't have the text TEST.

Thanks for any help!

Cheers

Body:
I managed to make my own solution, taking a bit from this crate.

Quick note: "If you want to skip all of the code and immeditly want to start coding from a template repo, scoll to the bottom of this solution, and you should be able to find more info there."

The code, which reads the input, and then returns it, is the following:

pub fn read_input<R: Read>(mut input: R) -> io::Result<serde_json::Value> {
    let length = input.read_u32::<NativeEndian>().unwrap();
    let mut buffer = vec![0; length as usize];
    input.read_exact(&mut buffer)?;
    let json_val: serde_json::Value = serde_json::from_slice(&buffer).unwrap();
    Ok(json_val)
}

What the code does, is read the input, which is being passed as a parameter to the function, and then it reads it parses it in a json var and returns the sucess/err value of it.

That code is being used in the main.rs file like this:

let json_val = match lib::read_input(io::stdin()) {
    Err(why) => panic!("{}", why.to_string()),
    Ok(json_val) => json_val,
};

Here the input is being passed as a parameter to the read_input function.

And to send the code i used the following function:

pub fn write_output<W: Write>(mut output: W, value: &serde_json::Value) -> io::Result<()> {
    let msg = serde_json::to_string(value)?;
    let len = msg.len();
    // Chrome won't accept a message larger than 1MB
    if len > 1024 * 1024 {
        panic!("Message was too large", length: {}, len)
    }
    output.write_u32::<NativeEndian>(len as u32)?;
    output.write_all(msg.as_bytes())?;
    output.flush()?;
    Ok(())
}

Which gets the stdout and the message passed as parameters. The function then writes the message to the output (normally stdout, could also be a file for debugging purposes).

The code which calls the function write_output is the following:

    let response = serde_json::json!({ "msg": "pong" });
    match lib::write_output(io::stdout(), &response) {
        Err(why) => panic!("{}", why.to_string()),
        Ok(_) => (),
    };

The project uses these dependencies, so make sure to add them to Cargo.toml

    "byteorder" = "*"
    "serde_json" = "*"

The imports for the main.rs file are:

mod lib;
use std::io;

and for the lib.rs file, in which both functions reside:

extern crate serde_json;
use byteorder::{NativeEndian, ReadBytesExt, WriteBytesExt};
use std::error::Error;
use std::fs;
use std::io;
use std::io::{Read, Write};

I also created a git template repo, so that you can start really quick, you can find it here.


答:
As mentioned you are passing string argument as text "Logout" which is wrong.

The argument passed to the makeText() is wrong. You shoud call the method as

```<code>Toast.makeText(this, "Profile", Toast.LENGTH_SHORT).show()
</code>```

Body:
As mentioned you are passing string argument as text "Logout" which is wrong.

The argument passed to the makeText() is wrong. You shoud call the method as

Toast.makeText(this, "Profile", Toast.LENGTH_SHORT).show()


问:
How to retrieve data from Database in Android SQLite?
I would like to query the data from "names" how can I do it?
I try but it seems that I only have to consult through the primary key, I am totally new in java and I am starting, I don't know what is the method to search through "nombres" (names in english)

```<code>public class AdminSQLiteOpenHelper extends SQLiteOpenHelper {
    public AdminSQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase BaseDeDatos) {
        BaseDeDatos.execSQL("CREATE TABLE personajes (codigo text primary key, nombres text, contraseña text)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}
</code>```

When I register with a number in "codigo" and then consult it returns the data correctly, but when I register with text example: "asdasd" the console returns: E / SQLiteLog: (1) no such column: asdasd

Query method:

```<code>    private EditText et_codigo, et_nombres, et_contraseña;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_agregarpersonaje);

et_codigo = (EditText)findViewById(R.id.txt_codigo);
et_nombres = (EditText)findViewById(R.id.txt_nombres);
et_contraseña = (EditText)findViewById(R.id.txt_contraseña);

}

    public void Buscar(View view){
    AdminSQLiteOpenHelper admin = new AdminSQLiteOpenHelper(this, "administracion", null, 1);
    SQLiteDatabase BaseDeDatabase = admin.getWritableDatabase();

    String codigo = et_codigo.getText().toString();

    if(!codigo.isEmpty()){
        Cursor fila = BaseDeDatabase.rawQuery
                ("select nombres, contraseña from personajes where codigo =" + codigo, null);

        if(fila.moveToFirst()){
            et_nombres.setText(fila.getString(0));
            et_contraseña.setText(fila.getString(1));
            BaseDeDatabase.close();
        } else {
            Toast.makeText(this,"No existe el artículo", Toast.LENGTH_SHORT).show();
            BaseDeDatabase.close();
        }

    } else {
        Toast.makeText(this, "Debes introducir el código del artículo", Toast.LENGTH_SHORT).show();
    }
}
</code>```

答:
You can use Room database. It provides an abstraction layer over SQLite, and it is easier to use.

https://developer.android.com/topic/libraries/architecture/room

Body:
I would like to query the data from "names" how can I do it?
I try but it seems that I only have to consult through the primary key, I am totally new in java and I am starting, I don't know what is the method to search through "nombres" (names in english)

public class AdminSQLiteOpenHelper extends SQLiteOpenHelper {
    public AdminSQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase BaseDeDatos) {
        BaseDeDatos.execSQL("CREATE TABLE personajes (codigo text primary key, nombres text, contraseña text)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}

When I register with a number in "codigo" and then consult it returns the data correctly, but when I register with text example: "asdasd" the console returns: E / SQLiteLog: (1) no such column: asdasd

Query method:

    private EditText et_codigo, et_nombres, et_contraseña;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_agregarpersonaje);

et_codigo = (EditText)findViewById(R.id.txt_codigo);
et_nombres = (EditText)findViewById(R.id.txt_nombres);
et_contraseña = (EditText)findViewById(R.id.txt_contraseña);

}

    public void Buscar(View view){
    AdminSQLiteOpenHelper admin = new AdminSQLiteOpenHelper(this, "administracion", null, 1);
    SQLiteDatabase BaseDeDatabase = admin.getWritableDatabase();

    String codigo = et_codigo.getText().toString();

    if(!codigo.isEmpty()){
        Cursor fila = BaseDeDatabase.rawQuery
                ("select nombres, contraseña from personajes where codigo =" + codigo, null);

        if(fila.moveToFirst()){
            et_nombres.setText(fila.getString(0));
            et_contraseña.setText(fila.getString(1));
            BaseDeDatabase.close();
        } else {
            Toast.makeText(this,"No existe el artículo", Toast.LENGTH_SHORT).show();
            BaseDeDatabase.close();
        }

    } else {
        Toast.makeText(this, "Debes introducir el código del artículo", Toast.LENGTH_SHORT).show();
    }
}


问:
Can an Activity access a Fragment to know if a button has been pressed?
The Objective: I'm trying to make a notepad application. What my app does is, a button is pressed to create a new note. This pops up a fragment in which the user types his note. Within the same fragment, I have another button that signifies when the user is done typing.

Question 1: Is there a way by which pressing the other button in the Fragment could trigger a method in my Activity?

Question 2: Would this cause the app to become too bloated? Should I keep the button within my activity itself?

Thank you for your help.

答:
Just make your activity implement View.OnClickListener and on your fragment set your activity as onClickListener of your button.

your fragment:

```<code>   @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        myButton.setOnclickListener((MyActivity)getActivity));
    }
</code>```

Body:
Just make your activity implement View.OnClickListener and on your fragment set your activity as onClickListener of your button.

your fragment:

   @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        myButton.setOnclickListener((MyActivity)getActivity));
    }


问:
Creating a Column Link in an Interactive Report -Oracle Apex
I am using Apex 20.1.0.00.13, trying to create link on a column of a Classic Report.

I have followed the step to create the link for a column and redirect it to a page in the same application as the steps below :

To create a link to another page, in the Link Builder - Target dialog:
  Type - Select Page in this Application.
  Page - Specify the target page number.
  Set Items - Select a Name and Value to specify session state for an item.
  Clear Session State, Clear Cache - Specify the page numbers on which to clear cache. To specify multiple page, enter a comma-delimited list of page numbers.
  Rest Pagination - Select Yes to reset pagination for this page.v
  Advanced, Request - Specify the request to be used.
  Click OK.

But when I am setting the item and values to specify session state for an item, the Set Items : Name doesn't populate the columns, it appears blank, Could someone let me know where I am going wrong.

I am trying to achieve a link from page 1 say a row with dept no - 2, to be directed to page 2 with details of dept 2 . Is there any other way to do it. Since its a column and not an item I am unable to pass it as a parameter to the next page.

Thanks in advance !

答:
Right; there are no "items" here, you have to create hyperlinks within the report.

Suppose that this is classic report's query:

```<code>with test (id, name) as
  (select 1, 'Google' from dual union all
   select 2, 'Yahoo'  from dual union all
   select 3, 'Bing'   from dual
  )
select
  id,
  '<a href="' || case
                  when name = 'Google' then 'https://www.google.com'
                  when name = 'Yahoo'  then 'https://www.yahoo.com'
                  when name = 'Bing'   then 'https://www.bing.com'
                end
              || '" target="_blank">' || name || '</a>' as link
from test
order by name;
</code>```

Go to LINK column's properties and set "Escape special characters" to "No". Run the report; everything should work OK.

If - as you say - use it to navigate to another page in your application and set some items to some values (from the IR), then you'd do something like this:

```<code>SELECT
  'f?p=&APP_ID.:217'            ||
  ':&APP_SESSION.::NO::P217_ID' ||
  ':' || r.id
  as link, ...
FROM my_table r ...
</code>```

In other words: it navigates to page 217 and passes r.id column value into P217_ID item which is located on page 217.

link column from such a query can be referenced when creating a link column. It would be a

link to custom target

target type = URL

URL = #link# (literally, type #link#)

Body:
Right; there are no "items" here, you have to create hyperlinks within the report.

Suppose that this is classic report's query:

with test (id, name) as
  (select 1, 'Google' from dual union all
   select 2, 'Yahoo'  from dual union all
   select 3, 'Bing'   from dual
  )
select
  id,
  '<a href="' || case
                  when name = 'Google' then 'https://www.google.com'
                  when name = 'Yahoo'  then 'https://www.yahoo.com'
                  when name = 'Bing'   then 'https://www.bing.com'
                end
              || '" target="_blank">' || name || '</a>' as link
from test
order by name;

Go to LINK column's properties and set "Escape special characters" to "No". Run the report; everything should work OK.

If - as you say - use it to navigate to another page in your application and set some items to some values (from the IR), then you'd do something like this:

SELECT
  'f?p=&APP_ID.:217'            ||
  ':&APP_SESSION.::NO::P217_ID' ||
  ':' || r.id
  as link, ...
FROM my_table r ...

In other words: it navigates to page 217 and passes r.id column value into P217_ID item which is located on page 217.

link column from such a query can be referenced when creating a link column. It would be a

link to custom target

target type = URL

URL = #link# (literally, type #link#)


问:
JS function that compare today date to array of birthdays
I'm trying to create a JS function that compares today's date to an array of birthdays and alert users if today is someone's birthday. Below is my code;</p>

```<code>const birthdays = [
  { name: "Bob Marley", birthmonth: "06", birthdate: "01" },
  { name: "Peter Pan", birthmonth: "08", birthdate: "04" },
];

const today = new Date();

if (
  today.getDate() === birthdays.birthdate &&
  today.getMonth() === birthdays.birthmonth
) {
  alert("Happy Birthday!" + birthdays.name);
} else {
  alert("Have a nice day!");
}
</code>```

答:
One reason it doesn't work as expected is that you store birthmonth as a string with a leading zero, while today.getMonth() outputs the month in numeric values ranged 0-11 where 0 is the first month.
Same goes for birthdate (only without the range).
A working example should be:

```<code>const birthdays = [
  { name: "Bob Marley", birthmonth: 5, birthdate: 1 },
  { name: "Peter Pan", birthmonth: 7, birthdate: 4 },
];
</code>```

Another reason is that birthdays is an array, and you don't treat it this way.

A possible fix using some:

```<code>if (birthdays.some(date =>
    today.getDate() === date.birthdate
    &&
    today.getMonth() === date.birthMonth
   )
</code>```

Body:
I'm trying to create a JS function that compares today's date to an array of birthdays and alert users if today is someone's birthday. Below is my code;

const birthdays = [
  { name: "Bob Marley", birthmonth: "06", birthdate: "01" },
  { name: "Peter Pan", birthmonth: "08", birthdate: "04" },
];

const today = new Date();

if (
  today.getDate() === birthdays.birthdate &&
  today.getMonth() === birthdays.birthmonth
) {
  alert("Happy Birthday!" + birthdays.name);
} else {
  alert("Have a nice day!");
}

Body:
One reason it doesn't work as expected is that you store birthmonth as a string with a leading zero, while today.getMonth() outputs the month in numeric values ranged 0-11 where 0 is the first month.
Same goes for birthdate (only without the range).
A working example should be:

const birthdays = [
  { name: "Bob Marley", birthmonth: 5, birthdate: 1 },
  { name: "Peter Pan", birthmonth: 7, birthdate: 4 },
];

Another reason is that birthdays is an array, and you don't treat it this way.

A possible fix using some:

if (birthdays.some(date =>
    today.getDate() === date.birthdate
    &&
    today.getMonth() === date.birthMonth
   )


问:
How to apply transformer plugin after Ingress serviceName is updated?
I have a kustomize transformer plugin that reads the value of serviceName in Ingress spec/rules/*/http/paths/0/backend/serviceName. The intent of the plugin is to update the host entries in the Ingress with the final serviceName after nameSuffix/namePrefix has been applied.

The plugins reads from stdin, but the state of the yaml isn't what I expected. The names of the Service and the Ingress have the nameSuffix/namePrefix applied, but the value of serviceName in the Ingress is still the raw service name. I verified this by dumping the Ingress yaml when the plugin executes. After the plugin runs, the final output does have the updated serviceName (with prefix/suffix). So something is running after the plugin that does the updating.

How do I configure the plugin so that it runs after the serviceName in the Ingress has been updated?

答:
According to this example: Transformer Configs

namePrefix and nameSuffix have reference only:

```<code> namePrefix:
- path: metadata/name
</code>```

If you want to include serviceName to the nameReference, you can create, for example, a kustomize-config.yml file with the content:

```<code>nameReference:
- kind: ServiceName
  fieldSpecs:
  - path: spec/rules/*/http/paths/0/backend/serviceName
    kind: Ingress
</code>```

Then, on your kustomization.yml you need to reference it:

```<code>configurations:
- kustomize-config.yml
</code>```

Next time you run kubectl kustomize . or kustomize build ., you may see both Prefix and Suffix reflect also to serviceName

Body:
According to this example: Transformer Configs

namePrefix and nameSuffix have reference only:

 namePrefix:
- path: metadata/name

If you want to include serviceName to the nameReference, you can create, for example, a kustomize-config.yml file with the content:

nameReference:
- kind: ServiceName
  fieldSpecs:
  - path: spec/rules/*/http/paths/0/backend/serviceName
    kind: Ingress

Then, on your kustomization.yml you need to reference it:

configurations:
- kustomize-config.yml

Next time you run kubectl kustomize . or kustomize build ., you may see both Prefix and Suffix reflect also to serviceName


问:
Bug in getBackgrounds() using custom theme colors
I've got a spreadsheet with colors from a custom theme.

When I read the colors using getBackgrounds() the colors returned are all #000000
If I read the colors cell-by-cell using getBackground() the colors are returned correctly.

If I use standard colors (ie not colors in my Theme) the colors are also returned correctly.

TEST SHEET
(available to view at https://docs.google.com/spreadsheets/d/1nCZeUbCjs_5p6_52v8ggqVgrgnJ-Pd6x-gzXUFfV8G0/edit?usp=sharing

Cells A1:D1 contain the names of the four Beatles, all with background color #b70906

TEST CODE

/** @OnlyCurrentDoc */

    function getbackgroundstwoways(){
    var  fullrange= SpreadsheetApp.getActiveSpreadsheet().getRange("A1:D1");

    // Read all cells using getBackgrounds
    var arBack = fullrange.getBackgrounds();
    var arValues=fullrange.getValues()

    Logger.log("Full array " +arBack + arValues);

    //Now do the cells individually with getBackground
    for (var i=0; i<fullrange.getLastRow();i++){
        for (var j=0; j<fullrange.getLastColumn();j++){

        Logger.log("Single cell " + i + " " + j + "  " + fullrange.offset(i,j).getBackground() + " " + fullrange.offset(i,j).getValue() ) ;

        }}}```
</div>
</div>
</p>

<p>LOGGER OUTPUT</p>

``` Full array #000000,#000000,#000000,#000000John,Paul,George,Ringo
 Single cell 0 0  #b70906 John
 Single cell 0 1  #b70906 Paul
 Single cell 0 2  #b70906 George
 Single cell 0 3  #b70906 Ringo
```

答:
How about this answer?

Issue and solution:

When I saw your shared Spreadsheet, the background colors of cells "A1:D1" has the color type of "THEME". I think that this is the reason of your issue.

In the current stage, it seems that getBackground() can directly retrieve the background color from the color type of "THEME" as the hex string. But, it seems that getBackgrounds() cannot directly retrieve them. The retrieved values using it becomes #000000. I'm not sure whether this is the bug or the current specification. But in the current stage, the background colors of the color type of "THEME" can be retrieved by the methods in Spreadsheet service.

One of several solution is to use getBackground() as your script. This has already been achieved in your script.

In this answer, as another pattern, the colors are retrieved from the values retrieved by getThemeColors. The flow of this script is as follows.

Create an object for searching the colors from the theme color type.

Retrieve background objects.

Retrieve the background colors from backgroundObjects.

Sample script:

```<code>function getbackgroundstwoways() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const fullrange = ss.getActiveSheet().getRange("A1:D1");  // Range from your script.

  // 1. Create an object for searching the colors from the theme color type.
  const theme = ss.getSpreadsheetTheme();
  const themeColorObj = theme.getThemeColors().reduce((o, e) => Object.assign(o, {[e]: theme.getConcreteColor(SpreadsheetApp.ThemeColorType[e]).asRgbColor().asHexString()}), {});
//  const fullrange = SpreadsheetApp.getActiveSpreadsheet().getDataRange();

  // 2. Retrieve background objects.
  const backgroundObjects = fullrange.getBackgroundObjects();

  // 3. Retrieve the background colors from backgroundObjects.
  const backgroundColors = backgroundObjects.map(r => {
    return r.map(c => {
      if (c.getColorType() == SpreadsheetApp.ColorType.RGB) {
        return c.asRgbColor().asHexString();
      } else if (c.getColorType() == SpreadsheetApp.ColorType.THEME) {
        return themeColorObj[c.asThemeColor().getThemeColorType()];
      } else {
        return null;
      }
    });
  });

  console.log(backgroundColors);
}
</code>```

This script can be used for the color types of both "RGB" and "THEME". When this script is run at your shared Spreadsheet, [ [ '#b70906', '#b70906', '#b70906', '#b70906' ] ] can be seen at the log.

Even when the RGB types and the THEME types are mixed, this script can retrieve the background colors as the hex string.

Note:

In this case, the background colors are retrieved from the theme colors. But when you overcoat the background colors as the RGB type of #b70906, you can retrieve them using getBackgrounds().

When I searched about this that getBackgrounds() cannot be used for the THEME color type at the issue tracker, I couldn't find this. So how about reporting this? Ref

Please use this script with V8.

References:

getSpreadsheetTheme()

This method is added at December 18, 2019.

Class SpreadsheetTheme

getBackgroundObjects()

Body:
I've got a spreadsheet with colors from a custom theme.

When I read the colors using getBackgrounds() the colors returned are all #000000
If I read the colors cell-by-cell using getBackground() the colors are returned correctly.

If I use standard colors (ie not colors in my Theme) the colors are also returned correctly.

TEST SHEET
(available to view at https://docs.google.com/spreadsheets/d/1nCZeUbCjs_5p6_52v8ggqVgrgnJ-Pd6x-gzXUFfV8G0/edit?usp=sharing

Cells A1:D1 contain the names of the four Beatles, all with background color #b70906

TEST CODE

/** @OnlyCurrentDoc */

    function getbackgroundstwoways(){
    var  fullrange= SpreadsheetApp.getActiveSpreadsheet().getRange("A1:D1");

    // Read all cells using getBackgrounds
    var arBack = fullrange.getBackgrounds();
    var arValues=fullrange.getValues()

    Logger.log("Full array " +arBack + arValues);

    //Now do the cells individually with getBackground
    for (var i=0; i<fullrange.getLastRow();i++){
        for (var j=0; j<fullrange.getLastColumn();j++){

        Logger.log("Single cell " + i + " " + j + "  " + fullrange.offset(i,j).getBackground() + " " + fullrange.offset(i,j).getValue() ) ;

        }}}

LOGGER OUTPUT

 Full array #000000,#000000,#000000,#000000John,Paul,George,Ringo
 Single cell 0 0  #b70906 John
 Single cell 0 1  #b70906 Paul
 Single cell 0 2  #b70906 George
 Single cell 0 3  #b70906 Ringo

Body:
How about this answer?

Issue and solution:

When I saw your shared Spreadsheet, the background colors of cells "A1:D1" has the color type of "THEME". I think that this is the reason of your issue.

In the current stage, it seems that getBackground() can directly retrieve the background color from the color type of "THEME" as the hex string. But, it seems that getBackgrounds() cannot directly retrieve them. The retrieved values using it becomes #000000. I'm not sure whether this is the bug or the current specification. But in the current stage, the background colors of the color type of "THEME" can be retrieved by the methods in Spreadsheet service.

One of several solution is to use getBackground() as your script. This has already been achieved in your script.

In this answer, as another pattern, the colors are retrieved from the values retrieved by getThemeColors. The flow of this script is as follows.

Create an object for searching the colors from the theme color type.

Retrieve background objects.

Retrieve the background colors from backgroundObjects.

Sample script:

function getbackgroundstwoways() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const fullrange = ss.getActiveSheet().getRange("A1:D1");  // Range from your script.

  // 1. Create an object for searching the colors from the theme color type.
  const theme = ss.getSpreadsheetTheme();
  const themeColorObj = theme.getThemeColors().reduce((o, e) => Object.assign(o, {[e]: theme.getConcreteColor(SpreadsheetApp.ThemeColorType[e]).asRgbColor().asHexString()}), {});
//  const fullrange = SpreadsheetApp.getActiveSpreadsheet().getDataRange();

  // 2. Retrieve background objects.
  const backgroundObjects = fullrange.getBackgroundObjects();

  // 3. Retrieve the background colors from backgroundObjects.
  const backgroundColors = backgroundObjects.map(r => {
    return r.map(c => {
      if (c.getColorType() == SpreadsheetApp.ColorType.RGB) {
        return c.asRgbColor().asHexString();
      } else if (c.getColorType() == SpreadsheetApp.ColorType.THEME) {
        return themeColorObj[c.asThemeColor().getThemeColorType()];
      } else {
        return null;
      }
    });
  });

  console.log(backgroundColors);
}

This script can be used for the color types of both "RGB" and "THEME". When this script is run at your shared Spreadsheet, [ [ '#b70906', '#b70906', '#b70906', '#b70906' ] ] can be seen at the log.

Even when the RGB types and the THEME types are mixed, this script can retrieve the background colors as the hex string.

Note:

In this case, the background colors are retrieved from the theme colors. But when you overcoat the background colors as the RGB type of #b70906, you can retrieve them using getBackgrounds().

When I searched about this that getBackgrounds() cannot be used for the THEME color type at the issue tracker, I couldn't find this. So how about reporting this? Ref

Please use this script with V8.

References:

getSpreadsheetTheme()

This method is added at December 18, 2019.

Class SpreadsheetTheme

getBackgroundObjects()


问:
static methods can not run in a non-static context
I'm trying to simulate a game of Yahtzee by using various methods to roll, compare, and sum up dice.

This is an assignment and I'm required to use these three static methods to do all of my work in.

When I try to run my code however I get this error

```<code>exit status 1
Main.java:6: error: non-static method rollDice(int[]) cannot be referenced from a static context
   rollDice(dice);
   ^
Main.java:7: error: non-static method rollDice(int[]) cannot be referenced from a static context
   dice= rollDice(dice);
         ^
2 errors
</code>```

I tried running the methods before assigning the values they return to variables but that didn't seem to work. Here is my complete code:

```<code>class Main {
  public static void main(String[] args) {
  // int array to hold 5 dice

   int dice[] = new int[5];
   rollDice(dice);
   dice= rollDice(dice);

   fiveOfaKind(dice);
   int points = fiveOfaKind(dice);

   getChance(dice,points);
   int printpoint = getChance(dice,points);
   // You may roll the dice up to 3 times to try to get 5 of a Kind
   // If you get 5 of a Kind, stop if not keep trying.
   // If you do not get 5 of a Kind after the 3rd roll, you must take the
   // CHANCE score.

   System.out.println("Your score is " + printpoint);

  }// end of main method

  public int[] rollDice(int dice[]){
    // generate 5 random numbers / update dice array
     for (int i = 0; i < dice.length; i++) {
      dice[i] = (int)(Math.random() * 6 + 1);
     }
    return dice;

  }// end of rollDice - rolls 5 dice and puts them in an array
   // All 5 dice must be rolled each time

  public static int fiveOfaKind(int dice[]){
     int pts = 0;
     int rNum=0;

    for(int i=0; rNum<3; rNum++){
    if(dice[0]==dice[1]&&dice[1]==dice[2]&&dice[2]==dice[3]&&dice[3]==dice[4]&&dice[4]==dice[5]&&dice[5]==dice[6]){
      pts=50;
    }
    else if(rNum==3){
      pts=0;
    }
    else{
      int[] rollDice;
    }

    }//end of forloop

    // use Array dice - evaluate if all elements are equal
    // if true = pts = 50
    // if false - pts = 0

    return pts;

  }// end of fiveOfaKind - evaluates the dice roll to see if all 5 are equal
   // Returns 50 points if they do

  public static int getChance(int dice[], int points){

    if(points<50){
       points=0;
      for (int i = 0; i < dice.length; i++) {
         points+=dice[i];
      }
    }
    // use Array dice - sum the elements of the Array
    // pys = calculated value of the sum

    int p = points;

    return p;

  }// end of getChance - adds the total value of the dice
    // Returns the total points calculated

}// end of  class
</code>```

答:
Static methods are generalised and the same for all of the objects and the class that is they are shared and for them it is not compulsory to make an object of that class just calling the function by using class is sufficient but on the other hand for non-static methods it is important to make the object of that class because they are associated with the objects and can only be called using the object of the class

So you require to make a function of the class Main and then use it to call the rollDice function

Eg:

     Main ob1=new Main();

```<code> ob1.rollDice(dice);
</code>```

Body:
I'm trying to simulate a game of Yahtzee by using various methods to roll, compare, and sum up dice.

This is an assignment and I'm required to use these three static methods to do all of my work in.

When I try to run my code however I get this error

exit status 1
Main.java:6: error: non-static method rollDice(int[]) cannot be referenced from a static context
   rollDice(dice);
   ^
Main.java:7: error: non-static method rollDice(int[]) cannot be referenced from a static context
   dice= rollDice(dice);
         ^
2 errors

I tried running the methods before assigning the values they return to variables but that didn't seem to work. Here is my complete code:

class Main {
  public static void main(String[] args) {
  // int array to hold 5 dice

   int dice[] = new int[5];
   rollDice(dice);
   dice= rollDice(dice);

   fiveOfaKind(dice);
   int points = fiveOfaKind(dice);

   getChance(dice,points);
   int printpoint = getChance(dice,points);
   // You may roll the dice up to 3 times to try to get 5 of a Kind
   // If you get 5 of a Kind, stop if not keep trying.
   // If you do not get 5 of a Kind after the 3rd roll, you must take the
   // CHANCE score.

   System.out.println("Your score is " + printpoint);

  }// end of main method

  public int[] rollDice(int dice[]){
    // generate 5 random numbers / update dice array
     for (int i = 0; i < dice.length; i++) {
      dice[i] = (int)(Math.random() * 6 + 1);
     }
    return dice;

  }// end of rollDice - rolls 5 dice and puts them in an array
   // All 5 dice must be rolled each time

  public static int fiveOfaKind(int dice[]){
     int pts = 0;
     int rNum=0;

    for(int i=0; rNum<3; rNum++){
    if(dice[0]==dice[1]&&dice[1]==dice[2]&&dice[2]==dice[3]&&dice[3]==dice[4]&&dice[4]==dice[5]&&dice[5]==dice[6]){
      pts=50;
    }
    else if(rNum==3){
      pts=0;
    }
    else{
      int[] rollDice;
    }

    }//end of forloop

    // use Array dice - evaluate if all elements are equal
    // if true = pts = 50
    // if false - pts = 0

    return pts;

  }// end of fiveOfaKind - evaluates the dice roll to see if all 5 are equal
   // Returns 50 points if they do

  public static int getChance(int dice[], int points){

    if(points<50){
       points=0;
      for (int i = 0; i < dice.length; i++) {
         points+=dice[i];
      }
    }
    // use Array dice - sum the elements of the Array
    // pys = calculated value of the sum

    int p = points;

    return p;

  }// end of getChance - adds the total value of the dice
    // Returns the total points calculated

}// end of  class

Body:
Static methods are generalised and the same for all of the objects and the class that is they are shared and for them it is not compulsory to make an object of that class just calling the function by using class is sufficient but on the other hand for non-static methods it is important to make the object of that class because they are associated with the objects and can only be called using the object of the class

So you require to make a function of the class Main and then use it to call the rollDice function

Eg:

     Main ob1=new Main();

 ob1.rollDice(dice);


问:
String manipulation, removing a single comma
UPDATE 1:

This is how I am attempting to build the string:

```<code>header('Content-type:application/json');

function getdata($the_query)
{
    $connection = mysql_connect('server', 'user', 'pass') or die (mysql_error());
    $db = mysql_select_db('db_name', $connection) or die (mysql_error());

    $results = mysql_query($the_query) or die(mysql_error());

    $the_data = "{
            \"rss\": {
                \"channels\" : [
                    {
                        \"title\" : \"".$title."\",
                        \"link\": \"http://www.mycompany.com/external.php\",
                        \"description\": \"company description goes here\",";

                        while($row = mysql_fetch_array($results))
                        {
                            extract($row);

                            $the_data .= "\"items\" : [
                                {
                                    \"title\": \"".$title."\",
                                    \"link\": \"".$link."\",
                                    \"guid\": \"".$link."\",
                                    \"pubDate\": \"".$date."\",
                                    \"description\": \"".$description."\"
                                } ],";
                        }

                    $the_data .= "} ]
                }
                 }";

    mysql_close($connection);

    return $the_data;
}
</code>```

ORIGINAL QUESTION:

I have a string similar to this:

```<code>$mystring = "{
      \"rss\": {
        \"channels\" : [
          {
            \"title" : \"title goes here\",
            \"link": \"link goes here\",
            \"description": \"description goes here\",
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
         } ]
      }
    }";
</code>```

How do I remove the last comma?

答:
You could do:</p>

```<code>$pos= strripos($mystring, ",");
$mystring[$pos]=" ";
</code>```

Body:
UPDATE 1:

This is how I am attempting to build the string:

header('Content-type:application/json');

function getdata($the_query)
{
    $connection = mysql_connect('server', 'user', 'pass') or die (mysql_error());
    $db = mysql_select_db('db_name', $connection) or die (mysql_error());

    $results = mysql_query($the_query) or die(mysql_error());

    $the_data = "{
            \"rss\": {
                \"channels\" : [
                    {
                        \"title\" : \"".$title."\",
                        \"link\": \"http://www.mycompany.com/external.php\",
                        \"description\": \"company description goes here\",";

                        while($row = mysql_fetch_array($results))
                        {
                            extract($row);

                            $the_data .= "\"items\" : [
                                {
                                    \"title\": \"".$title."\",
                                    \"link\": \"".$link."\",
                                    \"guid\": \"".$link."\",
                                    \"pubDate\": \"".$date."\",
                                    \"description\": \"".$description."\"
                                } ],";
                        }

                    $the_data .= "} ]
                }
                 }";

    mysql_close($connection);

    return $the_data;
}

ORIGINAL QUESTION:

I have a string similar to this:

$mystring = "{
      \"rss\": {
        \"channels\" : [
          {
            \"title" : \"title goes here\",
            \"link": \"link goes here\",
            \"description": \"description goes here\",
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
         } ]
      }
    }";

How do I remove the last comma?

Body:
You could do:

$pos= strripos($mystring, ",");
$mystring[$pos]=" ";


问:
Regex for Numbers Zeros TrimAll (Large Numbers)
I am looking for one (1) regex to remove all leading and trailing zeros from large decimal numbers (whole and fractional numbers) that may not work with parseFloat().

All posts on Stackoverflow searched and found to address different situations (leading zeros and trailing zeros, etc. for either a whole number only or a fractional number only) but not when a number could be entered both as an integer or a fraction.

Many of the regex I found on SO to trim trailing zeros assume the number is always a fraction and remove trailing zeros in whole numbers.

I have the following one-liner but still needs to have added to it the part that removes the trailing zeros from fractional numbers.

The tests below are self-explanatory.

I am looking for a single regex solution.

Please note that number Input is in String Form.

Thanks

function numberTrimAll(numString) {
// remove leading and trailing zeros from deciaml numbers
// Both whole and fractional numbers
//
// Need to include the following (or one replacement) regex the part that
// trims the trailing zeros in a fractional nummber.
//
  return numString.replace(/([\.]0+$)|^0+(?=\d)/g,"");
}

//--------- following passed ----------------------
test( 1,"00100"       ,"100"     )
test( 2,"00100.0"     ,"100"     )
test( 3,"0100.00"     ,"100"     )
test( 4,"00100100.00" ,"100100"  )
test( 5,"00100101.00" ,"100101"  )
test( 6,"0000.101"    ,"0.101"   )
test( 7,"0000.1001"   ,"0.1001"  )
test( 8,"120000"      ,"120000"  )
test( 9,"00120000"    ,"120000"  )
test(10,"00000001288765433.123456789123567" ,"1288765433.123456789123567")
test(11,"0000001.123456789123567" ,"1.123456789123567")

// ------------ following failed -------------
test(12,"0000.10"     ,"0.1"     )
test(13,"0000.100"    ,"0.1"     )
test(14,"0000.123100" ,"0.1231"  )
test(16,"0500.123100" ,"500.1231")
test(14,"0500.002100" ,"500.0021")

//============ test function ==================
function test(test,input,should){
var  out=numberTrimAll(input),r=out===should?true:false;
if (!r) console.log("Test "+test+" Failed: "+out+" should be ==> "+should);
else console.log("Passed");}```

Body:
Here's an alternate approach which rather than attempting to strip leading and trailing zeros, captures the non-zero parts in the middle instead.

function numberTrimAll(numString) {
// remove leading and trailing zeros from deciaml numbers
// Both whole and fractional numbers
//
// Need to include the following (or one replacement) regex the part that
// trims the trailing zeros in a fractional nummber.
//
  return numString.replace(/^0*(\d+|\d+\.\d+?)\.?0*$/,"$1");
}

//--------- following passed ----------------------
test( 1,"00100"       ,"100"     )
test( 2,"00100.0"     ,"100"     )
test( 3,"0100.00"     ,"100"     )
test( 4,"00100100.00" ,"100100"  )
test( 5,"00100101.00" ,"100101"  )
test( 6,"0000.101"    ,"0.101"   )
test( 7,"0000.1001"   ,"0.1001"  )
test( 8,"120000"      ,"120000"  )
test( 9,"00120000"    ,"120000"  )
test(10,"00000001288765433.123456789123567" ,"1288765433.123456789123567")
test(11,"0000001.123456789123567" ,"1.123456789123567")

// ------------ following failed -------------
test(12,"0000.10"     ,"0.1"     )
test(13,"0000.100"    ,"0.1"     )
test(14,"0000.123100" ,"0.1231"  )
test(16,"0500.123100" ,"500.1231")
test(14,"0500.002100" ,"500.0021")

//============ test function ==================
function test(test,input,should){
var  out=numberTrimAll(input),r=out===should?true:false;
if (!r) console.log("Test "+test+" Failed: "+out+" should be ==> "+should);
else console.log("Passed");}


问:
Adding vertical line in each time series subplot in multiple time series
I have multiple time series. Each with common time stamp. I have plotting subplot for each time series. Now I want to add vertical line in each subplot. I have tried for loop. But it does not work. </p>

```<code>url_jobs="https://assets.datacamp.com/production/repositories/1259/datasets/1c6b4a977a3c14f2a00c2d74694b208d9ac86443/ch5_employment.csv"
jobs=pd.read_csv(url_jobs)
jobs['datestamp']=pd.to_datetime(jobs['datestamp'])
jobs=jobs.set_index('datestamp')
plot2=jobs.plot(subplots=True,layout=(4,4),figsize=(20,16),sharex=True,sharey=False)
for each in plot2:
    each.axvline('2008-09-01',color='red',linestyle='--')
plt.show()
</code>```

答:
Since you have a 4 x 4 layout DataFrame.plot will return a 4 x 4 numpy array. You can call flatten on it in order to turn it into a 1D array:

```<code>url_jobs="https://assets.datacamp.com/production/repositories/1259/datasets/1c6b4a977a3c14f2a00c2d74694b208d9ac86443/ch5_employment.csv"
jobs=pd.read_csv(url_jobs)
jobs['datestamp']=pd.to_datetime(jobs['datestamp'])
jobs=jobs.set_index('datestamp')
plot2=jobs.plot(subplots=True,layout=(4,4),figsize=(20,16),sharex=True,sharey=False)
for each in plot2.flatten():
    each.axvline('2008-09-01',color='red',linestyle='--')
plt.show()
</code>```

Body:
I have multiple time series. Each with common time stamp. I have plotting subplot for each time series. Now I want to add vertical line in each subplot. I have tried for loop. But it does not work.

url_jobs="https://assets.datacamp.com/production/repositories/1259/datasets/1c6b4a977a3c14f2a00c2d74694b208d9ac86443/ch5_employment.csv"
jobs=pd.read_csv(url_jobs)
jobs['datestamp']=pd.to_datetime(jobs['datestamp'])
jobs=jobs.set_index('datestamp')
plot2=jobs.plot(subplots=True,layout=(4,4),figsize=(20,16),sharex=True,sharey=False)
for each in plot2:
    each.axvline('2008-09-01',color='red',linestyle='--')
plt.show()

Body:
Since you have a 4 x 4 layout DataFrame.plot will return a 4 x 4 numpy array. You can call flatten on it in order to turn it into a 1D array:

url_jobs="https://assets.datacamp.com/production/repositories/1259/datasets/1c6b4a977a3c14f2a00c2d74694b208d9ac86443/ch5_employment.csv"
jobs=pd.read_csv(url_jobs)
jobs['datestamp']=pd.to_datetime(jobs['datestamp'])
jobs=jobs.set_index('datestamp')
plot2=jobs.plot(subplots=True,layout=(4,4),figsize=(20,16),sharex=True,sharey=False)
for each in plot2.flatten():
    each.axvline('2008-09-01',color='red',linestyle='--')
plt.show()


Title: Regex for Numbers Zeros TrimAll (Large Numbers)

Body:
I am looking for one (1) regex to remove all leading and trailing zeros from large decimal numbers (whole and fractional numbers) that may not work with parseFloat().

All posts on Stackoverflow searched and found to address different situations (leading zeros and trailing zeros, etc. for either a whole number only or a fractional number only) but not when a number could be entered both as an integer or a fraction.

Many of the regex I found on SO to trim trailing zeros assume the number is always a fraction and remove trailing zeros in whole numbers.

I have the following one-liner but still needs to have added to it the part that removes the trailing zeros from fractional numbers.

The tests below are self-explanatory.

I am looking for a single regex solution.

Please note that number Input is in String Form.

Thanks

function numberTrimAll(numString) {
// remove leading and trailing zeros from deciaml numbers
// Both whole and fractional numbers
//
// Need to include the following (or one replacement) regex the part that
// trims the trailing zeros in a fractional nummber.
//
  return numString.replace(/([\.]0+$)|^0+(?=\d)/g,"");
}

//--------- following passed ----------------------
test( 1,"00100"       ,"100"     )
test( 2,"00100.0"     ,"100"     )
test( 3,"0100.00"     ,"100"     )
test( 4,"00100100.00" ,"100100"  )
test( 5,"00100101.00" ,"100101"  )
test( 6,"0000.101"    ,"0.101"   )
test( 7,"0000.1001"   ,"0.1001"  )
test( 8,"120000"      ,"120000"  )
test( 9,"00120000"    ,"120000"  )
test(10,"00000001288765433.123456789123567" ,"1288765433.123456789123567")
test(11,"0000001.123456789123567" ,"1.123456789123567")

// ------------ following failed -------------
test(12,"0000.10"     ,"0.1"     )
test(13,"0000.100"    ,"0.1"     )
test(14,"0000.123100" ,"0.1231"  )
test(16,"0500.123100" ,"500.1231")
test(14,"0500.002100" ,"500.0021")

//============ test function ==================
function test(test,input,should){
var  out=numberTrimAll(input),r=out===should?true:false;
if (!r) console.log("Test "+test+" Failed: "+out+" should be ==> "+should);
else console.log("Passed");}

Body:
I'd honestly use BigNumber or big.js and call it a day.

But here's a regex using positive lookbehind as another match option.

Note: lookbehind not supported in Safari and some other browsers

function numberTrimAll(numString) {
// remove leading and trailing zeros from deciaml numbers
// Both whole and fractional numbers
//
// Need to include the following (or one replacement) regex the part that
// trims the trailing zeros in a fractional nummber.
//
  return numString.replace(/([\.]0+$)|((?<=[\.][0-9]*?)0+$)|^0+(?=\d)/g,"");
}

//--------- following passed ----------------------
test( 1,"00100"       ,"100"     )
test( 2,"00100.0"     ,"100"     )
test( 3,"0100.00"     ,"100"     )
test( 4,"00100100.00" ,"100100"  )
test( 5,"00100101.00" ,"100101"  )
test( 6,"0000.101"    ,"0.101"   )
test( 7,"0000.1001"   ,"0.1001"  )
test( 8,"120000"      ,"120000"  )
test( 9,"00120000"    ,"120000"  )
test(10,"00000001288765433.123456789123567" ,"1288765433.123456789123567")
test(11,"0000001.123456789123567" ,"1.123456789123567")

// ------------ following failed -------------
test(12,"0000.10"     ,"0.1"     )
test(13,"0000.100"    ,"0.1"     )
test(14,"0000.123100" ,"0.1231"  )
test(16,"0500.123100" ,"500.1231")
test(14,"0500.002100" ,"500.0021")

//============ test function ==================
function test(test,input,should){
var  out=numberTrimAll(input),r=out===should?true:false;
if (!r) console.log("Test "+test+" Failed: "+out+" should be ==> "+should);
else console.log("Passed");}


问:
Perl stash output
I am trying to run a code snippet from the Advanced Perl Programming book for dumping the stash. This is without any additional packages from CPAN.

The package containing the stash related instructions is as follows:

```<code>package DUMPVAR;

sub dumpvar {
    my ($packageName) = @_;

    local (*alias);
    *stash = *{"${packageName}::"};

    $, = " ";

    while (($varName, $globValue) = each %stash) {

        print "\n $varName ===========================================\n";
        *alias = $globValue;

        if (defined ($alias)) {
            print "\t \$$varName $alias \n";
        }
        if (@alias) {
            print "\t \@$varName @alias \n";
        }
        if (keys %alias) {
            print "\t \%$varName " , %alias, " \n";
        }
    };
};
1;
</code>```

The calling code is

```<code>#!/usr/bin/perl
use strict;
use warnings;

use DUMPVAR;

package MyData;

my $x = 10;
my @y = (1,2,3);
my %z = (1,2,3,4,5,6);
my $z = 300;

DUMPVAR::dumpvar('MyData');
</code>```

I get no output what so ever. what is the problem?

答:
Lexical Variables defined with my are not stored in the package.

You have to either declare them with "our" (instead of my), or don't declare them at all and add

```<code>use vars qw($x @y %z $z);
</code>```

to add them to the package.

Title: Perl stash output

Body:
I am trying to run a code snippet from the Advanced Perl Programming book for dumping the stash. This is without any additional packages from CPAN.

The package containing the stash related instructions is as follows:

package DUMPVAR;

sub dumpvar {
    my ($packageName) = @_;

    local (*alias);
    *stash = *{"${packageName}::"};

    $, = " ";

    while (($varName, $globValue) = each %stash) {

        print "\n $varName ===========================================\n";
        *alias = $globValue;

        if (defined ($alias)) {
            print "\t \$$varName $alias \n";
        }
        if (@alias) {
            print "\t \@$varName @alias \n";
        }
        if (keys %alias) {
            print "\t \%$varName " , %alias, " \n";
        }
    };
};
1;

The calling code is

#!/usr/bin/perl
use strict;
use warnings;

use DUMPVAR;

package MyData;

my $x = 10;
my @y = (1,2,3);
my %z = (1,2,3,4,5,6);
my $z = 300;

DUMPVAR::dumpvar('MyData');

I get no output what so ever. what is the problem?

Body:
Lexical Variables defined with my are not stored in the package.

You have to either declare them with "our" (instead of my), or don't declare them at all and add

use vars qw($x @y %z $z);

to add them to the package.


问:
Change the height of option tag from select
I have the next component:

 <Select
        mode="multiple"
        placeholder="Inserted are removed"
        value={selectedItems}
        onChange={this.handleChange}
        style={{ width: "100%" }}
      >
        {filteredOptions.map(item => (
          <Select.Option key={item} value={item}>
            {item}
          </Select.Option>
        ))}
 </Select>```
</div>
</div>

In my <strong>demo</strong>: https://codesandbox.io/s/hide-already-selected-ant-design-demo-39xfe?file=/index.js:542-889, i added some styles:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.ant-select-item-option-content {
  background-color: red;
}
.ant-select-item-option-active:not(.ant-select-item-option-disabled) {
  height: 10px;
  background-color: blue;
  height: auto;
}</code>```

Why  height:10px; does not work? And how to apply 10px of heigth for that selector?

答:
You should remove height:auto:

```<code>.ant-select-item-option-content {
  background-color: red;
  height: 5px;
}
.ant-select-item-option-active:not(.ant-select-item-option-disabled) {
  height: 10px;
  background-color: blue;
}
</code>```

Or perhaps you need something like this:

```<code>.ant-select-item-option-content {
  background-color: red;
}
.ant-select-item-option-active:not(.ant-select-item-option-disabled) {
  height: 10px;
  background-color: blue;
  height: auto;
}

.ant-select-item-option-active:not(.ant-select-item-option-disabled) .ant-select-item-option-content {
  background-color: blue;
}
</code>```

Body:
I have the next component:

 <Select
        mode="multiple"
        placeholder="Inserted are removed"
        value={selectedItems}
        onChange={this.handleChange}
        style={{ width: "100%" }}
      >
        {filteredOptions.map(item => (
          <Select.Option key={item} value={item}>
            {item}
          </Select.Option>
        ))}
 </Select>

In my demo: https://codesandbox.io/s/hide-already-selected-ant-design-demo-39xfe?file=/index.js:542-889, i added some styles:

.ant-select-item-option-content {
  background-color: red;
}
.ant-select-item-option-active:not(.ant-select-item-option-disabled) {
  height: 10px;
  background-color: blue;
  height: auto;
}

Why  height:10px; does not work? And how to apply 10px of heigth for that selector?

Body:
You should remove height:auto:

.ant-select-item-option-content {
  background-color: red;
  height: 5px;
}
.ant-select-item-option-active:not(.ant-select-item-option-disabled) {
  height: 10px;
  background-color: blue;
}

Or perhaps you need something like this:

.ant-select-item-option-content {
  background-color: red;
}
.ant-select-item-option-active:not(.ant-select-item-option-disabled) {
  height: 10px;
  background-color: blue;
  height: auto;
}

.ant-select-item-option-active:not(.ant-select-item-option-disabled) .ant-select-item-option-content {
  background-color: blue;
}


问:
Applying NSMutableAttributedString to a range of text
I have some text:

New Content - Published Today | 10 min read

I'd like to apply styles to everything after and including the pipe, so | 10 min read

I have tried the below but it has only styles the pipe itself.

  func makeAttributedText(using baseString: String?) -> NSMutableAttributedString? {
    guard let baseString = baseString else { return nil }
    let attributedString = NSMutableAttributedString(string: baseString, attributes: nil)
    let timeToReadRange = (attributedString.string as NSString).range(of: "|")
    attributedString.setAttributes([NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 18)], range: timeToReadRange)
    return attributedString
  }
```

答:
Rather than getting the range of a single character get the index of the character and create a range from that index to the end of the string.

```<code>func makeAttributedText(using baseString: String?) -> NSMutableAttributedString? {
    guard let baseString = baseString else { return nil }
    let attributedString = NSMutableAttributedString(string: baseString, attributes: nil)
    guard let timeToReadIndex = baseString.firstIndex(of: "|") else { return attributedString }
    let timeToReadRange = NSRange(timeToReadIndex..., in: baseString)
    attributedString.setAttributes([NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 18)], range: timeToReadRange)
    return attributedString
}
</code>```

Note:

Swift has dedicated methods to convert Range<String.Index> to NSRange. There's no reason for the bridge cast to NSString

Body:
Rather than getting the range of a single character get the index of the character and create a range from that index to the end of the string.

func makeAttributedText(using baseString: String?) -> NSMutableAttributedString? {
    guard let baseString = baseString else { return nil }
    let attributedString = NSMutableAttributedString(string: baseString, attributes: nil)
    guard let timeToReadIndex = baseString.firstIndex(of: "|") else { return attributedString }
    let timeToReadRange = NSRange(timeToReadIndex..., in: baseString)
    attributedString.setAttributes([NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 18)], range: timeToReadRange)
    return attributedString
}

Note:

Swift has dedicated methods to convert Range<String.Index> to NSRange. There's no reason for the bridge cast to NSString


问:
How to create a boolean value?
I am totally new to XSLT and can't work out where I am going wrong with the following code.

```<code><xsl:variable name="var" select="boolean('false')"/>

<xsl:if test="$var'">variable is true</xsl:if>
</code>```

It is always returning true when it is meant to be false. Why?

答:
A bit late at this stage perhaps but imo dealing with booleans is just not worth the effort. Heres how I dealt with a boolean (Mandatory) coming back from the DB:

```<code><xsl:variable name="vTrue" select="true()"/>
    <xsl:choose>
      <xsl:when test="string(Mandatory) = string($vTrue)">
        <xsl:text>Mandatory</xsl:text>
      </xsl:when>
      <xsl:otherwise>
      </xsl:otherwise>
    </xsl:choose>
</code>```

Hope this helps someone

Title: How to create a boolean value?

Body:
I am totally new to XSLT and can't work out where I am going wrong with the following code.

<xsl:variable name="var" select="boolean('false')"/>

<xsl:if test="$var'">variable is true</xsl:if>

It is always returning true when it is meant to be false. Why?

LastEditorDisplayName: Tomalak

Body:
A bit late at this stage perhaps but imo dealing with booleans is just not worth the effort. Heres how I dealt with a boolean (Mandatory) coming back from the DB:

<xsl:variable name="vTrue" select="true()"/>
    <xsl:choose>
      <xsl:when test="string(Mandatory) = string($vTrue)">
        <xsl:text>Mandatory</xsl:text>
      </xsl:when>
      <xsl:otherwise>
      </xsl:otherwise>
    </xsl:choose>

Hope this helps someone


问:
Build suite: "configure: error: cannot run /bin/sh tool/config.sub"
I try to compile the Ruby interpreter inside a virgin virtual box. I installed FreeBSD, pulled Ruby from Github and followed the instructions in README.md. The ./configure step gives me the message:

```<code>% ./configure
checking for ruby... false
configure: error: cannot run /bin/sh tool/config.sub
</code>```

I found by Google that this problem surfaces again and again over several years, but the old solutions
don't help me. For example, an autoreconf --install didn't solve the issue.

The file tool/config.sub doesn't exist.

What can I do next?

Thanks in advance, Bertram

答:
Solution:

To build Ruby from the Git repo there must be already an installed version of Ruby.

This does not apply to the .tar.gz archives you can download from the Ruby site.

Body:
I try to compile the Ruby interpreter inside a virgin virtual box. I installed FreeBSD, pulled Ruby from Github and followed the instructions in README.md. The ./configure step gives me the message:

% ./configure
checking for ruby... false
configure: error: cannot run /bin/sh tool/config.sub

I found by Google that this problem surfaces again and again over several years, but the old solutions
don't help me. For example, an autoreconf --install didn't solve the issue.

The file tool/config.sub doesn't exist.

What can I do next?

Thanks in advance, Bertram


问:
Will it be called augmented reality if I render a reality-based 3D model instead of render a camera view?
I've developed an application, and now I wonder if my work can be regarded as augmented reality:

Instead of overlap something on a camera preview, I build and render 3D buildings on a mobile phone. These models are the same (or similar to) some real buildings. I use GPS and gyros to decide the player's position and heading, so that I can render an animation with specified orientation so that the image will "look like" an image captured by the phone camera.

Then I can perform some games related to the real world. For example, I can make 3D models for restored Athenian ruins. When you go Athens and point your phone to the ruins, you'll see its original state on the screen. An early demo video: http://youtu.be/YIX3oZi1O_o

Can I define my application as a kind of augmented reality game, according to general meanings of augmented reality? If not, is there any proper term that can describe my work?

答:
I don't think so, the general definition of Augmented Reality is "Taking real time real world input, and adding a layer on top of this to augment (change) this reality". With real time world input usually a camera is meant.

Your idea sounds more like a simulation, since you simulate everything, the only input you receive from the real world is position.

Of course broadly speaking you might still consider your application to be AR, but I wouldn't put it on the box art.