问:
JSON extractorion issue
I have a JSON like below and I want to extract ID using a username by json extractor expression.
I am using $..username , it give me all the username. what I need is that I pass username = Albert and it give me id = 1234

is that doable ?

```<code>  {         "data": [
       {
            "country": 111,
            "role": {
                "name": "Admin",
                "id": 1
            },
            "last_name": "mir",
            "id": 1234,
            "first_name": "Albert",
            "username": "Albert.mir",
        },
               {
            "country": 112,
            "role": {
                "name": "Admin",
                "id": 1
            },
            "last_name": "marr",
            "id": 12345,
            "first_name": "Albbert",
            "username": "Albbert.mir",
        }

        ]
        }
</code>```

答:
.. is recursive descent in JsonPath

? is filter

@ current object

Thus,

```<code> $..[?(@.username='Albert')].id
</code>```

Note that JSON that you provides is invalid, and have no username Albert in it (only Albert.mir)
Read a good intro into JsonPATH, it is not that difficult to master https://goessner.net/articles/JsonPath/

Title: JSON extractorion issue

Body:
I have a JSON like below and I want to extract ID using a username by json extractor expression.
I am using $..username , it give me all the username. what I need is that I pass username = Albert and it give me id = 1234

is that doable ?

  {         "data": [
       {
            "country": 111,
            "role": {
                "name": "Admin",
                "id": 1
            },
            "last_name": "mir",
            "id": 1234,
            "first_name": "Albert",
            "username": "Albert.mir",
        },
               {
            "country": 112,
            "role": {
                "name": "Admin",
                "id": 1
            },
            "last_name": "marr",
            "id": 12345,
            "first_name": "Albbert",
            "username": "Albbert.mir",
        }

        ]
        }

Body:
.. is recursive descent in JsonPath

? is filter

@ current object

Thus,

 $..[?(@.username='Albert')].id

Note that JSON that you provides is invalid, and have no username Albert in it (only Albert.mir)
Read a good intro into JsonPATH, it is not that difficult to master https://goessner.net/articles/JsonPath/


来源: stackexchange

问:
Why does DocFX serve content over an internal server?
I've just started studying DocFX. According to its official guide we build content with a command similar to docfx docfx.json --serve and then view the generated site from http://localhost:8080. My question is: if DocFX is a static site generator, why does it serve content via a web server? Why does it not just say click index.html to view the generated site ? Is there a difference?

答:
DocFX does generate static content, however the main index.html page will attempt to load some assets such as table of contents (toc.html) using an XMLHttpRequest from the browser. Such requests will be blocked by the browser if you have loaded the site by opening the index.html page from disk.

If you try, run the F12 dev tools in Chrome (or browser of your choice) and you will see warnings such as:

Access to XMLHttpRequest at 'file:///your-path/_site/toc.html' from
  origin 'null' has been blocked by CORS policy: Cross origin requests
  are only supported for protocol schemes: http, data, chrome-extension,
  edge, https.

As a result, the site really needs to be loaded from a web server over HTTP to get the best result

ContentLicense: CC BY-SA 4.0


问:
Bash tool to get nth line from a file
Is there a "canonical" way of doing that? I've been using head -n | tail -1 which does the trick, but I've been wondering if there's a Bash tool that specifically extracts a line (or a range of lines) from a file.

By "canonical" I mean a program whose main function is doing that.

答:
You may also used sed print and quit:</p>

```<code>sed -n '10{p;q;}' file   # print line 10
</code>```

ContentLicense: CC BY-SA 3.0

Title: Bash tool to get nth line from a file

Body:
You may also used sed print and quit:

sed -n '10{p;q;}' file   # print line 10


问:
CSS: Is font-size not acurrate?
So, link and link give hints about how fonts are implementation dependent.
This question is very especific to font-size in the following case:

font-size: 50px; will take aditional space to render (60px in my case)

div {
  height: 50px;
  font-size: 50px;
  background: green;
}

span {
  background: red;
}

