问:
Stopping a blinking cursor at end of css animation
I guys I have tried a lot of things that didn't work. I have a css animation with a blinking cursor. I am trying to use it in this game I'm developing.

Link to game for visual reference: https://code.sololearn.com/WF65X6DEns7o/#css

+++

so here is the code that is a problem

HTML:

```<code>   <div id = "Header"> <b>Real Estate Agent</b> </div>
</code>```

CSS:

```<code>#Header{
font-size:50px; color:darkOrange; text-shadow:3px 3pxblack;
overflow:hidden;
letter-spacing: .15em;
animation: typing 3.5s steps(60, end), blink-caret .65s step-end infinite;
white-space: nowrap;
border-right: .15em solid orange;
width:500px;
}

 @keyframes typing {
  from { width: 0 }
   to { width: 500px }
   }

@keyframes blink-caret {
from, to { border-color: orange }
 50% { border-color: transparent; }
   }
</code>```

+++++++++++++

currently the cursor blinks until all the text is done typing and then it keeps blink at the end of the words.

How can i make the cursor stop blinking at the end of the animation and stop the animation cycle.

As i have said i have tried a few things and nothing is working.

thanks

答:
Try removing infinite like this:

```<code>animation: typing 3.5s steps(60, end), blink-caret .65s step-end;
</code>```

Body:
I guys I have tried a lot of things that didn't work. I have a css animation with a blinking cursor. I am trying to use it in this game I'm developing.

Link to game for visual reference: https://code.sololearn.com/WF65X6DEns7o/#css

+++

so here is the code that is a problem

HTML:

 Real Estate Agent

CSS:

#Header{
font-size:50px; color:darkOrange; text-shadow:3px 3pxblack;
overflow:hidden;
letter-spacing: .15em;
animation: typing 3.5s steps(60, end), blink-caret .65s step-end infinite;
white-space: nowrap;
border-right: .15em solid orange;
width:500px;
}

 @keyframes typing {
  from { width: 0 }
   to { width: 500px }
   }

@keyframes blink-caret {
from, to { border-color: orange }
 50% { border-color: transparent; }
   }

+++++++++++++

currently the cursor blinks until all the text is done typing and then it keeps blink at the end of the words.

How can i make the cursor stop blinking at the end of the animation and stop the animation cycle.

As i have said i have tried a few things and nothing is working.

thanks

Body:
Try removing infinite like this:

animation: typing 3.5s steps(60, end), blink-caret .65s step-end;


来源: stackexchange

问:
iOS Run errors s Xamarin Live Player and Hanselman.Forms
I created an app based off the Hanselman Forms app.  I'm trying to get it to run with the new Xamarin iOS Live Player and i'm getting runtime build errors.

To make sure it wasn't something i broke i did a fresh install of Hanselman Forms and Visual Studio 2017 Preview and connected the iPhone live player.

The build compiles fine with VS.
Trying to run the debug app with Live Player on iPhone gives the following errors.

The following errors were encountered when building and running your app:

• TweetStore.cs: The type or namespace name 'ITweetStore' could not be found (are you missing a using directive or an assembly reference?)
• TweetStore.cs: The type or namespace name 'Tweet' does not exist in the namespace 'Hanselman.Portable' (are you missing an assembly reference?)
• LaunchTwitter.cs: The type or namespace name 'ILaunchTwitter' could not be found (are you missing a using directive or an assembly reference?)

• AppDelegate.cs: The type or namespace name 'App' could not be found (are you missing a using directive or an assembly reference?)

OK

The packets have been refreshed.
I've removed the bin/obj files to do a fresh build.

I've removed the reference, built clean, got similar errors in VS, added the reference back in and the VS build succeeds.

Android works fine.

Any ideas as to what i'm missing?

答: Check that you have selected a Startup Project that matches your device type (iOS or Android) and that the configuration matches that device type (eg. Debug|iPhone Simulator for iOS).</p>

ContentLicense: CC BY-SA 3.0


问:
How to exclude username from gitlab url
I just finished installing gitlab and noticed that when i create a new repo, the url to the repo includes my username right before the gitlab url.

```<code>git clone http://jonesdem@gitlab.example.com/jonesdem/firstrepo.git
cd firstrepo
touch README.md
git add README.md
git commit -m "add README"
git push -u origin master
</code>```

I would like the url to look like so

```<code>git clone http://gitlab.example.com/jonesdem/firstrepo.git
cd firstrepo
touch README.md
git add README.md
git commit -m "add README"
git push -u origin master
</code>```

Any idea which configuration setting i need to tweak to fix this?

答:
This is not a configurable option in GitLab, as it is commonly accepted practice to use URLs in the format GitLab is providing them

However, the following should work to the best of my knowledge:

In the directory of your git repository:

```<code>git clone http://gitlab.example.com/jonesdem/firstrepo.git
</code>```

Then when you need to push:

```<code>git config credential.helper store
git push http://gitlab.example.com/jonesdem/firstrepo.git

Username for 'https://gitlab.example.com.com': <USERNAME>
Password for 'https://USERNAME@gitlab.example.com': <PASSWORD>
</code>```

The username before the @ on the HTTP(S) URL is used to indicate the user to authenticate as, you cannot push to a remote git repository if you have not authenticated - this is why it is present. It is common practice to use URLs such as http://jonesdem@gitlab.example.com/jonesdem/firstrepo.git, as opposed to using the method i have indicated above.

Title: How to exclude username from gitlab url

Body:
I just finished installing gitlab and noticed that when i create a new repo, the url to the repo includes my username right before the gitlab url.

git clone http://jonesdem@gitlab.example.com/jonesdem/firstrepo.git
cd firstrepo
touch README.md
git add README.md
git commit -m "add README"
git push -u origin master

I would like the url to look like so

git clone http://gitlab.example.com/jonesdem/firstrepo.git
cd firstrepo
touch README.md
git add README.md
git commit -m "add README"
git push -u origin master

Any idea which configuration setting i need to tweak to fix this?

Body:
This is not a configurable option in GitLab, as it is commonly accepted practice to use URLs in the format GitLab is providing them

However, the following should work to the best of my knowledge:

In the directory of your git repository:

git clone http://gitlab.example.com/jonesdem/firstrepo.git

Then when you need to push:

git config credential.helper store
git push http://gitlab.example.com/jonesdem/firstrepo.git

Username for 'https://gitlab.example.com.com': <USERNAME>
Password for 'https://USERNAME@gitlab.example.com': <PASSWORD>

The username before the @ on the HTTP(S) URL is used to indicate the user to authenticate as, you cannot push to a remote git repository if you have not authenticated - this is why it is present. It is common practice to use URLs such as http://jonesdem@gitlab.example.com/jonesdem/firstrepo.git, as opposed to using the method i have indicated above.


问:
three.js-Uncaught ReferenceError: scene is not defined
I am new to a-frame,three.js and am trying to create a simple scene using a .obj model my aim is to create one tree and then clone it but it gives an error stating Uncaught ReferenceError: scene is not defined

```<code> <a-scene>
 <a-assets>
   <img id="my-image" src="sky.jpg">
   <img id="grass" src="grass.jpg">
   <a-asset-item id="tree-obj" src="tree-05.obj"></a-asset-item>
   <a-asset-item id="tree-mtl" src="tree-05.mtl"></a-asset-item>
   <a-asset-item id="lion-cub-obj" src="lion-cub.obj"></a-asset-item>
   <a-asset-item id="lion-cub-mtl" src="lion-cub.mtl"></a-asset-item>
 </a-assets>
  <a-plane src="#grass" height="200" width="200" rotation="-90 0 0"></a-plane>
   <a-obj-model src="#tree-obj" mtl="#tree-mtl" scale="0.05 0.05 0.05" id="group" position=" 4 0.5 0"></a-obj-model>
   <script>
    var mtlLoader = new THREE.MTLLoader();
    mtlLoader.setPath('./');
    mtlLoader.load('tree-05.mtl', function(materials) {
    materials.preload();
    var objLoader = new THREE.OBJLoader();
    objLoader.setMaterials(materials);
    objLoader.setPath('./');
    objLoader.load('tree-05.obj', function(object) {
      object.scale.set(0.05, 0.05, 0.05);
      object.position.set( 6, 0.5, 0 );
      scene.add(object);
      });
     });
  </script>
 <a-obj-model src="#lion-cub-obj" mtl="#lion-cub-mtl" scale="0.25 0.25 0.25" rotation="0 -180 0" position=" 0 1 0"></a-obj-model>
<a-sky src="#my-image" position="0 -200 0"></a-sky>
</code>```

答: You didn't define the scene in Your

Body:
You didn't define the scene in Your <script> tags, You need to make a reference either by making a:

document.querySelector('a-scene').object3D; reference or,

making a reference this.el.sceneEl.object3D on any <a-entity> for it seems to return the a-scene reference, in Your case: document.querySelector('a-plane').sceneEl.object3D;

btw when you put the <script> tag like you did, the scope is the window, not the <a-obj-model>. My advise would be creating a component:

