问:
Json apparently broken by running Python code
I am using the Googletrans API for python, which Google translates any given input string with optional specification of target and source languages.

My problem: after using it as a part of a code to process many lines of dialogue transcription line by line, I seem to have broken something that has to do with Json and now the API refuses to run.

An example piece of code, which ran perfectly before but now throws the following error:

```<code>from googletrans import Translator
translator = Translator()
translator.translate('안녕하세요.')
</code>```

```<code>---------------------------------------------------------------------------
JSONDecodeError                           Traceback (most recent call last)
<ipython-input-1-2a9f8e95ca66> in <module>
      1 from googletrans import Translator
      2 translator = Translator()
----> 3 translator.translate('안녕하세요.')

/usr/local/anaconda3/lib/python3.7/site-packages/googletrans/client.py in translate(self, text, dest, src)
    170
    171         origin = text
--> 172         data = self._translate(text, dest, src)
    173
    174         # this code will be updated when the format is changed.

/usr/local/anaconda3/lib/python3.7/site-packages/googletrans/client.py in _translate(self, text, dest, src)
     79         r = self.session.get(url, params=params)
     80
---> 81         data = utils.format_json(r.text)
     82         return data
     83

/usr/local/anaconda3/lib/python3.7/site-packages/googletrans/utils.py in format_json(original)
     60         converted = json.loads(original)
     61     except ValueError:
---> 62         converted = legacy_format_json(original)
     63
     64     return converted

/usr/local/anaconda3/lib/python3.7/site-packages/googletrans/utils.py in legacy_format_json(original)
     52             text = text[:p] + states[j][1] + text[nxt:]
     53
---> 54     converted = json.loads(text)
     55     return converted
     56

/usr/local/anaconda3/lib/python3.7/json/__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    346             parse_int is None and parse_float is None and
    347             parse_constant is None and object_pairs_hook is None and not kw):
--> 348         return _default_decoder.decode(s)
    349     if cls is None:
    350         cls = JSONDecoder

/usr/local/anaconda3/lib/python3.7/json/decoder.py in decode(self, s, _w)
    335
    336         """
--> 337         obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    338         end = _w(s, end).end()
    339         if end != len(s):

/usr/local/anaconda3/lib/python3.7/json/decoder.py in raw_decode(self, s, idx)
    353             obj, end = self.scan_once(s, idx)
    354         except StopIteration as err:
--> 355             raise JSONDecodeError("Expecting value", s, err.value) from None
    356         return obj, end

JSONDecodeError: Expecting value: line 1 column 1 (char 0)
</code>```

What might have happened and what might be done to fix it?

答:
I read the PyPI documentation of googletrans 2.4.0

It mentions the following

The maximum character limit on a single text is 15k.

Due to limitations of the web version of google translate, this API does not guarantee that the library would work properly at all times (so please use this library if you don’t care about stability).

Probably the text you are translating is too long. Thus, throwing the error.

Body:
I am using the Googletrans API for python, which Google translates any given input string with optional specification of target and source languages.

My problem: after using it as a part of a code to process many lines of dialogue transcription line by line, I seem to have broken something that has to do with Json and now the API refuses to run.

An example piece of code, which ran perfectly before but now throws the following error:

from googletrans import Translator
translator = Translator()
translator.translate('안녕하세요.')

---------------------------------------------------------------------------
JSONDecodeError                           Traceback (most recent call last)
<ipython-input-1-2a9f8e95ca66> in <module>
      1 from googletrans import Translator
      2 translator = Translator()
----> 3 translator.translate('안녕하세요.')

/usr/local/anaconda3/lib/python3.7/site-packages/googletrans/client.py in translate(self, text, dest, src)
    170
    171         origin = text
--> 172         data = self._translate(text, dest, src)
    173
    174         # this code will be updated when the format is changed.

/usr/local/anaconda3/lib/python3.7/site-packages/googletrans/client.py in _translate(self, text, dest, src)
     79         r = self.session.get(url, params=params)
     80
---> 81         data = utils.format_json(r.text)
     82         return data
     83

/usr/local/anaconda3/lib/python3.7/site-packages/googletrans/utils.py in format_json(original)
     60         converted = json.loads(original)
     61     except ValueError:
---> 62         converted = legacy_format_json(original)
     63
     64     return converted

/usr/local/anaconda3/lib/python3.7/site-packages/googletrans/utils.py in legacy_format_json(original)
     52             text = text[:p] + states[j][1] + text[nxt:]
     53
---> 54     converted = json.loads(text)
     55     return converted
     56

/usr/local/anaconda3/lib/python3.7/json/__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    346             parse_int is None and parse_float is None and
    347             parse_constant is None and object_pairs_hook is None and not kw):
--> 348         return _default_decoder.decode(s)
    349     if cls is None:
    350         cls = JSONDecoder