.lineheight {
  line-height: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Green is 50px, Red is not</p>
<div><span>fg</span></div>

<p>You can still see the overflow without span:</p>
<div>jAaMgÁ</div>

<p>line-height does not solve the issue (just makes it prettier)</p>
<div class="lineheight"><span>jAaMgÁ</span></div></code>```

What i expect to happen is: ascender and descender inside em square

What i get is: descender is draw outside the em square.

From the documentation link: "The font size corresponds to the em square"

From this reference the em square should include both descender and ascender:

So why is the browser doing something else? I tried Firefox and Chrome, and both seem consistent with this (miss?)behaviour... did the specification change? if so, what is the appropiate way to tell the browser the font height including descender and ascender?

(width can be ignored, and you are free to use up to CSS4, but CSS3 is appreciated)

答:
The default line-height is higher than the font-size, that's why the span is higher than 50px in your example. If you set line-height to 1 or 100%, you see that the span has the same "real" height as the div: 50px. The accent on the "A" simply exceeds the 100% line-height and goes beyond the font-size, as an addition/exception.

div {
  height: 50px;
  font-size: 50px;
  line-height: 1;
  background: green;
}

span {
  background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Green and Red are 50px high, with line-height 100%:
<div><span>jAaMgÁ</span></div>
The only thing that overflows is the accent on the "A" (and the very first letter "j", but to the left...):
<div>jAaMgÁ</div></code>```

Title: CSS: Is font-size not acurrate?

Body:
So, link and link give hints about how fonts are implementation dependent.
This question is very especific to font-size in the following case:

font-size: 50px; will take aditional space to render (60px in my case)

div {
  height: 50px;
  font-size: 50px;
  background: green;
}

span {
  background: red;
}

.lineheight {
  line-height: 50px;
}

Green is 50px, Red is not

fg

You can still see the overflow without span:

jAaMgÁ

line-height does not solve the issue (just makes it prettier)

jAaMgÁ

What i expect to happen is: ascender and descender inside em square

What i get is: descender is draw outside the em square.

From the documentation link: "The font size corresponds to the em square"

From this reference the em square should include both descender and ascender:

So why is the browser doing something else? I tried Firefox and Chrome, and both seem consistent with this (miss?)behaviour... did the specification change? if so, what is the appropiate way to tell the browser the font height including descender and ascender?

(width can be ignored, and you are free to use up to CSS4, but CSS3 is appreciated)

Body:
The default line-height is higher than the font-size, that's why the span is higher than 50px in your example. If you set line-height to 1 or 100%, you see that the span has the same "real" height as the div: 50px. The accent on the "A" simply exceeds the 100% line-height and goes beyond the font-size, as an addition/exception.

div {
  height: 50px;
  font-size: 50px;
  line-height: 1;
  background: green;
}

span {
  background: red;
}

Green and Red are 50px high, with line-height 100%:
<div><span>jAaMgÁ</span></div>
The only thing that overflows is the accent on the "A" (and the very first letter "j", but to the left...):
<div>jAaMgÁ</div>


问:
How to pass Current user to Django_filters ModelChoiceFilter queryset
How to pass Current user to Django_filters ModelChoiceFilter queryset.

I'm trying to filter the ModelChoiceFilter based on the current user , i've used the init method in the filter but it failed:

here is the code I've used :

views.py

def requests_reports(request):
    f = RequestsFilter(request.GET, queryset=LeaveRequest.objects.filter(user=request.user), user=request.user)
    context = {
        'filter': f,
    }
    return render(request, 'requests_reports.html', context)
```

<p><strong>forms.py</strong></p>

<pre class="lang-py prettyprint-override"><code>class RequestsFilter(django_filters.FilterSet):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super(RequestsFilter, self).__init__(*args, **kwargs)
        self.fields['employee'].queryset = Employee.objects.filter(user=self.user)

    start_date = DateFilter(field_name='date_time', lookup_expr='gt', widget=forms.TextInput(attrs={'type': 'date'}))
    end_date = DateFilter(field_name='date_time', lookup_expr='lt', widget=forms.TextInput(attrs={'type': 'date'}))

    class Meta:
        model = LeaveRequest
        fields = ['employee', 'type']
</code>```

It returns this error :

```<code>'RequestsFilter' object has no attribute 'fields'
</code>```

答:
I don't have much experiance in Django, but what I see is you can not use meta attributes inside just like self.fields, you have to find another way to do it.

you can find more information on how to use filters here

Body:
How to pass Current user to Django_filters ModelChoiceFilter queryset.

I'm trying to filter the ModelChoiceFilter based on the current user , i've used the init method in the filter but it failed:

here is the code I've used :

views.py

def requests_reports(request):
    f = RequestsFilter(request.GET, queryset=LeaveRequest.objects.filter(user=request.user), user=request.user)
    context = {
        'filter': f,
    }
    return render(request, 'requests_reports.html', context)

forms.py

class RequestsFilter(django_filters.FilterSet):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super(RequestsFilter, self).__init__(*args, **kwargs)
        self.fields['employee'].queryset = Employee.objects.filter(user=self.user)

    start_date = DateFilter(field_name='date_time', lookup_expr='gt', widget=forms.TextInput(attrs={'type': 'date'}))
    end_date = DateFilter(field_name='date_time', lookup_expr='lt', widget=forms.TextInput(attrs={'type': 'date'}))

    class Meta:
        model = LeaveRequest
        fields = ['employee', 'type']

It returns this error :

'RequestsFilter' object has no attribute 'fields'


问:
Reorder array of objects based on array of strings?
I have the following data structures:

```<code>const fieldOrder = [
  'title',
  'first_name',
  'last_name',
  'address_1',
  'address_2',
  'city',
  'state',
  'zipcode',
  'country',
]

const fields = [
  {
    name: 'first_name',
    value: 'John'
  },
  {
    name: 'title',
    value: 'Mr'
  }
  ...etc
]
</code>```

And I'd like to reorder the fields array of objects based on the position of the name key in the fieldOrder array. How is this possible? Perhaps with the Array.sort method somehow?

And, generally speaking, is this the best way to represent order?

答:
Look for the index of the name in fieldOrder and use .sort to achieve that :

const fieldOrder = [
  "title",
  "first_name",
  "last_name",
  "address_1",
  "address_2",
  "city",
  "state",
  "zipcode",
  "country"
];

const fields = [
  {
    name: "first_name",
    value: "John"
  },
  {
    name: "title",
    value: "Mr"
  }
];

const result = fields.sort((a,b) => {
  const aNdx = fieldOrder.findIndex(e => e === a.name);
  const bNdx = fieldOrder.findIndex(e => e === b.name);

  return aNdx - bNdx;
})

console.log(result);```

Body:
I have the following data structures:

const fieldOrder = [
  'title',
  'first_name',
  'last_name',
  'address_1',
  'address_2',
  'city',
  'state',
  'zipcode',
  'country',
]

const fields = [
  {
    name: 'first_name',
    value: 'John'
  },
  {
    name: 'title',
    value: 'Mr'
  }
  ...etc
]

And I'd like to reorder the fields array of objects based on the position of the name key in the fieldOrder array. How is this possible? Perhaps with the Array.sort method somehow?

And, generally speaking, is this the best way to represent order?


问:
Error: "Could not find a storyboard named 'main' in bundle NSBundle"
when I click the button the application aport and I get "Thread 1: signal SIGABRT".

I also get the following error: "Could not find a storyboard named 'main' in bundle NSBundle"

I've created a simple form with the username text field, password text field, and a submit button.

The text fields have reference outlets that set to the view they are on, however, no reference outlet is created for the button?

Is this normal? as I am getting "Thread 1: signal SIGABRT", and this is the only abnormal thing I found?

答:
This error has come up randomly for me a couple of times with Xcode 11. One day my iPad app is building and running fine, the next - with no changes to the code or project whatsoever - I will see a warning at build time:

no rule to process file '...$filename.xcdatamodeld'...

and then when the app runs it will break immediately with this message:

Could not find a storyboard named 'Main' in bundle NSBundle

It is an older iPad app project that has been updated for newer Xcode versions over the years. The project uses Core Data and the workspace includes several CocoaPods, a mix of Objective-C, Swift as well as XIBs and Storyboards.

Over the last 6 months it's happened a few times and I've wasted a lot of time on this, even recreating the project, changing project configuration as suggested around StackOverflow, etc. but the only thing that works is to follow the steps below. I'm not sure what step actually fixes the problem, but so far I've discovered that I have to do all three!

Reset Xcode and clean the project using this Gist

Delete the app from the Simulator

Restart my MacBook


问:
Angular add a random JPG image?
I have created an Angular app that has a button which adds a new item to the list, here is a picture of it:

I searched for sites that provide random images and found "picsum.photos" (Lorem Picsum), which upon refresh indeed gives me a random picture each time.

I've tried implementing this in the code, but I'm getting the same image every time.

TypeScript Code:

```<code>imgUrl = 'https://some_long_path.jpeg';
randomImgUrl = 'https://picsum.photos/536/354';

recipes1: Recipes[] = [
    new Recipes('A Test Recipe',
      'This is simply a test', this.imgUrl)
];

addRecipe() {
   this.recipes1.push(new Recipes('name', 'description', this.randomImgUrl));
}
</code>```

HTML Code:

```<code><button class="btn btn-success" (click)="addRecipe()" (keyup.d)="removeRecipe()">New Recipe</button>
</code>```

It seems only one random image link gets saved into the variable 'randomImgUrl'...

Does anyone know what is the issue? How can I get a random image each time I call the addRecipe() function?

Thank you!

答:
add random queryparam to prevent your browser from caching this image.</p>

```<code>addRecipe() {
  this.recipes1.push(new Recipes('name', 'description', this.randomImgUrl + '?q=' + Math.random()));
}
</code>```

Title: Angular add a random JPG image?

Body:
I have created an Angular app that has a button which adds a new item to the list, here is a picture of it:

I searched for sites that provide random images and found "picsum.photos" (Lorem Picsum), which upon refresh indeed gives me a random picture each time.

I've tried implementing this in the code, but I'm getting the same image every time.

TypeScript Code:

imgUrl = 'https://some_long_path.jpeg';
randomImgUrl = 'https://picsum.photos/536/354';

recipes1: Recipes[] = [
    new Recipes('A Test Recipe',
      'This is simply a test', this.imgUrl)
];

addRecipe() {
   this.recipes1.push(new Recipes('name', 'description', this.randomImgUrl));
}

HTML Code:

<button class="btn btn-success" (click)="addRecipe()" (keyup.d)="removeRecipe()">New Recipe</button>

It seems only one random image link gets saved into the variable 'randomImgUrl'...

Does anyone know what is the issue? How can I get a random image each time I call the addRecipe() function?

Thank you!

Body:
add random queryparam to prevent your browser from caching this image.

addRecipe() {
  this.recipes1.push(new Recipes('name', 'description', this.randomImgUrl + '?q=' + Math.random()));
}


问:
Mysql workbench timestamp change format
I have a table with a column in which are inserted timestamps.

exactTime : ' 2017-12-17 05:00:12 ' and i want to change this format into '2017-12-17 05:00'

i would need some help with this .

答:
You could use date_format for this.

```<code>select date_format(your_date,'%Y-%m-%d %H:%i')
from your_table;
</code>```

Resource

Title: Mysql workbench timestamp change format

Body:
You could use date_format for this.

select date_format(your_date,'%Y-%m-%d %H:%i')
from your_table;

Resource


问:
Running procmon.exe programmatically using C#
I have a code in AutoIt that runs procmon.exe programmatically. Now I want to translate the code into C# so that I can run it via Microsoft Visual Studios thus can anyone guide me to completing it ?

Code in AutoIt

```<code>{

Global $scriptDir = FileGetShortName(@ScriptDir)

Global $logDir = "C:\\log\\registry\\"

Global $date = @YEAR & @MON & @MDAY

Global $time = @HOUR & @MIN & @SEC

$ReadUsername = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\COM\Upload", "I")

Run("procmon.exe /LoadConfig " & $scriptDir
    & "\\registrymonitoring.pmc /Quiet /AcceptEula /BackingFile "
    & $logDir & $ReadUsername & "-" & $date & "-" & $time, "", @SW_HIDE)

}
</code>```

Any advice is translating it to C# ?

答:
This should be it:

```<code>using System;
using System.IO;
using System.Diagnostics;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.Win32;

class Program
{
    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public static extern int GetShortPathName(
        [MarshalAs(UnmanagedType.LPTStr)]
        string path,
        [MarshalAs(UnmanagedType.LPTStr)]
        StringBuilder shortPath,
        int shortPathLength
        );

    static void Main(string[] args)
    {
        string scriptDirLong = Directory.GetParent(Process.GetCurrentProcess().MainModule.FileName).FullName;
        StringBuilder scriptDir = new StringBuilder(255);
        GetShortPathName(scriptDirLong, scriptDir, 255);

        string logDir = @"C:\log\registry\";
        string date = System.DateTime.Now.ToString("yyyyMMdd");
        string time = System.DateTime.Now.ToString("HHmmss");

        string ReadUsername = (string)Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\COM\Upload", "I", null);

        Console.WriteLine(scriptDir + "\r\n" + logDir + "\r\n" + date + "\r\n" + time);
        Console.ReadKey();

        Process.Start("procmon.exe",
            "/LoadConfig '" + scriptDir.ToString() + "\\registrymonitoring.pmc' /Quiet /AcceptEula /BackingFile " +
            logDir + ReadUsername + "-" + date + "-" + time);
    }
}
</code>```

I don't have that registry key or procmon to hand so I'm relying on the Console.WriteLine to see it it's right. The only thing I couldn't figure out how to do was getting the short name, so I just imported the winapi function and used that (taken from here).

Body:
I have a code in AutoIt that runs procmon.exe programmatically. Now I want to translate the code into C# so that I can run it via Microsoft Visual Studios thus can anyone guide me to completing it ?

Code in AutoIt

{

Global $scriptDir = FileGetShortName(@ScriptDir)

Global $logDir = "C:\\log\\registry\\"

Global $date = @YEAR & @MON & @MDAY

Global $time = @HOUR & @MIN & @SEC

$ReadUsername = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\COM\Upload", "I")

Run("procmon.exe /LoadConfig " & $scriptDir
    & "\\registrymonitoring.pmc /Quiet /AcceptEula /BackingFile "
    & $logDir & $ReadUsername & "-" & $date & "-" & $time, "", @SW_HIDE)

}

Any advice is translating it to C# ?

Body:
This should be it:

using System;
using System.IO;
using System.Diagnostics;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.Win32;

class Program
{
    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public static extern int GetShortPathName(
        [MarshalAs(UnmanagedType.LPTStr)]
        string path,
        [MarshalAs(UnmanagedType.LPTStr)]
        StringBuilder shortPath,
        int shortPathLength
        );

    static void Main(string[] args)
    {
        string scriptDirLong = Directory.GetParent(Process.GetCurrentProcess().MainModule.FileName).FullName;
        StringBuilder scriptDir = new StringBuilder(255);
        GetShortPathName(scriptDirLong, scriptDir, 255);

        string logDir = @"C:\log\registry\";
        string date = System.DateTime.Now.ToString("yyyyMMdd");
        string time = System.DateTime.Now.ToString("HHmmss");

        string ReadUsername = (string)Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\COM\Upload", "I", null);

        Console.WriteLine(scriptDir + "\r\n" + logDir + "\r\n" + date + "\r\n" + time);
        Console.ReadKey();

        Process.Start("procmon.exe",
            "/LoadConfig '" + scriptDir.ToString() + "\\registrymonitoring.pmc' /Quiet /AcceptEula /BackingFile " +
            logDir + ReadUsername + "-" + date + "-" + time);
    }
}

I don't have that registry key or procmon to hand so I'm relying on the Console.WriteLine to see it it's right. The only thing I couldn't figure out how to do was getting the short name, so I just imported the winapi function and used that (taken from here).


问:
make file.exists() case insensitive
I have a line of code in my script that checks if a file exists (actually, many files, this one line gets looped for a bunch of different files):

```<code>file.exists(Sys.glob(file.path(getwd(), "files", "*name*")))
</code>```

This looks for any file in the directory /files/  that has "name" in it, e.g. "filename.csv". However, some of my files are named "fileName.csv" or "thisfileNAME.csv". They do not get recognized. How can i make file.exists treat this check in a case insensitive way?

In my other code i usually make any imported names or lists immediately lowercase with the tolower function. But I don't see any option to include that in the file.exists function.

答:
Suggested solution using list.files:

If we have many files we might want to do this only once, otherwise we can put in in the function (and pass path_to_root_directory instead of found_files to the function)

```<code>  found_files <- list.files(path_to_root_directory, recursive=FALSE)
</code>```

Behaviour as file.exists (return value is boolean):

```<code>  fileExIsTs <- function(file_path, found_files) {
    return(tolower(file_path) %in% tolower(found_files))
  }
</code>```

Return value is file with spelling as found in directory or character(0) if no match:

```<code>  fileExIsTs <- function(file_path, found_files) {
    return(found_files[tolower(found_files) %in% tolower(file_path)])
  }
</code>```

Edit:

New solution to fit new requirements:

```<code>keywordExists <- function(keyword, found_files) {
  return(any(grepl(keyword, found_files, ignore.case=TRUE)))
}

keywordExists("NaMe", found_files=c("filename.csv", "morefilenames.csv"))
</code>```

Returns:

```<code>[1] TRUE
</code>```

Or

Return value are files with spelling as found in directory or character(0) if no match:

```<code>keywordExists2 <- function(file_path, found_files) {
  return(found_files[grepl(keyword, found_files, ignore.case=TRUE)])
}

keywordExists2("NaMe", found_files=c("filename.csv", "morefilenames.csv"))
</code>```

Returns:

```<code>[1] "filename.csv"      "morefilenames.csv"
</code>```

Title: make file.exists() case insensitive

Body:
I have a line of code in my script that checks if a file exists (actually, many files, this one line gets looped for a bunch of different files):

file.exists(Sys.glob(file.path(getwd(), "files", "*name*")))

This looks for any file in the directory /files/  that has "name" in it, e.g. "filename.csv". However, some of my files are named "fileName.csv" or "thisfileNAME.csv". They do not get recognized. How can i make file.exists treat this check in a case insensitive way?

In my other code i usually make any imported names or lists immediately lowercase with the tolower function. But I don't see any option to include that in the file.exists function.

Body:
Suggested solution using list.files:

If we have many files we might want to do this only once, otherwise we can put in in the function (and pass path_to_root_directory instead of found_files to the function)

  found_files <- list.files(path_to_root_directory, recursive=FALSE)

Behaviour as file.exists (return value is boolean):

  fileExIsTs <- function(file_path, found_files) {
    return(tolower(file_path) %in% tolower(found_files))
  }

Return value is file with spelling as found in directory or character(0) if no match:

  fileExIsTs <- function(file_path, found_files) {
    return(found_files[tolower(found_files) %in% tolower(file_path)])
  }

Edit:

New solution to fit new requirements:

keywordExists <- function(keyword, found_files) {
  return(any(grepl(keyword, found_files, ignore.case=TRUE)))
}

keywordExists("NaMe", found_files=c("filename.csv", "morefilenames.csv"))

Returns:

[1] TRUE

Or

Return value are files with spelling as found in directory or character(0) if no match:

keywordExists2 <- function(file_path, found_files) {
  return(found_files[grepl(keyword, found_files, ignore.case=TRUE)])
}

keywordExists2("NaMe", found_files=c("filename.csv", "morefilenames.csv"))

Returns:

[1] "filename.csv"      "morefilenames.csv"


答:
You can sort it based on the index in the array;

const fieldOrder = [
    'title',
    'first_name',
    'last_name',
    'address_1',
    'address_2',
    'city',
    'state',
    'zipcode',
    'country',
  ]

  const fields = [
    {
        name: 'first_name',
        value: 'John'
    },
    {
        name: 'title',
        value: 'Mr'
    },
    {
        name: 'city',
        value: 'JNB'
    },
    {
        name: 'country',
        value: 'RSA'
    }
]

fields.sort( (a, b) => fieldOrder.indexOf(a.name) - fieldOrder.indexOf(b.name));

console.log(fields)```

Title: Reorder array of objects based on array of strings?


问:
Lazy Loading results in ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment:
I implement lazy loading and result into this error. I have seen many post and none of them are giving the solution.

How to reproduce:

Go to https://stackblitz.com/edit/angular-sxmpj8

Click on orders tab

Click Test

Expected: It opens Test component
Actual: It results into "Uncaught (in promise): Error: Cannot match any routes. URL Segment:" error

I am trying to lazy load the orders module which has two components orders and test. The orders route is working fine but the test component route throws error.

The application is at https://stackblitz.com/edit/angular-sxmpj8

At orders-routing.module.ts the routes are defined as below:

```<code>    const routes: Routes = [
  {
    path: '',
    component: OrdersComponent,

    children: [
      { path: 'test', component: TestComponent
  }]
  }
];
</code>```

The routes at app-routing.module.ts are defined as below.

```<code>const routes: Routes = [
  {
    path: 'customers',
    loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule)
  },
  {
   path: 'orders',

   // Tried this also
   // loadChildren:  './orders/orders.module#OrdersModule'
    loadChildren: () => import('./orders/orders.module').then(m => m.OrdersModule)
  },
  {
    path: '',
    redirectTo: '',
    pathMatch: 'full'
  }
];
</code>```

In orders.component.ts file I have an entry

```<code><button routerLink="/test">Test</button>
</code>```

Clicking this result into error

ERROR
Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'test'
Error: Cannot match any routes. URL Segment: 'test'

答:
You need to add routerLink="/orders/test" instead of just routerLink="/test".
Also you need to add <router-outlet></router-outlet> in the orders.component.html to show the testComponent's view.

Change in orders.component.html

```<code>     <p>
      orders works!
    </p>

    <button routerLink="/orders/test">Test</button>
    <router-outlet></router-outlet>
</code>```

Hope this helps !!

Body:
I implement lazy loading and result into this error. I have seen many post and none of them are giving the solution.

How to reproduce:

Go to https://stackblitz.com/edit/angular-sxmpj8

Click on orders tab

Click Test

Expected: It opens Test component
Actual: It results into "Uncaught (in promise): Error: Cannot match any routes. URL Segment:" error

I am trying to lazy load the orders module which has two components orders and test. The orders route is working fine but the test component route throws error.

The application is at https://stackblitz.com/edit/angular-sxmpj8

At orders-routing.module.ts the routes are defined as below:

    const routes: Routes = [
  {
    path: '',
    component: OrdersComponent,

    children: [
      { path: 'test', component: TestComponent
  }]
  }
];

The routes at app-routing.module.ts are defined as below.

const routes: Routes = [
  {
    path: 'customers',
    loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule)
  },
  {
   path: 'orders',

   // Tried this also
   // loadChildren:  './orders/orders.module#OrdersModule'
    loadChildren: () => import('./orders/orders.module').then(m => m.OrdersModule)
  },
  {
    path: '',
    redirectTo: '',
    pathMatch: 'full'
  }
];