AFRAME.registerComponent('myloader', {
    init: function(){
    var self = this;
    var mtlLoader = new THREE.MTLLoader();
    mtlLoader.setPath('./');
    mtlLoader.load('tree-05.mtl', function(materials) {
    materials.preload();
    var objLoader = new THREE.OBJLoader();
    objLoader.setMaterials(materials);
    objLoader.setPath('./');
    objLoader.load('tree-05.obj', function(object) {
      object.scale.set(0.05, 0.05, 0.05);
      object.position.set( 6, 0.5, 0 );
      self.el.sceneEl.object3D.add(object);
}
});

then add it as follows: <a-obj-model myloader (...)

It's not the best component, as You'd need to define the update and remove functions, still i'd do it this way.


问:
.ideavimrc file mapping Esc key
I would like this vim mapping to work in ideavim.

```<code>    inoremap <S-Space> <Esc>
</code>```

It maps Shift Space with Esc in insert mode.

Any ideas what to put in my .ideavimrc?

答:
You can put exactly this line into your ~/.ideavimrc and it will result in the expected mapping.

You can try it interactively as well by typing :inoremap <S-Space> <Esc>.

Edit: It's currently not possible. Vote for VIM-1026 at IdeaVim's bug tracker to get updates.

Title: .ideavimrc file mapping Esc key

Body:
I would like this vim mapping to work in ideavim.

    inoremap <S-Space> <Esc>

It maps Shift Space with Esc in insert mode.

Any ideas what to put in my .ideavimrc?


问:
How to update each and every keys of redux state by iteration with immutable principle
I have a redux state as follows:-

```<code>data = {"facebook":true,"twitter":false,"google":false,"instagram":false,"watsapp":false}
</code>```

I will be passing the key values in action ex:-("facebook","twitter")

lets say i passed "facebook".
Then I want the state to be updated to

```<code>{"facebook":true,"twitter":false,"google":false,"instagram":false,"watsapp":false}
</code>```

here is my reducer function

```<code>function data = (state=initialstate,action) => {
   return {...state, [action.account]=true}
}
</code>```

For first time, it will give desired result.

```<code>{"facebook":true,"twitter":false,"google":false,"instagram":false,"watsapp":false}
</code>```

Now lets say, I am passing the key "twitter"

What I want:

```<code>{"facebook":false,"twitter":true,"google":false,"instagram":false,"watsapp":false}
</code>```

What I was getting with above reducer function (as expected)

```<code>{"facebook":true,"twitter":true,"google":false,"instagram":false,"watsapp":false}
</code>```

So I updated my reducer function to as following:-

```<code>function data = (state, action) => {
  Object.keys(state).forEach(function(key) {
    if(key!=action.account){
      state[key]=false;
    } else {
      state[key]=true;
    }
   });
  return state
}
</code>```

But this is against redux principle of immutable data.
As I am using selector as well, it is showing some unexpected behaviour.

How to update my reducer function which will set all the previously set values to false and will only set the current key to true keeping in mind immutable data principle of redux

答:
From what I understand, you would like all keys to be set to false, with the exception of the dispatched action.account to be set to true.

```<code>const data = (state, action) => {
    let { account } = action
    var newObj = {}

    Object.keys(state).forEach(function(key) {
        newObj[key] = false
    })

    return {...newObj, [account]:true }
}
</code>```

Body:
I have a redux state as follows:-

data = {"facebook":true,"twitter":false,"google":false,"instagram":false,"watsapp":false}

I will be passing the key values in action ex:-("facebook","twitter")

lets say i passed "facebook".
Then I want the state to be updated to

{"facebook":true,"twitter":false,"google":false,"instagram":false,"watsapp":false}

here is my reducer function

function data = (state=initialstate,action) => {
   return {...state, [action.account]=true}
}

For first time, it will give desired result.

{"facebook":true,"twitter":false,"google":false,"instagram":false,"watsapp":false}

Now lets say, I am passing the key "twitter"

What I want:

{"facebook":false,"twitter":true,"google":false,"instagram":false,"watsapp":false}

What I was getting with above reducer function (as expected)

{"facebook":true,"twitter":true,"google":false,"instagram":false,"watsapp":false}

So I updated my reducer function to as following:-

function data = (state, action) => {
  Object.keys(state).forEach(function(key) {
    if(key!=action.account){
      state[key]=false;
    } else {
      state[key]=true;
    }
   });
  return state
}

But this is against redux principle of immutable data.
As I am using selector as well, it is showing some unexpected behaviour.

How to update my reducer function which will set all the previously set values to false and will only set the current key to true keeping in mind immutable data principle of redux

Body:
From what I understand, you would like all keys to be set to false, with the exception of the dispatched action.account to be set to true.

const data = (state, action) => {
    let { account } = action
    var newObj = {}

    Object.keys(state).forEach(function(key) {
        newObj[key] = false
    })

    return {...newObj, [account]:true }
}


问:
Volume too low on iPhone when playing back the recorded file
I am developing an iOS app wherein I should be able to record a sound, save it to the filesystem and then play it back from the disk. When I try to play the file off the disk, I could barely hear anything. The volume is too low. But I'm pretty sure I'd set the device volume to max. I am using AVAudioRecorder and AVAudioPlayer` for recording and playing.

Could someone please point out what the issue could be?

答:
For most the solution here will probably be to use the .defaultToSpeaker option with the AVAudioSessionCategoryPlayAndRecord category:

```<code>try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, with: [.defaultToSpeaker])
</code>```

But for me the issue turned out to be that a different component in my app was setting the AVAudioSessionModeMeasurement mode on the audio session, which for whatever reason reduces the output volume.

ContentLicense: CC BY-SA 4.0

Body:
For most the solution here will probably be to use the .defaultToSpeaker option with the AVAudioSessionCategoryPlayAndRecord category:

try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, with: [.defaultToSpeaker])

But for me the issue turned out to be that a different component in my app was setting the AVAudioSessionModeMeasurement mode on the audio session, which for whatever reason reduces the output volume.


问:
Java Biometric Finger Print with Secugen hamster iv
I'am trying to read finger print with secugen hamster iv device in my java app, i have already request the sdk, installed FDx SDK Pro for Windows v3.7, imported jars from FDx SDK Pro for Java v1.8. but now when i try to run a sample code i receive this error

```<code>**Exception in thread "AWT-EventQueue-0" java.lang.UnsatisfiedLinkError: C:\Windows\System32\jnisgfplib.dll: Can't load IA 32-bit .dll on a AMD 64-bit platform
    at java.lang.ClassLoader$NativeLibrary.load(Native Method)
    at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1941)
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1857)
    at java.lang.Runtime.loadLibrary0(Runtime.java:870)
    at java.lang.System.loadLibrary(System.java:1122)
    at SecuGen.FDxSDKPro.jni.JSGFPLib.<clinit>(JSGFPLib.java:78)
    at main.SecuGen.FDxSDKPro.samples.JSGD.jButtonInitActionPerformed(JSGD.java:783)
    at main.SecuGen.FDxSDKPro.samples.JSGD.access$1(JSGD.java:759)
    at main.SecuGen.FDxSDKPro.samples.JSGD$2.actionPerformed(JSGD.java:164)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6533)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6298)
    at java.awt.Container.processEvent(Container.java:2236)
    at java.awt.Component.dispatchEventImpl(Component.java:4889)
    at java.awt.Container.dispatchEventImpl(Container.java:2294)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
    at java.awt.Container.dispatchEventImpl(Container.java:2280)
    at java.awt.Window.dispatchEventImpl(Window.java:2746)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)**
</code>```

am runing windows 10 pro, jdk 1.8.0_131 please help

答: In the first line it says that you are trying to read a 32Bit file on a 64Bit device which is not possible.</p>

Body:
I'am trying to read finger print with secugen hamster iv device in my java app, i have already request the sdk, installed FDx SDK Pro for Windows v3.7, imported jars from FDx SDK Pro for Java v1.8. but now when i try to run a sample code i receive this error

**Exception in thread "AWT-EventQueue-0" java.lang.UnsatisfiedLinkError: C:\Windows\System32\jnisgfplib.dll: Can't load IA 32-bit .dll on a AMD 64-bit platform
    at java.lang.ClassLoader$NativeLibrary.load(Native Method)
    at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1941)
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1857)
    at java.lang.Runtime.loadLibrary0(Runtime.java:870)
    at java.lang.System.loadLibrary(System.java:1122)
    at SecuGen.FDxSDKPro.jni.JSGFPLib.<clinit>(JSGFPLib.java:78)
    at main.SecuGen.FDxSDKPro.samples.JSGD.jButtonInitActionPerformed(JSGD.java:783)
    at main.SecuGen.FDxSDKPro.samples.JSGD.access$1(JSGD.java:759)
    at main.SecuGen.FDxSDKPro.samples.JSGD$2.actionPerformed(JSGD.java:164)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6533)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6298)
    at java.awt.Container.processEvent(Container.java:2236)
    at java.awt.Component.dispatchEventImpl(Component.java:4889)
    at java.awt.Container.dispatchEventImpl(Container.java:2294)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
    at java.awt.Container.dispatchEventImpl(Container.java:2280)
    at java.awt.Window.dispatchEventImpl(Window.java:2746)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)**

am runing windows 10 pro, jdk 1.8.0_131 please help


问:
Unable to get Swagger UI with spring boot
This is my configuration class

```<code>@SpringBootApplication
@EnableJpaRepositories
@EnableTransactionManagement
@EnableSwagger2
public class SwaggerExampleApplication {

public static void main(String[] args) {
    SpringApplication.run(SwaggerExampleApplication.class, args);
}

 @Bean
    public Docket productApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select().apis(RequestHandlerSelectors.basePackage("com.example.controller")).paths(PathSelectors.any()).build().pathMapping("/");
    }

 private ApiInfo apiInfo() {
      return new ApiInfoBuilder()
      .title("Simple Hello App")
      .description("A simple calculator REST service made with Spring Boot in Java")
      .contact("lavya")
      .version("1.0")
      .build();
    }