/usr/local/anaconda3/lib/python3.7/json/decoder.py in decode(self, s, _w)
    335
    336         """
--> 337         obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    338         end = _w(s, end).end()
    339         if end != len(s):

/usr/local/anaconda3/lib/python3.7/json/decoder.py in raw_decode(self, s, idx)
    353             obj, end = self.scan_once(s, idx)
    354         except StopIteration as err:
--> 355             raise JSONDecodeError("Expecting value", s, err.value) from None
    356         return obj, end

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

What might have happened and what might be done to fix it?


来源: stackexchange

问:
Scrolling to the bottom of the WKWebView programmatically doesn't work
I had some legacy code that should be changed a bit to comply to Apple standards, actually to avoid using UIWebView and change it to WKWebView in order to be able to release the app regularly.

Code in that legacy part that was dedicated for the scrolling of the page to the bottom after loading it was like this, and it was absolutely functional:

```<code>    public func webViewDidFinishLoad(_ webView: UIWebView) {
        var scrollHeight: CGFloat = webView.scrollView.contentSize.height - webView.bounds.size.height
        if 0.0 > scrollHeight {
            scrollHeight = 0.0
        }
        webView.scrollView.setContentOffset(CGPoint.init(x: 0.0, y: scrollHeight), animated: true)
    }
</code>```

And since I had to get rid of UIWebView components from the app I adjusted the code like this.
Added the WebKit import, make my class conform to the WKNavigationDelegate protocol and set the delegate like this:
webView.navigationDelegate = self and implemented appropriate function as follows:

```<code>public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    var scrollHeight: CGFloat = webView.scrollView.contentSize.height - webView.bounds.size.height
    if 0.0 > scrollHeight {
        scrollHeight = 0.0
    }
    webView.scrollView.setContentOffset(CGPoint.init(x: 0.0, y: scrollHeight), animated: true)
}
</code>```

Right now I do not understand where I am making mistake when the WKWebView refuses to scroll the page to the bottom?

答:
Found the solution, removed the code I used and switched it to the following one:</p>

```<code>    public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
          webView.evaluateJavaScript("var scrollingElement = (document.scrollingElement || document.body); scrollingElement.scrollTop = scrollingElement.scrollHeight;")
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I had some legacy code that should be changed a bit to comply to Apple standards, actually to avoid using UIWebView and change it to WKWebView in order to be able to release the app regularly.

Code in that legacy part that was dedicated for the scrolling of the page to the bottom after loading it was like this, and it was absolutely functional:

    public func webViewDidFinishLoad(_ webView: UIWebView) {
        var scrollHeight: CGFloat = webView.scrollView.contentSize.height - webView.bounds.size.height
        if 0.0 > scrollHeight {
            scrollHeight = 0.0
        }
        webView.scrollView.setContentOffset(CGPoint.init(x: 0.0, y: scrollHeight), animated: true)
    }

And since I had to get rid of UIWebView components from the app I adjusted the code like this.
Added the WebKit import, make my class conform to the WKNavigationDelegate protocol and set the delegate like this:
webView.navigationDelegate = self and implemented appropriate function as follows:

public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    var scrollHeight: CGFloat = webView.scrollView.contentSize.height - webView.bounds.size.height
    if 0.0 > scrollHeight {
        scrollHeight = 0.0
    }
    webView.scrollView.setContentOffset(CGPoint.init(x: 0.0, y: scrollHeight), animated: true)
}

Right now I do not understand where I am making mistake when the WKWebView refuses to scroll the page to the bottom?

Body:
Found the solution, removed the code I used and switched it to the following one:

    public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
          webView.evaluateJavaScript("var scrollingElement = (document.scrollingElement || document.body); scrollingElement.scrollTop = scrollingElement.scrollHeight;")
}


问:
TS2339: Property 'sort' does not exist on type 'BehaviorSubject<AbstractControl[]
I am looking to create a dynamic table using angular material where i can add/remove data dynamically.
Being very new to Angular , i have referred follwing stackblitz to create the table.

https://stackblitz.com/edit/angular-material-editable-table-fazhbc

While all my changes work - i am not able to sort the data at

```<code> ngAfterViewInit() {
    this.dataSource.sort = this.matSort;
  }
</code>```

The error i get
TS2339:  Property 'sort' does not exist on type 'BehaviorSubject<AbstractControl[]

is the sorting isn't supported like in material table data source or am i missing something ?

答: As BehaviorSubject return observable hence first subscribe that data then apply sort funct</p>

Body:
I am looking to create a dynamic table using angular material where i can add/remove data dynamically.
Being very new to Angular , i have referred follwing stackblitz to create the table.

https://stackblitz.com/edit/angular-material-editable-table-fazhbc

While all my changes work - i am not able to sort the data at

 ngAfterViewInit() {
    this.dataSource.sort = this.matSort;
  }

The error i get
TS2339:  Property 'sort' does not exist on type 'BehaviorSubject<AbstractControl[]

is the sorting isn't supported like in material table data source or am i missing something ?


问:
Google Sheets Query for Maximum Date
I have a table which I would like to return in its entirety but filtered by column H with the maximum date as rows have duplicate account numbers with different dates.

https://docs.google.com/spreadsheets/d/1x3hYy1igiL3_lqhFE3IwrQNFbOjdpXRtHLAbOXB2BE4/edit?usp=sharing

I'm using this query right now, but clearly I'm overlooking something, can anyone help, please?

```<code>=QUERY(B3:I12, "Select *, Max(H) WHERE B is not null Group by C")
</code>```

答:
The final formula was ={DataTable;SORTN(SORT(Data,17,0),99^99,2,2,1)}

DataTable is the headings and Data is the dataset. Out of 14,000 lines this filtered down to around 7,000 lines of unique rows with the highest (Maximum) date.

Title: Google Sheets Query for Maximum Date

Body:
I have a table which I would like to return in its entirety but filtered by column H with the maximum date as rows have duplicate account numbers with different dates.

https://docs.google.com/spreadsheets/d/1x3hYy1igiL3_lqhFE3IwrQNFbOjdpXRtHLAbOXB2BE4/edit?usp=sharing

I'm using this query right now, but clearly I'm overlooking something, can anyone help, please?

=QUERY(B3:I12, "Select *, Max(H) WHERE B is not null Group by C")


问:
How can convert System::Int32 to wchar_t*
I have this piece of code:

```<code>int casted_dbValue=3;
wchar_t* nativeData=(wchar_t*)casted_dbValue;
</code>```

it is incorrect conversion between int to const wchar_t*. How can deal with this error?

答:
Have you tried the _itow function?

```<code>wchar_t * _itow(
                int value,
                wchar_t *str,
                int radix
                );
</code>```

Or, the more secure version, _itow_s.

The first parameter (value) is the integer value to be converted, the second is the string result, and the third is the base of the numeric value. It returns a pointer to the str value.

ContentLicense: CC BY-SA 3.0

Body:
I have this piece of code:

int casted_dbValue=3;
wchar_t* nativeData=(wchar_t*)casted_dbValue;

it is incorrect conversion between int to const wchar_t*. How can deal with this error?

Body:
Have you tried the _itow function?

wchar_t * _itow(
                int value,
                wchar_t *str,
                int radix
                );

Or, the more secure version, _itow_s.

The first parameter (value) is the integer value to be converted, the second is the string result, and the third is the base of the numeric value. It returns a pointer to the str value.


问:
How can I create columns out of a nested dictionary in python pandas
I'm trying to filter my data frame by making separate columns to increase readability and usability.

Problem statement:
Column "Editables" has a nested dictionary as the value I'm trying to create separate columns as per the key. For instance 'photo_repace' 'text_remove', 'text_add' has different columns.

The nested dictionary:

```<code>{
'photo': {
    'photo_replace': None,
    'photo_remove': None,
    'photo_add': None,
    'photo_effect': None,
    'photo_brightness': None,
    'background_color': None,
    'photo_resize': None,
    'photo_rotate': None,
    'photo_mirror': None,
    'photo_layer_rearrange': None,
    'photo_move': None
},
'text': {
    'text_remove': None,
    'text_add': None,
    'text_edit': None,
    'font_select': None,
    'text_color': None,
    'text_style': None,
    'background_color': None,
    'text_align': None,
    'text_resize': None,
    'text_rotate': None,
    'text_move': None,
    'text_layer_rearrange': None
}
}

</code>```

Output

Code I've been using:

```<code>df["editables"] = df["editables"].apply(lambda x : dict(eval(x)))
df_edit = df["editables"].apply(pd.Series )
</code>```

Output:

答:
Try this:

```<code>>>> dct = {
'photo': {
    'photo_replace': None,
    'photo_remove': None,
    'photo_add': None,
    'photo_effect': None,
    'photo_brightness': None,
    'background_color': None,
    'photo_resize': None,
    'photo_rotate': None,
    'photo_mirror': None,
    'photo_layer_rearrange': None,
    'photo_move': None
},
'text': {
    'text_remove': None,
    'text_add': None,
    'text_edit': None,
    'font_select': None,
    'text_color': None,
    'text_style': None,
    'background_color': None,
    'text_align': None,
    'text_resize': None,
    'text_rotate': None,
    'text_move': None,
    'text_layer_rearrange': None
}
}
>>> pd.DataFrame(dct).T
       photo_replace  photo_remove  ...  text_move  text_layer_rearrange
photo            NaN           NaN  ...        NaN                   NaN
text             NaN           NaN  ...        NaN                   NaN

[2 rows x 22 columns]
>>> pd.DataFrame(dct).T[['photo_replace', 'photo_remove', 'text_remove']]
       photo_replace  photo_remove  text_remove
photo            NaN           NaN          NaN
text             NaN           NaN          NaN
</code>```

NOTE: .T transposes the dataframe.

Body:
I'm trying to filter my data frame by making separate columns to increase readability and usability.

Problem statement:
Column "Editables" has a nested dictionary as the value I'm trying to create separate columns as per the key. For instance 'photo_repace' 'text_remove', 'text_add' has different columns.

The nested dictionary:

{
'photo': {
    'photo_replace': None,
    'photo_remove': None,
    'photo_add': None,
    'photo_effect': None,
    'photo_brightness': None,
    'background_color': None,
    'photo_resize': None,
    'photo_rotate': None,
    'photo_mirror': None,
    'photo_layer_rearrange': None,
    'photo_move': None
},
'text': {
    'text_remove': None,
    'text_add': None,
    'text_edit': None,
    'font_select': None,
    'text_color': None,
    'text_style': None,
    'background_color': None,
    'text_align': None,
    'text_resize': None,
    'text_rotate': None,
    'text_move': None,
    'text_layer_rearrange': None
}
}

Output

Code I've been using:

df["editables"] = df["editables"].apply(lambda x : dict(eval(x)))
df_edit = df["editables"].apply(pd.Series )

Output:

Body:
Try this:

>>> dct = {
'photo': {
    'photo_replace': None,
    'photo_remove': None,
    'photo_add': None,
    'photo_effect': None,
    'photo_brightness': None,
    'background_color': None,
    'photo_resize': None,
    'photo_rotate': None,
    'photo_mirror': None,
    'photo_layer_rearrange': None,
    'photo_move': None
},
'text': {
    'text_remove': None,
    'text_add': None,
    'text_edit': None,
    'font_select': None,
    'text_color': None,
    'text_style': None,
    'background_color': None,
    'text_align': None,
    'text_resize': None,
    'text_rotate': None,
    'text_move': None,
    'text_layer_rearrange': None
}
}
>>> pd.DataFrame(dct).T
       photo_replace  photo_remove  ...  text_move  text_layer_rearrange
photo            NaN           NaN  ...        NaN                   NaN
text             NaN           NaN  ...        NaN                   NaN

[2 rows x 22 columns]
>>> pd.DataFrame(dct).T[['photo_replace', 'photo_remove', 'text_remove']]
       photo_replace  photo_remove  text_remove
photo            NaN           NaN          NaN
text             NaN           NaN          NaN

NOTE: .T transposes the dataframe.


问:
{Makefile Error} "commands commence before first target. Stop."
I'm trying to produce a makefile for use with my Raspberry Pi, the intention is to use the Pi's camera board to detect faces with opencv. However I keep facing myself  with the following error:

```<code>Makefile:12: *** commands commence before first target.  Stop.
</code>```

I use the following makefile:

```<code>FLAGS = 'pkg-config --cflags opencv --libs opencv'
CC = g++
HOME = /home/pi
LDFLAGS_CAMCV = -L$(HOME)/git/robidouille/raspicam_cv -lraspicamcv
LDFLAGS_USER =-L$(HOME)/git/raspberrypi/userland/build/lib -lmmal_core -lmmal -$
LDFLAGS_FACE = -l$(HOME)/git/emobot/libfacere0.04
LDFLAGS = $(LDFLAGS_CAMCV) $(LDFLAGS_USER)  $(LDFLAGS_FACE)
INCLUDE = -I$(HOME)/git/robidouille/raspicam_cv
        $(CC) -o emobot_test.exe:  main.cpp $(INCLUDE) $(LDFLAGS)
</code>```

LDFLAGS_CAMCV and LDFLAGS_USER are required for the raspicamcv library and INCLUDE is the associated header file. LDFLAGS_FACE is needed to detect faces in opencv2.3 as 2.4 is currently unsupported by the Pi.

I'm certain this error is incredibly trivial however clear documentation about makefiles is few and far between if anyone can provide a solution I would be grateful.

答:
I had the same issue ...

I already have rules for check, test and build...  but wanted to string them together...

Easy I thought...

```<code>.DEFAULT_GOAL := fullcheck
    $(MAKE) check
    $(MAKE) test
    $(MAKE) build
</code>```

But no commands commence before first target.  Stop.

What I had omitted was, the name of the rule. It should be like this.

```<code>.DEFAULT_GOAL := fullcheck
fullcheck:
    $(MAKE) check
    $(MAKE) test
    $(MAKE) build
</code>```

Body:
I'm trying to produce a makefile for use with my Raspberry Pi, the intention is to use the Pi's camera board to detect faces with opencv. However I keep facing myself  with the following error:

Makefile:12: *** commands commence before first target.  Stop.

I use the following makefile:

FLAGS = 'pkg-config --cflags opencv --libs opencv'
CC = g++
HOME = /home/pi
LDFLAGS_CAMCV = -L$(HOME)/git/robidouille/raspicam_cv -lraspicamcv
LDFLAGS_USER =-L$(HOME)/git/raspberrypi/userland/build/lib -lmmal_core -lmmal -$
LDFLAGS_FACE = -l$(HOME)/git/emobot/libfacere0.04
LDFLAGS = $(LDFLAGS_CAMCV) $(LDFLAGS_USER)  $(LDFLAGS_FACE)
INCLUDE = -I$(HOME)/git/robidouille/raspicam_cv
        $(CC) -o emobot_test.exe:  main.cpp $(INCLUDE) $(LDFLAGS)

LDFLAGS_CAMCV and LDFLAGS_USER are required for the raspicamcv library and INCLUDE is the associated header file. LDFLAGS_FACE is needed to detect faces in opencv2.3 as 2.4 is currently unsupported by the Pi.

I'm certain this error is incredibly trivial however clear documentation about makefiles is few and far between if anyone can provide a solution I would be grateful.

Body:
I had the same issue ...

I already have rules for check, test and build...  but wanted to string them together...

Easy I thought...

.DEFAULT_GOAL := fullcheck
    $(MAKE) check
    $(MAKE) test
    $(MAKE) build

But no commands commence before first target.  Stop.

What I had omitted was, the name of the rule. It should be like this.

.DEFAULT_GOAL := fullcheck
fullcheck:
    $(MAKE) check
    $(MAKE) test
    $(MAKE) build


问:
Could not load file or assembly 'Merged' or one of its dependencies
I am trying to start an iis site (asp.net mvc) which has worked perfectly before my changes. I have referenced some nuget-packages (nothing special, but some of them reference netstandard) and have done some minor code changes.
Now I am getting the error Could not load file or assembly 'Merged' or one of its dependencies with this stacktrace while trying to connect to the site:

```<code>[FileLoadException: Could not load file or assembly 'Merged' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
   System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
   System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +225
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +110
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +22
   System.Reflection.Assembly.Load(String assemblyString) +34
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +48

[ConfigurationErrorsException: Could not load file or assembly 'Merged' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +725
   System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +247
   System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +157
   System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +226
   System.Web.Compilation.BuildManager.GetPreStartInitMethodsFromReferencedAssemblies() +73
   System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +319
   System.Web.Compilation.BuildManager.ExecutePreAppStart() +170
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +820

[HttpException (0x80004005): Could not load file or assembly 'Merged' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +523
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +107
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +688
</code>```

I also provide assembly binding logs:

```<code>Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll
Running under executable  c:\windows\system32\inetsrv\w3wp.exe
--- A detailed error log follows.

=== Pre-bind state information ===
LOG: DisplayName = Merged
 (Partial)
WRN: Partial binding information was supplied for an assembly:
WRN: Assembly Name: Merged | Domain ID: 3
WRN: A partial bind occurs when only part of the assembly display name is provided.
WRN: This might result in the binder loading an incorrect assembly.
WRN: It is recommended to provide a fully specified textual identity for the assembly,
WRN: that consists of the simple name, version, culture, and public key token.
WRN: See whitepaper http://go.microsoft.com/fwlink/?LinkId=109270 for more information and common solutions to this issue.
LOG: Appbase = file:///C:/Proj/Test/FmsFront/
LOG: Initial PrivatePath = C:\Proj\Test\FmsFront\bin
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Proj\Test\ProjFront\web.config
LOG: Using host configuration file: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework64/v4.0.30319/Temporary ASP.NET Files/root/fcbbd808/fa43678c/Merged.DLL.
LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework64/v4.0.30319/Temporary ASP.NET Files/root/fcbbd808/fa43678c/Merged/Merged.DLL.
LOG: Attempting download of new URL file:///C:/Proj/Test/ProjFront/bin/Merged.DLL.
WRN: Comparing the assembly name resulted in the mismatch: NAME
ERR: Failed to complete setup of assembly (hr = 0x80131040). Probing terminated.
</code>```

I have looked around trying to find the dll with the name "Merged". But it seems to be partial assembly name. Also it looks like this error is thrown before my actual code starts.
I tried restoring packages. Also it works fine on local machine, but on the other server it fails.

How can I fix this error?

答:
So finally I figured it out. The problem was that one of the packages that I've installed took the netcoreapp dependency. But my application is netframework. So none of this netcoreapp library dependencies was put to the binary directory and this library could not be loaded. I found this Merged.dll in my app's binary folder and removed it. After that it works.

Now I am in contact with this package authors to find out why netcoreapp dependency was put in netframework app.

Body:
I am trying to start an iis site (asp.net mvc) which has worked perfectly before my changes. I have referenced some nuget-packages (nothing special, but some of them reference netstandard) and have done some minor code changes.
Now I am getting the error Could not load file or assembly 'Merged' or one of its dependencies with this stacktrace while trying to connect to the site:

[FileLoadException: Could not load file or assembly 'Merged' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
   System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
   System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +225
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +110
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +22
   System.Reflection.Assembly.Load(String assemblyString) +34
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +48

[ConfigurationErrorsException: Could not load file or assembly 'Merged' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +725
   System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +247
   System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +157
   System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +226
   System.Web.Compilation.BuildManager.GetPreStartInitMethodsFromReferencedAssemblies() +73
   System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +319
   System.Web.Compilation.BuildManager.ExecutePreAppStart() +170
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +820

[HttpException (0x80004005): Could not load file or assembly 'Merged' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +523
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +107
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +688

I also provide assembly binding logs:

Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll
Running under executable  c:\windows\system32\inetsrv\w3wp.exe
--- A detailed error log follows.

=== Pre-bind state information ===
LOG: DisplayName = Merged
 (Partial)
WRN: Partial binding information was supplied for an assembly:
WRN: Assembly Name: Merged | Domain ID: 3
WRN: A partial bind occurs when only part of the assembly display name is provided.
WRN: This might result in the binder loading an incorrect assembly.
WRN: It is recommended to provide a fully specified textual identity for the assembly,
WRN: that consists of the simple name, version, culture, and public key token.
WRN: See whitepaper http://go.microsoft.com/fwlink/?LinkId=109270 for more information and common solutions to this issue.
LOG: Appbase = file:///C:/Proj/Test/FmsFront/
LOG: Initial PrivatePath = C:\Proj\Test\FmsFront\bin
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Proj\Test\ProjFront\web.config
LOG: Using host configuration file: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework64/v4.0.30319/Temporary ASP.NET Files/root/fcbbd808/fa43678c/Merged.DLL.
LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework64/v4.0.30319/Temporary ASP.NET Files/root/fcbbd808/fa43678c/Merged/Merged.DLL.
LOG: Attempting download of new URL file:///C:/Proj/Test/ProjFront/bin/Merged.DLL.
WRN: Comparing the assembly name resulted in the mismatch: NAME
ERR: Failed to complete setup of assembly (hr = 0x80131040). Probing terminated.

I have looked around trying to find the dll with the name "Merged". But it seems to be partial assembly name. Also it looks like this error is thrown before my actual code starts.
I tried restoring packages. Also it works fine on local machine, but on the other server it fails.

How can I fix this error?


问:
Firebase functions.https.onCall returns null
I have the following firebase cloud function written in node.js that I call from my Android app.The function works fine but I get null when trying to get results in Android. I need return to my android app console.log(result.data); line, but that line called after firebase function completely done, so my Android app gets null.

index.js

```<code>'use strict'

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const subcheck = require('./subcheck');
admin.initializeApp();

exports.subcheck = functions.https.onCall((data, context) => {
    subcheck.verifySubscription(data, context);
});
</code>```

And this is my subcheck.js

```<code>'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const key =  require('./service-account-key.json'); // JSON key file
const {google} = require('googleapis');

const authClient = new google.auth.JWT({
    email: key.client_email,
    key: key.private_key,
    scopes: ["https://www.googleapis.com/auth/androidpublisher"]
});

const playDeveloperApiClient = google.androidpublisher({
    version: 'v3',
    auth: authClient
});

//admin.initializeApp(functions.config().firebase);

exports.verifySubscription = function(data, context) {
    const skuId = data.sku_id;
    const purchaseToken = data.purchase_token;
    const packageName = data.package_name;

    return authClient.authorize()
        .then(function(result) {
            return playDeveloperApiClient.purchases.subscriptions.get({
                packageName: packageName,
                subscriptionId: skuId,
                token: purchaseToken
            }).then(function(result) {
                if (result.status === 200) {
                    console.log(result.data);
                    return {
                        data: result.data,
                        status: 200,
                        message: "Verified Subscription"
                    };
                } else {
                    console.log("Failed to verify subscription, Try again!");
                    return {
                        data: result.data,
                        status: 500,
                        message: "Failed to verify subscription, Try again!"
                    };
                }
            })
            .catch(function(error) {
                console.log(error);
            });

        })
        .catch(function(error) {
            console.log(error);
        });

}
</code>```

This is my firebase functions console log:

I'm trying to get results in Android with the following method :

```<code>    private Task<String> checkUserSubscribed(PurchaseHistoryRecord purchase) {
    Map<String, Object> mapUserPurchase = new HashMap<>();
    mapUserPurchase.put("sku_id", purchase.getSku());
    mapUserPurchase.put("purchase_token", purchase.getPurchaseToken());
    mapUserPurchase.put("package_name", "xxxxxxx");

    return mFirebaseFunctions
            .getHttpsCallable("subcheck")
            .call(mapUserPurchase)
            .continueWith(new Continuation<HttpsCallableResult, String>() {
                @Override
                public String then(@NonNull Task<HttpsCallableResult> task) throws Exception {
                    String result = (String) task.getResult().getData();
                    return result;
                }
            }).addOnCompleteListener(new OnCompleteListener<String>() {
                @Override
                public void onComplete(@NonNull Task<String> task) {
                    String result = task.getResult();
                    Toast.makeText(MainActivity.this, "func results: " + result, Toast.LENGTH_SHORT).show();
                }
            });
}
</code>```

答:
The problem most probably comes from the fact that you don't return the result of the call to the verifySubscription() function in:

```<code>exports.subcheck = functions.https.onCall((data, context) => {
    subcheck.verifySubscription(data, context);
});
</code>```

You should do:

```<code>exports.subcheck = functions.https.onCall((data, context) => {
    return subcheck.verifySubscription(data, context);
});
</code>```

Also, you should probably re-organize your Promise chaining as follows, to avoid nesting the calls to then(), see more details/explanantions here.

```<code>exports.verifySubscription = function(data, context) {
    const skuId = data.sku_id;
    const purchaseToken = data.purchase_token;
    const packageName = data.package_name;

    return authClient.authorize()
        .then(result => {
            return playDeveloperApiClient.purchases.subscriptions.get({
                packageName: packageName,
                subscriptionId: skuId,
                token: purchaseToken
            })
        })
        .then(result => {
                if (result.status === 200) {
                    console.log(result.data);
                    return {
                        data: result.data,
                        status: 200,
                        message: "Verified Subscription"
                    };
                } else {
                    console.log("Failed to verify subscription, Try again!");
                    return {
                        data: result.data,
                        status: 500,
                        message: "Failed to verify subscription, Try again!"
                    };
                }
            })
        })
        .catch(function(error) {
            console.log(error);
        });

}
</code>```

Finally, you may have a look at the documentation on error handling in a Callable Cloud Function. Instead of returning {data: result.data,status: 500, ...}; you may throw an instance of functions.https.HttpsError.

Body:
I have the following firebase cloud function written in node.js that I call from my Android app.The function works fine but I get null when trying to get results in Android. I need return to my android app console.log(result.data); line, but that line called after firebase function completely done, so my Android app gets null.

index.js

'use strict'

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const subcheck = require('./subcheck');
admin.initializeApp();

exports.subcheck = functions.https.onCall((data, context) => {
    subcheck.verifySubscription(data, context);
});

And this is my subcheck.js

'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const key =  require('./service-account-key.json'); // JSON key file
const {google} = require('googleapis');

const authClient = new google.auth.JWT({
    email: key.client_email,
    key: key.private_key,
    scopes: ["https://www.googleapis.com/auth/androidpublisher"]
});

const playDeveloperApiClient = google.androidpublisher({
    version: 'v3',
    auth: authClient
});

//admin.initializeApp(functions.config().firebase);

exports.verifySubscription = function(data, context) {
    const skuId = data.sku_id;
    const purchaseToken = data.purchase_token;
    const packageName = data.package_name;

    return authClient.authorize()
        .then(function(result) {
            return playDeveloperApiClient.purchases.subscriptions.get({
                packageName: packageName,
                subscriptionId: skuId,
                token: purchaseToken
            }).then(function(result) {
                if (result.status === 200) {
                    console.log(result.data);
                    return {
                        data: result.data,
                        status: 200,
                        message: "Verified Subscription"
                    };
                } else {
                    console.log("Failed to verify subscription, Try again!");
                    return {
                        data: result.data,
                        status: 500,
                        message: "Failed to verify subscription, Try again!"
                    };
                }
            })
            .catch(function(error) {
                console.log(error);
            });

        })
        .catch(function(error) {
            console.log(error);
        });

}

This is my firebase functions console log:

I'm trying to get results in Android with the following method :

    private Task<String> checkUserSubscribed(PurchaseHistoryRecord purchase) {
    Map<String, Object> mapUserPurchase = new HashMap<>();
    mapUserPurchase.put("sku_id", purchase.getSku());
    mapUserPurchase.put("purchase_token", purchase.getPurchaseToken());
    mapUserPurchase.put("package_name", "xxxxxxx");

    return mFirebaseFunctions
            .getHttpsCallable("subcheck")
            .call(mapUserPurchase)
            .continueWith(new Continuation<HttpsCallableResult, String>() {
                @Override
                public String then(@NonNull Task<HttpsCallableResult> task) throws Exception {
                    String result = (String) task.getResult().getData();
                    return result;
                }
            }).addOnCompleteListener(new OnCompleteListener<String>() {
                @Override
                public void onComplete(@NonNull Task<String> task) {
                    String result = task.getResult();
                    Toast.makeText(MainActivity.this, "func results: " + result, Toast.LENGTH_SHORT).show();
                }
            });
}

Body:
The problem most probably comes from the fact that you don't return the result of the call to the verifySubscription() function in:

exports.subcheck = functions.https.onCall((data, context) => {
    subcheck.verifySubscription(data, context);
});

You should do:

exports.subcheck = functions.https.onCall((data, context) => {
    return subcheck.verifySubscription(data, context);
});

Also, you should probably re-organize your Promise chaining as follows, to avoid nesting the calls to then(), see more details/explanantions here.

exports.verifySubscription = function(data, context) {
    const skuId = data.sku_id;
    const purchaseToken = data.purchase_token;
    const packageName = data.package_name;

    return authClient.authorize()
        .then(result => {
            return playDeveloperApiClient.purchases.subscriptions.get({
                packageName: packageName,
                subscriptionId: skuId,
                token: purchaseToken
            })
        })
        .then(result => {
                if (result.status === 200) {
                    console.log(result.data);
                    return {
                        data: result.data,
                        status: 200,
                        message: "Verified Subscription"
                    };
                } else {
                    console.log("Failed to verify subscription, Try again!");
                    return {
                        data: result.data,
                        status: 500,
                        message: "Failed to verify subscription, Try again!"
                    };
                }
            })
        })
        .catch(function(error) {
            console.log(error);
        });

}

Finally, you may have a look at the documentation on error handling in a Callable Cloud Function. Instead of returning {data: result.data,status: 500, ...}; you may throw an instance of functions.https.HttpsError.


问:
Array loop always returning last value
I have the following loop:

```<code>var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];

var html = "";

for (let i = 0; i < array.length; i++) {
  var html = "<div class='group' data-department='"+array[i]+"'>";
  html += "<div class='title'>" + textArray[i] + "</div>";
  html += "</div>";
}
</code>```

The output of this JS is:

```<code><div class="group" data-department="Value 3">
   <div class="title">Text 3</div>
</div>

<div class="group" data-department="Value 3">
   <div class="title">Text 3</div>
</div>

<div class="group" data-department="Value 3">
   <div class="title">Text 3</div>
</div>
</code>```

What I'm after is:

```<code><div class="group" data-department="Value 1">
   <div class="title">Text 1</div>
</div>

<div class="group" data-department="Value 2">
   <div class="title">Text 2</div>
</div>

<div class="group" data-department="Value 3">
   <div class="title">Text 3</div>
</div>
</code>```

A console.log("Value: " + array[i]); returns:

```<code>Value: Value 1
Value: Value 2
Value: Value 3
</code>```

And a console.log("Text: " + textArray[i]); returns:

```<code>Text: Text 1
Text: Text 2
Text: Text 3
</code>```

So unsure why my markup is being rendered based on the last item in the array?

Following the removal of var from with the loop, I'm getting the following results (container divs get nested within each other):

var html = "";

for (let i = 0; i < array.length; i++) {
  html += "
";
  html += "
" + textArray[i] + "
";
  html += "
";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="group" data-department="Value 1">
  <div class="title">Text 1</div>
  <div class="group" data-department="Value 2">
    <div class="title">Text 2</div>
    <div class="group" data-department="Value 3">
      <div class="title">Text 3</div>
    </div>
  </div>
</div></code>```

答:
You don't need the var html within the loop.

```<code>var array = ["Value 1", "Value 2", "Value 3"],
    textArray = ["Text 1", "Text 2", "Text 3"],
    html = "";

for (let i = 0; i < array.length; i++) {
  html += "<div class='group' data-department='"+array[i]+"'>";
  html += "<div class='title'>" + textArray[i] + "</div>";
  html += "</div>";
}
console.log(html);
</code>```

Title: Array loop always returning last value

Body:
I have the following loop:

var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];

var html = "";

for (let i = 0; i < array.length; i++) {
  var html = "
";
  html += "
" + textArray[i] + "
";
  html += "
";
}

The output of this JS is:

Text 3

Text 3

Text 3

What I'm after is:

Text 1

Text 2

Text 3

A console.log("Value: " + array[i]); returns:

Value: Value 1
Value: Value 2
Value: Value 3

And a console.log("Text: " + textArray[i]); returns:

Text: Text 1
Text: Text 2
Text: Text 3

So unsure why my markup is being rendered based on the last item in the array?

Following the removal of var from with the loop, I'm getting the following results (container divs get nested within each other):

var html = "";

for (let i = 0; i < array.length; i++) {
  html += "
";
  html += "
" + textArray[i] + "
";
  html += "
";
}

Text 1

Text 2

Text 3

Body:
You don't need the var html within the loop.

var array = ["Value 1", "Value 2", "Value 3"],
    textArray = ["Text 1", "Text 2", "Text 3"],
    html = "";

for (let i = 0; i < array.length; i++) {
  html += "<div class='group' data-department='"+array[i]+"'>";
  html += "<div class='title'>" + textArray[i] + "</div>";
  html += "</div>";
}
console.log(html);


问:
Dictionary<StudentType, List<Student>> to IDictionary<StudentType, IList<Student>>?
Please consider the following code:

```<code>class Student
{
}

enum StudentType
{
}

static void foo(IDictionary<StudentType, IList<Student>> students)
{
}

static void Main(string[] args)
{
    Dictionary<StudentType, List<Student>> studentDict =
                     new Dictionary<StudentType, List<Student>>();

    foo(studentDict);

    ...
}
</code>```

There is the error:

error CS1503: Argument '1': cannot
  convert from
  'System.Collections.Generic.Dictionary>'
  to
  'System.Collections.Generic.IDictionary>'

Is there any way to call foo function?

答:
You could use the Linq ToDictionary method to create a new dictionary where the value has the correct type:</p>

```<code>static void Main(string[] args)
{
  Dictionary<StudentType, List<Student>> studentDict = new Dictionary<StudentType, List<Student>>();
  var dicTwo = studentDict.ToDictionary(item => item.Key, item => (IList<Student>)item.Value);
  foo(dicTwo);
}
</code>```

Body:
Please consider the following code:

class Student
{
}

enum StudentType
{
}

static void foo(IDictionary<StudentType, IList<Student>> students)
{
}

static void Main(string[] args)
{
    Dictionary<StudentType, List<Student>> studentDict =
                     new Dictionary<StudentType, List<Student>>();

    foo(studentDict);

    ...
}

There is the error:

error CS1503: Argument '1': cannot
  convert from
  'System.Collections.Generic.Dictionary>'
  to
  'System.Collections.Generic.IDictionary>'

Is there any way to call foo function?

Body:
You could use the Linq ToDictionary method to create a new dictionary where the value has the correct type:

static void Main(string[] args)
{
  Dictionary<StudentType, List<Student>> studentDict = new Dictionary<StudentType, List<Student>>();
  var dicTwo = studentDict.ToDictionary(item => item.Key, item => (IList<Student>)item.Value);
  foo(dicTwo);
}


问:
Extract substring from row in SQL table and convert to date
I am trying to extract one row of data from a SQL Server table via PowerShell and convert the extracted value into a date.

The first 8 chars of the string should be in yyyymmdd format.

Firstly, I am having problems extracting the row...

As per various posts I've seen, it appears that when you grab a row, the data type that is returned is System.Data.DataRow. You then need to convert it into an Array. How do I grab the values from the array/datarow? Ideally, I'd like the value to come back as a String - as there will only be one value returned.
I am currently using something like this - but the content is null (even though the statement in SSMS returns one row)...

[array]$lastSQLdateArray = Invoke-Sqlcmd -ServerInstance INSTANCE -Database DATABASE -Query "SELECT TOP 1 LEFT(Column, 8) FROM [dbo].[Table] ORDER BY ID DESC"

```<code>for ($i=0; $i -le $lastSQLdateArray.Length; $i++)
{
  $formatOut = $formatOut + ($lastSQLdateArray[$i].ItemArray -join ",")
}
</code>```

Then there is the question of converting the extracted yyyymmdd value (which ever data type it is) and convert it to a date.

How can I do this please?

答:
Thanks for your assistance.
With your help, I have managed to sort the issue using the following syntax:

```<code>$strSQL = 'SELECT TOP 1 LEFT(Colname, 8) AS Col FROM [dbo].[Table] ORDER BY ID DESC'

$lastSQLdateArray1 = Invoke-Sqlcmd -ServerInstance 'server' -Database 'database' -Query $strSQL

$newvar = [datetime]::ParseExact($lastSQLdateArray1.Col.ToString(),'yyyyMMdd',$null)

$newvar
</code>```

Only main difference is that I placed .ToString() in the date conversion line.

Thanks once again for your help. Much appreciated!

Body:
I am trying to extract one row of data from a SQL Server table via PowerShell and convert the extracted value into a date.

The first 8 chars of the string should be in yyyymmdd format.

Firstly, I am having problems extracting the row...

As per various posts I've seen, it appears that when you grab a row, the data type that is returned is System.Data.DataRow. You then need to convert it into an Array. How do I grab the values from the array/datarow? Ideally, I'd like the value to come back as a String - as there will only be one value returned.
I am currently using something like this - but the content is null (even though the statement in SSMS returns one row)...

[array]$lastSQLdateArray = Invoke-Sqlcmd -ServerInstance INSTANCE -Database DATABASE -Query "SELECT TOP 1 LEFT(Column, 8) FROM [dbo].[Table] ORDER BY ID DESC"

for ($i=0; $i -le $lastSQLdateArray.Length; $i++)
{
  $formatOut = $formatOut + ($lastSQLdateArray[$i].ItemArray -join ",")
}

Then there is the question of converting the extracted yyyymmdd value (which ever data type it is) and convert it to a date.

How can I do this please?

Body:
Thanks for your assistance.
With your help, I have managed to sort the issue using the following syntax:

$strSQL = 'SELECT TOP 1 LEFT(Colname, 8) AS Col FROM [dbo].[Table] ORDER BY ID DESC'

$lastSQLdateArray1 = Invoke-Sqlcmd -ServerInstance 'server' -Database 'database' -Query $strSQL

$newvar = [datetime]::ParseExact($lastSQLdateArray1.Col.ToString(),'yyyyMMdd',$null)

$newvar

Only main difference is that I placed .ToString() in the date conversion line.

Thanks once again for your help. Much appreciated!


问:
Is there a way to reference an audit table for Specifications (Spring)?
I've been looking for a similar question to this, without success.

My goal: I need to obtain the username of whoever created a certain entity, which is stored in the audit table of said entity referenced via Spring's @AuditTable.

A bit (hopefully) explained: In this particular situation I'm adding to a previously existing query built with the org.springframework.data.jpa.repository.JpaSpecificationExecutor class, along with the Predicate class (javax.persistence.criteria.Predicate). Joins tend to be made with the name of the class (example Join), from which then Spring gets the table name.
My question is, is there a way to make Spring look in the audit table name, instead of the Entity's table name?

An example would be:

```<code>@Entity @Table(name = "persons")
@Audited @AuditTable(name = "audit_persons")
public class Person {
        private String id;
        private String name;
        private Job job;
        /*getters and setters*/
}

@Entity @Table(name = "jobs")
@Audited @AuditTable(name = "audit_jobs")
public class Job {
        private String id;
        private String name;
        /*getters and setters*/
}

public final class PersonSpecification {
    private PersonSpecification(){}

    public static Specification<Person> findBy(final String attributeName, final Object filterValue) {
        return new Specification<Person>() {
            @Override
            public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                return cb.equal(root.get(attributeName), filterValue);
            }
        };
    }

    public static Specification<Person> findByJob(final Job job) {
        return new Specification<Person>() {

            @Override
            public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

                Join<Person, Job> joinJob = root.join("job", JoinType.LEFT);
                return cb.equal(joinJob.<Job>get("job"), job);
            }
        };
    }

/*
    public static Specification<Person> findByUsername(final String username) {
        return new Specification<Person>() {
            @Override
            public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Join<Person, audit person?> join? = root.join(?, JoinType.LEFT);
                return I don't know how to access;
            }
        };
    }
*/
}

import static ().PersonSpecification.findBy;
import static ().PersonSpecification.findByJob;
@Service(value="personService")
public class PersonService {

    @Autowired
    private PersonDao personDao;

    public List<Person> find(String id, String name, Job job /*, String username*/){

        Specifications<Person> specifications = null;

        if (!StringUtils.isBlank(id) && StringUtils.isNumeric(id)) {
            specifications = loadFilter(specifications, findBy("id", id));
        }else{
            if (!StringUtils.isBlank(name)) {
                specifications = loadFilter(specifications, findBy("name", name));
            }
            if (job != null) {
                specifications = loadFilter(specifications, findByJob("job", job));
            }
            /*
            if (!StringUtils.isBlank(username)) {
                specifications = I don't know what to do here;
            }
            */
        }
        return personDao.findAll(specifications);
    }
}

</code>```

A possible solution: I was thinking about adding a new entity which would reference the audited entity, like this:

```<code>@Entity @Table(name = "audit_persons")
public class AuditedPerson {
       private String id;
       private Integer rev;
       private Integer revtype;
       private String username;
       /*getters and setters*/
}
</code>```

And then my method would be

```<code>public static Specification<Person> findByUsername(final String username) {
       return new Specification<Person>() {
           @Override
           public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
               Join<Person, AuditedPerson> joinAudit = root.join(id, JoinType.LEFT);
               return cb.and(cb.equal(joinAudit.get("username"), username),
                               cb.equal(joinAudit.get("revtype"), 0)); //this is so I get the creation instance's username
           }
       };
   }
</code>```

I'll be trying to make this work. Is there already a way to do this? Should I just add a native query that does this?
Thanks!

答:
One solution would be to use JPA @SecondaryTable with a database view.

Firstly, create a view  (say vw_person_additional_data) from the audit table that selects only the initial 'created' record for each Person.

Update your person Entity as below. The @SecondaryTable annotation lets us map an Entity to one or more tables or views.

```<code>@Entity
@Table(name = "persons")
@Audited
@AuditTable(name = "audit_persons")
//secondary table referencing our new view
@SecondaryTable(name = "vw_person_additional_data",
                   pkJoinColumns = {@PrimaryKeyJoinColumn(name = "person_id",
                        referencedColumnName = "id")})
public class Person {
        private String id;
        private String name;
        private Job job;

        @Column(name = "username", table="vw_person_additional_data") //column in view
        private String createdBy;
}
</code>```

The createdBy property is now just like any other property of Person when it comes to writing specifications.

Body:
I've been looking for a similar question to this, without success.

My goal: I need to obtain the username of whoever created a certain entity, which is stored in the audit table of said entity referenced via Spring's @AuditTable.

A bit (hopefully) explained: In this particular situation I'm adding to a previously existing query built with the org.springframework.data.jpa.repository.JpaSpecificationExecutor class, along with the Predicate class (javax.persistence.criteria.Predicate). Joins tend to be made with the name of the class (example Join), from which then Spring gets the table name.
My question is, is there a way to make Spring look in the audit table name, instead of the Entity's table name?

An example would be:

@Entity @Table(name = "persons")
@Audited @AuditTable(name = "audit_persons")
public class Person {
        private String id;
        private String name;
        private Job job;
        /*getters and setters*/
}

@Entity @Table(name = "jobs")
@Audited @AuditTable(name = "audit_jobs")
public class Job {
        private String id;
        private String name;
        /*getters and setters*/
}

public final class PersonSpecification {
    private PersonSpecification(){}

    public static Specification<Person> findBy(final String attributeName, final Object filterValue) {
        return new Specification<Person>() {
            @Override
            public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                return cb.equal(root.get(attributeName), filterValue);
            }
        };
    }

    public static Specification<Person> findByJob(final Job job) {
        return new Specification<Person>() {

            @Override
            public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

                Join<Person, Job> joinJob = root.join("job", JoinType.LEFT);
                return cb.equal(joinJob.<Job>get("job"), job);
            }
        };
    }

/*
    public static Specification<Person> findByUsername(final String username) {
        return new Specification<Person>() {
            @Override
            public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Join<Person, audit person?> join? = root.join(?, JoinType.LEFT);
                return I don't know how to access;
            }
        };
    }
*/
}

import static ().PersonSpecification.findBy;
import static ().PersonSpecification.findByJob;
@Service(value="personService")
public class PersonService {

    @Autowired
    private PersonDao personDao;

    public List<Person> find(String id, String name, Job job /*, String username*/){

        Specifications<Person> specifications = null;

        if (!StringUtils.isBlank(id) && StringUtils.isNumeric(id)) {
            specifications = loadFilter(specifications, findBy("id", id));
        }else{
            if (!StringUtils.isBlank(name)) {
                specifications = loadFilter(specifications, findBy("name", name));
            }
            if (job != null) {
                specifications = loadFilter(specifications, findByJob("job", job));
            }
            /*
            if (!StringUtils.isBlank(username)) {
                specifications = I don't know what to do here;
            }
            */
        }
        return personDao.findAll(specifications);
    }
}

A possible solution: I was thinking about adding a new entity which would reference the audited entity, like this:

@Entity @Table(name = "audit_persons")
public class AuditedPerson {
       private String id;
       private Integer rev;
       private Integer revtype;
       private String username;
       /*getters and setters*/
}

And then my method would be

public static Specification<Person> findByUsername(final String username) {
       return new Specification<Person>() {
           @Override
           public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
               Join<Person, AuditedPerson> joinAudit = root.join(id, JoinType.LEFT);
               return cb.and(cb.equal(joinAudit.get("username"), username),
                               cb.equal(joinAudit.get("revtype"), 0)); //this is so I get the creation instance's username
           }
       };
   }

I'll be trying to make this work. Is there already a way to do this? Should I just add a native query that does this?
Thanks!

Body:
One solution would be to use JPA @SecondaryTable with a database view.

Firstly, create a view  (say vw_person_additional_data) from the audit table that selects only the initial 'created' record for each Person.

Update your person Entity as below. The @SecondaryTable annotation lets us map an Entity to one or more tables or views.

@Entity
@Table(name = "persons")
@Audited
@AuditTable(name = "audit_persons")
//secondary table referencing our new view
@SecondaryTable(name = "vw_person_additional_data",
                   pkJoinColumns = {@PrimaryKeyJoinColumn(name = "person_id",
                        referencedColumnName = "id")})
public class Person {
        private String id;
        private String name;
        private Job job;

        @Column(name = "username", table="vw_person_additional_data") //column in view
        private String createdBy;
}

The createdBy property is now just like any other property of Person when it comes to writing specifications.


问:
HibernatePersistenceProvider : Unsupported major.minor version 52.0 intellij
i searched for this problem such

How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version

but the answer didnt work for me

i am using jdk 1.7 , i set the compiler to 1.7.0_79 which meant to be java 7 but when i run i still getting the error , i set the project byte code version to 1.7 but the same message

```<code>Exception in thread "main" java.lang.UnsupportedClassVersionError: org/hibernate/jpa/HibernatePersistenceProvider : Unsupported major.minor version 52.0
</code>```

this exception happens when try to load the
persistence.xml on this line

```<code>    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
</code>```

and in the java code on this line

```<code>    EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("sample");
</code>```

答:
As hibernate core version 5.2 and upper not support with JDK 1.7 . So Please change maven dependency into 5.1.x and lower version for JDK 1.7. But in all lower version of hibernate core have missing all class of "org.hibernate.jpa" package.

If you need hibernate persistence provider then get exception for not class found. So that you should add a new dependency.

```<code><dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.1.4.Final</version>
</dependency>
</code>```

After add this dependency if you still get not class found exception then add @EnableJpaRepositories for JPA repositories.

Body:
i searched for this problem such

How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version

but the answer didnt work for me

i am using jdk 1.7 , i set the compiler to 1.7.0_79 which meant to be java 7 but when i run i still getting the error , i set the project byte code version to 1.7 but the same message

Exception in thread "main" java.lang.UnsupportedClassVersionError: org/hibernate/jpa/HibernatePersistenceProvider : Unsupported major.minor version 52.0

this exception happens when try to load the
persistence.xml on this line

    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

and in the java code on this line

    EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("sample");

Body:
As hibernate core version 5.2 and upper not support with JDK 1.7 . So Please change maven dependency into 5.1.x and lower version for JDK 1.7. But in all lower version of hibernate core have missing all class of "org.hibernate.jpa" package.

If you need hibernate persistence provider then get exception for not class found. So that you should add a new dependency.

<dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.1.4.Final</version>
</dependency>

After add this dependency if you still get not class found exception then add @EnableJpaRepositories for JPA repositories.


问:
PHPMailer seems to not install correctly: Uncaught Error: Class 'PHPMailer\PHPMailer\PHPMailer
I am getting the error above when I run my code. Following the instructions on the PHPMAiler Github page, I added  "phpmailer/phpmailer": "^6.0" to my composer.json but PHPMailer seems not to load.

I tried using $mail = new PHPMailer\PHPMailer\PHPMailer(true) instead of $Mail = new PHPMailer(true).  I went to the Composer IRC channel to see if my problem was with Composer.  I have also tried using the full path in the require 'vendor/autoload.php'; statement.

```<code>// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

//Load Composer's autoloader
require 'vendor/autoload.php';

//other code...

//Create a new PHPMailer instance
    $mail = new PHPMailer(true);
</code>```

I expect PHPMailer to run.  Where did I go wrong?

答:
Scott

Your problem may be solved if you would have read the documentations. Use the below code at first.

```<code>use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';
</code>```

Body:
I am getting the error above when I run my code. Following the instructions on the PHPMAiler Github page, I added  "phpmailer/phpmailer": "^6.0" to my composer.json but PHPMailer seems not to load.

I tried using $mail = new PHPMailer\PHPMailer\PHPMailer(true) instead of $Mail = new PHPMailer(true).  I went to the Composer IRC channel to see if my problem was with Composer.  I have also tried using the full path in the require 'vendor/autoload.php'; statement.

// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

//Load Composer's autoloader
require 'vendor/autoload.php';

//other code...

//Create a new PHPMailer instance
    $mail = new PHPMailer(true);

I expect PHPMailer to run.  Where did I go wrong?

Body:
Scott

Your problem may be solved if you would have read the documentations. Use the below code at first.

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';


问:
Set multiple menu theme locations using functions on theme install
I have a network of wordpress sites, some of them need to install an alternative theme with additional functionality. The original theme has 4 menu locations, and I would like to set these when the new theme is installed.

I used this: http://mharis.net/how-to-set-wordpress-menus-to-theme-locations/ and this: https://wordpress.stackexchange.com/questions/15455/how-to-hard-code-custom-menu-items as a base and have this:

```<code>$locations = get_theme_mod( 'nav_menu_locations' ); // registered menu locations in theme
$menus = wp_get_nav_menus(); // registered menus

if($menus) {
foreach($menus as $menu) { // assign menus to theme locations
    if( $menu->name == 'ffh' ) {
        $locations['menu'] = $menu->term_id;
    } else if( $menu->name == 'ffh' ) {
        $locations['admin'] = $menu->term_id;
    } else if( $menu->name == 'ffh' ) {
        $locations['primary'] = $menu->term_id;
    } else if( $menu->name == 'ffh-guest' ) {
        $locations['visitor'] = $menu->term_id;
}}}
set_theme_mod('nav_menu_locations', $locations); // set menus to locations
}
 add_action('menu_location_register' );
</code>```

But it's not working. I'd appreciate any suggestions.

答:
$locations = get_theme_mod( 'nav_menu_locations' );

$adveits_menus = wp_get_nav_menus();

```<code>if ( $adveits_menus ) {
    foreach ( $adveits_menus as $adveits_menu ) {
        if ( $adveits_menu->name == 'Front page EN' ) {
            $locations['menu-1'] = $adveits_menu->term_id;
        } else if ( $adveits_menu->name == 'Front page RU' ) {
            $locations['menu-1___ru'] = $adveits_menu->term_id;
        } else if ( $adveits_menu->name == 'Front page LT' ) {
            $locations['menu-1___lt'] = $adveits_menu->term_id;
        }
    }
}

set_theme_mod( 'nav_menu_locations', $locations );
</code>```

Body:
I have a network of wordpress sites, some of them need to install an alternative theme with additional functionality. The original theme has 4 menu locations, and I would like to set these when the new theme is installed.

I used this: http://mharis.net/how-to-set-wordpress-menus-to-theme-locations/ and this: https://wordpress.stackexchange.com/questions/15455/how-to-hard-code-custom-menu-items as a base and have this:

$locations = get_theme_mod( 'nav_menu_locations' ); // registered menu locations in theme
$menus = wp_get_nav_menus(); // registered menus

if($menus) {
foreach($menus as $menu) { // assign menus to theme locations
    if( $menu->name == 'ffh' ) {
        $locations['menu'] = $menu->term_id;
    } else if( $menu->name == 'ffh' ) {
        $locations['admin'] = $menu->term_id;
    } else if( $menu->name == 'ffh' ) {
        $locations['primary'] = $menu->term_id;
    } else if( $menu->name == 'ffh-guest' ) {
        $locations['visitor'] = $menu->term_id;
}}}
set_theme_mod('nav_menu_locations', $locations); // set menus to locations
}
 add_action('menu_location_register' );

But it's not working. I'd appreciate any suggestions.

Body:
$locations = get_theme_mod( 'nav_menu_locations' );

$adveits_menus = wp_get_nav_menus();

if ( $adveits_menus ) {
    foreach ( $adveits_menus as $adveits_menu ) {
        if ( $adveits_menu->name == 'Front page EN' ) {
            $locations['menu-1'] = $adveits_menu->term_id;
        } else if ( $adveits_menu->name == 'Front page RU' ) {
            $locations['menu-1___ru'] = $adveits_menu->term_id;
        } else if ( $adveits_menu->name == 'Front page LT' ) {
            $locations['menu-1___lt'] = $adveits_menu->term_id;
        }
    }
}

set_theme_mod( 'nav_menu_locations', $locations );


问:
Laravel Example.vue not updating
I'm trying to figure out how to use Vue in a Laravel 5 project. Basic Laravel install ships with app.js and Example.vue. I was able to have the
"I'm an example component!" show up in my view by adding  to home.blade.php. What's mystifying me is that I can't change this component at all, among other issues.

If I change the text in the Example.vue (just in the template part, not the logic) it doesn't update at all. (I've tried running npm run dev as per Laravel docs, etc, and it seems to compile without errors, and /public/js/app.js is modified at that time, but the view in the browser doesn't change.)

When I modify app.blade.php, those changes show up, as do changes in home.blade.php. However, I can't find evidence that changing the content of /resources/assets/js/app.js or Example.vue has any effect. Even more confusing, if I remove the id="app" from app.blade.php div element, this does not cause the Example component to disappear. Based on playing with the vue jsfiddle, it seems like this should break the component.

I'm not sure if it's some sort of caching issue, or compile issue, or I'm not understanding the way vue works, or what, but I have no idea what's going wrong. I'm using the webpack.mix.js file straight out of the laravel installation, and I tried halting and restarting vagrant, and reloading the browser, and php artisan cache:clear. (Earlier I tried using Elixir instead of Mix, and vueify and gulp, same issue.)

Any suggestions would be much appreciated!

答:
With a simple Vue.js project we serve the project via npm run serve which also simultaneously runs the npm watcher. The watcher watches for changes in the Vue.js project. Since we are serving via php artisian serve we also need to run npm run watch because php artisan serve only watches for Laravel changes.

The solution is running php artisan serve and npm run watch together while you're changing your development project.

Install: npm install npm-watch

Title: Laravel Example.vue not updating


问:
How to change the order in which files are listed by bash
I have some files. When I list them I get the order:

```<code>frame0001i0002.png
frame0001.png
frame0002i0003.png
frame0002.png
frame0003i0004.png
frame0003.png
frame0004.png
frame0005.png
frame0006.png
</code>```

I had assumed that frame0001.png would come before frame0001i0002.png, because I need to operate on them in the order:

```<code>frame0001.png
frame0001i0002.png
frame0002.png
frame0002i0003.png
frame0003.png
frame0003i0004.png
frame0004.png
frame0005.png
frame0006.png
</code>```

Do I need to rename them to appear in the order that I want?

Ultimately I want to change their names to:

```<code>frame0001.png
frame0002.png
frame0003.png
frame0004.png
frame0005.png
frame0006.png
frame0007.png
frame0008.png
frame0009.png
</code>```

and in the order from the cell above.

答:
You encounter this problem because i comes before . in your default sort order.

Using the following you can get the expected order :

```<code>sort -t'.' -k 1,1
</code>```

This defines . is a field separator and that we should only consider the first field (the part before the extention) for the sort order. We're now comparing frame0001 with frame0001i0002, and the shortest will be printed first.

Body:
I have some files. When I list them I get the order:

frame0001i0002.png
frame0001.png
frame0002i0003.png
frame0002.png
frame0003i0004.png
frame0003.png
frame0004.png
frame0005.png
frame0006.png

I had assumed that frame0001.png would come before frame0001i0002.png, because I need to operate on them in the order:

frame0001.png
frame0001i0002.png
frame0002.png
frame0002i0003.png
frame0003.png
frame0003i0004.png
frame0004.png
frame0005.png
frame0006.png

Do I need to rename them to appear in the order that I want?

Ultimately I want to change their names to:

frame0001.png
frame0002.png
frame0003.png
frame0004.png
frame0005.png
frame0006.png
frame0007.png
frame0008.png
frame0009.png

and in the order from the cell above.

Body:
You encounter this problem because i comes before . in your default sort order.

Using the following you can get the expected order :

sort -t'.' -k 1,1

This defines . is a field separator and that we should only consider the first field (the part before the extention) for the sort order. We're now comparing frame0001 with frame0001i0002, and the shortest will be printed first.


问:
Android DataBinding custom adapter in multiple modules

Context

I have 3 modules: A, B, and app. app depends on A, and A depends on B.

Custom data binding adapters are in B.

```<code>app -> A -> B
</code>```

All modules have data binding enabled, as well as kapt plugin.

```<code>plugins {
    kotlin("kapt")
}

android {
    dataBinding.isEnabled = true
}
</code>```

Problem

Let's say I have the following binding adpater function:

```<code>@BindingAdapter("fontWeight")
fun TextView.setFontWeight(family: String)
</code>```

In app, I can use it as an extension function, but cannot use it as a custom binding adapter.

```<code>textView.setFontWeight("bold") // It works

<TextView
  app:fontWeight='@{"bold"}' // It doesn't work
</code>```

What's interesting is that If I make app module directly depends on B, then the binding adapter works as expected.

```<code>app -> B
</code>```

What's the problem? Do you have any ideas? Thanks in advance.

Update

When I remove this lines of code from build.gradle.kts it works properly, but I cannot figure out what's going on.

```<code>flavorDimensions("dimension")

productFlavors {
    create("dev")
    create("staging")
    create("production")

    forEach { flavor ->
        with(flavor) {
            dimension = "dimension"
            versionCode = generateVersionCode(name)
            versionName = generateVersionName(name)

            if (name != "production") {
                applicationIdSuffix = ".$name"
            }
        }
    }
}
</code>```

答:
The problem is that I used same package name in AndroidManifest.xml for both module A and module B.

<manifest package="co.riiid.santa.design" />

<manifest package="co.riiid.santa.design" />
```

<p>Changing package name of module B solves the problem.</p>

```
<manifest package="co.riiid.santa.design.components" />
```

I didn't expect that it might cause a problem..

I'm not sure why it causes the problem, but here's my guess:

Annotation processing tool kapt generates a class DataBinderMapperImpl for each module that has enabled data binding. The resulting class is located in the package where one specified in AndroidManifest.xml

Hence if there're modules which have the same package name, a conflict occurs.

Body:
Context

I have 3 modules: A, B, and app. app depends on A, and A depends on B.

Custom data binding adapters are in B.

app -> A -> B

All modules have data binding enabled, as well as kapt plugin.

plugins {
    kotlin("kapt")
}

android {
    dataBinding.isEnabled = true
}

Problem

Let's say I have the following binding adpater function:

@BindingAdapter("fontWeight")
fun TextView.setFontWeight(family: String)

In app, I can use it as an extension function, but cannot use it as a custom binding adapter.

textView.setFontWeight("bold") // It works

<TextView
  app:fontWeight='@{"bold"}' // It doesn't work

What's interesting is that If I make app module directly depends on B, then the binding adapter works as expected.

app -> B

What's the problem? Do you have any ideas? Thanks in advance.

Update

When I remove this lines of code from build.gradle.kts it works properly, but I cannot figure out what's going on.

flavorDimensions("dimension")

productFlavors {
    create("dev")
    create("staging")
    create("production")

    forEach { flavor ->
        with(flavor) {
            dimension = "dimension"
            versionCode = generateVersionCode(name)
            versionName = generateVersionName(name)

            if (name != "production") {
                applicationIdSuffix = ".$name"
            }
        }
    }
}

Body:
The problem is that I used same package name in AndroidManifest.xml for both module A and module B.

<!-- AndroidManifest.xml in Module A -->
<manifest package="co.riiid.santa.design" />

<!-- AndroidManifest.xml in Module B -->
<manifest package="co.riiid.santa.design" />

Changing package name of module B solves the problem.

<!-- Append "components" at the end -->
<manifest package="co.riiid.santa.design.components" />

I didn't expect that it might cause a problem..

I'm not sure why it causes the problem, but here's my guess:

Annotation processing tool kapt generates a class DataBinderMapperImpl for each module that has enabled data binding. The resulting class is located in the package where one specified in AndroidManifest.xml

Hence if there're modules which have the same package name, a conflict occurs.


问:
How can I combine JSON rows in a logic app grouped by another property
I have a logic app that is taking failed runs from an app writing to application insights, and I want to group all the errors by the operation name into a single message.  Can someone explain how to do this?

my starting data looks like:

```<code>[{ "messageError": "Notification sent to AppName but not received for request: 20200213215520_hUu22w9RZlyc, user email@email.com Status: NotFound",
   "transactionKey": "20200213215520_hUu22w9RZlyc"},
 { "messageError": "App to App Import Request: 20200213215520_hUu22w9RZlyc from user email@email.com was unable to insert to following line(s) into App with error(s) :\r\n Line 123: Unable to unlock this record.",
   "transactionKey": "20200213215520_hUu22w9RZlyc"}]
</code>```

What I am trying to get out of that would be a single row that concatenates both messageError values into one statement on a common transaction key.  Something like this:

```<code>[{ "messageErrors": [{"Notification sent to AppName but not received for request: 20200213215520_hUu22w9RZlyc, user email@email.com Status: NotFound"},
                     {"App to App Import Request: 20200213215520_hUu22w9RZlyc from user email@email.com was unable to insert to following line(s) into App with error(s) :\r\n Line 123: Unable to unlock this record."}],
   "transactionKey": "20200213215520_hUu22w9RZlyc"}]
</code>```

There might be as many as 20 rows in the dataset, and the concatenation needs to be smart enough to group only if there are multiple rows with the same transactionKey.  Has anyone done this, and have a suggestion on how to group them?

答:
For this requirement, I thought that we can use liquid template to do the "group by" operation for your json data at the beginning. But according to some test, it seems azure logic app doesn't support "group by" in its liquid template. So there two solutions for us to choose:

A. One solution is do these operations in logic app by "For each" loop, "If" condition, compose the json data and so many other actions, and also we have to initialize many variables. I tried this solution first, but I gave up it after creating so many actions in logic app. It's too complicated.

B. The other solution is call a azure function in logic app, and we can do the operations for the json data in function code. It's not easy either, but I think it's better than the first solution. So I tried this solution and got success. Please refer to the steps below:

1. We need to create a azure function app with a "HTTP" trigger in it.

2. In your "HTTP" trigger, please refer to my code below:

```<code>#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public static async Task<object> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");

    string body = await req.Content.ReadAsStringAsync();
    JArray array = JArray.Parse(body);

    JArray resultArray = new JArray();
    JObject tempObj = new JObject();

    foreach (var obj in array)
    {
        JObject jsonObj = JObject.Parse(obj.ToString());
        string transactionKey = jsonObj.GetValue("transactionKey").ToString();
        string messageError = jsonObj.GetValue("messageError").ToString();
        Boolean hasKey = false;
        foreach (var item in tempObj)
        {
            JObject jsonItem = (JObject)item.Value;
            string keyInItem = jsonItem.GetValue("transactionKey").ToString();
            if (transactionKey.Equals(keyInItem))
            {
                hasKey = true;
                break;
            }else
            {
                hasKey = false;
            }
        }
        if (hasKey.Equals(false))
        {
            JObject newObj = new JObject();
            JArray newArr = new JArray();
            newArr.Add(messageError);
            newObj.Add("transactionKey", transactionKey);
            newObj.Add("messageErrors", newArr);
            tempObj.Add(transactionKey, newObj);
        }
        else
        {
            JObject oldObj = (JObject)tempObj.GetValue(transactionKey);
            JArray oldArr = (JArray)oldObj.GetValue("messageErrors");
            oldArr.Add(messageError);
            oldObj.Property("messageErrors").Remove();
            oldObj.Add("messageErrors", oldArr);
            tempObj.Property(transactionKey).Remove();
            tempObj.Add(transactionKey, oldObj);
        }
    }

    foreach (var x in tempObj)
    {
        resultArray.Add(x.Value);
    }

    return resultArray;
}
</code>```

3. Test and save the function, and then go to your logic app. In logic app, I initialize a variable named "data" with the json data below to simulate your scene.

4. Then create function in your logic app and choose the "HTTP" trigger which you created just now.

5. After running the logic app, we can get the result shown as below:

```<code>[
  {
    "transactionKey": "20200213215520_hUu22w9RZlyc",
    "messageErrors": [
      "xxxxxxxxx",
      "yyyyyyyy"
    ]
  },
  {
    "transactionKey": "keykey",
    "messageErrors": [
      "testtest11",
      "testtest22",
      "testtest33"
    ]
  }
]
</code>```

Body:
I have a logic app that is taking failed runs from an app writing to application insights, and I want to group all the errors by the operation name into a single message.  Can someone explain how to do this?

my starting data looks like:

[{ "messageError": "Notification sent to AppName but not received for request: 20200213215520_hUu22w9RZlyc, user email@email.com Status: NotFound",
   "transactionKey": "20200213215520_hUu22w9RZlyc"},
 { "messageError": "App to App Import Request: 20200213215520_hUu22w9RZlyc from user email@email.com was unable to insert to following line(s) into App with error(s) :\r\n Line 123: Unable to unlock this record.",
   "transactionKey": "20200213215520_hUu22w9RZlyc"}]

What I am trying to get out of that would be a single row that concatenates both messageError values into one statement on a common transaction key.  Something like this:

[{ "messageErrors": [{"Notification sent to AppName but not received for request: 20200213215520_hUu22w9RZlyc, user email@email.com Status: NotFound"},
                     {"App to App Import Request: 20200213215520_hUu22w9RZlyc from user email@email.com was unable to insert to following line(s) into App with error(s) :\r\n Line 123: Unable to unlock this record."}],
   "transactionKey": "20200213215520_hUu22w9RZlyc"}]

There might be as many as 20 rows in the dataset, and the concatenation needs to be smart enough to group only if there are multiple rows with the same transactionKey.  Has anyone done this, and have a suggestion on how to group them?

Body:
For this requirement, I thought that we can use liquid template to do the "group by" operation for your json data at the beginning. But according to some test, it seems azure logic app doesn't support "group by" in its liquid template. So there two solutions for us to choose:

A. One solution is do these operations in logic app by "For each" loop, "If" condition, compose the json data and so many other actions, and also we have to initialize many variables. I tried this solution first, but I gave up it after creating so many actions in logic app. It's too complicated.

B. The other solution is call a azure function in logic app, and we can do the operations for the json data in function code. It's not easy either, but I think it's better than the first solution. So I tried this solution and got success. Please refer to the steps below:

1. We need to create a azure function app with a "HTTP" trigger in it.

2. In your "HTTP" trigger, please refer to my code below:

#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public static async Task<object> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");

    string body = await req.Content.ReadAsStringAsync();
    JArray array = JArray.Parse(body);

    JArray resultArray = new JArray();
    JObject tempObj = new JObject();

    foreach (var obj in array)
    {
        JObject jsonObj = JObject.Parse(obj.ToString());
        string transactionKey = jsonObj.GetValue("transactionKey").ToString();
        string messageError = jsonObj.GetValue("messageError").ToString();
        Boolean hasKey = false;
        foreach (var item in tempObj)
        {
            JObject jsonItem = (JObject)item.Value;
            string keyInItem = jsonItem.GetValue("transactionKey").ToString();
            if (transactionKey.Equals(keyInItem))
            {
                hasKey = true;
                break;
            }else
            {
                hasKey = false;
            }
        }
        if (hasKey.Equals(false))
        {
            JObject newObj = new JObject();
            JArray newArr = new JArray();
            newArr.Add(messageError);
            newObj.Add("transactionKey", transactionKey);
            newObj.Add("messageErrors", newArr);
            tempObj.Add(transactionKey, newObj);
        }
        else
        {
            JObject oldObj = (JObject)tempObj.GetValue(transactionKey);
            JArray oldArr = (JArray)oldObj.GetValue("messageErrors");
            oldArr.Add(messageError);
            oldObj.Property("messageErrors").Remove();
            oldObj.Add("messageErrors", oldArr);
            tempObj.Property(transactionKey).Remove();
            tempObj.Add(transactionKey, oldObj);
        }
    }

    foreach (var x in tempObj)
    {
        resultArray.Add(x.Value);
    }

    return resultArray;
}

3. Test and save the function, and then go to your logic app. In logic app, I initialize a variable named "data" with the json data below to simulate your scene.

4. Then create function in your logic app and choose the "HTTP" trigger which you created just now.

5. After running the logic app, we can get the result shown as below:

[
  {
    "transactionKey": "20200213215520_hUu22w9RZlyc",
    "messageErrors": [
      "xxxxxxxxx",
      "yyyyyyyy"
    ]
  },
  {
    "transactionKey": "keykey",
    "messageErrors": [
      "testtest11",
      "testtest22",
      "testtest33"
    ]
  }
]


问:
How to set unique style to tool tip attribute?
I have tool tip attribute in my table, I want to set width to this attribute related to my column width, so I have different size tool tips. I have different column widths and I want to set width to the tool tip based on my column width, I mean how can I access data-md-tooptip attribute (tool tip element) through JavaScript and ad style like document.querySelector([data-md-tooltip]).style.width = "000px"

[data-md-tooltip] {
  position: relative;
}

[data-md-tooltip]:before {
  content: attr(data-md-tooltip);
  position: absolute;

  /*width: 360px;*/
  top: 95%;
  left: 50%;
  padding: 8px;
  transform: translateX(-50%) scale(0);
  transition: transform 0.2s ease-in-out;
  transform-origin: top;
  background: #232F34;
  color: white;
  border-radius: 2px;
  font-size: 12px;
  font-family: Roboto, sans-serif;
  font-weight: 400;
  z-index: 2;
}

[data-md-tooltip]:hover:before {
  transform: translateX(-50%) scale(1);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><td class="mdc-data-table__cell" data-md-tooltip="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since,Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since">
  <div class="long-text">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been      the industry's standard dummy text ever since,Lorem Ipsum is simply dummy text of the printing and typesetting          industry. Lorem Ipsum has been the industry's standard dummy text ever since
  </div>
</td>
<hr>
<!-- Here I want different tool tip width -->
<td class="mdc-data-table__cell" data-md-tooltip="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since,Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since">
  <div class="long-text">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been      the industry's standard dummy text ever since,L
  </div>
</td></code>```

答:
document.querySelector requires a String as a parameter so you need to write

```<code>document.querySelector('[data-md-tooltip]').style.width = ...
</code>```

But this method will return only the first element matched by that selector: if you need to apply the style to more than one [data-md-tooltip] element you need to use document.querySelectorAll and walk over the node collection you retrieve (e.g. using the spread ... operator)

```<code>[...document.querySelectorAll('[data-md-tooltip]')].forEach((tt) => {
   tt.width = ...
})
</code>```

Body:
I have tool tip attribute in my table, I want to set width to this attribute related to my column width, so I have different size tool tips. I have different column widths and I want to set width to the tool tip based on my column width, I mean how can I access data-md-tooptip attribute (tool tip element) through JavaScript and ad style like document.querySelector([data-md-tooltip]).style.width = "000px"

[data-md-tooltip] {
  position: relative;
}

[data-md-tooltip]:before {
  content: attr(data-md-tooltip);
  position: absolute;

  /*width: 360px;*/
  top: 95%;
  left: 50%;
  padding: 8px;
  transform: translateX(-50%) scale(0);
  transition: transform 0.2s ease-in-out;
  transform-origin: top;
  background: #232F34;
  color: white;
  border-radius: 2px;
  font-size: 12px;
  font-family: Roboto, sans-serif;
  font-weight: 400;
  z-index: 2;
}

[data-md-tooltip]:hover:before {
  transform: translateX(-50%) scale(1);
}

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been      the industry's standard dummy text ever since,Lorem Ipsum is simply dummy text of the printing and typesetting          industry. Lorem Ipsum has been the industry's standard dummy text ever since

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been      the industry's standard dummy text ever since,L

Body:
document.querySelector requires a String as a parameter so you need to write

document.querySelector('[data-md-tooltip]').style.width = ...

But this method will return only the first element matched by that selector: if you need to apply the style to more than one [data-md-tooltip] element you need to use document.querySelectorAll and walk over the node collection you retrieve (e.g. using the spread ... operator)

[...document.querySelectorAll('[data-md-tooltip]')].forEach((tt) => {
   tt.width = ...
})