In orders.component.ts file I have an entry

<button routerLink="/test">Test</button>

Clicking this result into error

ERROR
Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'test'
Error: Cannot match any routes. URL Segment: 'test'

Body:
You need to add routerLink="/orders/test" instead of just routerLink="/test".
Also you need to add <router-outlet></router-outlet> in the orders.component.html to show the testComponent's view.

Change in orders.component.html

     <p>
      orders works!
    </p>

    <button routerLink="/orders/test">Test</button>
    <router-outlet></router-outlet>

Hope this helps !!


问:
How To Create Flutter Moor Relationship With One-To-Many Join
I have a table Category which is Related to a Task table in a one-to-many relationship and I am attempting to perform a join using Moor.

I would like to return a list for the list of tasks that match a category. How do I do it?

      Stream<List<CategoryWithTask>> watchAllCategories() {
        return (select(categories)
              ..orderBy(([
                (c) => OrderingTerm(expression: c.name),
              ])))
            .join([leftOuterJoin(tasks, tasks.categoryId.equalsExp(categories.id))])
            .watch()
            .map((rows) => rows.map(
                  (row) {
                    return CategoryWithTask(
                        category: row.readTable(categories),
                        task: row.readTable(tasks)); // How do I modify this line to return a list of tasks corresponding to a category?
                  },
                ).toList());
      }
```

答:
I managed to find a way with the support of the guys at Flutter Moor after creating an issue on Github. Below is the working code;

  Stream<List<CategoryWithTasks>> watchAllCategories() {
    return (select(categories)
          ..orderBy(([
            (c) => OrderingTerm(expression: c.name),
          ])))
        .join([leftOuterJoin(tasks, tasks.categoryId.equalsExp(categories.id))])
        .watch()
        .map((rows) {
          final groupedData = <Category, List<Task>>{};

          for (final row in rows) {
            final category = row.readTable(categories);
            final task = row.readTable(tasks);

            final list = groupedData.putIfAbsent(category, () => []);
            if (task != null) list.add(task);
          }

          return [
            for (final entry in groupedData.entries)
              CategoryWithTasks(category: entry.key, tasks: entry.value)
          ];
        });
  }
```


问:
Can I reduce to 0 seconds the PreviewScreen(White) time at the start?
There's a white-blank screen in android, just before the launch screen, at the start of the Application, that white-blank screen it's about 2 seconds in devices like Samsung j1 with android 5.1. That 2 seconds it's due to the app performance or the Android and hardware performance, that 2 seconds can be reduced?.

We make up the problem using the following in our app theme: <item name="android:windowDisablePreview">true</item>, that means that the white screen now it's transparent, so it seems to be an Android problem from the user perspective, but it's a way to reduce the time of this preview screen to a half or near zero?

Reference to this problem in:

https://developer.android.com/topic/performance/vitals/launch-time

Android - Disable dummy starting window of application

https://stackoverflow.com/questions/40905317/how-can-i-remove-white-screen-which-appear-before-splash-screenhttps://stackoverflow.com/questions/37437037/android-prevent-white-screen-at-startup

https://www.tothenew.com/blog/disabling-the-preview-or-start-window-in-android/

blank screen comes before splash

答:
Have a look at the startup guidelines and performance measurement techniques here:

https://developer.android.com/topic/performance/vitals/launch-time

This will tell you where the time is being spent during startup and give you suggestions on how to improve that.

Also, you can provide a splash screen that shows instead of the white screen. See details here:

https://android.jlelse.eu/the-complete-android-splash-screen-guide-c7db82bce565


问:
No Such Field Error in android project using kotlin
I get a NoSuchField runtime error  in my android app using Kotlin whereas the field exists
I've tried renaming as stated here No static field list_container of type I in class Landroid/support/v7/preference/R$id yet no solution

This is my MainActivityWarrant class