</code>```

}

This is my resource class

```<code>@Component
@Path("/hello")
@Api(value="Test Hello",description="testing swagger")
public class ResourceController {

@GET
@Produces({MediaType.APPLICATION_JSON})
@ApiOperation(value="list employess",notes="list employees")
public List<Employee> displayDetails(){
    System.out.println("inside display");
    return Arrays.asList(new Employee(1,"ab","cdd","sass"));
    }
</code>```

iam unable to retrive swagger ui, http://localhost:8080/swagger-ui.html on running the app, can anyone tell why?

答:
Try this. It works for me.</p>

```<code>@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {

    @Override
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        // Make Swagger meta-data available via <baseURL>/v2/api-docs/
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        // Make Swagger UI available via <baseURL>/swagger-ui.html
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}
</code>```

Body:
This is my configuration class

@SpringBootApplication
@EnableJpaRepositories
@EnableTransactionManagement
@EnableSwagger2
public class SwaggerExampleApplication {

public static void main(String[] args) {
    SpringApplication.run(SwaggerExampleApplication.class, args);
}

 @Bean
    public Docket productApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select().apis(RequestHandlerSelectors.basePackage("com.example.controller")).paths(PathSelectors.any()).build().pathMapping("/");
    }

 private ApiInfo apiInfo() {
      return new ApiInfoBuilder()
      .title("Simple Hello App")
      .description("A simple calculator REST service made with Spring Boot in Java")
      .contact("lavya")
      .version("1.0")
      .build();
    }

}

This is my resource class

@Component
@Path("/hello")
@Api(value="Test Hello",description="testing swagger")
public class ResourceController {

@GET
@Produces({MediaType.APPLICATION_JSON})
@ApiOperation(value="list employess",notes="list employees")
public List<Employee> displayDetails(){
    System.out.println("inside display");
    return Arrays.asList(new Employee(1,"ab","cdd","sass"));
    }

iam unable to retrive swagger ui, http://localhost:8080/swagger-ui.html on running the app, can anyone tell why?

Body:
Try this. It works for me.

@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {

    @Override
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        // Make Swagger meta-data available via <baseURL>/v2/api-docs/
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        // Make Swagger UI available via <baseURL>/swagger-ui.html
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}


问:
Where can I find a bit shifting guide for C?
I have looked at What are bitwise shift (bit-shift) operators and how do they work?, but I still find the concept of bit shifting difficult to understand.

Can someone point me in the direction of a more basic guide to bit shifting in C? I expect it will be something really long since it will need to cover the whole subject.

I am learning the The C Programming Language (AKA K&R), and that is what this is for, so I can do the exercises. I understand the basics, but I still cannot do correct bit shift operations.

Here are the exercises from K&R that have stumped me

Exercise 2-6: Write a function setbits(x, p, n, y) that returns x with the n bits that begin at position p set to the rightmost n bits of y, leaving the other bits unchanged.

Exercise 2-7: Write a function invert(x, p, n) that returns x with the n bits that begin at position p inverted (i.e., 1 changed into 0 and vice versa), leaving the others unchanged.

Exercise 2-8: Write a function rightrot(x, n) that returns the value of the integer x rotated to the right by n bit positions

Exercise 2-9: In a two's complement number system, x &= (x-1) deletes the rightmost 1-bit in x. Explain why, and use this observation to write a faster version of bitcount.

These are exercises from the k&R (the C programming language) book. It's the best C book there is, but I am having trouble understanding bit shifting, so I am having problems with these exercises.

答:
Let's go through one exercise, for a sample.

Exercise 2-6: Write a function
  setbits(x, p, n, y) that returns x
  with the n bits that begin at position
  p set to the rightmost n bits of y,
  leaving the other bits unchanged.

Let's keep in mind that the least significant bit is bit 0 (is at position 0).

Here is the pseudocode:

Move the bits p to p+n in x to position 0 to n. That's where you right-shift.

Prepare a bit mask that will turn anything from bit n to the highest bit into 0s. You can use a lookup array for this (for example, 0xFF for n=8, 0x7F for 7 and so on), or you can use a combination of setting bit 0 and left-shifting in a loop.

Apply the bit mask to x using &. All the bits we don't care about in x are now 0.

Invert the bit mask. We now have a bunch of 1s at the high end, and a bunch of 0s at the low end. The bits we want to change in y all have 0s in bit mask.

Apply the bit mask to y using & . All the bits in y that we will replace with bits in x are now set to 0, and the bits that we don't want to change are unchanged.

Set the bits we want to change in y by combining x and y using |. This is the crucial point - go over what's happening with a pen and paper. The bits in x that were set to 0 in (3) will not affect the corresponding bits in y. The bits in x that were not affected by (3) will combine with 0s in y (0s because of step5), setting the resulting bit to the value it had in x.

OwnerDisplayName: angie

LastEditorDisplayName: Rich B


问:
arc4random Random Number Generator
```<code>int randomNumber = (arc4random() % 83) + 1;
</code>```

Is this the best way to generate "the most random" number? Or is there a better way to generate a random number?

答: arc4random has a superior algorithm for generating random numbers based on the current time. There are other rand functions but they are not as good and require seeding.</p>

ContentLicense: CC BY-SA 2.5

Title: arc4random Random Number Generator

Body:
int randomNumber = (arc4random() % 83) + 1;

Is this the best way to generate "the most random" number? Or is there a better way to generate a random number?


问:
Add values from array into Realm database
I have my Device class defined as such:

```<code>class Device: Object {
    dynamic var asset_tag = ""

}
</code>```

I have an array like this ["43", "24", "23", "64"]

and I would like to loop through the array and add each one into the asset_tag attribute of the Device entity in Realm.

答:
To create an array in Realm you use List. According to Realm's docs, List is the container type in Realm used to define to-many relationships. It goes on to say, "Properties of List type defined on Object subclasses must be declared as let and cannot be dynamic." This means you need to define an entirely separate object to create a list in Realm, there are no native types that will allow you to do something like

```<code>    let assetTagList = List<String>().
</code>```

You need to create an AssetTags object and make a list of it in your Device object as follows:

```<code>    class AssetTags: Object {
        dynamic var stringValue = ""
    }

    class Device: Object {

        var asset_tags: [String] {
    get {
        return _assetTags.map { $0.stringValue }
    }
    set {
        _assetTags.removeAll()
        _assetTags.append(objectsIn: newValue.map({ AssetTags(value: [$0]) }))
    }
}
        let _assetTags = List<AssetTags>()

        override static func ignoredProperties() -> [String] {
           return ["asset_tags"]
        }
    }
</code>```

Now you can do this to add asset tags to Device.

```<code>    //adding asset tags
    let realm = try! Realm()

    try! realm.write {
        let device = Device()
        device.asset_tags = ["1", "2"]
        realm.add(device)
    }

    //looking at all device objects and asking for list of asset tags
    for thisDevice in realm.objects(Device.self) {
        print("\(thisDevice.asset_tags)")
    }
</code>```

SECOND EDIT

This is not the way I would do it but I think this is what you might find easier to understand.

```<code>    class AssetTags: Object {

        dynamic var id = 0

        override static func primaryKey() -> String? {
        return "id"
        }

        dynamic var tagValue = ""
    }

    class Device: Object {

        let assetTags = List<AssetTags>()

     }
</code>```

So now Device has a list of asset tags. I added a primary id for Asset Tags because you indicated you might want to add more properties so an id should help make each one unique. It is optional though, so you can remove it if you do not need it.

To add assetTags objects to a Device object in a for-loop style (note: device in this code exampl is the device object you want to save the asset tags to):

```<code>    var assetTagArray: [String] = ["1", "2"]

    let realm = try! Realm()

