问:
Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference
Things I've tried after searching:

in Web.Config put a binding on the old version:

```<code><dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.1.0" />
</dependentAssembly>
</code>```

Edit my .csproj file to make sure there is only one Newtonsoft reference

```<code><Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
   <HintPath>..\packages\Newtonsoft.Json.6.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
   <SpecificVersion>False</SpecificVersion>
   <Private>True</Private>
</Reference>
</code>```

Search my computer for every Newtonsoft.Json.dll and delete every non 6.0.1 version and delete the contents of my temp folder

Repair/Reinstall the package in nuget manager console

It succeeds on building, but gets the error when going to the site.

EDIT

ok, so then I tried to reinstall like every nuget package, and it seems to have added back the 4.5 version of the newtonsoft.json.dll, but I'm getting the same error. My project's Target freamework is .NET 4.5.1 and here is the stack trace I'm getting now:

Server Error in '/' Application.

Could not load file or assembly Newtonsoft.Json or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IO.FileLoadException: Could not load file or assembly Newtonsoft.Json or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Assembly Load Trace: The following information can be helpful to determine why the assembly Newtonsoft.Json could not be loaded.

```<code>=== Pre-bind state information ===
LOG: DisplayName = Newtonsoft.Json
(Partial)
WRN: Partial binding information was supplied for an assembly:
WRN: Assembly Name: Newtonsoft.Json | Domain ID: 2
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:/users/user/documents/visual studio 2013/Projects/foo/bar/
LOG: Initial PrivatePath = c:\users\user\documents\visual studio 2013\Projects\foo\bar\bin
Calling assembly : (Unknown).
 ===
LOG: This bind starts in default load context.
LOG: Using application configuration file: c:\users\user\documents\visual studio 2013\Projects\foo\bar\web.config
LOG: Using host configuration file: C:\Users\user\Documents\IISExpress\config\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\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:/Users/user/AppData/Local/Temp/1/Temporary ASP.NET Files/root/48686d37/9d7a6572/Newtonsoft.Json.DLL.
LOG: Attempting download of new URL file:///C:/Users/user/AppData/Local/Temp/1/Temporary ASP.NET Files/root/48686d37/9d7a6572/Newtonsoft.Json/Newtonsoft.Json.DLL.
LOG: Attempting download of new URL file:///c:/users/user/documents/visual studio 2013/Projects/foo/bar/bin/Newtonsoft.Json.DLL.
LOG: Using application configuration file: c:\users\user\documents\visual studio 2013\Projects\foo\bar\web.config
LOG: Using host configuration file: C:\Users\user\Documents\IISExpress\config\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Redirect found in application configuration file: 4.5.0.0 redirected to 6.0.1.0.
LOG: Post-policy reference: Newtonsoft.Json, Version=6.0.1.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed
LOG: Attempting download of new URL file:///C:/Users/user/AppData/Local/Temp/1/Temporary ASP.NET Files/root/48686d37/9d7a6572/Newtonsoft.Json.DLL.
LOG: Attempting download of new URL file:///C:/Users/user/AppData/Local/Temp/1/Temporary ASP.NET Files/root/48686d37/9d7a6572/Newtonsoft.Json/Newtonsoft.Json.DLL.
LOG: Attempting download of new URL file:///c:/users/user/documents/visual studio 2013/Projects/foo/bar/bin/Newtonsoft.Json.DLL.
WRN: Comparing the assembly name resulted in the mismatch: Major Version
ERR: Failed to complete setup of assembly (hr = 0x80131040). Probing terminated.
</code>```

Stack Trace:

```<code>[FileLoadException: Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]

[FileLoadException: Could not load file or assembly 'Newtonsoft.Json, Version=6.0.1.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' 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.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +34
       System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +152
       System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +77
       System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +16
       System.Reflection.Assembly.Load(String assemblyString) +28
       System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +38

[ConfigurationErrorsException: Could not load file or assembly 'Newtonsoft.Json, Version=6.0.1.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' 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) +752
       System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +218
       System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +130
        System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +170
       System.Web.Compilation.BuildManager.GetPreStartInitMethodsFromReferencedAssemblies() +91
       System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +285
       System.Web.Compilation.BuildManager.ExecutePreAppStart() +153
       System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +516

[HttpException (0x80004005): Could not load file or assembly 'Newtonsoft.Json, Version=6.0.1.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' 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) +9913572
       System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
       System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18408
</code>```

答:
I have tried the steps by Oleg, and they worked for my same situation.

Steps:

Run update-package Newtonsoft.Json -reinstall in Package Manager.

Delete your bin by enabling viewing the hidden files and deleting the bin folder.

Close your Visual Studio and re-open it.

Now run your project again. I believe it should be ok!

Body:
Things I've tried after searching:

in Web.Config put a binding on the old version:

<dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.1.0" />
</dependentAssembly>

Edit my .csproj file to make sure there is only one Newtonsoft reference

<Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
   <HintPath>..\packages\Newtonsoft.Json.6.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
   <SpecificVersion>False</SpecificVersion>
   <Private>True</Private>
</Reference>

Search my computer for every Newtonsoft.Json.dll and delete every non 6.0.1 version and delete the contents of my temp folder

Repair/Reinstall the package in nuget manager console

It succeeds on building, but gets the error when going to the site.

EDIT

ok, so then I tried to reinstall like every nuget package, and it seems to have added back the 4.5 version of the newtonsoft.json.dll, but I'm getting the same error. My project's Target freamework is .NET 4.5.1 and here is the stack trace I'm getting now:

Server Error in '/' Application.

Could not load file or assembly Newtonsoft.Json or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IO.FileLoadException: Could not load file or assembly Newtonsoft.Json or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Assembly Load Trace: The following information can be helpful to determine why the assembly Newtonsoft.Json could not be loaded.

=== Pre-bind state information ===
LOG: DisplayName = Newtonsoft.Json
(Partial)
WRN: Partial binding information was supplied for an assembly:
WRN: Assembly Name: Newtonsoft.Json | Domain ID: 2
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:/users/user/documents/visual studio 2013/Projects/foo/bar/
LOG: Initial PrivatePath = c:\users\user\documents\visual studio 2013\Projects\foo\bar\bin
Calling assembly : (Unknown).
 ===
LOG: This bind starts in default load context.
LOG: Using application configuration file: c:\users\user\documents\visual studio 2013\Projects\foo\bar\web.config
LOG: Using host configuration file: C:\Users\user\Documents\IISExpress\config\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\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:/Users/user/AppData/Local/Temp/1/Temporary ASP.NET Files/root/48686d37/9d7a6572/Newtonsoft.Json.DLL.
LOG: Attempting download of new URL file:///C:/Users/user/AppData/Local/Temp/1/Temporary ASP.NET Files/root/48686d37/9d7a6572/Newtonsoft.Json/Newtonsoft.Json.DLL.
LOG: Attempting download of new URL file:///c:/users/user/documents/visual studio 2013/Projects/foo/bar/bin/Newtonsoft.Json.DLL.
LOG: Using application configuration file: c:\users\user\documents\visual studio 2013\Projects\foo\bar\web.config
LOG: Using host configuration file: C:\Users\user\Documents\IISExpress\config\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Redirect found in application configuration file: 4.5.0.0 redirected to 6.0.1.0.
LOG: Post-policy reference: Newtonsoft.Json, Version=6.0.1.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed
LOG: Attempting download of new URL file:///C:/Users/user/AppData/Local/Temp/1/Temporary ASP.NET Files/root/48686d37/9d7a6572/Newtonsoft.Json.DLL.
LOG: Attempting download of new URL file:///C:/Users/user/AppData/Local/Temp/1/Temporary ASP.NET Files/root/48686d37/9d7a6572/Newtonsoft.Json/Newtonsoft.Json.DLL.
LOG: Attempting download of new URL file:///c:/users/user/documents/visual studio 2013/Projects/foo/bar/bin/Newtonsoft.Json.DLL.
WRN: Comparing the assembly name resulted in the mismatch: Major Version
ERR: Failed to complete setup of assembly (hr = 0x80131040). Probing terminated.

Stack Trace:

[FileLoadException: Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]