```<code>package com.android.example.cameraxbasic

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.android.example.cameraxbasic.helpers.PH
import com.android.example.cameraxbasic.utils.FLAGS_FULLSCREEN
import java.io.File

const val KEY_EVENT_ACTION = "key_event_action"
const val KEY_EVENT_EXTRA = "key_event_extra"
private const val IMMERSIVE_FLAG_TIMEOUT = 500L

/**
 * Main entry point into our app. This app follows the single-activity pattern, and all
 * functionality is implemented in the form of fragments.
 */
class MainActivityWarrant : AppCompatActivity() {
    private lateinit var container: FrameLayout

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        container = this.findViewById(R.id.fragment_contain)

        Zonedata =  PH.get().getString(this.applicationContext, "ZoneData", "")
        Statedata = PH.get().getString(this.applicationContext, "StateData", "")
        Prisondata = PH.get().getString(this.applicationContext, "PrisonData", "")

//         = intent.getStringExtra("Zonedata")
//        intent.getStringExtra("Statedata")
//        intent.getStringExtra("Prisondata")

        val currentDBPath = getDatabasePath("your_db_name").absolutePath
        println()
        println("$Zonedata <<<<<<<>>>>>>>>>> $Statedata <<<<<<<<>>>>>>> $Prisondata")
    }

    override fun onResume() {
        super.onResume()
        // Before setting full screen flags, we must wait a bit to let UI settle; otherwise, we may
        // be trying to set app to immersive mode before it's ready and the flags do not stick
        container.postDelayed({
            container.systemUiVisibility = FLAGS_FULLSCREEN
        }, IMMERSIVE_FLAG_TIMEOUT)
    }

    /** When key down event is triggered, relay it via local broadcast so fragments can handle it */
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        return when (keyCode) {
            KeyEvent.KEYCODE_VOLUME_DOWN -> {
                val intent = Intent(KEY_EVENT_ACTION).apply { putExtra(KEY_EVENT_EXTRA, keyCode) }
                LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
                true
            }
            else -> super.onKeyDown(keyCode, event)
        }
    }

    companion object {

        var Zonedata: String = ""
        var Statedata: String = ""
        var Prisondata: String = ""
        /** Use external media if it is available, our app's file directory otherwise */
        fun getOutputDirectory(context: Context): File {
            val appContext = context.applicationContext
            val mediaDir = context.externalMediaDirs.firstOrNull()?.let {
                File(it, appContext.resources.getString(R.string.app_name) + "/" + Zonedata + "/" + Statedata + "/" + Prisondata).apply { mkdirs() }
            }
            return if (mediaDir != null && mediaDir.exists())
                mediaDir else appContext.filesDir
        }

        //send selected prison values to be used as file name

        //        var ZoneNameInFull:String = Zonedata
//        var StateNameInFull:String = Statedata
//        var PrisonNameInFull:String = Prisondata
        @SuppressLint("StaticFieldLeak")
        var openCameraForNewDocument = SelectPrisonActivity()

    }

//    fun openCamera(view: View) {}
}

</code>```

and this is the log

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.virtusync.scanningtool, PID: 21098
    java.lang.NoSuchFieldError: No static field fragment_contain of type I in class Lcom/android/example/cameraxbasic/R$id; or its superclasses (declaration of 'com.android.example.cameraxbasic.R$id' appears in /data/app/com.virtusync.scanningtool-ud2au9eFKL3JmFqFoLWYtQ==/base.apk!classes2.dex)
        at com.android.example.cameraxbasic.MainActivityWarrant.onCreate(MainActivityWarrant.kt:49)
        at android.app.Activity.performCreate(Activity.java:7136)
        at android.app.Activity.performCreate(Activity.java:7127)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2990)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3148)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1861)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6819)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:497)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:912)
</code>```

答:
I believe your issue is because there is no element in any of your xml that has the id of "fragment_contain". Could you double check that your id matches whichever element you are looking for? Should look something like:</p>

```<code><android.widget.FrameLayout
        android:id="@+id/fragment_contain"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</code>```

Body:
I get a NoSuchField runtime error  in my android app using Kotlin whereas the field exists
I've tried renaming as stated here No static field list_container of type I in class Landroid/support/v7/preference/R$id yet no solution

This is my MainActivityWarrant class

package com.android.example.cameraxbasic

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.android.example.cameraxbasic.helpers.PH
import com.android.example.cameraxbasic.utils.FLAGS_FULLSCREEN
import java.io.File

const val KEY_EVENT_ACTION = "key_event_action"
const val KEY_EVENT_EXTRA = "key_event_extra"
private const val IMMERSIVE_FLAG_TIMEOUT = 500L

/**
 * Main entry point into our app. This app follows the single-activity pattern, and all
 * functionality is implemented in the form of fragments.
 */
class MainActivityWarrant : AppCompatActivity() {
    private lateinit var container: FrameLayout

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        container = this.findViewById(R.id.fragment_contain)

        Zonedata =  PH.get().getString(this.applicationContext, "ZoneData", "")
        Statedata = PH.get().getString(this.applicationContext, "StateData", "")
        Prisondata = PH.get().getString(this.applicationContext, "PrisonData", "")

//         = intent.getStringExtra("Zonedata")
//        intent.getStringExtra("Statedata")
//        intent.getStringExtra("Prisondata")

        val currentDBPath = getDatabasePath("your_db_name").absolutePath
        println()
        println("$Zonedata <<<<<<<>>>>>>>>>> $Statedata <<<<<<<<>>>>>>> $Prisondata")
    }

    override fun onResume() {
        super.onResume()
        // Before setting full screen flags, we must wait a bit to let UI settle; otherwise, we may
        // be trying to set app to immersive mode before it's ready and the flags do not stick
        container.postDelayed({
            container.systemUiVisibility = FLAGS_FULLSCREEN
        }, IMMERSIVE_FLAG_TIMEOUT)
    }

    /** When key down event is triggered, relay it via local broadcast so fragments can handle it */
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        return when (keyCode) {
            KeyEvent.KEYCODE_VOLUME_DOWN -> {
                val intent = Intent(KEY_EVENT_ACTION).apply { putExtra(KEY_EVENT_EXTRA, keyCode) }
                LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
                true
            }
            else -> super.onKeyDown(keyCode, event)
        }
    }

    companion object {

        var Zonedata: String = ""
        var Statedata: String = ""
        var Prisondata: String = ""
        /** Use external media if it is available, our app's file directory otherwise */
        fun getOutputDirectory(context: Context): File {
            val appContext = context.applicationContext
            val mediaDir = context.externalMediaDirs.firstOrNull()?.let {
                File(it, appContext.resources.getString(R.string.app_name) + "/" + Zonedata + "/" + Statedata + "/" + Prisondata).apply { mkdirs() }
            }
            return if (mediaDir != null && mediaDir.exists())
                mediaDir else appContext.filesDir
        }

        //send selected prison values to be used as file name

        //        var ZoneNameInFull:String = Zonedata
//        var StateNameInFull:String = Statedata
//        var PrisonNameInFull:String = Prisondata
        @SuppressLint("StaticFieldLeak")
        var openCameraForNewDocument = SelectPrisonActivity()

    }

//    fun openCamera(view: View) {}
}

and this is the log

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.virtusync.scanningtool, PID: 21098
    java.lang.NoSuchFieldError: No static field fragment_contain of type I in class Lcom/android/example/cameraxbasic/R$id; or its superclasses (declaration of 'com.android.example.cameraxbasic.R$id' appears in /data/app/com.virtusync.scanningtool-ud2au9eFKL3JmFqFoLWYtQ==/base.apk!classes2.dex)
        at com.android.example.cameraxbasic.MainActivityWarrant.onCreate(MainActivityWarrant.kt:49)
        at android.app.Activity.performCreate(Activity.java:7136)
        at android.app.Activity.performCreate(Activity.java:7127)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2990)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3148)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1861)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6819)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:497)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:912)

Body:
I believe your issue is because there is no element in any of your xml that has the id of "fragment_contain". Could you double check that your id matches whichever element you are looking for? Should look something like:

<android.widget.FrameLayout
        android:id="@+id/fragment_contain"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />


问:
What project would you recommend me to get up to speed with C++
I know that C++ is a very complex language that takes many years of practice to master.

Taking that into account do you know of a small project (around a 1k of loc) that tests all of C++ major features (inheritance, pointers, memory management, etc).

The thing is I'm a Java/Python programmer and I really want to learn C++ so I've been studying C++ for a while but haven't tested anything of what I've learned beyond small exercises.

I want to take all of that knowledge and put into practice.

答:
I would suggest a simple text editor would be a reasonable goal.

It's a problem domain that you have a good grasp of.

You have memory management issues, library class reuse issues (stl/curses?), pointer issues, and lots of options where derived classes can be used.

For polymorphism, perhaps, you can have the editor read from a keyboard, or suck commands in from a text file.

There is another good one.... dealing with files.

You don't have to cross platform it.  You don't have to open source it.  You don't have to show it to anyone.  You don't even have to finish it.  It can be an exercise just for you.

OwnerDisplayName: climatewarrior

OwnerDisplayName: EvilTeach

ContentLicense: CC BY-SA 2.5


问:
Python or Java for text processing (text mining, information retrieval, natural language processing)
I'm soon to start on a new project where I am going to do lots of text processing tasks like searching, categorization/classifying, clustering, and so on.

There's going to be a huge amount of documents that need to be processed; probably millions of documents. After the initial processing, it also has to be able to be updated daily with multiple new documents.

Can I use Python to do this, or is Python too slow? Is it best to use Java?

If possible, I would prefer Python since that's what I have been using lately. Plus, I would finish the coding part much faster. But it all depends on Python's speed. I have used Python for some small scale text processing tasks with only a couple of thousand documents, but I am not sure how well it scales up.

答: Just write it, the biggest flaw in programming people have is premature optimization. Work on a project, write it out and get it working. Then go back and fix the bugs and ensure that its optimized. There are going to be a number of people harping on about speed of x vs y and y is better than x but at the end of a day its just a language. Its not what a language is but how it does it.</p>


问:
What is exactly sklearn.pipeline.Pipeline?
I can't figure out how the sklearn.pipeline.Pipeline works exactly.

There are a few explanation in the doc. For example what do they mean by:

Pipeline of transforms with a final estimator.

To make my question clearer, what are steps? How do they work?

Edit

Thanks to the answers I can make my question clearer:

When I call pipeline and pass, as steps, two transformers and one estimator, e.g:

```<code>pipln = Pipeline([("trsfm1",transformer_1),
                  ("trsfm2",transformer_2),
                  ("estmtr",estimator)])