    for assetTag in assetTagArray {

    let newAssetTag = AssetTags()

    newAssetTag.tagValue = assetTag

    newAssetTag.id = (realm.objects(AssetTags.self).max(ofProperty: "id") as Int? ?? 0) + 1

    do {

        try realm.write {

            device?.assetTags.append(newAssetTag)

        }

    } catch let error as NSError {

        print(error.localizedDescription)

        return

    }

    }
</code>```

Body:
I have my Device class defined as such:

class Device: Object {
    dynamic var asset_tag = ""

}

I have an array like this ["43", "24", "23", "64"]

and I would like to loop through the array and add each one into the asset_tag attribute of the Device entity in Realm.

Body:
To create an array in Realm you use List. According to Realm's docs, List is the container type in Realm used to define to-many relationships. It goes on to say, "Properties of List type defined on Object subclasses must be declared as let and cannot be dynamic." This means you need to define an entirely separate object to create a list in Realm, there are no native types that will allow you to do something like

    let assetTagList = List<String>().

You need to create an AssetTags object and make a list of it in your Device object as follows:

    class AssetTags: Object {
        dynamic var stringValue = ""
    }

    class Device: Object {

        var asset_tags: [String] {
    get {
        return _assetTags.map { $0.stringValue }
    }
    set {
        _assetTags.removeAll()
        _assetTags.append(objectsIn: newValue.map({ AssetTags(value: [$0]) }))
    }
}
        let _assetTags = List<AssetTags>()

        override static func ignoredProperties() -> [String] {
           return ["asset_tags"]
        }
    }

Now you can do this to add asset tags to Device.

    //adding asset tags
    let realm = try! Realm()

    try! realm.write {
        let device = Device()
        device.asset_tags = ["1", "2"]
        realm.add(device)
    }

    //looking at all device objects and asking for list of asset tags
    for thisDevice in realm.objects(Device.self) {
        print("\(thisDevice.asset_tags)")
    }

SECOND EDIT

This is not the way I would do it but I think this is what you might find easier to understand.

    class AssetTags: Object {

        dynamic var id = 0

        override static func primaryKey() -> String? {
        return "id"
        }

        dynamic var tagValue = ""
    }

    class Device: Object {

        let assetTags = List<AssetTags>()

     }

So now Device has a list of asset tags. I added a primary id for Asset Tags because you indicated you might want to add more properties so an id should help make each one unique. It is optional though, so you can remove it if you do not need it.

To add assetTags objects to a Device object in a for-loop style (note: device in this code exampl is the device object you want to save the asset tags to):

    var assetTagArray: [String] = ["1", "2"]

    let realm = try! Realm()

    for assetTag in assetTagArray {

    let newAssetTag = AssetTags()

    newAssetTag.tagValue = assetTag

    newAssetTag.id = (realm.objects(AssetTags.self).max(ofProperty: "id") as Int? ?? 0) + 1

    do {

        try realm.write {

            device?.assetTags.append(newAssetTag)

        }

    } catch let error as NSError {

        print(error.localizedDescription)

        return

    }

    }


问:
Supervisor unrecognized service issue after install
If I install supervisor from apt-get I get version 3.0b2-1 and if I run sudo service supervisor status I get is running (older beta version working fine)

A directory at /etc/supervisor is created with supervisord.conf file inside and empty dir conf.d

However, trying to install latest version (3.1.1) with pip or easy_install and running service supervisor status I get supervisor: unrecognized service (latest version not working)

No configuration files are created at /etc so I did echo_supervisord_conf > /etc/supervisord.conf as said at docs.

I can't run service start/stop/restart/status... And I don't know if supervisor will actually work. Any ideas here?

Note: I'm using an Ubuntu 14.04 x64 machine.

答:
Faced a similar issue due to /etc/init.d/supervisord lacking executable mode.

```<code>sudo chmod +x /etc/init.d/supervisord
</code>```

Fixed it for me.

Body:
Faced a similar issue due to /etc/init.d/supervisord lacking executable mode.

sudo chmod +x /etc/init.d/supervisord

Fixed it for me.


问:
generating new page in ionic 2 error No ionic-angular package found
when i type ionic generate page new-place
it shows as follow
No ionic-angular package found, do you have Ionic installed? (CLI v2.0.0)

```<code>Your system information:

Cordova CLI: 7.0.1
Ionic Framework Version: 3.3.0
Ionic CLI Version: 2.0.0
</code>```

plz give me suggestion for it

答:
The first suggestion: if you used beta version of CLI you need to uninstall the beta version of the cli by running npm uninstall -g ionic, then install the latest stable version of the cli npm install -g ionic and try again.

If this is not working then use the second suggestion:

1- Remove ionic and cordova using these commands:

```<code> npm uninstall -g cordova
 npm uninstall -g ionic
 npm cache clean
</code>```

2- Then, re-installed:

```<code>npm install -g cordova
npm install -g ionic@beta
npm install -g n
</code>```

the two previous commands will install the last stable version of
  node.

```<code>npm install -g typescript
npm install -g typeings
</code>```

So the problem is all about the version of node, this solution worked
  well for me, but I would like to advice you to try just the two
  mentioned commands to install a stable version of the node if it works
  for you then no need to remove ionic and reinstall it.

The second suggestion is a resolution from this issue on ionic-cli.

The third  suggestion: if you are using ionic 3.3 then it is Important to use the last version of Nodejs for now it is 6.10.3
that is all possibilities.
Good luck :)
 Thanks

Body:
when i type ionic generate page new-place
it shows as follow
No ionic-angular package found, do you have Ionic installed? (CLI v2.0.0)

Your system information:

Cordova CLI: 7.0.1
Ionic Framework Version: 3.3.0
Ionic CLI Version: 2.0.0

plz give me suggestion for it

Body:
The first suggestion: if you used beta version of CLI you need to uninstall the beta version of the cli by running npm uninstall -g ionic, then install the latest stable version of the cli npm install -g ionic and try again.

If this is not working then use the second suggestion:

1- Remove ionic and cordova using these commands:

 npm uninstall -g cordova
 npm uninstall -g ionic
 npm cache clean

2- Then, re-installed:

npm install -g cordova
npm install -g ionic@beta
npm install -g n

the two previous commands will install the last stable version of
  node.

npm install -g typescript
npm install -g typeings

So the problem is all about the version of node, this solution worked
  well for me, but I would like to advice you to try just the two
  mentioned commands to install a stable version of the node if it works
  for you then no need to remove ionic and reinstall it.

The second suggestion is a resolution from this issue on ionic-cli.

The third  suggestion: if you are using ionic 3.3 then it is Important to use the last version of Nodejs for now it is 6.10.3
that is all possibilities.
Good luck :)
 Thanks


问:
NODE 8.0.0 and NPM 4.2.0 ERROR express-load require.extensions.hasOwnProperty is not a function
I am creating an app in Node 8.0.0 and NPM 5.0.0 and when i using express-load var load = require("express-load"); my server returns:

```<code>load/lib/express-load.js:32