[FileLoadException: Could not load file or assembly 'Newtonsoft.Json, Version=6.0.1.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' 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.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +34
       System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +152
       System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +77
       System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +16
       System.Reflection.Assembly.Load(String assemblyString) +28
       System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +38

[ConfigurationErrorsException: Could not load file or assembly 'Newtonsoft.Json, Version=6.0.1.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' 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) +752
       System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +218
       System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +130
        System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +170
       System.Web.Compilation.BuildManager.GetPreStartInitMethodsFromReferencedAssemblies() +91
       System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +285
       System.Web.Compilation.BuildManager.ExecutePreAppStart() +153
       System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +516

[HttpException (0x80004005): Could not load file or assembly 'Newtonsoft.Json, Version=6.0.1.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' 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) +9913572
       System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
       System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18408


来源: stackexchange

问:
MS Word VBA code to align image to top right corner
I was trying to write a VBA macro to align an image to the top right corner of the page and set text wrapping to "Behind Text" and "Fixed Position on Page."

Normally I select the image and do all those settings through dialog boxes. But it gets tedious after a while. I'm wondering if there's a way to do it programmatically. I'm hoping I could open the page header, paste in my header image, and then click a macro button to have the macro align the still-selected image.

I tried recording a macro of my operations, but the macro did not record any of my dialog actions (behind text, fixed page position, etc).  So that method provided no solution. I tried it with images inside and outside of page headers, without success.

Is it possible to have some VBA code align the currently selected image object? Ideally, I would open up the page header, paste in my header image, and run a VBA macro to do the four operations above (behind text, fixed position on page, align top to page, align right side to page). I'm hoping someone can show me how or point me to some documentation or examples that show how to do it.

UPDATE

I couldn't post to the forum for some reason, so I worked on the problem for a couple of days and finally pieced together this solution for the next person. I wish I knew where to look in a manual or tutorial for this kind of thing.

But the only way seems to be to cobble solutions together from forums on the net. Here's my contribution! :-)

```<code>Sub AlignTopRight()
' Paste an image into Word so it is still selected
' Then invoke this macro to align it to the top right corner
' And to set it behind text, fixed position on the page

Application.ScreenUpdating = False
Dim Shp As Shape
On Error Resume Next
    'I'm not sure if this block is required, but it works
     Set Shp = Selection.InlineShapes(1)
     If Not Shp Is Nothing Then
          Set Shp = Selection.InlineShapes(1).ConvertToShape
     Else
          Set Shp = Selection.ShapeRange.Item(1)
     End If

    If Not Shp Is Nothing Then
    With Shp
      .LockAspectRatio = True
      ' for absolute positioning
      '.Left = CentimetersToPoints(5.5)
      '.Top = CentimetersToPoints(0.5)
      '.Width = CentimetersToPoints(2.5)
      'put the image behind text
      .WrapFormat.Type = wdWrapBehind
      'this was the tricky part, discovering this
      .RelativeHorizontalPosition = wdRelativeHorizontalPositionPage
      .RelativeVerticalPosition = wdRelativeVerticalPositionPage
      .Top = wdShapeTop 'if you say =0, it sets the AbsolutePx in the dialog
      .Left = wdShapeRight 'these wdShapeXX objects set the Align field in the dialog
    End With
    End If
Set Shp = Nothing
Application.ScreenUpdating = True
End Sub
</code>```

答: Just discovered this feature to answer my own question. See the answer in the question posting.</p>

ContentLicense: CC BY-SA 3.0

Body:
I was trying to write a VBA macro to align an image to the top right corner of the page and set text wrapping to "Behind Text" and "Fixed Position on Page."

Normally I select the image and do all those settings through dialog boxes. But it gets tedious after a while. I'm wondering if there's a way to do it programmatically. I'm hoping I could open the page header, paste in my header image, and then click a macro button to have the macro align the still-selected image.

I tried recording a macro of my operations, but the macro did not record any of my dialog actions (behind text, fixed page position, etc).  So that method provided no solution. I tried it with images inside and outside of page headers, without success.

Is it possible to have some VBA code align the currently selected image object? Ideally, I would open up the page header, paste in my header image, and run a VBA macro to do the four operations above (behind text, fixed position on page, align top to page, align right side to page). I'm hoping someone can show me how or point me to some documentation or examples that show how to do it.

UPDATE

I couldn't post to the forum for some reason, so I worked on the problem for a couple of days and finally pieced together this solution for the next person. I wish I knew where to look in a manual or tutorial for this kind of thing.

But the only way seems to be to cobble solutions together from forums on the net. Here's my contribution! :-)

Sub AlignTopRight()
' Paste an image into Word so it is still selected
' Then invoke this macro to align it to the top right corner
' And to set it behind text, fixed position on the page

Application.ScreenUpdating = False
Dim Shp As Shape
On Error Resume Next
    'I'm not sure if this block is required, but it works
     Set Shp = Selection.InlineShapes(1)
     If Not Shp Is Nothing Then
          Set Shp = Selection.InlineShapes(1).ConvertToShape
     Else
          Set Shp = Selection.ShapeRange.Item(1)
     End If

    If Not Shp Is Nothing Then
    With Shp
      .LockAspectRatio = True
      ' for absolute positioning
      '.Left = CentimetersToPoints(5.5)
      '.Top = CentimetersToPoints(0.5)
      '.Width = CentimetersToPoints(2.5)
      'put the image behind text
      .WrapFormat.Type = wdWrapBehind
      'this was the tricky part, discovering this
      .RelativeHorizontalPosition = wdRelativeHorizontalPositionPage
      .RelativeVerticalPosition = wdRelativeVerticalPositionPage
      .Top = wdShapeTop 'if you say =0, it sets the AbsolutePx in the dialog
      .Left = wdShapeRight 'these wdShapeXX objects set the Align field in the dialog
    End With
    End If
Set Shp = Nothing
Application.ScreenUpdating = True
End Sub


问:
Customizing TabBar in iphone
Hai

Can anyone guide me on How to customize the Tabbar such that each TabBarItem look like rounded button in Tabbar. and how to change the Tabbar Selection color.

答: for the tabbar selection color there is no solution with UITabBarController. I ended up with for example 2 customize buttons with images that look like a tabbar.</p>

ContentLicense: CC BY-SA 2.5

Title: Customizing TabBar in iphone


问:
change() jQuery not working
I'm having some trouble getting my change() event working in jQuery. I am making a small program that converts temperatures to Kelvin, and I want the span that holds my value after conversion to update 1) every time the temperature to convert changes and 2) every time a different temperature scale is selected from the radio buttons.

Relevant Code:

$(document).ready(function() {
  $('input[type=radio]').checkboxradio();
  var temp = parseFloat()
  $('input.listener').change(function() {
    var name = $(this).attr("name");
    var val = $(this).val();

    switch (name) {
      case 'unit':
        var temperature = $('input#temp').val();
        switch (val) {
          case 'f':
            $('span#output').html(((temperature - 32) / 1.8) + 273.15);
            break;
          case 'c':
            $('span#output').html(temperature + 273.15);
            break;
          case 'r':
            $('span#output').html(temperature / 1.8);
            break;
        }
      case 'temp':
        var u = $('input[name=unit]:checked').val();
        switch (u) {
          case 'f':
            $('span#output').html(((val - 32) / 1.8) + 273.15);
            break;
          case 'c':
            $('span#output').html(val + 273.15);
            break;
          case 'r':
            $('span#output').html(val / 1.8);
            break;
        }
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="widget">
  <fieldset>
    <legend>Select a Unit to Convert to Kelvin: </legend>
    <label for="fRadio">Fahrenheit</label>
    <input id="fRadio" class="listener" type="radio" name="unit" value="f">
    <label for="cRadio">Celsius</label>
    <input id="cRadio" class="listener" type="radio" name="unit" value="c">
    <label for="rRadio">Rankine</label>
    <input id="rRadio" class="listener" type="radio" name="unit" value="r">
  </fieldset>
</div>
<h2>Temperature Converter</h2>
<p>Type a value in the Fahrenheit field to convert the value to Kelvin:</p>

<p>
  <label>Temperature</label>
  <input id="temp" class="listener" type="number" value="32">
</p>
<p>Kelvin: <span id="output"></span></p></code>```

My guess is I'm making a pretty dumb small mistake, but I can't seem to figure it out. Thanks for any and all help, suggestions, and solutions.

答:
You do not have break; after

```<code>case 'unit':
</code>```

and when var name = "temp"

```<code>var val = $(this).val();
</code>```

the value of var val above would be a number in string format, so when you do val + something in case 'temp' the number is getting appended instead getting added or substracted. Use parseInt(val) to convert the value of input box to integer in case of 'temp'.

Title: change() jQuery not working

Body:
I'm having some trouble getting my change() event working in jQuery. I am making a small program that converts temperatures to Kelvin, and I want the span that holds my value after conversion to update 1) every time the temperature to convert changes and 2) every time a different temperature scale is selected from the radio buttons.

Relevant Code:

$(document).ready(function() {
  $('input[type=radio]').checkboxradio();
  var temp = parseFloat()
  $('input.listener').change(function() {
    var name = $(this).attr("name");
    var val = $(this).val();

    switch (name) {
      case 'unit':
        var temperature = $('input#temp').val();
        switch (val) {
          case 'f':
            $('span#output').html(((temperature - 32) / 1.8) + 273.15);
            break;
          case 'c':
            $('span#output').html(temperature + 273.15);
            break;
          case 'r':
            $('span#output').html(temperature / 1.8);
            break;
        }
      case 'temp':
        var u = $('input[name=unit]:checked').val();
        switch (u) {
          case 'f':
            $('span#output').html(((val - 32) / 1.8) + 273.15);
            break;
          case 'c':
            $('span#output').html(val + 273.15);
            break;
          case 'r':
            $('span#output').html(val / 1.8);
            break;
        }
    }
  });
});

  <fieldset>
    <legend>Select a Unit to Convert to Kelvin: </legend>
    Fahrenheit
    <input id="fRadio" class="listener" type="radio" name="unit" value="f">
    Celsius
    <input id="cRadio" class="listener" type="radio" name="unit" value="c">
    Rankine
    <input id="rRadio" class="listener" type="radio" name="unit" value="r">
  </fieldset>

Temperature Converter

Type a value in the Fahrenheit field to convert the value to Kelvin:

  Temperature
  <input id="temp" class="listener" type="number" value="32">

Kelvin:

My guess is I'm making a pretty dumb small mistake, but I can't seem to figure it out. Thanks for any and all help, suggestions, and solutions.

Body:
You do not have break; after

case 'unit':

and when var name = "temp"

var val = $(this).val();

the value of var val above would be a number in string format, so when you do val + something in case 'temp' the number is getting appended instead getting added or substracted. Use parseInt(val) to convert the value of input box to integer in case of 'temp'.


问:
Keep a character found by preg_replace
I want to replace a dot followed by a space followed by a uppercase and I tried this pattern to replace it by    :

```<code>preg_replace('/\. [A-Z]/', '.    'With marriage came a move to the beautiful Birmingham, Alabama area. Diving in head first.');
</code>```

It's working but I am loosing the D of Diving in head first.

How can I keep it?

答:
Put the letter matching pattern into a non-consuming lookahead:

```<code>'/\.\s+(?=[A-Z])/'
</code>```

The \s+ will match 1 or more whitespaces (or if you do not want that, keep the regular space) and (?=[A-Z]) makes the engine require an uppercase ASCII letter to appear right after the current location in the string.

See the PHP demo printing With marriage came a move to the beautiful Birmingham, Alabama area.   Diving in head first..

Title: Keep a character found by preg_replace

Body:
I want to replace a dot followed by a space followed by a uppercase and I tried this pattern to replace it by    :

preg_replace('/\. [A-Z]/', '.    'With marriage came a move to the beautiful Birmingham, Alabama area. Diving in head first.');

It's working but I am loosing the D of Diving in head first.

How can I keep it?

Body:
Put the letter matching pattern into a non-consuming lookahead:

'/\.\s+(?=[A-Z])/'

The \s+ will match 1 or more whitespaces (or if you do not want that, keep the regular space) and (?=[A-Z]) makes the engine require an uppercase ASCII letter to appear right after the current location in the string.

See the PHP demo printing With marriage came a move to the beautiful Birmingham, Alabama area.&nbsp;&nbsp;&nbsp;Diving in head first..


问:
bootstrap make accordion responsive?
I'm using the Bootstrap 3 Accordion Collapse,right now everything loads in one column, how can I make it so the panels use multiple columns in desktop resolution and one column in mobile mode?

```<code>        <div class="row">

            <div class="panel-group" id="accordion">

                <?php
                foreach ($states as &$state) {
                    ?>
                    <div class="panel panel-default">
                        <div class="panel-heading">
                            <h4 class="panel-title">
                                <a data-toggle="collapse" data-parent="#accordion" href="#<?php echo $state; ?>">
                                    <?php echo $state; ?></a>
                            </h4>
                        </div>
                        <div id="<?php echo $state; ?>" class="panel-collapse collapse in">
                            <div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,
                                sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
                                minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
                                commodo consequat.</div>
                        </div>
                    </div>
                <?php }
                ?>
            </div>

        </div>
</code>```

EDIT

This is my edided html

```<code>            <div class="row">

                <div class="col-md-4 col-xs-12">

                    <div class="panel-group" id="accordion">

                        <?php
                        foreach ($states as &$state) {
                            ?>
                            <div class="panel panel-default">
                                <div class="panel-heading">
                                    <h4 class="panel-title">
                                        <a data-toggle="collapse" data-parent="#accordion" href="#<?php echo preg_replace('/\s+/', '', $state); ?>">
                                            <?php echo $state; ?></a>
                                    </h4>
                                </div>
                                <div id="<?php echo preg_replace('/\s+/', '', $state); ?>" class="panel-collapse collapse in">
                                    <div class="panel-body">test</div>
                                </div>
                            </div>
                        <?php }
                        ?>

                    </div>

                </div>

            </div>
</code>```

and it looks like this now. Only one slim column in desktop resolution

答:
Your amended code wont work simply because you are defining the col before the foreach so you are wrapping all of them into one col. You should have the col inside your foreach so they all wrap independently.

Try this:

```<code><div class="panel-group" id="accordion">
<div class="row">
    <?php foreach ($states as &$state) { ?>
        <div class="col-xs-12 col-md-4">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h4 class="panel-title">
                        <a data-toggle="collapse" data-parent="#accordion" href="#<?php echo $state; ?>">
                            <?php echo $state; ?></a>
                    </h4>
                </div>
                <div id="<?php echo $state; ?>" class="panel-collapse collapse in">
                    <div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,
                        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
                        minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
                        commodo consequat.</div>
                </div>
            </div>
        </div><!-- col-md-4 now closes here -->
    <?php } ?>
</div>
</code>```

Also it is bad practise within Bootstrap to have a div inbetween your row and cols

Hopefully this works for you!

Title: bootstrap make accordion responsive?

Body:
I'm using the Bootstrap 3 Accordion Collapse,right now everything loads in one column, how can I make it so the panels use multiple columns in desktop resolution and one column in mobile mode?

                <?php
                foreach ($states as &$state) {
                    ?>

                                <a data-toggle="collapse" data-parent="#accordion" href="#<?php echo $state; ?>">
                                    <?php echo $state; ?>

                        <div id="<?php echo $state; ?>" class="panel-collapse collapse in">

Lorem ipsum dolor sit amet, consectetur adipisicing elit,
                                sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
                                minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
                                commodo consequat.

                <?php }
                ?>

EDIT

This is my edided html

                        <?php
                        foreach ($states as &$state) {
                            ?>

                                        <a data-toggle="collapse" data-parent="#accordion" href="#<?php echo preg_replace('/\s+/', '', $state); ?>">
                                            <?php echo $state; ?>

                                <div id="<?php echo preg_replace('/\s+/', '', $state); ?>" class="panel-collapse collapse in">

test

                        <?php }
                        ?>

and it looks like this now. Only one slim column in desktop resolution

Body:
Your amended code wont work simply because you are defining the col before the foreach so you are wrapping all of them into one col. You should have the col inside your foreach so they all wrap independently.

Try this:

<div class="panel-group" id="accordion">
<div class="row">
    <?php foreach ($states as &$state) { ?>
        <div class="col-xs-12 col-md-4">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h4 class="panel-title">
                        <a data-toggle="collapse" data-parent="#accordion" href="#<?php echo $state; ?>">
                            <?php echo $state; ?></a>
                    </h4>
                </div>
                <div id="<?php echo $state; ?>" class="panel-collapse collapse in">
                    <div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,
                        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
                        minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
                        commodo consequat.</div>
                </div>
            </div>
        </div><!-- col-md-4 now closes here -->
    <?php } ?>
</div>

Also it is bad practise within Bootstrap to have a div inbetween your row and cols

Hopefully this works for you!


问:
SceneKit Editor modifying duplicated element changes original element
In the SceneKit editor, if I copy a node, either using copy-paste or via option-drag, the resulting node is somehow "linked" to the original. Attempting to modify this new node in any way other than position changes the attributes of the original as well. This is infuriating, how do I "unlink" a duplicated node from the original?

UPDATE: Per request, here is a video of the behavior I am describing: https://www.dropbox.com/s/vtcom4iejjdtjv0/SceneKit%20Weirdness.mov?dl=0

答:
By Apple documents

However, it also means that changes to the objects attached to one node will affect other nodes that share the same attachments.

https://developer.apple.com/documentation/scenekit/scnnode/1408046-clone

When yor copiying node in editor it actually makes a clone node.
I am not aware about the default values of geometries, but if the geometry specified as shared then all the similar clones will get changed when you are changing one of them.

In your case you just have to click the Unshare button to let the clones to use a distinct copy of the geometry.
Which will not be affected by another node changes.

ContentLicense: CC BY-SA 4.0


问:
Converting .xls to .csv before recombining multiple files into a .xls
I am working on a webscraper tool which downloads excel files from a website. Of course, those .xls files are actually just renamed .csv files, which prevents me from just combining the .xls files together. Instead, I need to convert them all to .csv, them use pyexcel's pyexcel.merge_csv_to_a_book(filelist, outfilename='merged.xls') function to create a excel book from these .csv files.

Here is what I tried:

```<code>        def concatenate_excel_files():
        indexer = 0
        excel_file_list = []
        for file in glob.glob(os.getcwd()+'\Reports\*.'):
            pyexcel.save_as(file_name=file, dest_file_name=str(indexer)+'.csv')
            excel_file_list[indexer] = file
            indexer += 1
        pyexcel.merge_csv_to_a_book(excel_file_list, outfilename='merged.xls')
</code>```

This fails to even convert the files to .csv (IndexError: list index out of range error.)

Any help rewriting this would be appreciated.

答:
Answer by chfw:

for pyexcel to work properly, it needs to know file extension but in your case, the file extension is missing. And it will more helpful if the full stack trace is shown.

Body:
I am working on a webscraper tool which downloads excel files from a website. Of course, those .xls files are actually just renamed .csv files, which prevents me from just combining the .xls files together. Instead, I need to convert them all to .csv, them use pyexcel's pyexcel.merge_csv_to_a_book(filelist, outfilename='merged.xls') function to create a excel book from these .csv files.

Here is what I tried:

        def concatenate_excel_files():
        indexer = 0
        excel_file_list = []
        for file in glob.glob(os.getcwd()+'\Reports\*.'):
            pyexcel.save_as(file_name=file, dest_file_name=str(indexer)+'.csv')
            excel_file_list[indexer] = file
            indexer += 1
        pyexcel.merge_csv_to_a_book(excel_file_list, outfilename='merged.xls')

This fails to even convert the files to .csv (IndexError: list index out of range error.)

Any help rewriting this would be appreciated.


答:
You have a couple of problems here. Firstly the array arguments in your input value should rather be compared with $in which many "any of these in the list" in order to match.

The second problem is that that since the paths are "nested" here you actually need to transform to "dot notation" otherwise you have another variant of the first problem where the conditions would be looking in the "test" array for elements that only have the supplied fields you specify in the input.

So unless you "dot notate" the path as well then since your array items also contain "evaluation" which is not supplied in the input, then it would not match as well.

The other issue here, but easily corrected is the "top" and "testing" separation here is not actually needed. Both conditions actually apply within "both" the $match stages in your pipeline. So you could in fact "flatten" that, as the example shows:

```<code>var outputObject = {
        "top" : {
                "place" : [
                        "A"
                ]
        },
        "testing" : {
                "tests" : {
                        "name" : [
                                "1"
                        ],
                        "thing" : [
                                "X",
                                "Y"
                        ]
                }
        }
};

function dotNotate(obj,target,prefix) {
  target = target || {},
  prefix = prefix || "";

  Object.keys(obj).forEach(function(key) {
    if ( Array.isArray( obj[key] ) ) {
      return target[prefix + key] = { "$in": obj[key] };
    } else if ( typeof(obj[key]) === "object" ) {
      dotNotate(obj[key],target,prefix + key + ".");
    } else {
      return target[prefix + key] = obj[key];
    }
  });

  return target;
}

// Run the transformation
var queryObject = dotNotate(Object.assign(outputObject.top,outputObject.testing));
</code>```

This produces queryObject which now looks like:

```<code>{
    "place" : {
        "$in" : [
            "A"
        ]
    },
    "tests.name" : {
        "$in" : [
            "1"
        ]
    },
    "tests.thing" : {
        "$in" : [
            "X",
            "Y"
        ]
    }
}
</code>```

And then you can run the aggregation:

```<code>db.test.aggregate([
  { '$match': queryObject },
  { '$unwind': "$tests" },
  { '$match': queryObject },
  { '$unwind': "$tests.evaluation" },
  { '$group': {
    '_id': null,
    'uniqueValues': {
      '$addToSet': "$tests.evaluation._id"
    }
  }}
])
</code>```

Which correctly filters the objects

```<code>{
    "_id" : null,
    "uniqueValues" : [
        ObjectId("58f79487bebac50d5b2ae7f1"),
        ObjectId("58f79159bebac50d5b2ae75c"),
        ObjectId("58f782fbbebac50d5b2ae558"),
        ObjectId("58f78c37bebac50d5b2ae704"),
        ObjectId("58f78525bebac50d5b2ae5c9"),
        ObjectId("58f78695bebac50d5b2ae60e")
    ]
}
</code>```

Please note that the conditions you supply here actually matches all documents and array entries you supplied in your question anyway. But it will of course actually remove anything that does not match.

Also ideally the "initial" query would rather use $elemMatch

```<code>{
    "place" : {
        "$in" : [
            "A"
        ]
    },
    "tests": {
      "$elemMatch": {
        "name" : { "$in" : [ "1" ] },
        "thing" : { "$in" : [ "X", "Y" ] }
      }
    }
}
</code>```

Which would actually filter all of the documents properly in the initial query stage, since it would only select documents that actually had array elements which did in fact match "only" those conditions as opposed to the dot notated form in the "initial" query which would also return documents where the notated conditions for the "test" array were met in "any element" instead of "both conditions" on the element. But that may be another exercise to consider as the restructured query can apply to both the initial and "inner" filters without the $elemMatch.

Actually with thanks to this nice solution to a "Deep Object Merge" without additional library dependencies, you can use the $elemMatch like this:

```<code>var outputObject = {
        "top" : {
                "place" : [
                        "A"
                ]
        },
        "testing" : {
                "tests" : {
                        "name" : [
                                "1"
                        ],
                        "thing" : [
                                "X",
                                "Y"
                        ]
                }
        }
};

function dotNotate(obj,target,prefix) {
  target = target || {},
  prefix = prefix || "";

  Object.keys(obj).forEach(function(key) {
    if ( Array.isArray( obj[key] ) ) {
      return target[prefix + key] = { "$in": obj[key] };
    } else if ( typeof(obj[key]) === "object" ) {
      dotNotate(obj[key],target,prefix + key + ".");
    } else {
      return target[prefix + key] = obj[key];
    }
  });

  return target;
}

function isObject(item) {
  return (item && typeof item === 'object' && !Array.isArray(item));
}

function mergeDeep(target, ...sources) {
  if (!sources.length) return target;
  const source = sources.shift();

  if (isObject(target) && isObject(source)) {
    for (var key in source) {
      if (isObject(source[key])) {
        if (!target[key]) Object.assign(target, { [key]: {} });
        mergeDeep(target[key], source[key]);
      } else {
        Object.assign(target, { [key]: source[key] });
      }
    }
  }

  return mergeDeep(target, ...sources);
}

var queryObject = dotNotate(Object.assign(outputObject.top,outputObject.testing));

// Replace dot with $elemMatch
var initialQuery = Object.keys(queryObject).map( k => (
  ( k.split(/\./).length > 1 )
   ? { [k.split(/\./)[0]]: { "$elemMatch": { [k.split(/\./)[1]]: queryObject[k] } } }
   : { [k]: queryObject[k] }
)).reduce((acc,curr) => mergeDeep(acc,curr),{})

db.test.aggregate([
  { '$match': initialQuery },
  { '$unwind': "$tests" },
  { '$match': queryObject },
  { '$unwind': "$tests.evaluation" },
  { '$group': {
    '_id': null,
    'uniqueValues': {
      '$addToSet': "$tests.evaluation._id"
    }
  }}
])
</code>```

With the pipeline being sent to the server as:

```<code>[
    {
        "$match" : {
            "place" : {
                "$in" : [
                    "A"
                ]
            },
            "tests" : {
                "$elemMatch" : {
                    "name" : {
                        "$in" : [
                            "1"
                        ]
                    },
                    "thing" : {
                        "$in" : [
                            "X",
                            "Y"
                        ]
                    }
                }
            }
        }
    },
    {
        "$unwind" : "$tests"
    },
    {
        "$match" : {
            "place" : {
                "$in" : [
                    "A"
                ]
            },
            "tests.name" : {
                "$in" : [
                    "1"
                ]
            },
            "tests.thing" : {
                "$in" : [
                    "X",
                    "Y"
                ]
            }
        }
    },
    {
        "$unwind" : "$tests.evaluation"
    },
    {
        "$group" : {
            "_id" : null,
            "uniqueValues" : {
                "$addToSet" : "$tests.evaluation._id"
            }
        }
    }
]
</code>```

Also your $group is probably better written as:

```<code>{ "$group": { "_id": "$tests.evaluation._id" } }
</code>```

Which returns "distinct" just like $addToSet does, but also puts the output into separate documents, instead of trying to combine into "one" which is probably not the best practice and could in extreme cases break the BSON limit of 16MB. So it is generally better to obtain "distinct" in that way instead.

Title: Dynamically Querying From an Input Object

Body:
I'm trying to dynamically query a database that looks like this:

db.test.insert({
    "_id" : ObjectId("58e574a768afb6085ec3a388"),
    "place": "A",
    "tests" : [
        {
            "name" : "1",
            "thing" : "X",
            "evaluation" : [
                {
                    "_id": ObjectId("58f782fbbebac50d5b2ae558"),
                    "aHigh" : [1,2],
                    "aLow" : [ ],
                    "zHigh" : [ ],
                    "zLow" : [1,3]
                },
                {
                    "_id": ObjectId("58f78525bebac50d5b2ae5c9"),
                    "aHigh" : [1,4],
                    "aLow" : [2],
                    "zHigh" : [ 3],
                    "zLow" : [ ]
                },
                {
                    "_id": ObjectId("58f78695bebac50d5b2ae60e"),
                    "aHigh" : [ ],
                    "aLow" : [1,2,3],
                    "zHigh" : [1,2,3,4],
                    "zLow" : [ ]
                },]
            },
            {
            "name" : "1",
            "thing" : "Y",
            "evaluation" : [
                {
                    "_id": ObjectId("58f78c37bebac50d5b2ae704"),
                    "aHigh" : [1,3],
                    "aLow" : [4],
                    "zHigh" : [ ],
                    "zLow" : [3]
                },
                {
                    "_id": ObjectId("58f79159bebac50d5b2ae75c"),
                    "aHigh" : [1,3,4],
                    "aLow" : [2],
                    "zHigh" : [2],
                    "zLow" : [ ]
                },
                {
                    "_id": ObjectId("58f79487bebac50d5b2ae7f1"),
                    "aHigh" : [1,2,3],
                    "aLow" : [ ],
                    "zHigh" : [ ],
                    "zLow" : [1,2,3,4]
                },]
            }
            ]
        })
db.test.insert({
    "_id" : ObjectId("58eba09e51f7f631dd24aa1c"),
    "place": "B",
    "tests" : [
        {
            "name" : "2",
            "thing" : "Y",
            "evaluation" : [
                {
                    "_id": ObjectId("58f7879abebac50d5b2ae64f"),
                    "aHigh" : [2],
                    "aLow" : [3 ],
                    "zHigh" : [ ],
                    "zLow" : [1,2,3,4]
                },
                {
                    "_id": ObjectId("58f78ae1bebac50d5b2ae6db"),
                    "aHigh" : [ ],
                    "aLow" : [ ],
                    "zHigh" : [ ],
                    "zLow" : [3,4]
                },
                {
                    "_id": ObjectId("58f78ae1bebac50d5b2ae6dc"),
                    "aHigh" : [1,2],
                    "aLow" : [3,4],
                    "zHigh" : [ ],
                    "zLow" : [1,2,3,4]
                },]
            }
            ]
        })

In order to query the database, I have an object that is created by another part of my program. It comes in the form of:

var outputObject = {
    "top": {
        "place": [
        "A"
        ]
    },
    "testing": {
        "tests": {
            "name": [
                "1",
            ],
            "thing": [
                "X",
                "Y"
            ]
        }
    }
    }

I then use that outputObject and $match statements within the aggregate framework to execute the query. I have included two queries which do not seem to work.

db.test.aggregate([
        {$match: {outputObject.top}},
        {$unwind: '$tests'},
        {$match: {outputObject.testing}},
        {$unwind: '$tests.evaluation'},
        {$group: {_id: null, uniqueValues: {$addToSet: "$tests.evaluation._id"}}}
    ])

db.test.aggregate([
        {$match: {$and: [outputObject.top]}},
        {$unwind: '$tests'},
        {$match: {$and: [outputObject.testing]}},
        {$unwind: '$tests.evaluation'},
        {$group: {_id: null, uniqueValues: {$addToSet: "$tests.evaluation._id"}}}
    ])

However, this approach does not seem to be functioning. I have a couple questions:

Do I need to modify the object outputObject before applying it to the $match statement?

Are my queries correct?

Should I be using $and or $in in combination with the $match statement?

What code will produce the desired result?

Currently using mongoDB 3.4.4

Body:
You have a couple of problems here. Firstly the array arguments in your input value should rather be compared with $in which many "any of these in the list" in order to match.

The second problem is that that since the paths are "nested" here you actually need to transform to "dot notation" otherwise you have another variant of the first problem where the conditions would be looking in the "test" array for elements that only have the supplied fields you specify in the input.

So unless you "dot notate" the path as well then since your array items also contain "evaluation" which is not supplied in the input, then it would not match as well.

The other issue here, but easily corrected is the "top" and "testing" separation here is not actually needed. Both conditions actually apply within "both" the $match stages in your pipeline. So you could in fact "flatten" that, as the example shows:

var outputObject = {
        "top" : {
                "place" : [
                        "A"
                ]
        },
        "testing" : {
                "tests" : {
                        "name" : [
                                "1"
                        ],
                        "thing" : [
                                "X",
                                "Y"
                        ]
                }
        }
};

function dotNotate(obj,target,prefix) {
  target = target || {},
  prefix = prefix || "";

  Object.keys(obj).forEach(function(key) {
    if ( Array.isArray( obj[key] ) ) {
      return target[prefix + key] = { "$in": obj[key] };
    } else if ( typeof(obj[key]) === "object" ) {
      dotNotate(obj[key],target,prefix + key + ".");
    } else {
      return target[prefix + key] = obj[key];
    }
  });

  return target;
}

// Run the transformation
var queryObject = dotNotate(Object.assign(outputObject.top,outputObject.testing));

This produces queryObject which now looks like:

{
    "place" : {
        "$in" : [
            "A"
        ]
    },
    "tests.name" : {
        "$in" : [
            "1"
        ]
    },
    "tests.thing" : {
        "$in" : [
            "X",
            "Y"
        ]
    }
}

And then you can run the aggregation:

db.test.aggregate([
  { '$match': queryObject },
  { '$unwind': "$tests" },
  { '$match': queryObject },
  { '$unwind': "$tests.evaluation" },
  { '$group': {
    '_id': null,
    'uniqueValues': {
      '$addToSet': "$tests.evaluation._id"
    }
  }}
])

Which correctly filters the objects

{
    "_id" : null,
    "uniqueValues" : [
        ObjectId("58f79487bebac50d5b2ae7f1"),
        ObjectId("58f79159bebac50d5b2ae75c"),
        ObjectId("58f782fbbebac50d5b2ae558"),
        ObjectId("58f78c37bebac50d5b2ae704"),
        ObjectId("58f78525bebac50d5b2ae5c9"),
        ObjectId("58f78695bebac50d5b2ae60e")
    ]
}

Please note that the conditions you supply here actually matches all documents and array entries you supplied in your question anyway. But it will of course actually remove anything that does not match.

Also ideally the "initial" query would rather use $elemMatch

{
    "place" : {
        "$in" : [
            "A"
        ]
    },
    "tests": {
      "$elemMatch": {
        "name" : { "$in" : [ "1" ] },
        "thing" : { "$in" : [ "X", "Y" ] }
      }
    }
}

Which would actually filter all of the documents properly in the initial query stage, since it would only select documents that actually had array elements which did in fact match "only" those conditions as opposed to the dot notated form in the "initial" query which would also return documents where the notated conditions for the "test" array were met in "any element" instead of "both conditions" on the element. But that may be another exercise to consider as the restructured query can apply to both the initial and "inner" filters without the $elemMatch.

Actually with thanks to this nice solution to a "Deep Object Merge" without additional library dependencies, you can use the $elemMatch like this:

var outputObject = {
        "top" : {
                "place" : [
                        "A"
                ]
        },
        "testing" : {
                "tests" : {
                        "name" : [
                                "1"
                        ],
                        "thing" : [
                                "X",
                                "Y"
                        ]
                }
        }
};

function dotNotate(obj,target,prefix) {
  target = target || {},
  prefix = prefix || "";

  Object.keys(obj).forEach(function(key) {
    if ( Array.isArray( obj[key] ) ) {
      return target[prefix + key] = { "$in": obj[key] };
    } else if ( typeof(obj[key]) === "object" ) {
      dotNotate(obj[key],target,prefix + key + ".");
    } else {
      return target[prefix + key] = obj[key];
    }
  });

  return target;
}

function isObject(item) {
  return (item && typeof item === 'object' && !Array.isArray(item));
}

function mergeDeep(target, ...sources) {
  if (!sources.length) return target;
  const source = sources.shift();

  if (isObject(target) && isObject(source)) {
    for (var key in source) {
      if (isObject(source[key])) {
        if (!target[key]) Object.assign(target, { [key]: {} });
        mergeDeep(target[key], source[key]);
      } else {
        Object.assign(target, { [key]: source[key] });
      }
    }
  }

  return mergeDeep(target, ...sources);
}

var queryObject = dotNotate(Object.assign(outputObject.top,outputObject.testing));

// Replace dot with $elemMatch
var initialQuery = Object.keys(queryObject).map( k => (
  ( k.split(/\./).length > 1 )
   ? { [k.split(/\./)[0]]: { "$elemMatch": { [k.split(/\./)[1]]: queryObject[k] } } }
   : { [k]: queryObject[k] }
)).reduce((acc,curr) => mergeDeep(acc,curr),{})

db.test.aggregate([
  { '$match': initialQuery },
  { '$unwind': "$tests" },
  { '$match': queryObject },
  { '$unwind': "$tests.evaluation" },
  { '$group': {
    '_id': null,
    'uniqueValues': {
      '$addToSet': "$tests.evaluation._id"
    }
  }}
])

With the pipeline being sent to the server as:

[
    {
        "$match" : {
            "place" : {
                "$in" : [
                    "A"
                ]
            },
            "tests" : {
                "$elemMatch" : {
                    "name" : {
                        "$in" : [
                            "1"
                        ]
                    },
                    "thing" : {
                        "$in" : [
                            "X",
                            "Y"
                        ]
                    }
                }
            }
        }
    },
    {
        "$unwind" : "$tests"
    },
    {
        "$match" : {
            "place" : {
                "$in" : [
                    "A"
                ]
            },
            "tests.name" : {
                "$in" : [
                    "1"
                ]
            },
            "tests.thing" : {
                "$in" : [
                    "X",
                    "Y"
                ]
            }
        }
    },
    {
        "$unwind" : "$tests.evaluation"
    },
    {
        "$group" : {
            "_id" : null,
            "uniqueValues" : {
                "$addToSet" : "$tests.evaluation._id"
            }
        }
    }
]

Also your $group is probably better written as:

{ "$group": { "_id": "$tests.evaluation._id" } }

Which returns "distinct" just like $addToSet does, but also puts the output into separate documents, instead of trying to combine into "one" which is probably not the best practice and could in extreme cases break the BSON limit of 16MB. So it is generally better to obtain "distinct" in that way instead.


问:
how do i reference an id with concatenated variable in jquery appendTo()?
I am appending html code to a div using jquery. Part of that code references a div's id using a concatenated variable from a loop.

```<code>$(... +
    '<div class="recommendations filter" id="recCards-'+ i +'">' +
    '<div><h5>Recommended Cards</h5></div>' +
        '<ul></ul>' +
    '</div>' +
  ...
 ).appendTo('.someDiv');
</code>```

I'm then trying to append code from another loop into the ul by referencing the ".recommendations" div's ID like so...

```<code>var recCardsList = $(div).attr('id', '.recCards-'"+i+"' ul');

$('<div>'+recCardName+'</div>').appendTo(recCardsList);
</code>```

I've tried every combination of quotation marks that i can think of, but nothing grabs the div correctly to append the new content

答:
Assuming that variable i is still within the scope of the function the solution stated above

```<code>'recCards-'+i+' ul'
</code>```

Would definitely work, as stated in the comment check either with console.log() or alert() what variable i is there is a chance due to what was given i is null.

If they are within the same function you can also look at this post to combine the 2 loops with appendTo() and append()

jQuery append inside appended element

Body:
I am appending html code to a div using jquery. Part of that code references a div's id using a concatenated variable from a loop.

$(... +
    '
' +
    '

Recommended Cards

' +
        '

' +
    '
' +
  ...
 ).appendTo('.someDiv');

I'm then trying to append code from another loop into the ul by referencing the ".recommendations" div's ID like so...

var recCardsList = $(div).attr('id', '.recCards-'"+i+"' ul');

$('
'+recCardName+'
').appendTo(recCardsList);

I've tried every combination of quotation marks that i can think of, but nothing grabs the div correctly to append the new content

Body:
Assuming that variable i is still within the scope of the function the solution stated above

'recCards-'+i+' ul'

Would definitely work, as stated in the comment check either with console.log() or alert() what variable i is there is a chance due to what was given i is null.

If they are within the same function you can also look at this post to combine the 2 loops with appendTo() and append()

jQuery append inside appended element


问:
How can I use sequences in SQLite?
I'm writing a PHP-based web application that should work with multiple database systems. The most important are MySQL and SQLite but PostgreSQL and others would also be nice. For this I try to use as portable SQL as possible. Where this isn't possible, I have defined some meta words in my queries that are handled by my DB layer and converted to platform-specific SQL commands.

I'm now trying to add sequences support. Every DBMS handles sequences differently, there is no common way to write them in SQL. I have read and understood the way PostgreSQL does it. I have found an interesting solution for MySQL that uses MyISAM tables to escape the isolation constraints of a transaction. After all, sequences are not rolled back with the transaction they're used in and that's exactly what I want. Sequences are supposed to be multi-user safe.

Now I haven't found a solution for SQLite. It lacks built-in sequence support. It doesn't provide ways to store data outside a running transaction. My current implementation is to lock the table far enough to do a SELECT MAX(...) and use that value. But I want to get rid of that entirely. In SQLite, this approach requires locking the whole database!

Does anybody know a solution for this with SQLite?

答:
I would use lastInsertRowID. This returns the rowid of the last inserted data (which equals the INTEGER PRIMARY KEY value of that row).
You won't need any sequence then.</p>

Title: How can I use sequences in SQLite?


问:
Odd behavior with SSRS and table spacing on a new page
In my report in SSRS, I have about .2 inches of space between the headers and tables. However, I have an issue where I have a table that is multiple pages long, and there ends up being no space between the table and the next row on the new page, like so:

And this is what my report likes in the viewer. Note that my .2 inches of white space is inside each subreport.

Is there anything to be done about this?

答:
It sounds like you don't have margins set on the report output. Make sure  you have a top margin set in:

Report Properties > Margins


答:
You'll hardly get the list that way.
Try this:

```<code>var recCardsList = $('#recCards-' + i + ' ul');
</code>```

Also it's not valid to append
 to
. It'd rather be
:

```<code>$('<li>'+recCardName+'</li>').appendTo(recCardsList);
</code>```

Title: how do i reference an id with concatenated variable in jquery appendTo()?

Body:
You'll hardly get the list that way.
Try this:

var recCardsList = $('#recCards-' + i + ' ul');

Also it's not valid to append <div> to <ul>. It'd rather be <li>:

$('<li>'+recCardName+'</li>').appendTo(recCardsList);


问:
make status bar translucent - swift
i want to make the status bar translucent so that the it wont differ with the background image in app

i tried with this code

```<code>override func preferredStatusBarStyle() -> UIStatusBarStyle {
    return UIStatusBarStyle.LightContent
}
</code>```

but it makes the status bar as white

i need the status bar but it should be translucent.

for navigation bar i used this in didload

```<code>    self.navigationController?.navigationBarHidden = false      // Show navigationbar.

    self.navigationItem.leftItemsSupplementBackButton = true        // To add back button.

    self.navigationController?.navigationBar.topItem!.title = ""  // set nav bar title

    self.navigationController?.navigationBar.backItem?.title = "" //set back button text

    self.navigationController?.navigationBar.tintColor = UIColor(red: 0 / 255.0, green: 94 / 255.0, blue: 245 / 255.0, alpha: 1.0)

    //        setting navigation bar translucent background need 3 lines of code

    self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
    self.navigationController?.navigationBar.shadowImage = UIImage()
    self.navigationController?.navigationBar.translucent = true
</code>```

any guess i am using simulator.

答:
```<code>UIApplication.shared.statusBarView?.backgroundColor = .clear
</code>```

Title: make status bar translucent - swift

Body:
i want to make the status bar translucent so that the it wont differ with the background image in app

i tried with this code

override func preferredStatusBarStyle() -> UIStatusBarStyle {
    return UIStatusBarStyle.LightContent
}

but it makes the status bar as white

i need the status bar but it should be translucent.

for navigation bar i used this in didload

    self.navigationController?.navigationBarHidden = false      // Show navigationbar.

    self.navigationItem.leftItemsSupplementBackButton = true        // To add back button.

    self.navigationController?.navigationBar.topItem!.title = ""  // set nav bar title

    self.navigationController?.navigationBar.backItem?.title = "" //set back button text

    self.navigationController?.navigationBar.tintColor = UIColor(red: 0 / 255.0, green: 94 / 255.0, blue: 245 / 255.0, alpha: 1.0)

    //        setting navigation bar translucent background need 3 lines of code

    self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
    self.navigationController?.navigationBar.shadowImage = UIImage()
    self.navigationController?.navigationBar.translucent = true

any guess i am using simulator.


问:
Publish from VS 2017 doesn't include views/web.config which throws 500 error
As the title says, I publish my MVC/.Net 4.6.2 app to my Server 2012R2 server and it throws a 500 error. If I manually copy my Views/web.config everything works again.

Am I missing an option to get it to deploy?

答:
In this situation you all you have to do is make sure that the Build Action for the web.config file is set to Content. I have found that sometimes files that you need don't get set like this automatically within Visual Studio.

To make this change, find the file in the Solution Explorer. Select the file. Then in the Properties pane, set the Build Action to Content by choosing Content form the dropdown next to the property label.

Glad this helped you out.


问:
Matplotlib xlabel in Arial with one word italicised
I want to create a matplotlib figure with an x-axis label that is in Arial font, and has one word italicised.

I can create figures with x-axis labels in latex-font with one word italicised; I can also create figures with x-axis labels in Arial, as long as I have either the entire label italicised or the entire label normal; but I can't get part of the xlabel in Arial italicised and the other part in arial normal.

I'm mostly trying permutations of the following code:

```<code>from matplotlib import pyplot as plt
import numpy as n
import matplotlib
from matplotlib.font_manager import FontProperties
font = {'family' : 'Arial',
    'weight' : 'medium',
    'size'   : 20,
    'style'  : 'normal'}
font0 = {'family' : 'Arial',
    'weight' : 'medium',
    'size'   : 20,
    'style'  : 'italic'}

matplotlib.rcParams['mathtext.fontset'] = 'custom'
matplotlib.rcParams['mathtext.rm'] = 'Arial'
matplotlib.rcParams['mathtext.it'] = 'Arial'

matplotlib.rc('font', **font)
#matplotlib.rc('font', **font0)
matplotlib.rc('text', usetex=False)

plt.figure(); plt.plot(n.linspace(0,3,10), n.linspace(0,3,10))
plt.xlabel(r'$\mathit{italics}$ - rest normal')
</code>```

答:
```<code>from matplotlib.pyplot import *

# Need to use precise font names in rcParams; I found my fonts with
#>>> import matplotlib.font_manager
#>>> [f.name for f in matplotlib.font_manager.fontManager.ttflist]

rcParams['mathtext.fontset'] = 'custom'
rcParams['mathtext.it'] = 'Arial:italic'
rcParams['mathtext.rm'] = 'Arial'

fig, ay = subplots()

# Using the specialized math font elsewhere, plus a different font
xlabel(r"$\mathit{Italic}$ $\mathrm{and\ just\ Arial}$ and not-math-font",fontsize=18)
# No math formatting, for comparison
ylabel(r'Italic and just Arial and not-math-font', fontsize=18)
grid()

show()
</code>```

Body:
I want to create a matplotlib figure with an x-axis label that is in Arial font, and has one word italicised.

I can create figures with x-axis labels in latex-font with one word italicised; I can also create figures with x-axis labels in Arial, as long as I have either the entire label italicised or the entire label normal; but I can't get part of the xlabel in Arial italicised and the other part in arial normal.

I'm mostly trying permutations of the following code:

from matplotlib import pyplot as plt
import numpy as n
import matplotlib
from matplotlib.font_manager import FontProperties
font = {'family' : 'Arial',
    'weight' : 'medium',
    'size'   : 20,
    'style'  : 'normal'}
font0 = {'family' : 'Arial',
    'weight' : 'medium',
    'size'   : 20,
    'style'  : 'italic'}

matplotlib.rcParams['mathtext.fontset'] = 'custom'
matplotlib.rcParams['mathtext.rm'] = 'Arial'
matplotlib.rcParams['mathtext.it'] = 'Arial'

matplotlib.rc('font', **font)
#matplotlib.rc('font', **font0)
matplotlib.rc('text', usetex=False)

plt.figure(); plt.plot(n.linspace(0,3,10), n.linspace(0,3,10))
plt.xlabel(r'$\mathit{italics}$ - rest normal')


问:
Android service connection leaked after starting new activity
I am trying to figure out why my service is leaking from my application.

The official error I am getting is that the Service is not registered any longer.

Here's what works:
I create a service which creates a listener, when the listener is triggered the service sets of an intent to start another activity. The new activity begins and does its thing.

The problem:
When I get back to a main screen which gives me the option to turn off the service, I get the error which I stated previously which causes an IllegalArgumentException (when I try to unbind the service which is not registered).

Any help would be greatly appreciated. Here is the code for my service. It is all I've included because this seems to be where the problem is, but if you need any more let me know.

Thanks in advance, here is the code.

```<code>import java.lang.ref.WeakReference;
import java.util.List;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class AccelService extends Service
{
public static boolean listening = false;
public boolean callMade = false;
private static Sensor sensor;
private static SensorManager ASensorManager;

private SensorEventListener EventListener =
    new SensorEventListener() {

    private float x = 0;
    private float y = 0;
    private float z = 0;
    private double max = 0;
    private double force = 0;

    public void onAccuracyChanged(Sensor sensor, int accuracy) {}

    public void onSensorChanged(SensorEvent event)
    {

        x = event.values[0];
        y = event.values[1];
        z = event.values[2];
        force = Math.sqrt(x*x+y*y+z*z);
        Log.i("LocalService", "Event happened: " + force);

        if (force > Main.dropValue)
        {
            onDrop(force);
        }
    }
};

public void startListener()
{
    ASensorManager = (SensorManager) this.getSystemService(Context.SENSOR_SERVICE);
    List<Sensor> sensors = ASensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
    if (sensors.size() > 0)
    {
        sensor = sensors.get(0);
        listening = ASensorManager.registerListener(accelEventListener, sensor, SensorManager.SENSOR_DELAY_GAME);

    }
}

public class AccelBinder<S> extends Binder
{
    private WeakReference<S> mService;

    public AccelBinder (S service)
    {
        mService = new WeakReference<S>(service);
    }

    public S getService()
    {
        return mService.get();
    }
}

public IBinder mBinder;

@Override
public void onCreate()
{
    startListener();

    mBinder = new AccelBinder<AccelService>(this);
}

public boolean isListening()
{
    return listening;
}

/*@Override
public void onStart(Intent intent, int startId)
{
    Log.i("LocalService", "Received start id " + startId + ": " + intent);
}*/

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    Log.i("LocalService", "Received start id " + startId + ": " + intent);
    return AccelService.START_STICKY;
}

@Override
public void onDestroy()
{
    if (listening)
        stopListening();
    mBinder = null;

    super.onDestroy();
}

public void onDrop(double force)
{
    if (!callMade)
    {
        Toast.makeText(this, "Phone dropped: " + force, 5000).show();
        Intent i = new Intent(this,Next.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        callMade = true;
        //stopListening();
        //onDestroy();
        //SafetyNet.ctxt.unbindService(SafetyNet.AccelWatch);
        this.startActivity(i);
    }
}

public void stopListening()
{

    listening = false;
    try {
        if (ASensorManager != null && accelEventListener != null)
        {
            ASensorManager.unregisterListener(accelEventListener);
        }
    } catch (Exception e) {}
}

@Override
public IBinder onBind(Intent intent)
{
    return mBinder;
}

}
</code>```

答:
I don't know much about Sensors, but your Service is looking pretty good.

IF AccelBinder is an inner class of your service make it a static inner class or, as I generally do, a separate class altogether. Static inner classes don't have a reference to the outer class. Remember you WILL leak your Binder. If your Binder is a non-static inner class, it has a reference to your Service so that will leak as well.

I am guessing - like really wildly guessing - in the absence of any code that there is something wrong with the management of your Activity life-cycle and how you handle your Binder objects.

Things to keep in mind....

Don't keep a static reference to your Binder object - they are disposable - get a new one each time you bind.

Keep your Binding symmetrical with regards to your Activity life-cycle. If you bind in onCreate(), unbind in onDestroy() ( or onPause if isFinishing() ) etc. This is particularly important if you don't understand that a physical rotation of a phone with Sensor destroys your Activity the recreates it from scratch.

You seem altogether too fond of "static" class variables. In Android static things tend to lead to memory leaks - and if what you leak has a Context - things get nasty. If you want to keep state between instances of the same class, consider using Preferences instead.

For example,

```<code>private static Sensor sensor;
private static SensorManager ASensorManager;
</code>```

Throw these away between uses.

Make sure you especially are not keeping a static reference to your Service in your Activity. Services are singletons by the very nature of the Android, if it is still running you will get the same Service each time you bind. Count on your Service being killed by the OS at some point in time. Write your Service so that it does it's job if it is restarted afresh.

That's enough guessing for one day.

Body:
I am trying to figure out why my service is leaking from my application.

The official error I am getting is that the Service is not registered any longer.

Here's what works:
I create a service which creates a listener, when the listener is triggered the service sets of an intent to start another activity. The new activity begins and does its thing.

The problem:
When I get back to a main screen which gives me the option to turn off the service, I get the error which I stated previously which causes an IllegalArgumentException (when I try to unbind the service which is not registered).

Any help would be greatly appreciated. Here is the code for my service. It is all I've included because this seems to be where the problem is, but if you need any more let me know.

Thanks in advance, here is the code.

import java.lang.ref.WeakReference;
import java.util.List;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class AccelService extends Service
{
public static boolean listening = false;
public boolean callMade = false;
private static Sensor sensor;
private static SensorManager ASensorManager;

private SensorEventListener EventListener =
    new SensorEventListener() {

    private float x = 0;
    private float y = 0;
    private float z = 0;
    private double max = 0;
    private double force = 0;

    public void onAccuracyChanged(Sensor sensor, int accuracy) {}

    public void onSensorChanged(SensorEvent event)
    {

        x = event.values[0];
        y = event.values[1];
        z = event.values[2];
        force = Math.sqrt(x*x+y*y+z*z);
        Log.i("LocalService", "Event happened: " + force);

        if (force > Main.dropValue)
        {
            onDrop(force);
        }
    }
};

public void startListener()
{
    ASensorManager = (SensorManager) this.getSystemService(Context.SENSOR_SERVICE);
    List<Sensor> sensors = ASensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
    if (sensors.size() > 0)
    {
        sensor = sensors.get(0);
        listening = ASensorManager.registerListener(accelEventListener, sensor, SensorManager.SENSOR_DELAY_GAME);

    }
}

public class AccelBinder<S> extends Binder
{
    private WeakReference<S> mService;

    public AccelBinder (S service)
    {
        mService = new WeakReference<S>(service);
    }

    public S getService()
    {
        return mService.get();
    }
}

public IBinder mBinder;

@Override
public void onCreate()
{
    startListener();

    mBinder = new AccelBinder<AccelService>(this);
}

public boolean isListening()
{
    return listening;
}

/*@Override
public void onStart(Intent intent, int startId)
{
    Log.i("LocalService", "Received start id " + startId + ": " + intent);
}*/

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    Log.i("LocalService", "Received start id " + startId + ": " + intent);
    return AccelService.START_STICKY;
}

@Override
public void onDestroy()
{
    if (listening)
        stopListening();
    mBinder = null;

    super.onDestroy();
}

public void onDrop(double force)
{
    if (!callMade)
    {
        Toast.makeText(this, "Phone dropped: " + force, 5000).show();
        Intent i = new Intent(this,Next.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        callMade = true;
        //stopListening();
        //onDestroy();
        //SafetyNet.ctxt.unbindService(SafetyNet.AccelWatch);
        this.startActivity(i);
    }
}

public void stopListening()
{

    listening = false;
    try {
        if (ASensorManager != null && accelEventListener != null)
        {
            ASensorManager.unregisterListener(accelEventListener);
        }
    } catch (Exception e) {}
}

@Override
public IBinder onBind(Intent intent)
{
    return mBinder;
}

}

Body:
I don't know much about Sensors, but your Service is looking pretty good.

IF AccelBinder is an inner class of your service make it a static inner class or, as I generally do, a separate class altogether. Static inner classes don't have a reference to the outer class. Remember you WILL leak your Binder. If your Binder is a non-static inner class, it has a reference to your Service so that will leak as well.

I am guessing - like really wildly guessing - in the absence of any code that there is something wrong with the management of your Activity life-cycle and how you handle your Binder objects.

Things to keep in mind....

Don't keep a static reference to your Binder object - they are disposable - get a new one each time you bind.

Keep your Binding symmetrical with regards to your Activity life-cycle. If you bind in onCreate(), unbind in onDestroy() ( or onPause if isFinishing() ) etc. This is particularly important if you don't understand that a physical rotation of a phone with Sensor destroys your Activity the recreates it from scratch.

You seem altogether too fond of "static" class variables. In Android static things tend to lead to memory leaks - and if what you leak has a Context - things get nasty. If you want to keep state between instances of the same class, consider using Preferences instead.

For example,

private static Sensor sensor;
private static SensorManager ASensorManager;

Throw these away between uses.

Make sure you especially are not keeping a static reference to your Service in your Activity. Services are singletons by the very nature of the Android, if it is still running you will get the same Service each time you bind. Count on your Service being killed by the OS at some point in time. Write your Service so that it does it's job if it is restarted afresh.

That's enough guessing for one day.