</code>```

What happens when I call this?

```<code>pipln.fit()
OR
pipln.fit_transform()
</code>```

I can't figure out how an estimator can be a transformer and how a transformer can be fitted.

答:
ML algorithms typically process tabular data. You may want to do preprocessing and post-processing of this data before and after your ML algorithm. A pipeline is a way to chain those data processing steps.

What are ML pipelines and how do they work?

A pipeline is a series of steps in which data is transformed. It comes from the old "pipe and filter" design pattern (for instance, you could think of unix bash commands with pipes “|” or redirect operators “>”). However, pipelines are objects in the code. Thus, you may have a class for each filter (a.k.a. each pipeline step), and then another class to combine those steps into the final pipeline. Some pipelines may combine other pipelines in series or in parallel, have multiple inputs or outputs, and so on. We like to view Pipelining Machine Learning as:

Pipe and filters. The pipeline’s steps process data, and they manage their inner state which can be learned from the data.

Composites. Pipelines can be nested: for example a whole pipeline can be treated as a single pipeline step in another pipeline. A pipeline step is not necessarily a pipeline, but a pipeline is itself at least a pipeline step by definition.

Directed Acyclic Graphs (DAG). A pipeline step's output may be sent to many other steps, and then the resulting outputs can be recombined, and so on. Side note: despite pipelines are acyclic, they can process multiple items one by one, and if their state change (e.g.: using the fit_transform method each time), then they can be viewed as recurrently unfolding through time, keeping their states (think like an RNN). That’s an interesting way to see pipelines for doing online learning when putting them in production and training them on more data.

Methods of a Scikit-Learn Pipeline

Pipelines (or steps in the pipeline) must have those two methods:

“fit” to learn on the data and acquire state (e.g.: neural network’s neural weights are such state)

“transform" (or "predict") to actually process the data and generate a prediction.

It's also possible to call this method to chain both:

“fit_transform” to fit and then transform the data, but in one pass, which allows for potential code optimizations when the two methods must be done one after the other directly.

Problems of the sklearn.pipeline.Pipeline class

Scikit-Learn’s “pipe and filter” design pattern is simply beautiful. But how to use it for Deep Learning, AutoML, and complex production-level pipelines?

Scikit-Learn had its first release in 2007, which was a pre deep learning era. However, it’s one of the most known and adopted machine learning library, and is still growing. On top of all, it uses the Pipe and Filter design pattern as a software architectural style - it’s what makes Scikit-Learn so fabulous, added to the fact it provides algorithms ready for use. However, it has massive issues when it comes to do the following, which we should be able to do in 2020 already:

Automatic Machine Learning (AutoML),

Deep Learning Pipelines,

More complex Machine Learning pipelines.

Solutions that we’ve Found to Those Scikit-Learn's Problems

For sure, Scikit-Learn is very convenient and well-built. However, it needs a refresh. Here are our solutions with Neuraxle to make Scikit-Learn fresh and useable within modern computing projects!

Inability to Reasonably do Automatic Machine Learning (AutoML)

Problem: Defining the Search Space (Hyperparameter Distributions)

Problem: Defining Hyperparameters in the Constructor is Limiting

Problem: Different Train and Test Behavior

Problem: You trained a Pipeline and You Want Feedback on its Learning.

Inability to Reasonably do Deep Learning Pipelines

Problem: Scikit-Learn Hardly Allows for Mini-Batch Gradient Descent (Incremental Fit)

Problem: Initializing the Pipeline and Deallocating Resources

Problem: It is Difficult to Use Other Deep Learning (DL) Libraries in Scikit-Learn

Problem: The Ability to Transform Output Labels

Not ready for Production nor for Complex Pipelines

Problem: Processing 3D, 4D, or ND Data in your Pipeline with Steps Made for Lower-Dimensional Data

Problem: Modify a Pipeline Along the Way, such as for Pre-Training or Fine-Tuning

Problem: Getting Model Attributes from Scikit-Learn Pipeline

Problem: You can't Parallelize nor Save Pipelines Using Steps that Can't be Serialized "as-is" by Joblib

Additional pipeline methods and features offered through Neuraxle

Note: if a step of a pipeline doesn’t need to have one of the fit or transform methods, it could inherit from NonFittableMixin or NonTransformableMixin to be provided a default implementation of one of those methods to do nothing.

As a starter, it is possible for pipelines or their steps to also optionally define those methods:

“setup” which will call the “setup” method on each of its step. For instance, if a step contains a TensorFlow, PyTorch, or Keras neural network, the steps could create their neural graphs and register them to the GPU in the “setup” method before fit. It is discouraged to create the graphs directly in the constructors of the steps for several reasons, such as if the steps are copied before running many times with different hyperparameters within an Automatic Machine Learning algorithm that searches for the best hyperparameters for you.

“teardown”, which is the opposite of the “setup” method: it clears resources.

The following methods are provided by default to allow for managing hyperparameters:

“get_hyperparams” will return you a dictionary of the hyperparameters. If your pipeline contains more pipelines (nested pipelines), then the hyperparameter’ keys are chained with double underscores “__” separators.

“set_hyperparams” will allow you to set new hyperparameters in the same format of when you get them.

“get_hyperparams_space” allows you to get the space of hyperparameter, which will be not empty if you defined one. So, the only difference with “get_hyperparams” here is that you’ll get statistic distributions as values instead of a precise value. For instance, one hyperparameter for the number of layers could be a RandInt(1, 3) which means 1 to 3 layers. You can call .rvs() on this dict to pick a value randomly and send it to “set_hyperparams” to try training on it.

“set_hyperparams_space” can be used to set a new space using the same hyperparameter distribution classes as in “get_hyperparams_space”.

For more info on our suggested solutions, read the entries in the big list with links above.

Body:
I can't figure out how the sklearn.pipeline.Pipeline works exactly.

There are a few explanation in the doc. For example what do they mean by:

Pipeline of transforms with a final estimator.

To make my question clearer, what are steps? How do they work?

Edit

Thanks to the answers I can make my question clearer:

When I call pipeline and pass, as steps, two transformers and one estimator, e.g:

pipln = Pipeline([("trsfm1",transformer_1),
                  ("trsfm2",transformer_2),
                  ("estmtr",estimator)])

What happens when I call this?

pipln.fit()
OR
pipln.fit_transform()

I can't figure out how an estimator can be a transformer and how a transformer can be fitted.


问:
how to add mindmap file to wordpress?
I am creating mindmaps with the help of freemind tool and it provides me a facility to store it as mm file extension.
do we have any way by which I can embed it in WordPress website as clickable way and not as an image</p>

答:
I did some researches apparently there's a plugin called "FreeMind WP Browser".
But please be aware I saw that the last update of this plugin was 8 years ago, it may present some vulnerabilities.</p>

Title: how to add mindmap file to wordpress?


问:
spaCy token.tag_ full list
The official documentation of token.tag_ in spaCy is as follows:

A fine-grained, more detailed tag that represents the word-class and some basic morphological information for the token. These tags are primarily designed to be good features for subsequent models, particularly the syntactic parser. They are language and treebank dependent. The tagger is trained to predict these fine-grained tags, and then a mapping table is used to reduce them to the coarse-grained  .pos tags.

But it doesn't list the full available tags and each tag's explanation. Where can I find it?

答:
Available values for token.tag_ are language specific. With language here, I don't mean English or Portuguese, I mean 'en_core_web_sm' or 'pt_core_news_sm'. In other words, they are language model specific and they are defined in the TAG_MAP, which is customizable and trainable. If you don't customize it, it will be default TAG_MAP for that language.

As of the writing of this answer, spacy.io/models lists all of the pre trained models and their labeling scheme.

Now, for the explanations. If you are working with English or German text, you're in luck! You can use spacy.explain() or access its glossary on github for the full list. If you are working with other languages, token.pos_ values are always those of Universal dependencies and will work regardless.

To finish up, if you are working with other languages, for a full explanation of the tags, you are going to have to look for them in the sources listed in the models page for your model of interest. For instance, for Portuguese I had to track the explanations for the tags in the Portuguese UD Bosque Corpus used to train the model.

Title: spaCy token.tag_ full list


问:
Exception on opening DataSet Visualizer due to the AssemblyResolve event
When trying to use the magnifing glasson one of my DataSet or DataTable in my .Net Core 3.1 WPF Project I get a System.IO.FileLoadException with following text:

Could not load file or assembly 'DataSetVisualizer.DebuggeeSide, Version=16.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. General Exception (0x80131500)

Stack trace:

```<code>at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, RuntimeAssembly assemblyContext, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, AssemblyLoadContext assemblyLoadContext)
at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, StackCrawlMark& stackMark, AssemblyLoadContext assemblyLoadContext)
at System.Reflection.Assembly.Load(AssemblyName assemblyRef, StackCrawlMark& stackMark, AssemblyLoadContext assemblyLoadContext)
at System.Reflection.Assembly.Load(AssemblyName assemblyRef)
at Microsoft.VisualStudio.DebuggerVisualizers.DebuggeeSide.Impl.ClrCustomVisualizerDebuggeeHost..ctor(String debuggeeSideVisualizerTypeName, String debuggeeSideVisualizerAssemblyName, String[] probePaths)
at Microsoft.VisualStudio.DebuggerVisualizers.DebuggeeSide.Impl.ClrCustomVisualizerDebuggeeHost.Create(String debuggeeSideVisualizerTypeName, String debuggeeSideVisualizerAssemblyName, String[] probePaths)
</code>```

I narrowed the cause for this problem down to my recently implemented method to load assemblies from subfolders at runtime, which I wrote based on Reza Aghaei's answer on my last question.

In narrowed it down to the subscription on the AppDomain.CurrentDomain.AssemblyResolve event, but couldn't find a way to solve it yet.

```<code>AppDomain.CurrentDomain.AssemblyResolve += (obj, arg) =>
{
  var name = $"{new AssemblyName(arg.Name).Name}.dll";
  var assemblyFile = referenceFiles.Where(x => x.EndsWith(name))
        .FirstOrDefault();
  if (assemblyFile != null)
      return Assembly.LoadFrom(assemblyFile);
  throw new Exception($"'{name}' Not found");
};
</code>```

It doesn't matter if I am trying to view the DataSet in one of the loaded assemblies or the startup application.

I would like to keep working with this method to load assemblies at runtime, but since I am working with a lot of DataSets being able to use the DataSet Visualizer is crucial for me.

Any suggestions?

edit: usage of dataset visualizer during debugging:

答:
Not an elegant solution, but as a workaround to unblock your debugging sessions, add the following to the beginning of the AssemblyResolve event handler:

```<code>#if DEBUG
    if (arg.Name.StartsWith("DataSetVisualizer"))
        return null;