  if (require.extensions.hasOwnProperty(ext) && extlist.indexOf(ext) === -1) {
                         ^

TypeError: require.extensions.hasOwnProperty is not a function
    at Object.<anonymous> (/Users/node_modules/express-load/lib/express-load.js:32:26)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Module.require (module.js:513:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/node_modules/express-load/index.js:8:18)
    at Module._compile (module.js:569:30)
</code>```

I tried downgrade to npm sudo npm install -g npm@4.2.0 version 4.2.0 (https://github.com/tjunnone/npm-check-updates/issues/355) and does not works

This post npm check updates works to me.

thanks!!!!

答: I had this error with require-dir@0.3.1. Upgrading to 0.3.2 solved my problem.

Body:
I am creating an app in Node 8.0.0 and NPM 5.0.0 and when i using express-load var load = require("express-load"); my server returns:

load/lib/express-load.js:32

  if (require.extensions.hasOwnProperty(ext) && extlist.indexOf(ext) === -1) {
                         ^

TypeError: require.extensions.hasOwnProperty is not a function
    at Object.<anonymous> (/Users/node_modules/express-load/lib/express-load.js:32:26)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Module.require (module.js:513:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/node_modules/express-load/index.js:8:18)
    at Module._compile (module.js:569:30)

I tried downgrade to npm sudo npm install -g npm@4.2.0 version 4.2.0 (https://github.com/tjunnone/npm-check-updates/issues/355) and does not works

This post npm check updates works to me.

thanks!!!!


问:
How to show login/logout links the rails way?
I have a property that is exposed in my view @is_logged_in

if its true, then I want to show the 'logout' link, otherwise I want to show the 'login' link.

Is there a fancy rails way to do this?

答:
```<code><% if @is_logged_in %>
  <%= link_to("Logout", logout_path) %>
<% else %>
  <%= link_to("Login", login_path) %>
<% end %>
</code>```


问:
Waiting for async request to return before proceeding Google Apps Script
Some code in Google Apps Script I am currently producing has a need for an object to be completed with one of the properties being set by the result of an async request. This object, and specifically, this property are then used later down the line. However, because the request has not returned by the time the functions needing that property run, they are not evaluating properly.
My code is as follows:

```<code>function Thing(val) {
    var self = this

    var createSuccess = function(data) {
        self.foo = data;
    }

    var init = function(val) {
        google.script.run.withSuccessHandler(createSuccess).serverFunc(val);
    };

    init(val);
}

function objStuff() {
    var foobar = new Thing('bar');
    // Do stuff with foobar.foo
}

objStuff();
</code>```

Currently the stuff using foobar.foo does not work correctly, as the script has not waited for the return value of the script before proceeding.

Is there a way I can wait for the foo property to be evaluated with the async request before proceeding with the rest of my script?

答:
You can add a callback as a parameter to the constructor:</p>

```<code>function Thing(val, cb) {
    var self = this

    var createSuccess = function(data) {
        self.foo = data;
        cb(); // this gets called when data is ready
    }

    var init = function(val) {
        google.script.run.withSuccessHandler(createSuccess).serverFunc(val);
    };

    init(val);
}

function objStuff() {
    var foobar = new Thing('bar', function() {
        // Do stuff with foobar.foo
    });
}

objStuff();
</code>```

Body:
Some code in Google Apps Script I am currently producing has a need for an object to be completed with one of the properties being set by the result of an async request. This object, and specifically, this property are then used later down the line. However, because the request has not returned by the time the functions needing that property run, they are not evaluating properly.
My code is as follows:

function Thing(val) {
    var self = this

    var createSuccess = function(data) {
        self.foo = data;
    }

    var init = function(val) {
        google.script.run.withSuccessHandler(createSuccess).serverFunc(val);
    };

    init(val);
}

function objStuff() {
    var foobar = new Thing('bar');
    // Do stuff with foobar.foo
}

objStuff();

Currently the stuff using foobar.foo does not work correctly, as the script has not waited for the return value of the script before proceeding.

Is there a way I can wait for the foo property to be evaluated with the async request before proceeding with the rest of my script?

Body:
You can add a callback as a parameter to the constructor:

function Thing(val, cb) {
    var self = this

    var createSuccess = function(data) {
        self.foo = data;
        cb(); // this gets called when data is ready
    }

    var init = function(val) {
        google.script.run.withSuccessHandler(createSuccess).serverFunc(val);
    };

    init(val);
}

function objStuff() {
    var foobar = new Thing('bar', function() {
        // Do stuff with foobar.foo
    });
}

objStuff();


问:
Unable to get Serial.print to work
I have a simple program:

```<code>void setup() {
  Serial.begin(9600);
}

void loop() {
  int x = 0;
  Serial.print(x++);
}
</code>```

Whenever I try to look and see the serial log nothing is shown, what am I doing wrong. I am using a Arduino Leonardo and the sketch compiles and uploads.

-----------------Update 1---------------

What I am really trying to get the console to print out is the following code. However since it failed I made a short and simple program:

```<code>// SparkFun Soil Moisture Sensor and Serial LCD example 1
// By Sarah Al-Mutlaq 2015
// Sketch reads sensor and desplays level and whether soil is wet or dry

// Use the softwareserial library to create a new "soft" serial port
// for the display. This prevents display corruption when uploading code.
#include <SoftwareSerial.h>

// Attach the serial display's RX line to digital pin 2
SoftwareSerial mySerial(3,2); // pin 2 = TX, pin 3 = RX (unused)

// Here we are setting up some water thersholds that we will
// use later. Note that you will need to change these to match
// your soil type and environment.

int thresholdUp = 400;
int thresholdDown = 250;

// We are setting up the pin A0 on the redboard to be our sensor
// pin input:

int sensorPin = A0;

void setup(){
  mySerial.begin(9600); // set up serial port for 9600 baud (speed)
  delay(500); // wait for display to boot up
}

void loop(){
  // Here we are declaring a string, which are lines of words,
  // and we want DisplayWords to be the words displayed on
  // the LCD screen, which will change based on whether the soil
  // wet or dry based on our threshold values above.
  String DisplayWords;

  // We need to set up a pin to get the value that the soil
  // moisture sensor is outputting, so sensorValue will get the
  // analog value from the sensor pin A0 on the redboard that we
  // set up earlier.

  int sensorValue;
  sensorValue = analogRead(sensorPin);

  // move cursor to beginning of first line on LCD:
  mySerial.write(254);
  mySerial.write(128);

  // clear display:
  mySerial.write("                ");
  mySerial.write("                ");

  // move cursor to beginning of first line of the LCD screen:
  mySerial.write(254);
  mySerial.write(128);

  //Write what we want to desplay on the screen:
  mySerial.write("Water Level: ");
  mySerial.print(sensorValue); //Using .print instead of .write for values

  // Now we are going to check if the water level is below a
  // out thresholdDown value we set earlier, and if it is have
  // words "Dry, Water it!" display one column over on the first
  // row:

  if (sensorValue <= thresholdDown){
    // move cursor to beginning of second line on LCD:
    mySerial.write(254);
    mySerial.write(192);

    DisplayWords = "Dry, Water it!";
    mySerial.print(DisplayWords);

  // If the value is not below our thresholdDown value we want to
  // check if it is above our thresholdUp value, and if it is
  // change the display words to "Wet, Leave it!":

  } else if (sensorValue >= thresholdUp){
    // move cursor to beginning of second line on LCD:
    mySerial.write(254);
    mySerial.write(192);

    DisplayWords = "Wet, Leave it!";
    mySerial.print(DisplayWords);

  // Otherwise if it is inbetween the two values we want it to
  // the display it had, so if our soil was really wet and drying
  // the words would only change to "Dry, Water it!" when it got to the lower threshold
  // (thresholdDown), but if it was dry and getting wetter the words
  // would only change to "Wet, Leave it!" when it got to the upper
  // threshold (thresholdUp_):

  } else {
    // move cursor to beginning of second line on LCD:
    mySerial.write(254);
    mySerial.write(192);

    mySerial.print(DisplayWords);
  }

  delay(500); //wait for half a second, so it is easier to read
}
</code>```

答:
I see now you're controlling a display.  Using these isn't like sending bytes to a terminal emulator.  They must be controlled.  Controlling these serial displays generally consists of sending some initialization commands, which are often (but not always) similar for different displays, provided they have the same display controller.

I don't know what display part you're using, but I'd venture that some initialization commands are missing.  The 500ms delay is usually part of it, but check your documentation for any other init commands you need to send before sending cursor positioning commands.

Usually you have to send an initial byte command to put the display into command mode, send a handful of configuration commands, then exit command mode to actually use the display.  If it's a Hitachi 44780 based display you might check out the datasheet at 44780 datasheet.

Title: Unable to get Serial.print to work

Body:
I have a simple program:

void setup() {
  Serial.begin(9600);
}

void loop() {
  int x = 0;
  Serial.print(x++);
}

Whenever I try to look and see the serial log nothing is shown, what am I doing wrong. I am using a Arduino Leonardo and the sketch compiles and uploads.

-----------------Update 1---------------

What I am really trying to get the console to print out is the following code. However since it failed I made a short and simple program:

// SparkFun Soil Moisture Sensor and Serial LCD example 1
// By Sarah Al-Mutlaq 2015
// Sketch reads sensor and desplays level and whether soil is wet or dry

// Use the softwareserial library to create a new "soft" serial port
// for the display. This prevents display corruption when uploading code.
#include <SoftwareSerial.h>

// Attach the serial display's RX line to digital pin 2
SoftwareSerial mySerial(3,2); // pin 2 = TX, pin 3 = RX (unused)

// Here we are setting up some water thersholds that we will
// use later. Note that you will need to change these to match
// your soil type and environment.

int thresholdUp = 400;
int thresholdDown = 250;

// We are setting up the pin A0 on the redboard to be our sensor
// pin input:

int sensorPin = A0;

void setup(){
  mySerial.begin(9600); // set up serial port for 9600 baud (speed)
  delay(500); // wait for display to boot up
}

void loop(){
  // Here we are declaring a string, which are lines of words,
  // and we want DisplayWords to be the words displayed on
  // the LCD screen, which will change based on whether the soil
  // wet or dry based on our threshold values above.
  String DisplayWords;

  // We need to set up a pin to get the value that the soil
  // moisture sensor is outputting, so sensorValue will get the
  // analog value from the sensor pin A0 on the redboard that we
  // set up earlier.

  int sensorValue;
  sensorValue = analogRead(sensorPin);

  // move cursor to beginning of first line on LCD:
  mySerial.write(254);
  mySerial.write(128);

  // clear display:
  mySerial.write("                ");
  mySerial.write("                ");

  // move cursor to beginning of first line of the LCD screen:
  mySerial.write(254);
  mySerial.write(128);

  //Write what we want to desplay on the screen:
  mySerial.write("Water Level: ");
  mySerial.print(sensorValue); //Using .print instead of .write for values

  // Now we are going to check if the water level is below a
  // out thresholdDown value we set earlier, and if it is have
  // words "Dry, Water it!" display one column over on the first
  // row:

  if (sensorValue <= thresholdDown){
    // move cursor to beginning of second line on LCD:
    mySerial.write(254);
    mySerial.write(192);

    DisplayWords = "Dry, Water it!";
    mySerial.print(DisplayWords);

  // If the value is not below our thresholdDown value we want to
  // check if it is above our thresholdUp value, and if it is
  // change the display words to "Wet, Leave it!":

  } else if (sensorValue >= thresholdUp){
    // move cursor to beginning of second line on LCD:
    mySerial.write(254);
    mySerial.write(192);

    DisplayWords = "Wet, Leave it!";
    mySerial.print(DisplayWords);

  // Otherwise if it is inbetween the two values we want it to
  // the display it had, so if our soil was really wet and drying
  // the words would only change to "Dry, Water it!" when it got to the lower threshold
  // (thresholdDown), but if it was dry and getting wetter the words
  // would only change to "Wet, Leave it!" when it got to the upper
  // threshold (thresholdUp_):

  } else {
    // move cursor to beginning of second line on LCD:
    mySerial.write(254);
    mySerial.write(192);

    mySerial.print(DisplayWords);
  }

  delay(500); //wait for half a second, so it is easier to read
}


问:
Convert from rxjava retrolambda expression to classic
I use retrolambda expression

```<code> _rxBus = getRxBusSingleton();
    _disposables = new CompositeDisposable();

    ConnectableFlowable<Object> tapEventEmitter = _rxBus.asFlowable().publish();

    _disposables
            .add(tapEventEmitter.subscribe(event -> {

             if (event instanceof EmployeeMvvmActivity.TapEvent) {
                _showTapText();
            }

            }));
</code>```

Everything work fine. Because of Roboelectric testing i need to convert retrolambda expression to classic. I have tried

```<code>_disposables.add(tapEventEmitter.subscribe(new Action1<Object>() {
        @Override
        public void call(Object event) {
            if (event instanceof EmployeeMvvmActivity.TapEvent) {
                _showTapText();
            }
        }
    }));
</code>```

I have got error cannot resolve method 'subscribe(anonymous rx.functions.Action1(java.lang.object)'.

答:
The Action1 comes from Rx1 while you're using Rx2. Instead you have to use the Consumer interface.

```<code>_disposables.add(tapEventEmitter.subscribe(new Consumer<Object>() {
    @Override
    public void accept(Object event) {
        if (event instanceof EmployeeMvvmActivity.TapEvent) {
            _showTapText();
        }
    }
}));
</code>```

Body:
I use retrolambda expression

 _rxBus = getRxBusSingleton();
    _disposables = new CompositeDisposable();

    ConnectableFlowable<Object> tapEventEmitter = _rxBus.asFlowable().publish();

    _disposables
            .add(tapEventEmitter.subscribe(event -> {

             if (event instanceof EmployeeMvvmActivity.TapEvent) {
                _showTapText();
            }

            }));

Everything work fine. Because of Roboelectric testing i need to convert retrolambda expression to classic. I have tried

_disposables.add(tapEventEmitter.subscribe(new Action1<Object>() {
        @Override
        public void call(Object event) {
            if (event instanceof EmployeeMvvmActivity.TapEvent) {
                _showTapText();
            }
        }
    }));

I have got error cannot resolve method 'subscribe(anonymous rx.functions.Action1(java.lang.object)'.

Body:
The Action1 comes from Rx1 while you're using Rx2. Instead you have to use the Consumer interface.

_disposables.add(tapEventEmitter.subscribe(new Consumer<Object>() {
    @Override
    public void accept(Object event) {
        if (event instanceof EmployeeMvvmActivity.TapEvent) {
            _showTapText();
        }
    }
}));


问:
Self sizing tableview
First of all this is not a question about how to automatically size the cells inside the tableview, moreover how to automatically resize the entire tableview.

So I have a scrollview which has a tableview and 2 other views as its subviews. The tableview's cells already automatically resize itself, again this question is not about the individual cells. However, the tableview does not resize at all.

What I have done:
1) Set up the tableview to have a top, bottom, leading and trailing constraint
2) Set the cells up to have auto layout enabled
3) * I do not know the cell size at build time
4) I have disabled scrolling mode on tableview

So long story short, how can I go along to get the tableview to resize itself?

Edit

The cells contain a label which can have various lines of text, so therefore the cells, which use auto layout, should then determine the height of the table view.

The following images show how the view is set up:

As you can see the tableview is only a small part of the view and since the scrollview from the tableview is deactivated there should, and aren't, any scrolling problems.

EDIT 2

This is actually how it should end however, i am calculating this on my own and everytime I want to make a small change to the cells the whole code, which calculates the height of the cell, needs to be rewritten and it is quite difficult for me to get the height just right.

Edit 3

Until now I had a height constraint on the tableview which I calculated manually, however removing this constraint and trying to let auto layout handle the tableview height size creates the following error:

Scroll View
  Need constraint for: Y position or height

I can conclude therefore that the tableview does not know how to automatically calculate the height based on its cells with autolayout.

答:
You can change your UITableView's frame by using tableview.frame = CGRect(x: <some_x>, y: <some_y>, width: <some_width>, height: <some_height>)

If your UITableViewCells use auto layout then they should resize when the UITableView's frame changes.

Title: Self sizing tableview


问:
unexpected token error when using onclick
this is my code

```<code>  const products = productArray.map(product =>
`
<tr>
  <td>${product.id}</td>
  <td>${product.type}</td>
  <td>${product.price}</td>
  <td><button onclick="${() => console.log('hello world')}">Examine</button></td>
</tr>
`
  );
  return tableBody.innerHTML = products.join('');
</code>```

I just don't get why I'm getting this unexpected token error, that points to the html. I'm pretty sure It's a very stupid but I just cannot get where it is.

答:
You can't substitute a function in a template literal. It simply inserts the function's source code.

There's also little point to it in this case. You can simply put the function body in the onclick attribute.

```<code>  const products = productArray.map(product =>
`
<tr>
  <td>${product.id}</td>
  <td>${product.type}</td>
  <td>${product.price}</td>
  <td><button onclick="console.log('hello world')">Examine</button></td>
</tr>
`
  );
  return tableBody.innerHTML = products.join('');
</code>```

Body:
this is my code

  const products = productArray.map(product =>
`

  ${product.id}
  ${product.type}
  ${product.price}
  <button onclick="${() => console.log('hello world')}">Examine</button>

`
  );
  return tableBody.innerHTML = products.join('');

I just don't get why I'm getting this unexpected token error, that points to the html. I'm pretty sure It's a very stupid but I just cannot get where it is.

Body:
You can't substitute a function in a template literal. It simply inserts the function's source code.

There's also little point to it in this case. You can simply put the function body in the onclick attribute.

  const products = productArray.map(product =>
`
<tr>
  <td>${product.id}</td>
  <td>${product.type}</td>
  <td>${product.price}</td>
  <td><button onclick="console.log('hello world')">Examine</button></td>
</tr>
`
  );
  return tableBody.innerHTML = products.join('');


问:
Reuse inheritance to define a method in Java
I'm a new Java developer and I met some difficulties with the concept of inheritance in java to define my classes...

In one side, I have a generic class named Vehicle that defines a decades of attributes (with their getters/setters). And I have a Vehicle1 class that extends Vehicle class.

In other side, I have a generic classe named VehicleFactory that defines one single static method like this :

```<code>public class VehicleFactory {

    protected static Vehicle makeResult() {
        Vehicle result = new Vehicle();

        result.setCode("1");
        result.setNumber("2");
        // other setters methods
        return result;
    }
</code>```

The problem is that I want to create a Vehicle1Factory class with its own makeResult method that USE the makeResult method of its parent class. But I failed to do this (the aim here is the optimisation since Vehicle1 has all the generic attributes of Vehicle classe but has some additional attributes).

What I tried to write is like this :

```<code>public class Vehicle1Factory extends VehicleFactory {

    protected static Vehicle1 makeResult() {
        Vehicle1 result = new Vehicle1();

         result = (Vehicle1) VehicleFactory.makeResult();

        // I want to reuse the makeResult of its parent class to define
        // its own makeResult method
    }
}
</code>```

But when I do this, Java told me that there a ClassCastException and that I can't use the cast here...

Is there any solution in that case?

答:
ClassCastException occurs because you're trying to cast Vehicle to Vehicle1;

Why you can't do that? Because you can cast it in case, if the object type is Vehicle1 under Vehicle reference type.

```<code>public class Vehicle1Factory extends VehicleFactory {

    protected static Vehicle1 makeResult() {
        // Change reference type to Vehicle
        Vehicle result = VehicleFactory.makeResult();

        // I want to reuse the makeResult of its parent class to define
        // its own makeResult method
    }
}
</code>```

Let's try to clarify all dark points of casting.

```<code>Super sub1 = new Sub(); // No casting required!
Super super1 = new Super();
Sub sub2 = new Sub();
sub2 = (Sub) sub1; // Casting required, because reference type is Super, but it's okay because real object under the reference is Sub();
sub2 = (Sub) super1(); // ClassCastException because real object is of Super type
</code>```

The cast at the last line tells the compiler not to worry, that I'm a good programmer and I know what I am doing and the object referenced by the super class reference will actually be of class Sub at run time. So there is no compile time error. But at run time, this fails because the actual object is not an Sub but is Super.

Body:
I'm a new Java developer and I met some difficulties with the concept of inheritance in java to define my classes...

In one side, I have a generic class named Vehicle that defines a decades of attributes (with their getters/setters). And I have a Vehicle1 class that extends Vehicle class.

In other side, I have a generic classe named VehicleFactory that defines one single static method like this :

public class VehicleFactory {

    protected static Vehicle makeResult() {
        Vehicle result = new Vehicle();

        result.setCode("1");
        result.setNumber("2");
        // other setters methods
        return result;
    }

The problem is that I want to create a Vehicle1Factory class with its own makeResult method that USE the makeResult method of its parent class. But I failed to do this (the aim here is the optimisation since Vehicle1 has all the generic attributes of Vehicle classe but has some additional attributes).

What I tried to write is like this :

public class Vehicle1Factory extends VehicleFactory {

    protected static Vehicle1 makeResult() {
        Vehicle1 result = new Vehicle1();

         result = (Vehicle1) VehicleFactory.makeResult();

        // I want to reuse the makeResult of its parent class to define
        // its own makeResult method
    }
}

But when I do this, Java told me that there a ClassCastException and that I can't use the cast here...

Is there any solution in that case?

Body:
ClassCastException occurs because you're trying to cast Vehicle to Vehicle1;

Why you can't do that? Because you can cast it in case, if the object type is Vehicle1 under Vehicle reference type.

public class Vehicle1Factory extends VehicleFactory {

    protected static Vehicle1 makeResult() {
        // Change reference type to Vehicle
        Vehicle result = VehicleFactory.makeResult();

        // I want to reuse the makeResult of its parent class to define
        // its own makeResult method
    }
}

Let's try to clarify all dark points of casting.

Super sub1 = new Sub(); // No casting required!
Super super1 = new Super();
Sub sub2 = new Sub();
sub2 = (Sub) sub1; // Casting required, because reference type is Super, but it's okay because real object under the reference is Sub();
sub2 = (Sub) super1(); // ClassCastException because real object is of Super type

The cast at the last line tells the compiler not to worry, that I'm a good programmer and I know what I am doing and the object referenced by the super class reference will actually be of class Sub at run time. So there is no compile time error. But at run time, this fails because the actual object is not an Sub but is Super.


问:
Retrofit 1.9 How to start new Activity from Callback
I have simply questions , I think is simply :)
I can't start new Activity from my CallBack method in Retrofit , I'm getting issue like

" android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?"

```<code>    sign_in_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String userEmail = email.getText().toString();
            String userPassword = password.getText().toString();

            final LoginService loginService = RetrofitClient.createService(LoginService.class, userEmail, userPassword);
            loginService.basicLogin(new Callback<User>() {
                @Override
                public void success(User user, Response response) {
                    Toast.makeText(getApplicationContext(),"You are Logged", Toast.LENGTH_SHORT).show();

                    Intent intent = new Intent(getApplicationContext(), BetweenActivity.class);
                    startActivity(intent);

                }

                @Override
                public void failure(RetrofitError error) {
                    Toast.makeText(getApplicationContext(),"Something went wrong", Toast.LENGTH_SHORT).show();

                }
            });
</code>```

This is my log:

FATAL EXCEPTION: main
                                                                              Process: com.example.bunzlau.retrofit, PID: 18138
                                                                              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bunzlau.retrofit/com.example.bunzlau.retrofit.BetweenActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.Button.findViewById(int)' on a null object reference
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3253)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
                                                                                at android.app.ActivityThread.access$1100(ActivityThread.java:221)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:158)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7225)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
                                                                               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.Button.findViewById(int)' on a null object reference
                                                                                at com.example.bunzlau.retrofit.BetweenActivity.onCreate(BetweenActivity.java:18)
                                                                                at android.app.Activity.performCreate(Activity.java:6876)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3206)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
                                                                                at android.app.ActivityThread.access$1100(ActivityThread.java:221)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:158)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7225)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

答:
You're calling startActivity() from within the scope of Callback, rather than the scope of the activity. You'll need to get a reference to the current activity, and use that to start the next one.</p>

```<code>private Context context = this;

sign_in_button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        String userEmail = email.getText().toString();
        String userPassword = password.getText().toString();

        final LoginService loginService = RetrofitClient.createService(LoginService.class, userEmail, userPassword);
        loginService.basicLogin(new Callback<User>() {
            @Override
            public void success(User user, Response response) {
                Toast.makeText(getApplicationContext(),"You are Logged", Toast.LENGTH_SHORT).show();

                Intent intent = new Intent(getApplicationContext(), BetweenActivity.class);
                context.startActivity(intent);

            }

            @Override
            public void failure(RetrofitError error) {
                Toast.makeText(getApplicationContext(),"Something went wrong", Toast.LENGTH_SHORT).show();

            }
        });
</code>```

Body:
I have simply questions , I think is simply :)
I can't start new Activity from my CallBack method in Retrofit , I'm getting issue like

" android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?"

    sign_in_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String userEmail = email.getText().toString();
            String userPassword = password.getText().toString();

            final LoginService loginService = RetrofitClient.createService(LoginService.class, userEmail, userPassword);
            loginService.basicLogin(new Callback<User>() {
                @Override
                public void success(User user, Response response) {
                    Toast.makeText(getApplicationContext(),"You are Logged", Toast.LENGTH_SHORT).show();

                    Intent intent = new Intent(getApplicationContext(), BetweenActivity.class);
                    startActivity(intent);

                }

                @Override
                public void failure(RetrofitError error) {
                    Toast.makeText(getApplicationContext(),"Something went wrong", Toast.LENGTH_SHORT).show();

                }
            });

This is my log:

FATAL EXCEPTION: main
                                                                              Process: com.example.bunzlau.retrofit, PID: 18138
                                                                              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bunzlau.retrofit/com.example.bunzlau.retrofit.BetweenActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.Button.findViewById(int)' on a null object reference
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3253)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
                                                                                at android.app.ActivityThread.access$1100(ActivityThread.java:221)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:158)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7225)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
                                                                               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.Button.findViewById(int)' on a null object reference
                                                                                at com.example.bunzlau.retrofit.BetweenActivity.onCreate(BetweenActivity.java:18)
                                                                                at android.app.Activity.performCreate(Activity.java:6876)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3206)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
                                                                                at android.app.ActivityThread.access$1100(ActivityThread.java:221)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:158)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7225)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

Body:
You're calling startActivity() from within the scope of Callback, rather than the scope of the activity. You'll need to get a reference to the current activity, and use that to start the next one.

private Context context = this;

sign_in_button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        String userEmail = email.getText().toString();
        String userPassword = password.getText().toString();

        final LoginService loginService = RetrofitClient.createService(LoginService.class, userEmail, userPassword);
        loginService.basicLogin(new Callback<User>() {
            @Override
            public void success(User user, Response response) {
                Toast.makeText(getApplicationContext(),"You are Logged", Toast.LENGTH_SHORT).show();

                Intent intent = new Intent(getApplicationContext(), BetweenActivity.class);
                context.startActivity(intent);

            }

            @Override
            public void failure(RetrofitError error) {
                Toast.makeText(getApplicationContext(),"Something went wrong", Toast.LENGTH_SHORT).show();

            }
        });


问:
Applescript: Strange characters ("¬†") replacing space
I've got a simple code reading a text file into a list. It's a list of CMYK values in this format: 00, 100, 64, 33. For some reason, the output is replacing spaces with strange characters... "¬†" (return and dagger?).

So this script:

```<code>set cmykList to {}
set eachLine to paragraphs of (read POSIX file "/Users/me/Desktop/cmyk.txt")
repeat with nextLine in eachLine
    if length of nextLine is greater than 0 then
        copy (nextLine as text) to the end of cmykList
    end if
end repeat
choose from list cmykList
</code>```

returns:
00,¬†100,¬†64,¬†33,
00,¬†00,¬†00,¬†00,
100,¬†72,¬†00,
100,¬†35,¬†00,¬†100

Any ideas on why this is, and how I can avoid this?

The text file is set up like so:

```<code>00, 100, 64, 33
00, 00, 00, 00
100, 72, 00, 18
100, 35, 00, 100
00, 16, 100, 00
00, 100, 63, 29
00, 66, 100, 07
03, 00, 00, 32
100, 35, 00, 100
00, 100, 81, 04
04, 02, 00, 45
00, 00, 00, 00
03, 00, 00, 32
100, 35, 00, 100
</code>```

Edit: Resolved this issue doing a find / replace:

```<code>set cmykList to {}
set eachLine to paragraphs of (read POSIX file "/Users/me/Desktop/cmyk.txt")
repeat with nextLine in eachLine
    if length of nextLine is greater than 0 then
        set theText to (nextLine as text)
        set AppleScript's text item delimiters to "¬†"
        set theTextItems to text items of theText
        set AppleScript's text item delimiters to " "
        set theText to theTextItems as string
        set AppleScript's text item delimiters to {""}
        copy (theText as text) to the end of cmykList
    end if
end repeat
set chooseList to choose from list cmykList
</code>```

But still very curious as to why this happened in the first place.

答:
Your file contains Unicode text in UTF8 encoding. Standard Additions’s read and write commands (stupidly) use ancient classic-MacOS-era legacy encodings by default, so you need to tell them to use UTF8 explicitly:

```<code>set eachLine to paragraphs of (read POSIX file "/Users/me/Desktop/cmyk.txt" as «class utf8»)
</code>```

Body:
I've got a simple code reading a text file into a list. It's a list of CMYK values in this format: 00, 100, 64, 33. For some reason, the output is replacing spaces with strange characters... "¬†" (return and dagger?).

So this script:

set cmykList to {}
set eachLine to paragraphs of (read POSIX file "/Users/me/Desktop/cmyk.txt")
repeat with nextLine in eachLine
    if length of nextLine is greater than 0 then
        copy (nextLine as text) to the end of cmykList
    end if
end repeat
choose from list cmykList

returns:
00,¬†100,¬†64,¬†33,
00,¬†00,¬†00,¬†00,
100,¬†72,¬†00,
100,¬†35,¬†00,¬†100

Any ideas on why this is, and how I can avoid this?

The text file is set up like so:

00, 100, 64, 33
00, 00, 00, 00
100, 72, 00, 18
100, 35, 00, 100
00, 16, 100, 00
00, 100, 63, 29
00, 66, 100, 07
03, 00, 00, 32
100, 35, 00, 100
00, 100, 81, 04
04, 02, 00, 45
00, 00, 00, 00
03, 00, 00, 32
100, 35, 00, 100

Edit: Resolved this issue doing a find / replace:

set cmykList to {}
set eachLine to paragraphs of (read POSIX file "/Users/me/Desktop/cmyk.txt")
repeat with nextLine in eachLine
    if length of nextLine is greater than 0 then
        set theText to (nextLine as text)
        set AppleScript's text item delimiters to "¬†"
        set theTextItems to text items of theText
        set AppleScript's text item delimiters to " "
        set theText to theTextItems as string
        set AppleScript's text item delimiters to {""}
        copy (theText as text) to the end of cmykList
    end if
end repeat
set chooseList to choose from list cmykList

But still very curious as to why this happened in the first place.

Body:
Your file contains Unicode text in UTF8 encoding. Standard Additions’s read and write commands (stupidly) use ancient classic-MacOS-era legacy encodings by default, so you need to tell them to use UTF8 explicitly:

set eachLine to paragraphs of (read POSIX file "/Users/me/Desktop/cmyk.txt" as «class utf8»)


问:
Why doesn't this FINDSTR example with multiple literal search strings find a match?
Sometimes FINDSTR with multiple literal search strings fails to find all matches. For example, the following FINDSTR example fails to find a match.

```<code>echo ffffaaa|findstr /l "ffffaaa faffaffddd"
</code>```

Why?

答:
I cannot tell why findstr may fail with multiple literal strings. However, I can provide a method to work around that annoying bug.

Given that the literal search strings are listed in a text file called search_strings.txt...:

ffffaaa
faffaffddd
```
</blockquote>

<p>..., you can convert it to regular expressions by inserting a backslash in front of every single character:</p>

<pre class="lang-cmd prettyprint-override"><code>@echo off
setlocal EnableExtensions DisableDelayedExpansion
> "regular_expressions.txt" (
    for /F usebackq^ delims^=^ eol^= %%S in ("search_strings.txt") do (
        set "REGEX=" & set "STRING=%%S"
        for /F delims^=^ eol^= %%T in ('
            cmd /U /V /C echo(!STRING!^| find /V ""
        ') do (
            set "ESCCHR=\%%T"
            if "%%T"="<" (set "ESCCHR=%%T") else if "%%T"=">" (set "ESCCHR=%%T")
            setlocal EnableDelayedExpansion
            for /F "delims=" %%U in ("REGEX=!REGEX!!ESCCHR!") do (
                endlocal & set "%%U"
            )
        )
        setlocal EnableDelayedExpansion
        echo(!REGEX!
        endlocal
    )
)
endlocal
</code>```

Then use the converted file regular_expressions.txt...:

\f\f\f\f\a\a\a
\f\a\f\f\a\f\f\d\d\d
```
</blockquote>

<p>...to do a regular expression search, which seems to work fine also with multiple search strings:</p>

<pre class="lang-cmd prettyprint-override"><code>echo ffffaaa| findstr /R /G:"regular_expressions.txt"
</code>```

The preceding backslashes simply escape every character including those that have a particular meaning in regular expression searches.

The characters < and > are excluded from being escaped in order to avoid conflicts with word boundaries, which were expressed by \< and \> when appearing at the beginning and at the end of a search string, respectively.

Since regular expressions are limited to 254 characters for findstr versions past Windows XP (opposed to literal strings, which are limited to 511 characters), the length of the original search strings is limited to 127 characters, because every such character is expressed by two characters due to the escaping.

Here is an alternative approach that only escapes the meta-characters ., *, ^, $, [, ], \, ":

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "_META=.*^$[]\"^" & rem (including `"`)
> "regular_expressions.txt" (
    for /F usebackq^ delims^=^ eol^= %%S in ("search_strings.txt") do (
        set "REGEX=" & set "STRING=%%S"
        for /F delims^=^ eol^= %%T in ('
            cmd /U /V /C echo(!STRING!^| find /V ""
        ') do (
            set "CHR=%%T"
            setlocal EnableDelayedExpansion
            if not "!_META!"=="!_META:*%%T=!" set "CHR=\!CHR!"
            for /F "delims=" %%U in ("REGEX=!REGEX!!CHR!") do (
                endlocal & set "%%U"
            )
        )
        setlocal EnableDelayedExpansion
        echo(!REGEX!
        endlocal
    )
)
endlocal
```

<p>The advantage of this method is that the length of the search strings is no longer limited to 127 characters but to 254 characters minus 1 for every occurring aforementioned meta-character, applying for <code>findstr</code> versions past Windows XP.</p>

<hr>

<p>Here is another work-around, using a case-insensitive search with <code>findstr</code> at the first place, then post-filtering the result by case-sensitive comparisons:</p>

<pre class="lang-cmd prettyprint-override"><code>echo ffffaaa|findstr /L /I "ffffaaa faffaffddd"|cmd /V /C set /P STR=""^&if @^^!STR^^!==@^^!STR:ffffaaa=ffffaaa^^! (echo(^^!STR^^!) else if @^^!STR^^!==@^^!STR:faffaffddd=faffaffddd^^! (echo(^^!STR^^!)
</code>```

The double-escaped exclamation marks ensure the variable STR is expanded in the explicitly invoked cmd instance even in case delayed expansion is enabled in the hosting cmd instance.

By the way, due to what I call a design flaw, searches with literal strings using findstr never work reliably as soon as they contain backslashes, because such may still be consumed to escape following meta-characters, although not necessary; for example, the search string \. actually matches .; to truly match \. literally, you must specify the search string \\.. I do not understand why meta-characters are still recognised when doing literal searches, that is not what I call literal.

Body:
Sometimes FINDSTR with multiple literal search strings fails to find all matches. For example, the following FINDSTR example fails to find a match.

echo ffffaaa|findstr /l "ffffaaa faffaffddd"

Why?

Body:
I cannot tell why findstr may fail with multiple literal strings. However, I can provide a method to work around that annoying bug.

Given that the literal search strings are listed in a text file called search_strings.txt...:

ffffaaa
faffaffddd

..., you can convert it to regular expressions by inserting a backslash in front of every single character:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
> "regular_expressions.txt" (
    for /F usebackq^ delims^=^ eol^= %%S in ("search_strings.txt") do (
        set "REGEX=" & set "STRING=%%S"
        for /F delims^=^ eol^= %%T in ('
            cmd /U /V /C echo(!STRING!^| find /V ""
        ') do (
            set "ESCCHR=\%%T"
            if "%%T"="<" (set "ESCCHR=%%T") else if "%%T"=">" (set "ESCCHR=%%T")
            setlocal EnableDelayedExpansion
            for /F "delims=" %%U in ("REGEX=!REGEX!!ESCCHR!") do (
                endlocal & set "%%U"
            )
        )
        setlocal EnableDelayedExpansion
        echo(!REGEX!
        endlocal
    )
)
endlocal

Then use the converted file regular_expressions.txt...:

\f\f\f\f\a\a\a
\f\a\f\f\a\f\f\d\d\d

...to do a regular expression search, which seems to work fine also with multiple search strings:

echo ffffaaa| findstr /R /G:"regular_expressions.txt"

The preceding backslashes simply escape every character including those that have a particular meaning in regular expression searches.

The characters < and > are excluded from being escaped in order to avoid conflicts with word boundaries, which were expressed by \< and \> when appearing at the beginning and at the end of a search string, respectively.

Since regular expressions are limited to 254 characters for findstr versions past Windows XP (opposed to literal strings, which are limited to 511 characters), the length of the original search strings is limited to 127 characters, because every such character is expressed by two characters due to the escaping.

Here is an alternative approach that only escapes the meta-characters ., *, ^, $, [, ], \, ":

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "_META=.*^$[]\"^" & rem (including `"`)
> "regular_expressions.txt" (
    for /F usebackq^ delims^=^ eol^= %%S in ("search_strings.txt") do (
        set "REGEX=" & set "STRING=%%S"
        for /F delims^=^ eol^= %%T in ('
            cmd /U /V /C echo(!STRING!^| find /V ""
        ') do (
            set "CHR=%%T"
            setlocal EnableDelayedExpansion
            if not "!_META!"=="!_META:*%%T=!" set "CHR=\!CHR!"
            for /F "delims=" %%U in ("REGEX=!REGEX!!CHR!") do (
                endlocal & set "%%U"
            )
        )
        setlocal EnableDelayedExpansion
        echo(!REGEX!
        endlocal
    )
)
endlocal

The advantage of this method is that the length of the search strings is no longer limited to 127 characters but to 254 characters minus 1 for every occurring aforementioned meta-character, applying for findstr versions past Windows XP.

Here is another work-around, using a case-insensitive search with findstr at the first place, then post-filtering the result by case-sensitive comparisons:

echo ffffaaa|findstr /L /I "ffffaaa faffaffddd"|cmd /V /C set /P STR=""^&if @^^!STR^^!==@^^!STR:ffffaaa=ffffaaa^^! (echo(^^!STR^^!) else if @^^!STR^^!==@^^!STR:faffaffddd=faffaffddd^^! (echo(^^!STR^^!)

The double-escaped exclamation marks ensure the variable STR is expanded in the explicitly invoked cmd instance even in case delayed expansion is enabled in the hosting cmd instance.

By the way, due to what I call a design flaw, searches with literal strings using findstr never work reliably as soon as they contain backslashes, because such may still be consumed to escape following meta-characters, although not necessary; for example, the search string \. actually matches .; to truly match \. literally, you must specify the search string \\.. I do not understand why meta-characters are still recognised when doing literal searches, that is not what I call literal.


问:
GET operation in ASP.NET API with Entity Framework
I've built an ASP.NET Web API using Entity Framework CodeFirst approach. The database tables it created represents a relational database as I expected. In the GET operation of my API I want to return values from 3 tables. Many of the examples I've seen only show a simple return like this:

```<code>// GET: api/Books
public IQueryable<Book> GetBooks()
{
    return db.Books;
}
</code>```

where only the fields from the Books object are returned. This wouldn't be very useful because I have foreign keys to Author and BookType. Using Entity Framework and Web API how is it normally done to return values of fields from more than one table? I imagine I could use a linq query to join the tables and return the results. Is that the most efficient way to do this or is there a better way?

Thanks

答:
Your best bet would be to create a ViewModel, which incorporates all the data that you need to return to your UI, and then populate that from your database entities (normally using a tool like AutoMapper).

You then return the ViewModel rather than your database entities, which means that you can optimise and simplify the data being sent across the wire, as well as prevent possibly sensitive information from being exposed.

Here's an example of how this might be accomplished:
http://bengtbe.com/blog/2009/04/14/using-automapper-to-map-view-models-in-asp-net-mvc/

Aside from the model aspect, I'd also suggest that you also try to avoid directly accessing your DB context in your controller actions, and rather abstract the data access into Repositories (and Services, if things start to get complex).

Body:
I've built an ASP.NET Web API using Entity Framework CodeFirst approach. The database tables it created represents a relational database as I expected. In the GET operation of my API I want to return values from 3 tables. Many of the examples I've seen only show a simple return like this:

// GET: api/Books
public IQueryable<Book> GetBooks()
{
    return db.Books;
}

where only the fields from the Books object are returned. This wouldn't be very useful because I have foreign keys to Author and BookType. Using Entity Framework and Web API how is it normally done to return values of fields from more than one table? I imagine I could use a linq query to join the tables and return the results. Is that the most efficient way to do this or is there a better way?

Thanks