#endif
</code>```

Body:
When trying to use the magnifing glasson one of my DataSet or DataTable in my .Net Core 3.1 WPF Project I get a System.IO.FileLoadException with following text:

Could not load file or assembly 'DataSetVisualizer.DebuggeeSide, Version=16.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. General Exception (0x80131500)

Stack trace:

at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, RuntimeAssembly assemblyContext, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, AssemblyLoadContext assemblyLoadContext)
at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, StackCrawlMark& stackMark, AssemblyLoadContext assemblyLoadContext)
at System.Reflection.Assembly.Load(AssemblyName assemblyRef, StackCrawlMark& stackMark, AssemblyLoadContext assemblyLoadContext)
at System.Reflection.Assembly.Load(AssemblyName assemblyRef)
at Microsoft.VisualStudio.DebuggerVisualizers.DebuggeeSide.Impl.ClrCustomVisualizerDebuggeeHost..ctor(String debuggeeSideVisualizerTypeName, String debuggeeSideVisualizerAssemblyName, String[] probePaths)
at Microsoft.VisualStudio.DebuggerVisualizers.DebuggeeSide.Impl.ClrCustomVisualizerDebuggeeHost.Create(String debuggeeSideVisualizerTypeName, String debuggeeSideVisualizerAssemblyName, String[] probePaths)

I narrowed the cause for this problem down to my recently implemented method to load assemblies from subfolders at runtime, which I wrote based on Reza Aghaei's answer on my last question.

In narrowed it down to the subscription on the AppDomain.CurrentDomain.AssemblyResolve event, but couldn't find a way to solve it yet.

AppDomain.CurrentDomain.AssemblyResolve += (obj, arg) =>
{
  var name = $"{new AssemblyName(arg.Name).Name}.dll";
  var assemblyFile = referenceFiles.Where(x => x.EndsWith(name))
        .FirstOrDefault();
  if (assemblyFile != null)
      return Assembly.LoadFrom(assemblyFile);
  throw new Exception($"'{name}' Not found");
};

It doesn't matter if I am trying to view the DataSet in one of the loaded assemblies or the startup application.

I would like to keep working with this method to load assemblies at runtime, but since I am working with a lot of DataSets being able to use the DataSet Visualizer is crucial for me.

Any suggestions?

edit: usage of dataset visualizer during debugging:

Body:
Not an elegant solution, but as a workaround to unblock your debugging sessions, add the following to the beginning of the AssemblyResolve event handler:

#if DEBUG
    if (arg.Name.StartsWith("DataSetVisualizer"))
        return null;
#endif


问:
How to check internet connection in AngularJs
This is how I would check internet connection in vanilla javascript:

```<code>setInterval(function(){
    if(navigator.onLine){
        $("body").html("Connected.");
    }else{
        $("body").html("Not connected.");
    }
},1000);
</code>```

I have angular controllers and modules in my project. Where should I put the  code above? It should be executed in global context and not be assigned to a certain controller. Are there some kind of global controllers maybe?

答:
For Angular 2+ you can use ng-speed-test:

Just install:

```<code>npm install ng-speed-test --save
</code>```

Inject into your module:

```<code>import { SpeedTestModule } from 'ng-speed-test';

@NgModule({
   ...
   imports: [
       SpeedTestModule,
       ...
   ],
   ...
})
export class AppModule {}
</code>```

Use service to get speed:

```<code>import {SpeedTestService} from 'ng-speed-test';

@Injectable()
export class TechCheckService {
  constructor(
    private speedTestService:SpeedTestService
  ) {
    this.speedTestService.getMbps().subscribe(
      (speed) => {
        console.log('Your speed is ' + speed);
      }
    );
  }
}
</code>```

Body:
This is how I would check internet connection in vanilla javascript:

setInterval(function(){
    if(navigator.onLine){
        $("body").html("Connected.");
    }else{
        $("body").html("Not connected.");
    }
},1000);

I have angular controllers and modules in my project. Where should I put the  code above? It should be executed in global context and not be assigned to a certain controller. Are there some kind of global controllers maybe?

Body:
For Angular 2+ you can use ng-speed-test:

Just install:

npm install ng-speed-test --save

Inject into your module:

import { SpeedTestModule } from 'ng-speed-test';

@NgModule({
   ...
   imports: [
       SpeedTestModule,
       ...
   ],
   ...
})
export class AppModule {}

Use service to get speed:

import {SpeedTestService} from 'ng-speed-test';

@Injectable()
export class TechCheckService {
  constructor(
    private speedTestService:SpeedTestService
  ) {
    this.speedTestService.getMbps().subscribe(
      (speed) => {
        console.log('Your speed is ' + speed);
      }
    );
  }
}


问:
Configuring Rails App to handle multiple subdomains and multiple cookies
I have a rails app which supports multiple domains and each domain may have multiple subdomains.

Users visiting mydomain1.com do not receive the same experience as mydomain2.com (although the base behaviour of the apps is the same)

Therefore, if a user is logged in to mydomain1.com, it shouldn't then be logged in to mydomain2.com

If a user is logged in to france.mydomain1.com, it should then be logged in to germany.mydomain1.com

Previously, I've handled this by setting the domain in the session store configs:

```<code>MyApp::Application.config.session_store :cookie_store, :key => '_MyApp_session', :domain => APP_CONFIG[:domain]
</code>```

I'm trying to work out the best way to handle this with multiple domains?

I've tried hacking around ActionDispatch::Callback but the request is not available from within there.

Can anybody suggest a good way of supporting multiple cookies from within one app?

Ideally I'd like to create a fresh cookie for each subdomain.

答:
You should do that:

```<code>class ActionDispatch::Session::MultiDomainStore < ActionDispatch::Session::CookieStore
  def initialize(app, options = {})
    super(app, options.merge!(:domain => compute_domain(app)))
  end

  def compute_domain(app)
    ...
  end
end

MyApp::Application.config.session_store :multi_domain_store, :key => '_MyApp_session'
</code>```

I.e. your domain should start with the dot.

Body:
I have a rails app which supports multiple domains and each domain may have multiple subdomains.

Users visiting mydomain1.com do not receive the same experience as mydomain2.com (although the base behaviour of the apps is the same)

Therefore, if a user is logged in to mydomain1.com, it shouldn't then be logged in to mydomain2.com

If a user is logged in to france.mydomain1.com, it should then be logged in to germany.mydomain1.com

Previously, I've handled this by setting the domain in the session store configs:

MyApp::Application.config.session_store :cookie_store, :key => '_MyApp_session', :domain => APP_CONFIG[:domain]

I'm trying to work out the best way to handle this with multiple domains?

I've tried hacking around ActionDispatch::Callback but the request is not available from within there.

Can anybody suggest a good way of supporting multiple cookies from within one app?

Ideally I'd like to create a fresh cookie for each subdomain.

Body:
You should do that:

class ActionDispatch::Session::MultiDomainStore < ActionDispatch::Session::CookieStore
  def initialize(app, options = {})
    super(app, options.merge!(:domain => compute_domain(app)))
  end

  def compute_domain(app)
    ...
  end
end

MyApp::Application.config.session_store :multi_domain_store, :key => '_MyApp_session'

I.e. your domain should start with the dot.


问:
Failed for buildpack
I am trying to run a python file on my heroku. I tried not setting a build pack as well as setting one and neither seems to work. The only files in my branch are a .py and the .git folder
Here is an error example:</p>

```<code>Enumerating objects: 3, done.
Counting objects: 100% (3/3), done.
Delta compression using up to 4 threads
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 590 bytes | 590.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote:  !     No default language could be detected for this app.
remote:                         HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically.
remote:                         See https://devcenter.heroku.com/articles/buildpacks
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !       Push rejected to google-results.
remote:
</code>```

答:
https://elements.heroku.com/buildpacks/heroku/heroku-buildpack-python

You need the following 2 files additionally in your git repo: runtime.txt and requirements.txt

runtime.txt is responsible for which Python version your program is going to use.

```<code>cat runtime.txt
python-3.7.2
</code>```

supported runtime.txt version changes from time to time so check out https://devcenter.heroku.com/articles/python-runtimes

requirements.txt is needed to specify which libraries from https://pypi.org/ your project is depending on. Be sure to specify a version to avoid breakage.

You can get a list of your currently installed python libraries with the command: python -m pip freeze > requirements.txt

Title: Failed for buildpack

Body:
I am trying to run a python file on my heroku. I tried not setting a build pack as well as setting one and neither seems to work. The only files in my branch are a .py and the .git folder
Here is an error example:

Enumerating objects: 3, done.
Counting objects: 100% (3/3), done.
Delta compression using up to 4 threads
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 590 bytes | 590.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote:  !     No default language could be detected for this app.
remote:                         HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically.
remote:                         See https://devcenter.heroku.com/articles/buildpacks
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !       Push rejected to google-results.
remote:

Body:
https://elements.heroku.com/buildpacks/heroku/heroku-buildpack-python

You need the following 2 files additionally in your git repo: runtime.txt and requirements.txt

runtime.txt is responsible for which Python version your program is going to use.

cat runtime.txt
python-3.7.2

supported runtime.txt version changes from time to time so check out https://devcenter.heroku.com/articles/python-runtimes

requirements.txt is needed to specify which libraries from https://pypi.org/ your project is depending on. Be sure to specify a version to avoid breakage.

You can get a list of your currently installed python libraries with the command: python -m pip freeze > requirements.txt


问:
Should I use GitHub OAuth or a GitHub App?
I'm building a nodejs command-line tool which takes the output from a client and pushes it to a GitHub repo and raise a PR.

The purpose behind it is that our users need to produce something that our team can process as code but our users are not coders, therefore they only need to complete a form and the code will be created for them. When they submit the form it will give them a preview of the code (on the off chance they know what they are doing but mostly to make them feel like coders) but in the background, it will push that code to a repo and raise a PR so we as developers get alerted to the new code. GitHub is being used for version-control and diffing abilities and is a specific request from the powers that be.

The users will not have GitHub accounts and really shouldn't even need to be aware that any GitHub stuff is happening so we don't want them to have to authenticate, instead we'd want the server itself to authenticate with GitHub using a token.

My question is, should it be an oAuth token or a GitHub app token? Apologies if it's a dumb question, not worked with Octokit before.

答:
i am also facing same situation.

what i read about OAuth App is if you want to use third application and using github identity to sign in . In this case you use OAUTH app.

While Github APP, if you want to access the github organisation repo or github user specific stuff.

Please correct me.Also share your scenario for more understanding.


问:
How to apply the eye Ball Rotation using ARKit in iOS from FaceTracking
I am using ARKit's ARFaceTrackingConfiguration to track the facial blendshapes along with left and right Eye Transforms. I am exporting this data into json and apply this data on 3d model ( which preconfigured shape keys, eye nodes). I was able to apply the blend shape data, but I got struck at how to apply the eye rotations. am getting leftEyeTransform, rightEyeTransform which is simd_float4*4 from FaceAnchor.

Here how to apply the rotation on eye nodes from the transform values.I believe for eyes, it is enough to apply the rotation.

I have tried with the below to get the orientation from eyeTransforms:

Method 1:

```<code>let faceNode = SCNNode()
faceNode.simdTransform = eyeTransform
let vector = faceNode.eulerAngles
eyeLeftNode.eulerAngles = vector
</code>```

Method:2

```<code>let faceNode = SCNNode()
faceNode.simdTransform = eyeTransform
let rotation = vector_float3(faceNode.orientation.x,faceNode.orientation.y,faceNode.orientaton.z)
let yaw = (rotation.y)
let pitch = (rotation.x)
let roll = (rotation.z)
let vector = SCNVector3(pitch, yaw, roll)

eyeLeftNode.eulerAngles = vector
</code>```

Method: 3

```<code>let simd_quatf = simd_quaternion(eyeTransform)
let vector = SCNVector3(simd_quatf.axis.x,simd_quatf.axis.y,simd_quatf.axis.z)

eyeLeftNode.eulerAngles = vector
</code>```

None of the ways are working. I am not able to figure out the actual problem on how to rotate the eyeBalls. Can you please tell me how to do this

Thanks,
Chaitanya

答:
I use the following two extensions in my apps for simd_float4x4 translation and orientation components if that's all you need:

```<code>extension float4x4 {
    var translation: SIMD3<Float> {
        let translation = columns.3
        return SIMD3<Float>(translation.x, translation.y, translation.z)
    }

    /**
     Factors out the orientation component of the transform.
    */
    var orientation: simd_quatf {
        return simd_quaternion(self)
    }
}
</code>```

Body:
I am using ARKit's ARFaceTrackingConfiguration to track the facial blendshapes along with left and right Eye Transforms. I am exporting this data into json and apply this data on 3d model ( which preconfigured shape keys, eye nodes). I was able to apply the blend shape data, but I got struck at how to apply the eye rotations. am getting leftEyeTransform, rightEyeTransform which is simd_float4*4 from FaceAnchor.

Here how to apply the rotation on eye nodes from the transform values.I believe for eyes, it is enough to apply the rotation.

I have tried with the below to get the orientation from eyeTransforms:

Method 1:

let faceNode = SCNNode()
faceNode.simdTransform = eyeTransform
let vector = faceNode.eulerAngles
eyeLeftNode.eulerAngles = vector

Method:2

let faceNode = SCNNode()
faceNode.simdTransform = eyeTransform
let rotation = vector_float3(faceNode.orientation.x,faceNode.orientation.y,faceNode.orientaton.z)
let yaw = (rotation.y)
let pitch = (rotation.x)
let roll = (rotation.z)
let vector = SCNVector3(pitch, yaw, roll)

eyeLeftNode.eulerAngles = vector

Method: 3

let simd_quatf = simd_quaternion(eyeTransform)
let vector = SCNVector3(simd_quatf.axis.x,simd_quatf.axis.y,simd_quatf.axis.z)

eyeLeftNode.eulerAngles = vector

None of the ways are working. I am not able to figure out the actual problem on how to rotate the eyeBalls. Can you please tell me how to do this

Thanks,
Chaitanya

Body:
I use the following two extensions in my apps for simd_float4x4 translation and orientation components if that's all you need:

extension float4x4 {
    var translation: SIMD3<Float> {
        let translation = columns.3
        return SIMD3<Float>(translation.x, translation.y, translation.z)
    }

    /**
     Factors out the orientation component of the transform.
    */
    var orientation: simd_quatf {
        return simd_quaternion(self)
    }
}


问:
How to resolve upgrade exception in guidewire
When I started the server in guidewire CC I got this error.

com.guidewire.pl.system.exception.UpgradeException: Encryption has been removed or changed, but the OldEncryption plugin is not defined. Please see your documentation for details on encryption upgrade.

Please help me to resolve this error.

答:
I found this was due to my not having the extensions.properties file updated to the latest number.  To fix:

Hit Cntl-Shift-n

Search for "extension.properties"

Go into the file and change the number to the appropriate number

Save

Restart Guidewire Studio

I was set after I did this.


问:
When to use Transactions in SQL Server
There are lots and lots of questions on HOW to use Transactions. What I want to know is WHEN? Under what circumstances? What types of queries? Can Try-Catch blocks suffice instead? Etc...

I've designed a database with ~20 tables and ~20 stored procedures. Currently none of my SPs use a transaction, but there are numerous Try-Catch blocks throughout. The reason is because every time I tried to wrap them in a transaction the SP would cease to function and I would end up with missing data and worse off than had I used Trans.

So again...

When is an appropriate time to use a Transaction?

As a follow-up question, if I use them, how can I use them in such a way as to ONLY prevent other SPs from accessing the same data at the same time in order to prevent corruption rather than causing my SPs to not function at all?

Here's a little sample SP I wrote for renaming a product:

CREATE PROCEDURE spRenameProduct
    @pKey int = NULL,
    @pName varchar(50)
AS
BEGIN
    BEGIN TRY
        IF LTRIM(RTRIM(@pName)) = '' SET @pName = NULL
        IF NOT @pKey IS NULL AND NOT @pName IS NULL BEGIN
            declare @pKeyExisting int = (select MIN(ID) from rProduct where Product like @pName and not ID = @pKey)
            IF @pKeyExisting is null BEGIN
                update rProduct set IsValid = 1, Product = @pName where ID = @pKey
            END ELSE BEGIN
                update Request set ProductID = @pKeyExisting where ProductID = @pKey
                update StatusReport set ProductID = @pKeyExisting where ProductID = @pKey
                delete from rProduct where ID = @pKey
            END
        END
    END TRY BEGIN CATCH END CATCH
END
```

Now what if two people were using this at the exact same time? I really don't want to, nor do I have time (unfortunately), to get to fancy. K.I.S.S. is best in this case. :)

答: Simple answer is to use transactions if you have more than 1 update or insert query in a single operation/function.</p>

Title: When to use Transactions in SQL Server

Body:
There are lots and lots of questions on HOW to use Transactions. What I want to know is WHEN? Under what circumstances? What types of queries? Can Try-Catch blocks suffice instead? Etc...

I've designed a database with ~20 tables and ~20 stored procedures. Currently none of my SPs use a transaction, but there are numerous Try-Catch blocks throughout. The reason is because every time I tried to wrap them in a transaction the SP would cease to function and I would end up with missing data and worse off than had I used Trans.

So again...

When is an appropriate time to use a Transaction?

As a follow-up question, if I use them, how can I use them in such a way as to ONLY prevent other SPs from accessing the same data at the same time in order to prevent corruption rather than causing my SPs to not function at all?

Here's a little sample SP I wrote for renaming a product:

CREATE PROCEDURE spRenameProduct
    @pKey int = NULL,
    @pName varchar(50)
AS
BEGIN
    BEGIN TRY
        IF LTRIM(RTRIM(@pName)) = '' SET @pName = NULL
        IF NOT @pKey IS NULL AND NOT @pName IS NULL BEGIN
            declare @pKeyExisting int = (select MIN(ID) from rProduct where Product like @pName and not ID = @pKey)
            IF @pKeyExisting is null BEGIN
                update rProduct set IsValid = 1, Product = @pName where ID = @pKey
            END ELSE BEGIN
                update Request set ProductID = @pKeyExisting where ProductID = @pKey
                update StatusReport set ProductID = @pKeyExisting where ProductID = @pKey
                delete from rProduct where ID = @pKey
            END
        END
    END TRY BEGIN CATCH END CATCH
END

Now what if two people were using this at the exact same time? I really don't want to, nor do I have time (unfortunately), to get to fancy. K.I.S.S. is best in this case. :)


问:
iPhone App :How to play Youtube video in app using MPMoviePlayerController
iPhone App :How to play Youtube video in app using MPMoviePlayerController

for that  i write the code:

```<code> NSString *urlAddress = @"http://www.youtube.com/xyz";
 NSLog(@"URL ADDress : %@",urlAddress);

 //Create a URL object.
  NSURL *url = [NSURL URLWithString:urlAddress];

movie = [[MPMoviePlayerController alloc] initWithContentURL:url];
movie.scalingMode=MPMovieScalingModeAspectFill;
    movie.view.frame = CGRectMake(0.0, 0.0, 320.0, 460.0);
[self.view addSubview:movie.view];
[movie play];
</code>```

if i pass the url of local directory it is playing video

```<code> NSString* filePath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"Video.mp4"];
NSURL* url = [[[NSURL alloc] initFileURLWithPath:filePath] autorelease];
</code>```

How can I play video directly from youtube url to MPMoviePlayerController?

答:
There is a great thread that on IphoneDevSDk.

They work with a hidden UIWebView:
http://www.iphonedevsdk.com/forum/iphone-sdk-development/61447-how-play-youtube-movie.html

Body:
iPhone App :How to play Youtube video in app using MPMoviePlayerController

for that  i write the code:

 NSString *urlAddress = @"http://www.youtube.com/xyz";
 NSLog(@"URL ADDress : %@",urlAddress);

 //Create a URL object.
  NSURL *url = [NSURL URLWithString:urlAddress];

movie = [[MPMoviePlayerController alloc] initWithContentURL:url];
movie.scalingMode=MPMovieScalingModeAspectFill;
    movie.view.frame = CGRectMake(0.0, 0.0, 320.0, 460.0);
[self.view addSubview:movie.view];
[movie play];

if i pass the url of local directory it is playing video

 NSString* filePath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"Video.mp4"];
NSURL* url = [[[NSURL alloc] initFileURLWithPath:filePath] autorelease];

How can I play video directly from youtube url to MPMoviePlayerController?


问:
Print Array in Text View
I have small challenge that I do not know how to overcome.
From a Firebase Database, I collect some data and I will like to print it out inside a "textview".

I have the flowing functional method

```<code> private void collect_comments(Map<String,Object> users) {

        ArrayList<String> fetch_title = new ArrayList<>();

        //iterate through each user, ignoring their UID
        for (Map.Entry<String, Object> entry : users.entrySet()) {

            //Get user map
            Map title = (Map) entry.getValue();
            Map msg = (Map) entry.getValue();
            //Get phone field and append to list
            fetch_title.add((String) title.get("post_title"));// Student X says:
            fetch_title.add((String) msg.get("message")); // the message

            post_update.setText(fetch_title.toString());

        }//end of for loop
</code>```

My problem is the current output:

```<code>Student Billy Bob says: Hello World Student Jony Jhon says: Hello Back Student Ben Dover says: I can not read this
</code>```

Help me please to format my output into:
Student Billy Bob says: Hello World
Student Jony Jhon says: Hello Back
Student Ben Dover says: I can not read this

As you can see, "Student Billy Bob says: " represents the "post_title" and "Hello World" is the "message". I will like to insert a new line after every "post_title" +"message".

I manage something close with the fallowing:

```<code>for(String s : fetch_title) {
    System.out.println(s);
}
</code>```

The only problem is that I do not know how to transpose the System.out.println into "textview".

I tried also with:

```<code>for(String s : fetch_title) {
                post_update.setText(s);
            }
</code>```

The output is only one line (Student Billy Bob says: Hello World) given that I added the "singleline=false" and "minlines=1" into my xml.

```<code><TextView
    android:id="@+id/tvValue"
    android:layout_width="408dp"
    android:layout_height="502dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:singleLine="false"
    android:minLines="1"
    />
</code>```

Please help me with this. Where I do wrong? The java? the XML?

答:
I think I understand what you are asking, to add a new line character add "\n" to the system.out.println or setText

```<code>System.out.println(s + "\n");
</code>```

or

post_update.setText(s + "\n");

Title: Print Array in Text View

Body:
I have small challenge that I do not know how to overcome.
From a Firebase Database, I collect some data and I will like to print it out inside a "textview".

I have the flowing functional method

 private void collect_comments(Map<String,Object> users) {

        ArrayList<String> fetch_title = new ArrayList<>();

        //iterate through each user, ignoring their UID
        for (Map.Entry<String, Object> entry : users.entrySet()) {

            //Get user map
            Map title = (Map) entry.getValue();
            Map msg = (Map) entry.getValue();
            //Get phone field and append to list
            fetch_title.add((String) title.get("post_title"));// Student X says:
            fetch_title.add((String) msg.get("message")); // the message

            post_update.setText(fetch_title.toString());

        }//end of for loop

My problem is the current output:

Student Billy Bob says: Hello World Student Jony Jhon says: Hello Back Student Ben Dover says: I can not read this

Help me please to format my output into:
Student Billy Bob says: Hello World
Student Jony Jhon says: Hello Back
Student Ben Dover says: I can not read this

As you can see, "Student Billy Bob says: " represents the "post_title" and "Hello World" is the "message". I will like to insert a new line after every "post_title" +"message".

I manage something close with the fallowing:

for(String s : fetch_title) {
    System.out.println(s);
}

The only problem is that I do not know how to transpose the System.out.println into "textview".

I tried also with:

for(String s : fetch_title) {
                post_update.setText(s);
            }

The output is only one line (Student Billy Bob says: Hello World) given that I added the "singleline=false" and "minlines=1" into my xml.

<TextView
    android:id="@+id/tvValue"
    android:layout_width="408dp"
    android:layout_height="502dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:singleLine="false"
    android:minLines="1"
    />

Please help me with this. Where I do wrong? The java? the XML?

Body:
I think I understand what you are asking, to add a new line character add "\n" to the system.out.println or setText

System.out.println(s + "\n");

or

post_update.setText(s + "\n");


问:
How can I get "if true" result from two other functions and use it in a third function?
I have a simple "if true" function where I need to get the result from two other currently working functions. I have been scouring SO and the internet to find nothing that actually works. I made two initial functions. The first one checks the date and the second checks the time. I want this third script to check to see if the other two functions resulted in true and if so, do something. The script is as follows:

$(function() {
  // attempted global variables but this did not work
  //var dateA = $('#startdate').val();
  //var dateB = $('#enddate').val();
  //var timeA = $('#starttime').val();
  //var timeB = $('#endtime').val();

  //This function appears to work
  $("#startdate, #enddate").on("change.apple", function() {
    var dateA = $('#startdate').val();
    var dateB = $('#enddate').val();

    if (((dateA).length && (dateB).length) && (dateA == dateB)) {
      alert("Apple");
      return true;
    } else {
      return false;
    }
  });

  //This function appears to work
  $("#starttime, #endtime").on("change.banana", function() {
    var timeA = $('#starttime').val();
    var timeB = $('#endtime').val();

    if (((timeA).length && (timeB).length) && (timeA >= timeB)) {
      alert("Banana");
      return true;
    } else {
      return false;
    }
  });

  //This function does NOT work
  $("#startdate, #enddate, #starttime, #endtime").change(function() {
    if (apple() && banana()) {
      // when its true
      alert("Hello");
    } else {
      // when its false
      alert("Goodbye");
    }
  });
});
```

<pre class="lang-html prettyprint-override"><code><form>
  <fieldset>
    <ul>
      <li>
        <p><input type="text" id="startdate"></p>
      </li>

      <li>
        <p><input type="text" id="starttime" </p>
      </li>

      <li>
        <p><input type="text" id="enddate" </p>
      </li>

      <li>
        <p><input type="text" id="endtime"></p>
      </li>
    </ul>
  </fieldset>
</form>
</code>```

I cleaned up the code for this question so it can be inspected easily. I have tried using global variables but for some reason I can not get the inner function to view the external variables. I have tried to check for errors in naming and and possible incorrect placement but I can not seem to locate the problem. Can anybody assist me in getting this script to work? I am lost at this point. Thanks

答:
just make the named functions -- like this:

```<code>$(function() {
  // attempted global variables but this did not work
  //var dateA = $('#startdate').val();
  //var dateB = $('#enddate').val();
  //var timeA = $('#starttime').val();
  //var timeB = $('#endtime').val();

 function apple() {
    var dateA = $('#startdate').val();
    var dateB = $('#enddate').val();

    if (((dateA).length && (dateB).length) && (dateA == dateB)) {
      alert("Apple");
      return true;
    } else {
      return false;
    }
  }

  //This function appears to work
  $("#startdate, #enddate").on("change.apple", apple);

  function banana() {
    var timeA = $('#starttime').val();
    var timeB = $('#endtime').val();

    if (((timeA).length && (timeB).length) && (timeA >= timeB)) {
      alert("Banana");
      return true;
    } else {
      return false;
    }
  }

  //This function appears to work
  $("#starttime, #endtime").on("change.banana", banana );

  //This function does NOT work
  $("#startdate, #enddate, #starttime, #endtime").change(function() {
    if (apple() && banana()) {
      // when its true
      alert("Hello");
    } else {
      // when its false
      alert("Goodbye");
    }
  });
});
</code>```

There is no magic to using anonymous functions... you can just use named ones instead.

Body:
I have a simple "if true" function where I need to get the result from two other currently working functions. I have been scouring SO and the internet to find nothing that actually works. I made two initial functions. The first one checks the date and the second checks the time. I want this third script to check to see if the other two functions resulted in true and if so, do something. The script is as follows:

$(function() {
  // attempted global variables but this did not work
  //var dateA = $('#startdate').val();
  //var dateB = $('#enddate').val();
  //var timeA = $('#starttime').val();
  //var timeB = $('#endtime').val();

  //This function appears to work
  $("#startdate, #enddate").on("change.apple", function() {
    var dateA = $('#startdate').val();
    var dateB = $('#enddate').val();

    if (((dateA).length && (dateB).length) && (dateA == dateB)) {
      alert("Apple");
      return true;
    } else {
      return false;
    }
  });

  //This function appears to work
  $("#starttime, #endtime").on("change.banana", function() {
    var timeA = $('#starttime').val();
    var timeB = $('#endtime').val();

    if (((timeA).length && (timeB).length) && (timeA >= timeB)) {
      alert("Banana");
      return true;
    } else {
      return false;
    }
  });

  //This function does NOT work
  $("#startdate, #enddate, #starttime, #endtime").change(function() {
    if (apple() && banana()) {
      // when its true
      alert("Hello");
    } else {
      // when its false
      alert("Goodbye");
    }
  });
});

<form>
  <fieldset>

<input type="text" id="startdate">

<input type="text" id="starttime"

<input type="text" id="enddate"

<input type="text" id="endtime">

  </fieldset>
</form>

I cleaned up the code for this question so it can be inspected easily. I have tried using global variables but for some reason I can not get the inner function to view the external variables. I have tried to check for errors in naming and and possible incorrect placement but I can not seem to locate the problem. Can anybody assist me in getting this script to work? I am lost at this point. Thanks

Body:
just make the named functions -- like this:

$(function() {
  // attempted global variables but this did not work
  //var dateA = $('#startdate').val();
  //var dateB = $('#enddate').val();
  //var timeA = $('#starttime').val();
  //var timeB = $('#endtime').val();

 function apple() {
    var dateA = $('#startdate').val();
    var dateB = $('#enddate').val();

    if (((dateA).length && (dateB).length) && (dateA == dateB)) {
      alert("Apple");
      return true;
    } else {
      return false;
    }
  }

  //This function appears to work
  $("#startdate, #enddate").on("change.apple", apple);

  function banana() {
    var timeA = $('#starttime').val();
    var timeB = $('#endtime').val();

    if (((timeA).length && (timeB).length) && (timeA >= timeB)) {
      alert("Banana");
      return true;
    } else {
      return false;
    }
  }

  //This function appears to work
  $("#starttime, #endtime").on("change.banana", banana );

  //This function does NOT work
  $("#startdate, #enddate, #starttime, #endtime").change(function() {
    if (apple() && banana()) {
      // when its true
      alert("Hello");
    } else {
      // when its false
      alert("Goodbye");
    }
  });
});

There is no magic to using anonymous functions... you can just use named ones instead.


问:
How can I copy the output of a command directly into my clipboard?
How can I pipe the output of a command into my clipboard and paste it back when using a terminal? For instance:</p>

```<code>cat file | clipboard
</code>```

答:
I usually run this command when I have to copy my ssh-key:

```<code>cat ~/.ssh/id_rsa.pub | pbcopy
</code>```

cmd+v or ctrl+v anywhere else.

Body:
How can I pipe the output of a command into my clipboard and paste it back when using a terminal? For instance:

cat file | clipboard

Body:
I usually run this command when I have to copy my ssh-key:

cat ~/.ssh/id_rsa.pub | pbcopy

cmd+v or ctrl+v anywhere else.