问:
How to list all methods for an object in Ruby?
How do I list all the methods that a particular object has access to?

I have a @current_user object, defined in the application controller:

```<code>def current_user
  @current_user ||= User.find(session[:user_id]) if session[:user_id]
end
</code>```

And want to see what methods I have available to me in the view file. Specifically, I want to see what methods a :has_many association provides. (I know what :has_many should provide, but want to check that.)

答:
If You are looking list of methods which respond by an instance (in your case @current_user). According to ruby documentation methods

Returns a list of the names of public and protected methods of obj.
  This will include all the methods accessible in obj's ancestors. If
  the optional parameter is false, it returns an array of obj's
  public and protected singleton methods, the array will not include
  methods in modules included in obj.

```<code>@current_user.methods
@current_user.methods(false) #only public and protected singleton methods and also array will not include methods in modules included in @current_user class or parent of it.
</code>```

Alternatively, You can also check that a method is callable on an object or not?.

```<code>@current_user.respond_to?:your_method_name
</code>```

If you don't want parent class methods then just subtract the parent class methods from it.

```<code>@current_user.methods - @current_user.class.superclass.new.methods #methods that are available to @current_user instance.
</code>```

Body:
How do I list all the methods that a particular object has access to?

I have a @current_user object, defined in the application controller:

def current_user
  @current_user ||= User.find(session[:user_id]) if session[:user_id]
end

And want to see what methods I have available to me in the view file. Specifically, I want to see what methods a :has_many association provides. (I know what :has_many should provide, but want to check that.)

Body:
If You are looking list of methods which respond by an instance (in your case @current_user). According to ruby documentation methods

Returns a list of the names of public and protected methods of obj.
  This will include all the methods accessible in obj's ancestors. If
  the optional parameter is false, it returns an array of obj's
  public and protected singleton methods, the array will not include
  methods in modules included in obj.

@current_user.methods
@current_user.methods(false) #only public and protected singleton methods and also array will not include methods in modules included in @current_user class or parent of it.

Alternatively, You can also check that a method is callable on an object or not?.

@current_user.respond_to?:your_method_name

If you don't want parent class methods then just subtract the parent class methods from it.

@current_user.methods - @current_user.class.superclass.new.methods #methods that are available to @current_user instance.


来源: stackexchange

问:
Execute multiple url
I have a little problem. I need to execute an script that execute 5000 URL in php.

```<code>$con = mysql_connect("localhost","user","psswd");

if (!$con) {
  die('Could not connect: ' . mysql_error());
}
mysql_select_db('db_name', $con);

print "connected";

$result = mysql_query ("SELECT name, uid FROM obinndocusers");

// I need to execute that url for each user
while ($row = mysql_fetch_array($result)) {
        header (Location http:xxxxxxxx?q=user/" . $row['uid'] . "/edit&destination=admin/user/user);
}
</code>```

Any idea??

Thx.

答:
Use cURL</p>

```<code><?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http:xxxxxxxx?q=user/" . $row['uid'] . "/edit&destination=admin/user/user");
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
?>
</code>```

ContentLicense: CC BY-SA 2.5

Title: Execute multiple url

Body:
I have a little problem. I need to execute an script that execute 5000 URL in php.

$con = mysql_connect("localhost","user","psswd");

if (!$con) {
  die('Could not connect: ' . mysql_error());
}
mysql_select_db('db_name', $con);

print "connected";

$result = mysql_query ("SELECT name, uid FROM obinndocusers");

// I need to execute that url for each user
while ($row = mysql_fetch_array($result)) {
        header (Location http:xxxxxxxx?q=user/" . $row['uid'] . "/edit&destination=admin/user/user);
}

Any idea??

Thx.

Body:
Use cURL

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http:xxxxxxxx?q=user/" . $row['uid'] . "/edit&destination=admin/user/user");
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
?>


问:
inputmask doesn't show number 9
I have a country select (in SlimSelect) with codes and a [type=tel] input with inputmask. I insert country codes (var takeIndex) to the mask, but inputmask doesn't show number 9 if it exists in code. I added "\" to the mask and now it is showing the first number 9, but in code like +995 it shows only +95. How can I have correct codes? Maybe I should change default value for numerics, but I haven't found how can I do this.</p>

```<code>$('input_phone_number').inputmask({mask: '+\\'+takeIndex+'9{10,13}', greedy: false, placeholder: ''});
</code>```

答:
Number 9 is used as mask for all the digits, if you want to use 9, change the mask using JavaScript, by redefining x as mask :

```<code>$.mask.definitions['9'] = '';
$.mask.definitions['x'] = '[0-9]';
</code>```

Now you can use x as mask:

```<code>$('input_phone_number').inputmask({mask: '+\\'+takeIndex+'x{10,13}', greedy: false, placeholder: ''});
</code>```

ContentLicense: CC BY-SA 3.0

Title: inputmask doesn't show number 9

Body:
I have a country select (in SlimSelect) with codes and a [type=tel] input with inputmask. I insert country codes (var takeIndex) to the mask, but inputmask doesn't show number 9 if it exists in code. I added "\" to the mask and now it is showing the first number 9, but in code like +995 it shows only +95. How can I have correct codes? Maybe I should change default value for numerics, but I haven't found how can I do this.

$('input_phone_number').inputmask({mask: '+\\'+takeIndex+'9{10,13}', greedy: false, placeholder: ''});

Body:
Number 9 is used as mask for all the digits, if you want to use 9, change the mask using JavaScript, by redefining x as mask :

$.mask.definitions['9'] = '';
$.mask.definitions['x'] = '[0-9]';

Now you can use x as mask:

$('input_phone_number').inputmask({mask: '+\\'+takeIndex+'x{10,13}', greedy: false, placeholder: ''});


问:
SolrCloud DIH performance
Got Solr 6.4.2 running in SolrCloud and some doubts about indexing performance.

I am using MSSql as data source and newest JDBC driver for MSSQL.

When Solr is started as standalone my DataImport runs at 31250 docs/s
When Solr is started as SolrCloud (2 replicas) my DataImport runs at 10000 docs/s

Is there any config parameter which have influence on this?

答:
It is expected that indexing in SolrCloud would be slower than indexing in standalone Solr (it has to index into the replicas too, so there is additional network traffic and latencies, and there are other things SolrCloud has to do too), but you can do some things to make sure it goes as fast as possible:

you can shard the index. Indexing into several shards should be faster (test diff. numbers, at some point it will be too many so don't go crazy)

send your docs to the shard leader. Indexing is done at the leader first, so if you send a doc to the leader you will save some network traffic. Of course here you have little control if you are using DIH. Unless you customize your DIH setup and have several handlers, each one would index only the docs for a shard, and you call each hanlder on the shard node.

Title: SolrCloud DIH performance


问:
React stateless component this.refs..value?
I don't know if I'm doing this correctly...
If I want to get value from an input I use this.refs.whatever.value.trim() but if that input is a stateless function component how do I do retrieve the value onSubmit?

I know this isn't correct now after researching but how are you supposed to get value from these input fields?

```<code>import React, {Component} from 'react'

import {InputField} from '../components/forms/InputField'
import {Button} from '../components/forms/Button'

export default class SignupWrapper extends Component {
  _handleSubmit(e) {
    e.preventDefault();
    const email = this.refs.email.value.trim();
    const password = this.refs.password.value.trim();
    const confirm = this.refs.confirm.value.trim();
    console.log({email, password, confirm});
  }

  render() {
    return (
      <form id="application-signup" onSubmit={this._handleSubmit.bind(this)}>
        <InputField type={'email'} name={'email'} text={'email'}
                    helpBlock={'email is required'} ref="email" />
        <InputField type={'password'} name={'password'} text={'password'}
                    helpBlock={'password is required'} ref="password" />
        <InputField type={'password'} name={'confirm'} text={'confirm password'}
                    helpBlock={'password confirmation is required'} ref="confirm" />
        <Button type={'submit'} className={'btn btn-primary'} text={'signup'} />
      </form>
    )
  }
}
</code>```

this is the stateless inputfield

```<code>import React from 'react'

export const InputField = (props) => (
  <div className="form-group col-xs-12">
    <label htmlFor={props.name}>{props.text}</label>
    <input type={props.type} name={props.name} className="form-control"
           data-stripe={props.stripe} />
    <span className="help-block">{props.helpBlock}</span>
  </div>
)
</code>```

答:
@inanc, show good method, but I propose an alternative way to use event target to get the DOM element reference. As you are using the form element, you can name your input elements and use it to access the form object.</p>

```<code>const onSubmit = fn => e => {
  e.preventDefault()
  const city = e.target.city.value // Access elements through `form`
  if (city) {
    fn(city)
  }
}

const MyComponent = ({
  onChange
}) => {
  return (
    <div>
      <form onSubmit={onSubmit(onChange)}>
        <input type='text' name='city' placeholder='Enter City Name' />
        <button>Go!</button>
      </form>
    </div>
  )
}
</code>```

Body:
I don't know if I'm doing this correctly...
If I want to get value from an input I use this.refs.whatever.value.trim() but if that input is a stateless function component how do I do retrieve the value onSubmit?

I know this isn't correct now after researching but how are you supposed to get value from these input fields?

import React, {Component} from 'react'

import {InputField} from '../components/forms/InputField'
import {Button} from '../components/forms/Button'

export default class SignupWrapper extends Component {
  _handleSubmit(e) {
    e.preventDefault();
    const email = this.refs.email.value.trim();
    const password = this.refs.password.value.trim();
    const confirm = this.refs.confirm.value.trim();
    console.log({email, password, confirm});
  }

  render() {
    return (
      <form id="application-signup" onSubmit={this._handleSubmit.bind(this)}>
        <InputField type={'email'} name={'email'} text={'email'}
                    helpBlock={'email is required'} ref="email" />
        <InputField type={'password'} name={'password'} text={'password'}
                    helpBlock={'password is required'} ref="password" />
        <InputField type={'password'} name={'confirm'} text={'confirm password'}
                    helpBlock={'password confirmation is required'} ref="confirm" />
        <Button type={'submit'} className={'btn btn-primary'} text={'signup'} />
      </form>
    )
  }
}

this is the stateless inputfield

import React from 'react'

export const InputField = (props) => (

    {props.text}
    <input type={props.type} name={props.name} className="form-control"
           data-stripe={props.stripe} />
    {props.helpBlock}

)

Body:
@inanc, show good method, but I propose an alternative way to use event target to get the DOM element reference. As you are using the form element, you can name your input elements and use it to access the form object.

const onSubmit = fn => e => {
  e.preventDefault()
  const city = e.target.city.value // Access elements through `form`
  if (city) {
    fn(city)
  }
}

const MyComponent = ({
  onChange
}) => {
  return (
    <div>
      <form onSubmit={onSubmit(onChange)}>
        <input type='text' name='city' placeholder='Enter City Name' />
        <button>Go!</button>
      </form>
    </div>
  )
}


问:
EntityFramework 6 Code First in Oracle 12.2.0
I use entity framework code firts 6.0

I used Oracle Client 12.1.0 and I added that section to  my web.config and it is working

```<code><entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
  <parameters>
    <parameter value="v11.0" />
  </parameters>
</defaultConnectionFactory>
<providers>
  <provider invariantName="Oracle.DataAccess.Client" type="Oracle.DataAccess.EntityFramework.EFOracleProviderServices, Oracle.DataAccess.EntityFramework, Version=6.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</providers>
</code>```

I upgrade my drive to oracle 12.2.0 and I change my web.config like this(only Version=6.122.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342" /> part was changed) but I got that error,what I am missing??

Unhandled Error Occured:System.NotSupportedException: Unable to
  determine the provider name for provider factory of type
  'Oracle.DataAccess.Client.OracleClientFactory'. Make sure that the
  ADO.NET provider is installed or registered in the application config.

```<code>   <entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
  <parameters>
    <parameter value="v11.0" />
  </parameters>
</defaultConnectionFactory>
<providers>
  <provider invariantName="Oracle.DataAccess.Client" type="Oracle.DataAccess.EntityFramework.EFOracleProviderServices, Oracle.DataAccess.EntityFramework, Version=6.122.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</providers>
</code>```

答:
```<code>I added this section and it works

<system.data>
<DbProviderFactories>
  <!-- Remove in case this is already defined in machine.config -->
  <remove invariant="Oracle.DataAccess.Client" />
  <add name="Oracle Data Provider for .NET" invariant="Oracle.DataAccess.Client" description="Oracle Data Provider for .NET" type="Oracle.DataAccess.Client.OracleClientFactory, Oracle.DataAccess, Version=4.122.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
  <add name="EF Tracing Data Provider" invariant="EFTracingProvider" description="Tracing Provider Wrapper" type="EFTracingProvider.EFTracingProviderFactory, EFTracingProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=def642f226e0e59b" />
</DbProviderFactories>
</code>```

Body:
I use entity framework code firts 6.0

I used Oracle Client 12.1.0 and I added that section to  my web.config and it is working

<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
  <parameters>
    <parameter value="v11.0" />
  </parameters>
</defaultConnectionFactory>
<providers>
  <provider invariantName="Oracle.DataAccess.Client" type="Oracle.DataAccess.EntityFramework.EFOracleProviderServices, Oracle.DataAccess.EntityFramework, Version=6.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</providers>

I upgrade my drive to oracle 12.2.0 and I change my web.config like this(only Version=6.122.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342" /> part was changed) but I got that error,what I am missing??

Unhandled Error Occured:System.NotSupportedException: Unable to
  determine the provider name for provider factory of type
  'Oracle.DataAccess.Client.OracleClientFactory'. Make sure that the
  ADO.NET provider is installed or registered in the application config.

   <entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
  <parameters>
    <parameter value="v11.0" />
  </parameters>
</defaultConnectionFactory>
<providers>
  <provider invariantName="Oracle.DataAccess.Client" type="Oracle.DataAccess.EntityFramework.EFOracleProviderServices, Oracle.DataAccess.EntityFramework, Version=6.122.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</providers>


问:
How to select rows with LEFT JOIN if specified value exists in joined table?
I not imagine how to build query. I need to select rows from table CONTENT which hasn't column tmplvarid=8 in left joined TEMPLATE VARIABLES column

SELECT con.id, con.alias, tv.tmplvarid FROM modx_site_content as con LEFT JOIN modx_site_tmplvar_contentvalues as tv ON con.id=tv.contentid WHERE con.deleted=0 AND (con.content IS NULL OR con.content='') AND con.template=5 AND tv.tmplvarid!=8/*not contains 8*/

Explanation: https://i.stack.imgur.com/gdgha.png

答:
Simple: Don't do an INNER join, do an OUTER JOIN instead:

```<code>SELECT con.id, con.alias, tv.tmplvarid FROM modx_site_content as con
    LEFT OUTER JOIN modx_site_tmplvar_contentvalues as tv ON con.id=tv.contentid
       AND tv.templvarid = 8
         WHERE con.deleted=0 AND (con.content IS NULL OR con.content='')
     AND con.template=5 AND tv.contentid IS NULL
</code>```

So you join for templvarid = 8 in an OUTER JOIN - and then select (in where) only the rows that have NULL in tv. contentid (that's those where not templvarid 8 could be found for join)

Body:
Simple: Don't do an INNER join, do an OUTER JOIN instead:

SELECT con.id, con.alias, tv.tmplvarid FROM modx_site_content as con
    LEFT OUTER JOIN modx_site_tmplvar_contentvalues as tv ON con.id=tv.contentid
       AND tv.templvarid = 8
         WHERE con.deleted=0 AND (con.content IS NULL OR con.content='')
     AND con.template=5 AND tv.contentid IS NULL

So you join for templvarid = 8 in an OUTER JOIN - and then select (in where) only the rows that have NULL in tv. contentid (that's those where not templvarid 8 could be found for join)


问:
create and use index on OrientDB
I create a database
Class: Tab,
Property:
    id (int unique)
    idTag (int)
    tagName( String)
    type (string)
    date (datetime)
    xy (Opoint) geospatial
    z (double)

I want to make an index to speed the query

If a create an index for 1 property (like idTag)

CREATE INDEX index_idTag ON Tab (idTag) notunique;

1/
Who can I query index_idTag and type  in the same query
Something like
Select from Tab where index_idTag= 10 and type=« Personne »

2/
I want to query an index (index_idTag), but return all information (id, index_idTag (idTag), tagName, type, date, xy, z)

Ty for your help

答:
When you have an index created and in use, you can query records in the index using the SELECT command.

Syntax:

SELECT FROM INDEX:<index-name> WHERE key = <key>

Example:

Selecting from the index dictionary where the key matches to Luke:

orientdb> SELECT FROM INDEX:dictionary WHERE key='Luke'

More information can be found in official documentation: https://orientdb.com/docs/last/Indexes.html

Title: create and use index on OrientDB


问:
Running Javascript from AJAX file
I've been trying to get this to work for ages now, tried loads of SO question/answers but not geting very far.

I think I originally had 2 issues, one which hopefully I've resolved.

I've been using JotForm (the easy form creator that uses prototype). What I have is a facebook style menu (AjaxFlagMenu) which creates a verticle ajax style menu that pulls in html snippets from external files (which in my case all have a Jotform form in there).

At the moment at the top of the 'main' page that contains the menu, I have:

```<code><script src="http://cdn.jquerytools.org/1.2.5/jquery.tools.min.js"></script>
<script type="text/javascript" src="/js/jquery.corner.js"></script>
<script type="text/javascript" src="/js/jquery.flagmenu.js"></script>
<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function($){
    var Menu = $("#_Menu").AjaxFlagMenu({
    Caption:'Manage Profile',
    CaptionClass:'CaptionClass',
    onOutClass:'onOutClass',
    onOverClass:'onOverClass',
    onClickClass:'onClickClass',
    hscOutClass:'hscOutClass',
    hscClickClass:'hscClickClass',
    Loading_gif:'/images/loading.gif',
    ajaxContent:'ajaxContent'
    });
    //Basic
    Menu.add({
        Title:'Basic Info',
        onOutIcon:'/images/icon-vcard-c.png',
        onClickIcon:'/images/icon-vcard-d.png',
        HtmlSatusContent:'',
        url:'/instructor/pages/mp-basic.php',
        data:''
    });
    //Profile Picture
    Menu.add({
        Title:'Profile Picture',
        onOutIcon:'/images/icon-camera-c.png',
        onClickIcon:'/images/icon-camera-d.png',
        HtmlSatusContent:'',
        url:'/instructor/pages/mp-photo.php',
        data:''
    });
    //Pricing and Offers
    Menu.add({
        Title:'Pricing and Offers',
        onOutIcon:'/images/icon-pound-c.png',
        onClickIcon:'/images/icon-pound-d.png',
        HtmlSatusContent:'',
        url:'/instructor/pages/mp-pricing.php',
        data:''
    });
    //Services
    Menu.add({
        Title:'Services',
        onOutIcon:'/images/icon-services-c.png',
        onClickIcon:'/images/icon-services-d.png',
        HtmlSatusContent:'',
        url:'/instructor/pages/mp-services.php',
        data:''
    });
    //Bio and Additional
    Menu.add({
        Title:'Bio and Additional',
        onOutIcon:'/images/icon-bio-c.png',
        onClickIcon:'/images/icon-bio-d.png',
        HtmlSatusContent:'',
        url:'/instructor/pages/mp-bio.php',
        data:''
    });
    $("#_td").corner("4px");
});
</script>
<script src="/js/jotform/prototype.js?v=3.1.92" type="text/javascript"></script>
<script src="/js/jotform/protoplus.js?v=3.1.92" type="text/javascript"></script>
<script src="/js/jotform/protoplus-ui.js?v=3.1.92" type="text/javascript"></script>
<script src="/js/jotform/jotform.js?v=3.1.92" type="text/javascript"></script>
<script src="/js/jotform/calendarview.js?v=3.1.92" type="text/javascript"></script>
</code>```

What I then need to do, is when the menu item is clicked and loads the HTML from the other page, I need to run JotForm.init(); to enable the JotForm validation functions. However, I don't even seem to be able to alert("Hello World"); to work on the page that is called in.

Any help would be great! Thank you!

答:
In the AjaxFlagMenu.js, at the line the ajax is executed:

```<code>//Ajax
var _XMLHTTPRequest = $.ajax({type: "GET",url:_url,data:_data });
</code>```

Try adding dataType: "html" like this:

```<code>//Ajax
var _XMLHTTPRequest = $.ajax({type: "GET",url:_url,data:_data,dataType: "html" });
</code>```

This wil evaluate the javascript you load via AJAX.

You will find more info here: http://api.jquery.com/jQuery.ajax/#options

LATER EDIT

The problem is that the AjaxFlagMenu doesn't evaluate the javascript from the ajax response!

Title: Running Javascript from AJAX file

Body:
I've been trying to get this to work for ages now, tried loads of SO question/answers but not geting very far.

I think I originally had 2 issues, one which hopefully I've resolved.

I've been using JotForm (the easy form creator that uses prototype). What I have is a facebook style menu (AjaxFlagMenu) which creates a verticle ajax style menu that pulls in html snippets from external files (which in my case all have a Jotform form in there).

At the moment at the top of the 'main' page that contains the menu, I have:

What I then need to do, is when the menu item is clicked and loads the HTML from the other page, I need to run JotForm.init(); to enable the JotForm validation functions. However, I don't even seem to be able to alert("Hello World"); to work on the page that is called in.

Any help would be great! Thank you!

Body:
In the AjaxFlagMenu.js, at the line the ajax is executed:

//Ajax
var _XMLHTTPRequest = $.ajax({type: "GET",url:_url,data:_data });

Try adding dataType: "html" like this:

//Ajax
var _XMLHTTPRequest = $.ajax({type: "GET",url:_url,data:_data,dataType: "html" });

This wil evaluate the javascript you load via AJAX.

You will find more info here: http://api.jquery.com/jQuery.ajax/#options

LATER EDIT

The problem is that the AjaxFlagMenu doesn't evaluate the javascript from the ajax response!


问:
Reading Through A List of Files, then Sending those Files via FTP
I am making weather model charts with the Grads scripting language, and I am using a bash script so I can use a while loop to download model data (in grib2 format) and call the grads scripts for each frame on the model run. Right now, I have a loop that runs through all the scripts for a given forecast hour and uploads the image output via FTP. After this for loop completes, the grib2 data for the next hour is downloaded, and the loop runs again.

```<code>for ((i=0;i<${#SCRIPTS[@]};i++)); do
    #define filename
    FILENAME="${FILENAMES[i]}${FORECASTHOUR}hrfcst.png"
    #run grads script
    /home/mint/opengrads/Contents/opengrads -lbc "run /home/mint/opengrads/Contents/plotscripts/${SCRIPTS[i]} $CTLFILE $INIT_STRINGDATE $INIT_INTDATE $INITHOUR $FILENAME $h $MODEL $MODELFORTITLE 500"
    #run ftp script
    #sh /home/mint/opengrads/Contents/bashscripts/ftpsample.sh $INIT_INTDATE $INITHOUR $FILENAME $MODEL
done
</code>```

This is inelegant because I open and close an FTP session each time I send a single image. I would much rather write the names of the filenames for a given forecast hour to a .txt file (ex: have a "echo ${FILENAME} >> FILEOFFILENAMES.txt" in the loop) and have my FTP script read and send all those files in a single session. Is this possible?

答:
It's possible. You can add this to your shell script to generate the ftp script and then have it run after you've generated the files:

```<code>echo open $HOST > ftp.txt
echo user $USER $PASS >> ftp.txt
find . -type f -name '*hrfcst.png' -printf "put destination/%f %f\n" >> ftp.txt
echo bye >> ftp.txt

ftp < ftp.txt
</code>```

The above code will generate file ftp.txt with commands and pass that to ftp. The generated ftp.txt will look like:

```<code>open host
user user pass
put destination/forecast1.hrfcst.png forecast1.hrfcst.png
put destination/forecast2.hrfcst.png forecast2.hrfcst.png
put destination/forecast3.hrfcst.png forecast3.hrfcst.png
...
bye
</code>```

Body:
I am making weather model charts with the Grads scripting language, and I am using a bash script so I can use a while loop to download model data (in grib2 format) and call the grads scripts for each frame on the model run. Right now, I have a loop that runs through all the scripts for a given forecast hour and uploads the image output via FTP. After this for loop completes, the grib2 data for the next hour is downloaded, and the loop runs again.

for ((i=0;i<${#SCRIPTS[@]};i++)); do
    #define filename
    FILENAME="${FILENAMES[i]}${FORECASTHOUR}hrfcst.png"
    #run grads script
    /home/mint/opengrads/Contents/opengrads -lbc "run /home/mint/opengrads/Contents/plotscripts/${SCRIPTS[i]} $CTLFILE $INIT_STRINGDATE $INIT_INTDATE $INITHOUR $FILENAME $h $MODEL $MODELFORTITLE 500"
    #run ftp script
    #sh /home/mint/opengrads/Contents/bashscripts/ftpsample.sh $INIT_INTDATE $INITHOUR $FILENAME $MODEL
done

This is inelegant because I open and close an FTP session each time I send a single image. I would much rather write the names of the filenames for a given forecast hour to a .txt file (ex: have a "echo ${FILENAME} >> FILEOFFILENAMES.txt" in the loop) and have my FTP script read and send all those files in a single session. Is this possible?

Body:
It's possible. You can add this to your shell script to generate the ftp script and then have it run after you've generated the files:

echo open $HOST > ftp.txt
echo user $USER $PASS >> ftp.txt
find . -type f -name '*hrfcst.png' -printf "put destination/%f %f\n" >> ftp.txt
echo bye >> ftp.txt

ftp < ftp.txt

The above code will generate file ftp.txt with commands and pass that to ftp. The generated ftp.txt will look like:

open host
user user pass
put destination/forecast1.hrfcst.png forecast1.hrfcst.png
put destination/forecast2.hrfcst.png forecast2.hrfcst.png
put destination/forecast3.hrfcst.png forecast3.hrfcst.png
...
bye


问:
Using regex in Powershell replace string in single quotation marks
considering this file

```<code>AppConfig = {
    version: '4.0.0',
    clientId: "guid",
    httpProxy: 'rest',
    restUrl: "http://url.contoso.com/v1/",

    conferences: ["lync", "hangouts", "webex"],    // "lync", "hangouts", "webex"

    dataRefreshInterval: 60 //seconds
}
</code>```

I want to replace  the string inside the single quotation marks with another string. I want to change the value of the specific property (in my case version).

```<code>$content = Get-Content $VersionFile

for($i = 0;$i -lt $content.Count; $i++)
{
    if($content[$i] -like "*version:*")
    {
        $content[$i] = $content[$i] -creplace <replaceWhat>, <replaceWith>
    }
}
</code>```

more elegant way how to find the line with version is appreciated.

答:
If you only want to replace the text inside the quotes for version, you can do the following :

```<code>$content = Get-Content $VersionFile
$replacement = <ReplaceWith>
$content = $content -creplace "version: '[^']*'","version: '$replacement'"
</code>```

It will replace 4.0.0 by <ReplaceWith> in you text

Body:
considering this file

AppConfig = {
    version: '4.0.0',
    clientId: "guid",
    httpProxy: 'rest',
    restUrl: "http://url.contoso.com/v1/",

    conferences: ["lync", "hangouts", "webex"],    // "lync", "hangouts", "webex"

    dataRefreshInterval: 60 //seconds
}

I want to replace  the string inside the single quotation marks with another string. I want to change the value of the specific property (in my case version).

$content = Get-Content $VersionFile

for($i = 0;$i -lt $content.Count; $i++)
{
    if($content[$i] -like "*version:*")
    {
        $content[$i] = $content[$i] -creplace <replaceWhat>, <replaceWith>
    }
}

more elegant way how to find the line with version is appreciated.

Body:
If you only want to replace the text inside the quotes for version, you can do the following :

$content = Get-Content $VersionFile
$replacement = <ReplaceWith>
$content = $content -creplace "version: '[^']*'","version: '$replacement'"

It will replace 4.0.0 by <ReplaceWith> in you text


问:
google tag manager, where to download binary container for android?
https://developers.google.com/tag-manager/android/v4/
says to download binary container.

I only see json version in my google tag manager console.

答:
If you end up with a json file, it may be because you're not using GTM Legacy Android but the Firebase(Android) version of the SDK.
The choice has been given to you when you created the container :

I hope this helps !


问:
Transform CSS { ul li:hover a } in JQUERY .hover
I want to now if there's a way to transform this css properties in a jquery .hover, or control this by javascript to change the colour dynamically.

CSS:

```<code>ul li:hover a {
    color: #FFF;
}
</code>```

Can anyone Help ?

EDIT:

My problem is:

I have a drop down menu and i want that when I hover the menu the text color change and when I hover the submenu the hover state stays for both.

JQuery:

```<code>$("ul li").hover(function () {
    $(this).stop().animate({ backgroundColor: "white"}, 500);
}, function () {
    $(this).stop().animate({ backgroundColor: "black"}, 400);
});
</code>```

To animate background color on hover in menu and submenu.

For example if the text are black I want to make the text white on hover. For this I use:(Submenu example, for menu change the selector of course)

```<code>$('ul.submenu li a').hover(function () {
    $(this).css({color:'#FFFFFF'});
}, function () {
    $(this).css({color:'#00FF00'});
});
</code>```

All This works fine, but when I hover the submenu the menu returns to the original state(because the mouseleave is activated on hover out). All I want is that when I hover submenu the hover state in menu stays active as well.

I've tried many things but all give me problems, only thing that works is css, but I need to control the text colours dynamically too.

HTML Structure:

```<code><ul class="menu">

      <li><a href="#">text</a></li>

      <li><a href="#">text</a>

        <ul class="submenu">
          <li><a href="#">text</a></li>
          <li><a href="#">text</a></li>
          <li><a href="#">text</a></li>
        </ul>

      </li>

      <li><a href="#">text</a></li>

</ul>
</code>```

答:
```<code>$('li').hover(
    function(){
         $(this).css({color:'white'}); //mouseover
    },
    function(){
         $(this).css({color:'black'}); // mouseout
    }
);
</code>```

Body:
I want to now if there's a way to transform this css properties in a jquery .hover, or control this by javascript to change the colour dynamically.

CSS:

ul li:hover a {
    color: #FFF;
}

Can anyone Help ?

EDIT:

My problem is:

I have a drop down menu and i want that when I hover the menu the text color change and when I hover the submenu the hover state stays for both.

JQuery:

$("ul li").hover(function () {
    $(this).stop().animate({ backgroundColor: "white"}, 500);
}, function () {
    $(this).stop().animate({ backgroundColor: "black"}, 400);
});

To animate background color on hover in menu and submenu.

For example if the text are black I want to make the text white on hover. For this I use:(Submenu example, for menu change the selector of course)

$('ul.submenu li a').hover(function () {
    $(this).css({color:'#FFFFFF'});
}, function () {
    $(this).css({color:'#00FF00'});
});

All This works fine, but when I hover the submenu the menu returns to the original state(because the mouseleave is activated on hover out). All I want is that when I hover submenu the hover state in menu stays active as well.

I've tried many things but all give me problems, only thing that works is css, but I need to control the text colours dynamically too.

HTML Structure:

text

text

text

text

text

text


问:
Java - Protect from interrupt SwingWorker
I need to interrupt swingworkers, but if the thread is running some fragment, it should interrupt after that. Something like this:

```<code>public class worker extends SwingWorker<Integer, String>{
    //(...) constructors and everything else

    protected Integer doInBackground() throws Exception{
        //Code that can be interrupted
        while(true){
            //(...) more code that can be interrupted

            //This shouldn't be interrupted, has to wait till the loop ends
            for(int i=0; i<10; i++){

            //(...) more code that can be interrupted
        }
    }
}
</code>```

Interrupting the worker with:

```<code>Worker worker = new Worker();
worker.execute();
worker.cancel(true);
</code>```

I've tried synchronized blocks, but not sure if that doesn't work or i'm just doing it wrong.

Is there a way? Thanks!

答:
Any way you can control either by a flag which will check the thread periodically.
So before start you can check the flag or interrupt then Proceed.

make flag as volatile so it will be visible to all thread or AtomicBoolean

```<code> while (flag) {
       //do stuff here
     }
</code>```

or you can use interrupt to cancel the task.

```<code> try {
      while(!Thread.currentThread().isInterrupted()) {
         // ...
      }
   } catch (InterruptedException consumed)

   }
</code>```

Body:
I need to interrupt swingworkers, but if the thread is running some fragment, it should interrupt after that. Something like this:

public class worker extends SwingWorker<Integer, String>{
    //(...) constructors and everything else

    protected Integer doInBackground() throws Exception{
        //Code that can be interrupted
        while(true){
            //(...) more code that can be interrupted

            //This shouldn't be interrupted, has to wait till the loop ends
            for(int i=0; i<10; i++){

            //(...) more code that can be interrupted
        }
    }
}

Interrupting the worker with:

Worker worker = new Worker();
worker.execute();
worker.cancel(true);

I've tried synchronized blocks, but not sure if that doesn't work or i'm just doing it wrong.

Is there a way? Thanks!

Body:
Any way you can control either by a flag which will check the thread periodically.
So before start you can check the flag or interrupt then Proceed.

make flag as volatile so it will be visible to all thread or AtomicBoolean

 while (flag) {
       //do stuff here
     }

or you can use interrupt to cancel the task.

 try {
      while(!Thread.currentThread().isInterrupted()) {
         // ...
      }
   } catch (InterruptedException consumed)

   }


问:
Chrome extension - select2 library working into console but not in content.js
Hello i'm working on a google chrome extension and workaround with https://select2.github.io .

Here is my manifest:

```<code>{
    "manifest_version": 2,

    "name": "Extension Test",
    "description": "Test extension",
    "version": "1.0",
    "content_scripts": [
        {
            "matches": ["https://www.mywebsite.com/*"],
            "js": ["jquery-1.11.3.js", "content.js"]
        }
    ],
    "background": {
        "scripts": ["jquery-1.11.3.js","background.js"]
    },
    "permissions": [
        "activeTab",
        "webNavigation",
        "*://*/*"
    ]
}
</code>```

Here is what i run directly into console:

```<code>$('#myselect2').select2('open');
</code>```

Then the same code into content js is not working and firing the following error:

```<code>content.js:151 Uncaught TypeError: $(...).select2 is not a function
</code>```

Is it possible to open select menu from extension to content of website and if so how ?

答:
It looks like you are not including the select2 plugin in your extension. Download it into your extension and, in your manifest, add:</p>

```<code>"js": ["jquery-1.11.3.js", "select2.min.js", "content.js"]
</code>```

Body:
Hello i'm working on a google chrome extension and workaround with https://select2.github.io .

Here is my manifest:

{
    "manifest_version": 2,

    "name": "Extension Test",
    "description": "Test extension",
    "version": "1.0",
    "content_scripts": [
        {
            "matches": ["https://www.mywebsite.com/*"],
            "js": ["jquery-1.11.3.js", "content.js"]
        }
    ],
    "background": {
        "scripts": ["jquery-1.11.3.js","background.js"]
    },
    "permissions": [
        "activeTab",
        "webNavigation",
        "*://*/*"
    ]
}

Here is what i run directly into console:

$('#myselect2').select2('open');

Then the same code into content js is not working and firing the following error:

content.js:151 Uncaught TypeError: $(...).select2 is not a function

Is it possible to open select menu from extension to content of website and if so how ?

Body:
It looks like you are not including the select2 plugin in your extension. Download it into your extension and, in your manifest, add:

"js": ["jquery-1.11.3.js", "select2.min.js", "content.js"]


问:
How to pass data from parent to child in Vue2
So I have 4 components as follow

Card-List Component

```<code>Vue.component('card-list',{

    template:`<div >
                    <card v-for="task in tasks" >{{task.month}}</card>
              </div>`,

    data(){

      return {

          tasks:[

              {description:'Get up from Bed',completed:true,month:12},
              {description:'Brush your teeth',completed:false,month:24},
              {description:'GO to POOP ',completed:false,month:36},
              {description:'Eat BreakFast',completed:true,month:12},
        ]

      }

    }
});
</code>```

Card Component

```<code>Vue.component('card',{

    template:`
                <div class="col-lg-2 col-md-3 col-sm-4 col-xs-12 bx_main">
                  <div class="flip3D col-md-12 pad">
                    <back><slot></slot></back>
                    <front><slot></slot></front>
                  </div>
                </div>`,

});
</code>```

front Component

```<code>Vue.component('front',{

    props: ['months'],
    template:`
                <div class="front"><span class="fav_main2"><span><i class="">{{months}}</i></span></span>
                  <div class="col-md-12 star_mn">
                    <div class="ico_main"><a href="#"><i class="fa fa-star"></i></a></div>
                    <div class="clearfix"></div>
                  </div>
              </div>`,

});
</code>```

back component

```<code>Vue.component('back',{

    props: ['months','rates'],

    template:`
                    <div class="back">
                    <span class="fav_main2"><span><i class="">{{months}}</i></span></span>
                    <div class="col-md-12 star_mn">
                      <div class="ico_main"><a href="#"><i class="fa fa-star"></i></a></div>
                      <div class="clearfix"></div>
                    </div>
                     <div class="back_main_cont">
                        <div class="col-md-12 back_tbl_main">
                          <div class="back_tbl">
                            Table goes here
                          </div>
                        </div>
                        <div class="col-md-12">
                          <div class="col-md-9 col-sm-9 col-xs-9 pad">
                            <div class="input-group bootstrap-touchspin">
                              <input class="commission form-control"
                              type="text" data-cardpos="0" value="0" style="display: block;"></div>
                          </div>
                          <div class="col-md-3 col-sm-3 col-xs-3 pad">
                            <button class="btn btn-primary btn-sm pull-right view_btn1" data-cardpos="0" type="button"><i class="fa fa-eye"></i></button>
                          </div>
                          <div class="clearfix"></div>
                        </div>
                      </div>
                    </div>
                  `,

});
</code>```

I want to pass the task.month    value to child component

how can I do that ?

Update1

tried this

```<code>Vue.component('card-list',{

        template:`<div >
                        <card v-for="task in tasks" :months="task.months" ></card>
                  </div>`,

        data(){

          return {

              tasks:[

                  {description:'Get up from Bed',completed:true,month:12},
                  {description:'Brush your teeth',completed:false,month:24},
                  {description:'GO to POOP ',completed:false,month:36},
                  {description:'Eat BreakFast',completed:true,month:12},
            ]

          }

        }
    });
</code>```

error

[Vue warn]: Error compiling template:

invalid expression: :months="{{task.months}}"

found in

--->

答:
You need to declare the prop in card, and then pass the prop in the HTML tag.

Vue.component('card-list', {

  template: `

                    <card v-for="task in tasks" :key="task" :months="task.month">{{task.month}}</card>

`,

  data() {

    return {

      tasks: [

        {
          description: 'Get up from Bed',
          completed: true,
          month: 12
        },
        {
          description: 'Brush your teeth',
          completed: false,
          month: 24
        },
        {
          description: 'GO to POOP ',
          completed: false,
          month: 36
        },
        {
          description: 'Eat BreakFast',
          completed: true,
          month: 12
        },
      ]

    }

  }
});

Vue.component('card', {

  template: `

                    <back :months="months"><slot></slot></back>
                    <front :months="months"><slot></slot></front>

`,
  props: ['months']

});

Vue.component('front', {

  props: ['months'],
  template: `

{{months}}

`,

});

Vue.component('back', {

  props: ['months', 'rates'],

  template: `

                    {{months}}

                            Table goes here

                              <input class="commission form-control"
                              type="text" data-cardpos="0" value="0" style="display: block;">

                            <button class="btn btn-primary btn-sm pull-right view_btn1" data-cardpos="0" type="button"></button>

                  `,

});

new Vue({
  el: '#app'
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.min.js"></script>
<card-list id="app">

</card-list></code>```

Body:
So I have 4 components as follow

Card-List Component

Vue.component('card-list',{

    template:`

                    <card v-for="task in tasks" >{{task.month}}</card>

`,

    data(){

      return {

          tasks:[

              {description:'Get up from Bed',completed:true,month:12},
              {description:'Brush your teeth',completed:false,month:24},
              {description:'GO to POOP ',completed:false,month:36},
              {description:'Eat BreakFast',completed:true,month:12},
        ]

      }

    }
});

Card Component

Vue.component('card',{

    template:`

                    <back><slot></slot></back>
                    <front><slot></slot></front>

`,

});

front Component

Vue.component('front',{

    props: ['months'],
    template:`

{{months}}

`,

});

back component

Vue.component('back',{

    props: ['months','rates'],

    template:`

                    {{months}}

                            Table goes here

                              <input class="commission form-control"
                              type="text" data-cardpos="0" value="0" style="display: block;">

                            <button class="btn btn-primary btn-sm pull-right view_btn1" data-cardpos="0" type="button"></button>

                  `,

});

I want to pass the task.month    value to child component

how can I do that ?

Update1

tried this

Vue.component('card-list',{

        template:`

                        <card v-for="task in tasks" :months="task.months" ></card>

`,

        data(){

          return {

              tasks:[

                  {description:'Get up from Bed',completed:true,month:12},
                  {description:'Brush your teeth',completed:false,month:24},
                  {description:'GO to POOP ',completed:false,month:36},
                  {description:'Eat BreakFast',completed:true,month:12},
            ]

          }

        }
    });

error

[Vue warn]: Error compiling template:

invalid expression: :months="{{task.months}}"

found in

--->

Body:
You need to declare the prop in card, and then pass the prop in the HTML tag.

Vue.component('card-list', {

  template: `<div >
                    <card v-for="task in tasks" :key="task" :months="task.month">{{task.month}}</card>
              </div>`,

  data() {

    return {

      tasks: [

        {
          description: 'Get up from Bed',
          completed: true,
          month: 12
        },
        {
          description: 'Brush your teeth',
          completed: false,
          month: 24
        },
        {
          description: 'GO to POOP ',
          completed: false,
          month: 36
        },
        {
          description: 'Eat BreakFast',
          completed: true,
          month: 12
        },
      ]

    }

  }
});

Vue.component('card', {

  template: `
                <div class="col-lg-2 col-md-3 col-sm-4 col-xs-12 bx_main">
                  <div class="flip3D col-md-12 pad">
                    <back :months="months"><slot></slot></back>
                    <front :months="months"><slot></slot></front>
                  </div>
                </div>`,
  props: ['months']

});

Vue.component('front', {

  props: ['months'],
  template: `
                <div class="front"><span class="fav_main2"><span><i class="">{{months}}</i></span></span>
                  <div class="col-md-12 star_mn">
                    <div class="ico_main"><a href="#"><i class="fa fa-star"></i></a></div>
                    <div class="clearfix"></div>
                  </div>
              </div>`,

});

Vue.component('back', {

  props: ['months', 'rates'],

  template: `
                    <div class="back">
                    <span class="fav_main2"><span><i class="">{{months}}</i></span></span>
                    <div class="col-md-12 star_mn">
                      <div class="ico_main"><a href="#"><i class="fa fa-star"></i></a></div>
                      <div class="clearfix"></div>
                    </div>
                     <div class="back_main_cont">
                        <div class="col-md-12 back_tbl_main">
                          <div class="back_tbl">
                            Table goes here
                          </div>
                        </div>
                        <div class="col-md-12">
                          <div class="col-md-9 col-sm-9 col-xs-9 pad">
                            <div class="input-group bootstrap-touchspin">
                              <input class="commission form-control"
                              type="text" data-cardpos="0" value="0" style="display: block;"></div>
                          </div>
                          <div class="col-md-3 col-sm-3 col-xs-3 pad">
                            <button class="btn btn-primary btn-sm pull-right view_btn1" data-cardpos="0" type="button"><i class="fa fa-eye"></i></button>
                          </div>
                          <div class="clearfix"></div>
                        </div>
                      </div>
                    </div>
                  `,

});

new Vue({
  el: '#app'
});

<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.min.js"></script>
<card-list id="app">

</card-list>


问:
Why does this code result in a NPE while sleeping to avoid rate limit in Twitter4J?
I am using Twitter4j to fetch the followers of a given user. At some point I always hit the rate limit. I am happy for the program to sleep for 15 minutes to over come this. However when it wakes, I get an error.

See the following code:

```<code>protected IDs fetchAndStoreFollowers(TwitterUser user) {
    Twitter twitter = this.getTwitterApi();
    long cursor = -1;
    IDs ids = null;
    do {
        try {
            ids = twitter.getFollowersIDs(user.getId(), cursor);
            System.out.println("Got a followers batch");
            cursor = ids.getNextCursor();
            this.storeFollowers(user, ids);
            System.out.println("Saved!");
        } catch (TwitterException e) {
            System.out.println("Oh no! Rate limit exceeded... going to sleep.");
            handleTwitterException(e);
            System.out.println("Waking up!");
        }
    } while (ids.hasNext());
    return ids;
}
</code>```

After waking up from the sleep the program throws a NullPointerException on this line:

```<code>} while (ids.hasNext());
</code>```

Can anybody spot why?

答:
The cause of the encountered error is reproducible and quite logic.

First, you initialize your ids to null.

In case a RateLimitException (TwitterException) occurs, no actual value is ever set to the variable ids in the line with:

```<code>ids = twitter.getFollowersIDs(user.getId(), cursor);
</code>```

The code in the catch-Block is then executed - while ids is still pointing to null. After this is processed (and you see output on your console...), the line:

```<code>while (ids.hasNext());
</code>```

produces the NullPointerException.

Solution

Change the while-condition as follows:

```<code>while (ids == null || (id!=null && ids.hasNext()));
</code>```

Be aware that the value in cursor might not have been or has to be changed accordingly, in case of an error situation.

Hope this helps.

Body:
I am using Twitter4j to fetch the followers of a given user. At some point I always hit the rate limit. I am happy for the program to sleep for 15 minutes to over come this. However when it wakes, I get an error.

See the following code:

protected IDs fetchAndStoreFollowers(TwitterUser user) {
    Twitter twitter = this.getTwitterApi();
    long cursor = -1;
    IDs ids = null;
    do {
        try {
            ids = twitter.getFollowersIDs(user.getId(), cursor);
            System.out.println("Got a followers batch");
            cursor = ids.getNextCursor();
            this.storeFollowers(user, ids);
            System.out.println("Saved!");
        } catch (TwitterException e) {
            System.out.println("Oh no! Rate limit exceeded... going to sleep.");
            handleTwitterException(e);
            System.out.println("Waking up!");
        }
    } while (ids.hasNext());
    return ids;
}

After waking up from the sleep the program throws a NullPointerException on this line:

} while (ids.hasNext());

Can anybody spot why?

Body:
The cause of the encountered error is reproducible and quite logic.

First, you initialize your ids to null.

In case a RateLimitException (TwitterException) occurs, no actual value is ever set to the variable ids in the line with:

ids = twitter.getFollowersIDs(user.getId(), cursor);

The code in the catch-Block is then executed - while ids is still pointing to null. After this is processed (and you see output on your console...), the line:

while (ids.hasNext());

produces the NullPointerException.

Solution

Change the while-condition as follows:

while (ids == null || (id!=null && ids.hasNext()));

Be aware that the value in cursor might not have been or has to be changed accordingly, in case of an error situation.

Hope this helps.


问:
Excel vba change value from one sheet to another
I have two named sheets and I want to change value from one sheet to another with following syntax; however I get Type Mismatch Error. Can anyone look into this and assist me?

Named Sheets: wks1 and wks2

```<code>wks1.cells(1,1).value=wks2.cells(1,3).value
</code>```

Any help would be much appreciated.

答:
One example:</p>

```<code>Sub Manish()
    Dim wks1 As Worksheet, wks2 As Worksheet

    Set wks1 = Sheets("wks1")
    Set wks2 = Sheets("wks2")

    wks1.Cells(1, 1).Value = wks2.Cells(1, 3).Value
End Sub
</code>```

Body:
I have two named sheets and I want to change value from one sheet to another with following syntax; however I get Type Mismatch Error. Can anyone look into this and assist me?

Named Sheets: wks1 and wks2

wks1.cells(1,1).value=wks2.cells(1,3).value

Any help would be much appreciated.

Body:
One example:

Sub Manish()
    Dim wks1 As Worksheet, wks2 As Worksheet

    Set wks1 = Sheets("wks1")
    Set wks2 = Sheets("wks2")

    wks1.Cells(1, 1).Value = wks2.Cells(1, 3).Value
End Sub


问:
Manipulate the java class path of an Eclipse plugin?
I am working on a plugin that consist of a homemade view to Eclipse.
When I run the plugin and display the classpath using  System.getProperty("java.class.path")
I get this as output : D:\Programs\eclipse\plugins\org.eclipse.equinox.launcher_1.3.100.v20150511-1540.jar

I would like to add some .jar files for the proper functioning of my view, but I can't figure out how... I guess you can do it by adding some specifications to the MANIFEST.MF of the plugin but I don't know how to do it propely.
any ideas ?

答:
Each Eclipse plugin has its own classpath. To use additional jars in the plugin you need to include them in the plugin.

Add your jars to the plugin directory. Usually they are put in a 'lib' directory.

Open the plugin MANIFEST.MF editor and on the 'Runtime' tab in the 'Classpath' section click the 'Add...' button and add your jars to the class path.

On the 'Build' tab of the editor make sure the 'lib' folder is include in the Binary Build section.

Your MANIFEST.MF should end up with a `Bundle-Classpath' entry that looks something like:

Bundle-ClassPath: .,
 lib/jogg-0.0.7.jar,
 lib/jorbis-0.0.15.jar,
 lib/vorbisspi1.0.2.jar
```

<p>(here I have 3 jars in a lib folder).</p>

<p>The build.properties file should be something like:</p>

<pre class="lang-none prettyprint-override"><code>bin.includes = META-INF/,\
               .,\
               plugin.xml,\
               lib/,\
               lib/jogg-0.0.7.jar,\
               lib/jorbis-0.0.15.jar,\
               lib/vorbisspi1.0.2.jar
</code>```

Body:
Each Eclipse plugin has its own classpath. To use additional jars in the plugin you need to include them in the plugin.

Add your jars to the plugin directory. Usually they are put in a 'lib' directory.

Open the plugin MANIFEST.MF editor and on the 'Runtime' tab in the 'Classpath' section click the 'Add...' button and add your jars to the class path.

On the 'Build' tab of the editor make sure the 'lib' folder is include in the Binary Build section.

Your MANIFEST.MF should end up with a `Bundle-Classpath' entry that looks something like:

Bundle-ClassPath: .,
 lib/jogg-0.0.7.jar,
 lib/jorbis-0.0.15.jar,
 lib/vorbisspi1.0.2.jar

(here I have 3 jars in a lib folder).

The build.properties file should be something like:

bin.includes = META-INF/,\
               .,\
               plugin.xml,\
               lib/,\
               lib/jogg-0.0.7.jar,\
               lib/jorbis-0.0.15.jar,\
               lib/vorbisspi1.0.2.jar


问:
Best way to subtract vector from matrix in Julia
What is the best way to subtract a vector of length N from a matrix of size (N, K) in Julia?

Of course, for loop or repmat should work but they do not seem to be the most efficient.

Can I use broadcast somehow?

答:
```<code>julia> [1 2 3; 4 5 6; 7 8 9] .- [1; 2; 3]
3×3 Array{Int64,2}:
 0  1  2
 2  3  4
 4  5  6
</code>```

(obviously, subtracting horizontal vectors is also broadcasted)

```<code>julia> [1 2 3; 4 5 6; 7 8 9] .- [1 2 3]
3×3 Array{Int64,2}:
 0  0  0
 3  3  3
 6  6  6
</code>```

Also, note that the broadcasted call .- in the top example is essentially equivalent to

```<code>julia> (-).([1 2 3; 4 5 6; 7 8 9], [1; 2; 3])
3×3 Array{Int64,2}:
 0  1  2
 2  3  4
 4  5  6
</code>```

as of julia 0.6, unifying the f.(args) syntax / under-the-hood implementation for broadcasting functions with that for broadcasting operators.

(i.e. .- is no longer a separately defined operator, which happens to be a 'broadcasted' version of - ).

Body:
julia> [1 2 3; 4 5 6; 7 8 9] .- [1; 2; 3]
3×3 Array{Int64,2}:
 0  1  2
 2  3  4
 4  5  6

(obviously, subtracting horizontal vectors is also broadcasted)

julia> [1 2 3; 4 5 6; 7 8 9] .- [1 2 3]
3×3 Array{Int64,2}:
 0  0  0
 3  3  3
 6  6  6

Also, note that the broadcasted call .- in the top example is essentially equivalent to

julia> (-).([1 2 3; 4 5 6; 7 8 9], [1; 2; 3])
3×3 Array{Int64,2}:
 0  1  2
 2  3  4
 4  5  6

as of julia 0.6, unifying the f.(args) syntax / under-the-hood implementation for broadcasting functions with that for broadcasting operators.

(i.e. .- is no longer a separately defined operator, which happens to be a 'broadcasted' version of - ).


问:
Passing data from JSON to table view cell in Swift 3
I'm trying to pass data from a JSON response to a table view cell. I'm having problems with capturing the response values that I'm extracting in URLSession.shared.dataTask.

```<code>    func callYouTubeAPIToGetAllVideos() {

    let url = URL(string: "https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=XYZ&maxResults=50&order=date&key=ABC")

    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error != nil {
            print(error!)
        } else {
            if let usableData = data {
                let json = try? JSONSerialization.jsonObject(with: usableData, options: [])
                if let dictionary = json as? [String: Any?] {
                    if let array = dictionary["items"] as? [Any] {
                        for object in array {
                            if let objectAsDictionary = object as? [String: Any?] {
                                if let objectWithKindAndVideoId = objectAsDictionary["id"] as? [String: String] {
                                    if let videoId = objectWithKindAndVideoId["videoId"] {
                                        //pass data to table cell
                                    }
                                }
                                if let snippet = objectAsDictionary["snippet"] as? [String: Any] {
                                    if let description = snippet["description"] {
                                        //pass data to table cell
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    task.resume()
}
</code>```

I tried appending the values to an instance variable but it didn't work.

Sorry about the messy code, this is my 1st time working with JSON in Swift.

答:
First of all never declare a received JSON dictionary as [String:Any?]. A received dictionary value can't be nil.

Declare a custom struct Video.

```<code>struct Video {
    let videoId : String
    let description : String
}
</code>```

Declare a data source array.

```<code>var videos = [Video]()
</code>```

Parse the JSON into the array and reload the table view on the main thread.

```<code>func callYouTubeAPIToGetAllVideos() {

    let url = URL(string: "https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=XYZ&maxResults=50&order=date&key=ABC")

    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
       if error != nil {
            print(error!)
        } else {
            do {
                if let dictionary = try JSONSerialization.jsonObject(with: data!) as? [String: Any],
                    let array = dictionary["items"] as? [[String: Any]] {
                    for object in array {
                        if let objectWithKindAndVideoId = object["id"] as? [String: String],
                           let snippet = object["snippet"] as? [String: Any] {
                               let videoId = objectWithKindAndVideoId["videoId"] ?? ""
                               let description = snippet["description"] as? String ?? ""
                               let video = Video(videoId: videoId, description: description)
                               self.videos.append(video)
                         }

                    }
                    DispatchQueue.main.async {
                        self.tableView.reloadData()
                    }
                }
            } catch {
                print(error)
            }
        }
    }
    task.resume()
}
</code>```

In cellForRow assign the values to the text properties

```<code>let video = videos[indexPath.row]
cell.textLabel!.text = video.videoId
cell.detailTextLabel?.text = video.description
</code>```

Body:
I'm trying to pass data from a JSON response to a table view cell. I'm having problems with capturing the response values that I'm extracting in URLSession.shared.dataTask.

    func callYouTubeAPIToGetAllVideos() {

    let url = URL(string: "https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=XYZ&maxResults=50&order=date&key=ABC")

    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error != nil {
            print(error!)
        } else {
            if let usableData = data {
                let json = try? JSONSerialization.jsonObject(with: usableData, options: [])
                if let dictionary = json as? [String: Any?] {
                    if let array = dictionary["items"] as? [Any] {
                        for object in array {
                            if let objectAsDictionary = object as? [String: Any?] {
                                if let objectWithKindAndVideoId = objectAsDictionary["id"] as? [String: String] {
                                    if let videoId = objectWithKindAndVideoId["videoId"] {
                                        //pass data to table cell
                                    }
                                }
                                if let snippet = objectAsDictionary["snippet"] as? [String: Any] {
                                    if let description = snippet["description"] {
                                        //pass data to table cell
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    task.resume()
}

I tried appending the values to an instance variable but it didn't work.

Sorry about the messy code, this is my 1st time working with JSON in Swift.

Body:
First of all never declare a received JSON dictionary as [String:Any?]. A received dictionary value can't be nil.

Declare a custom struct Video.

struct Video {
    let videoId : String
    let description : String
}

Declare a data source array.

var videos = [Video]()

Parse the JSON into the array and reload the table view on the main thread.

func callYouTubeAPIToGetAllVideos() {

    let url = URL(string: "https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=XYZ&maxResults=50&order=date&key=ABC")

    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
       if error != nil {
            print(error!)
        } else {
            do {
                if let dictionary = try JSONSerialization.jsonObject(with: data!) as? [String: Any],
                    let array = dictionary["items"] as? [[String: Any]] {
                    for object in array {
                        if let objectWithKindAndVideoId = object["id"] as? [String: String],
                           let snippet = object["snippet"] as? [String: Any] {
                               let videoId = objectWithKindAndVideoId["videoId"] ?? ""
                               let description = snippet["description"] as? String ?? ""
                               let video = Video(videoId: videoId, description: description)
                               self.videos.append(video)
                         }

                    }
                    DispatchQueue.main.async {
                        self.tableView.reloadData()
                    }
                }
            } catch {
                print(error)
            }
        }
    }
    task.resume()
}

In cellForRow assign the values to the text properties

let video = videos[indexPath.row]
cell.textLabel!.text = video.videoId
cell.detailTextLabel?.text = video.description


问:
Publish over CIFS Plugin
I am using “Publish over CIFS Plugin”. Test Configuration gives me success messages , I am using it under Post build step in job as “Send build artifact to a Windows share”. Logs just shows:

```<code>CIFS: Connecting from host [--------]
CIFS: Connecting with configuration [WebSites] ...
CIFS: Disconnecting configuration [WebSites] ...
CIFS: Transferred 0 file(s)
Finished: SUCCESS
</code>```

My job configuration is like this:

```<code>Source Files: publish
Remove prefix: publish
Remote directory: CCDEVWEB0/FIRECOM/DEVELOPMENT
</code>```

Configuration system:

```<code>Publish over CIFS -> CIFS Share:
name: Websites,
Hostname:srvdes3,
username:-----,
password: ----,
Share: WebStites.
</code>```

(The test configuration is successful)

It always transfer 0 files.

Can anyone help me? Thanks

I have publish in my workspace. (workspace/publish)

And development is in my server (CCDEVWEB0/FIRECOM/DEVELOPMENT)

SOLVED:
In this case the problem was my job configuration. It should be like this:

```<code>Source Files: publish/*.*
Remove prefix: publish/
Remote directory: CCDEVWEB0/FIRECOM/DEVELOPMENT
</code>```

(I had problems sending all files together so I had to send them folder by folder)

Title: Publish over CIFS Plugin

Body:
I am using “Publish over CIFS Plugin”. Test Configuration gives me success messages , I am using it under Post build step in job as “Send build artifact to a Windows share”. Logs just shows:

CIFS: Connecting from host [--------]
CIFS: Connecting with configuration [WebSites] ...
CIFS: Disconnecting configuration [WebSites] ...
CIFS: Transferred 0 file(s)
Finished: SUCCESS

My job configuration is like this:

Source Files: publish
Remove prefix: publish
Remote directory: CCDEVWEB0/FIRECOM/DEVELOPMENT

Configuration system:

Publish over CIFS -> CIFS Share:
name: Websites,
Hostname:srvdes3,
username:-----,
password: ----,
Share: WebStites.

(The test configuration is successful)

It always transfer 0 files.

Can anyone help me? Thanks

I have publish in my workspace. (workspace/publish)

And development is in my server (CCDEVWEB0/FIRECOM/DEVELOPMENT)

SOLVED:
In this case the problem was my job configuration. It should be like this:

Source Files: publish/*.*
Remove prefix: publish/
Remote directory: CCDEVWEB0/FIRECOM/DEVELOPMENT

(I had problems sending all files together so I had to send them folder by folder)


问:
Div not inline when window gets smaller?
I'm having a small issue with a couple divs. I have it set up with 5 divs all different colors, when the window size is shrunk the divs drop down under each other one by one. Is there a way I can make the space between them shrinks with it so they but up closer?

Thanks again guys

p {
  margin: 0;
}

.pageColourOn {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 155px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.pageColourOff {
  display: none;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

.bg01Off {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg02Off {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg03Off {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg04Off {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg05Off {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.center {
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="pageColourOn" id="pageColour">
  <div id="pageName">
    <p>Colour</p>
  </div>
  <div class="center">
    <div id="bg01" class="bg01Off">
    </div>
    <div id="bg02" class="bg02Off">
    </div>
    <div id="bg03" class="bg03Off">
    </div>
    <div id="bg04" class="bg04Off">
    </div>
    <div id="bg05" class="bg05Off">
    </div>
  </div></code>```

答:
Use media queries to make elements respond as the width of the viewport changes for example:

```<code>body {
background-color: lightgreen;
     }

@media only screen and (max-width: 500px) {
body {
    background-color: lightblue;
    }
}
</code>```

This would make the background color change when the width of the viewport goes below 500 px. You can use this same concept with the width of your divs.

** Also, check out Bootstrap. Bootstrap makes it easy to define widths of elements using a grid system. You are trying to make your site "RESPONSIVE" which is a well-known concept in web dev. Bootstrap has an already created library for this problem. It use media queries to do it. It is worth understanding media queries deeply, but for a quick fix, research bootstrap.

Body:
I'm having a small issue with a couple divs. I have it set up with 5 divs all different colors, when the window size is shrunk the divs drop down under each other one by one. Is there a way I can make the space between them shrinks with it so they but up closer?

Thanks again guys

p {
  margin: 0;
}

.pageColourOn {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 155px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.pageColourOff {
  display: none;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

.bg01Off {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg02Off {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg03Off {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg04Off {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg05Off {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.center {
  text-align: center;
}

Colour

Body:
Use media queries to make elements respond as the width of the viewport changes for example:

body {
background-color: lightgreen;
     }

@media only screen and (max-width: 500px) {
body {
    background-color: lightblue;
    }
}

This would make the background color change when the width of the viewport goes below 500 px. You can use this same concept with the width of your divs.

** Also, check out Bootstrap. Bootstrap makes it easy to define widths of elements using a grid system. You are trying to make your site "RESPONSIVE" which is a well-known concept in web dev. Bootstrap has an already created library for this problem. It use media queries to do it. It is worth understanding media queries deeply, but for a quick fix, research bootstrap.


问:
How to use abstract methods in inherited classes?
I'm currently working on a school project that's due to friday & I've got a whole lot to do.
The assignment is to make a video game with XNA framework using Monogame. I'm currently working with collisions.

The structure for gameobjects looks somewhat like this:

For collisions, I have a simple collision class

```<code>     class Collision{

public GameObject Other;

public GameObject Obj1;

public Collision(GameObject obj1, GameObject other)
{
    Other = other;
    Obj1 = obj1;
}}
</code>```

The collisions are handled in a static method in the GameObject class:

```<code>public static void UpdateCollisions()
{
    //Empty the list
    AllCollisions.Clear();

    for (int a = 0; a < AllGameObjectsWithCollision.Count; a++)
    {
        GameObject obja = AllGameObjectsWithCollision[a];
        for (int b = 0; b < AllGameObjectsWithCollision.Count; b++)
        {
            GameObject objb = AllGameObjectsWithCollision[b];

            if (obja.Mask != null & objb.Mask!= null && obja != objb)
            {
                if (obja.Mask.CollisionRectangle.Intersects(objb.Mask.CollisionRectangle))
                    AllCollisions.Add(new Collision(obja, objb));
            }
        }
    }

}
</code>```

This far it's working, the game is finding all collisions like it should. However now I need to let my objects know that they're colliding, and tell them what to do.
For this, I made the entity class abstract to be able to declare an abstract method called "OnCollision(Collision collision)"

abstract class Entity : GameObject
{
    public float Health;
    public float MaxHealth;
    public bool Alive;
    public float OriginalDmg;
    public float Dmg;

    public abstract void OnCollision(Collision collision);
}```
</div>
</div>
</p>

<p>Then I'm overriding the method in the classes that inherit the Entity class</p>

<p>Ex. Projectile</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>class Projectile : Entity
{
    Entity Owner;
    ProjectileType pType;

    public Projectile(Texture2D image, float maxSpeed, Entity owner, float dmg, ProjectileType type)
    {
        Image = image;
        MaxSpeed = maxSpeed;
        AccelerationSpeed = MaxSpeed;
        Owner = owner;
        Dmg = dmg;
        pType = type;
    }

    public override void OnCollision(Collision collision)
    {
        #region If this projectile friendly
        if (pType == ProjectileType.Friendly)
        {
            //If colliding with an enemy
            if (collision.Other.GetType() == typeof(Enemy))
            {
                var enemy = (Enemy)collision.Other;
                enemy.Health -= Dmg;
                Destroy(this);
            }
        }
        #endregion

        #region If this projectile is hostile
        if (pType == ProjectileType.Hostile)
        {

        }
        #endregion
    }
}</code>```

Then I'm trying to call the OnCollision method from my Update in the GameObject class.
This is how I try to inform my objects if they are collding and who they're colliding with:

        if (GetType().IsAssignableFrom(typeof(Entity)))
        {
            Entity entity = (Entity)this;

            if (GetType() == typeof(Player))
                entity = (Player)this;
            if (GetType() == typeof(Enemy))
                entity = (Enemy)this;
            if (GetType() == typeof(Projectile))
                entity = (Projectile)this;

            var entityCol = FindCollision(entity);

            if (entityCol != null)
                entity.OnCollision(entityCol);
        }```

I'm new to abstract classes & overriding, so I might have gotten the whole idea wrong.
But it seems the OnCollision method isn't reached as I've tried to Debug.WriteLine stuff but nothing shows up in the output window.

Thanks for reading & perhaps trying to help me out :)

Mediafire link to download the project in case you want to see all the code.

答:
You should read up on interfaces. An interface provides a contract (a bunch of methods and properties) that deriving classes must implement. Abstract classes are more concrete than interfaces in that they can also provide a base implementation for deriving classes. You can only derive from one abstract class whereas you can derive from multiple interfaces. From the code in your post it looks like you are using an abstract class like an interface.

You are using reflection to do type checking. There's the is keyword for testing type compatibility. For example:

```<code>if(entity is Player)
{
    var player = (Player)entity;

    // player specific code
}
</code>```

Finally; from what I can gather from your post it looks like you aren't quite using inheritance correctly. It looks like you are correctly using inheritance to build a type hierarchy but then putting all the logic in a base class.

Inheritance is meant to let you put the specialized logic in the appropriate class.

```<code>public interface IGameObject
{
    void OnCollision(IGameObject target);
}

public class Player : IGameObject
{
    public void OnCollision(IGameObject target)
    {
         Console.WriteLine("Player collision");
    }
}

public class Projectile : IGameObject
{
    public void OnCollision(IGameObject target)
    {
         Console.WriteLine("Projectile collision");
    }
}
</code>```

When we then have a reference to a IGameObject and call OnCollision the appropriate OnCollision function will automatically be called. For example:

```<code>IGameObject player = new Player();
IGameObject projectile = new Projectile();

player.OnCollision(projectile);
projectile.OnCollision(player);
</code>```

Output:

```<code>Player collision
Projectile collision
</code>```

Body:
I'm currently working on a school project that's due to friday & I've got a whole lot to do.
The assignment is to make a video game with XNA framework using Monogame. I'm currently working with collisions.

The structure for gameobjects looks somewhat like this:

For collisions, I have a simple collision class

     class Collision{

public GameObject Other;

public GameObject Obj1;

public Collision(GameObject obj1, GameObject other)
{
    Other = other;
    Obj1 = obj1;
}}

The collisions are handled in a static method in the GameObject class:

public static void UpdateCollisions()
{
    //Empty the list
    AllCollisions.Clear();

    for (int a = 0; a < AllGameObjectsWithCollision.Count; a++)
    {
        GameObject obja = AllGameObjectsWithCollision[a];
        for (int b = 0; b < AllGameObjectsWithCollision.Count; b++)
        {
            GameObject objb = AllGameObjectsWithCollision[b];

            if (obja.Mask != null & objb.Mask!= null && obja != objb)
            {
                if (obja.Mask.CollisionRectangle.Intersects(objb.Mask.CollisionRectangle))
                    AllCollisions.Add(new Collision(obja, objb));
            }
        }
    }

}

This far it's working, the game is finding all collisions like it should. However now I need to let my objects know that they're colliding, and tell them what to do.
For this, I made the entity class abstract to be able to declare an abstract method called "OnCollision(Collision collision)"

abstract class Entity : GameObject
{
    public float Health;
    public float MaxHealth;
    public bool Alive;
    public float OriginalDmg;
    public float Dmg;

    public abstract void OnCollision(Collision collision);
}

Then I'm overriding the method in the classes that inherit the Entity class

Ex. Projectile

class Projectile : Entity
{
    Entity Owner;
    ProjectileType pType;

    public Projectile(Texture2D image, float maxSpeed, Entity owner, float dmg, ProjectileType type)
    {
        Image = image;
        MaxSpeed = maxSpeed;
        AccelerationSpeed = MaxSpeed;
        Owner = owner;
        Dmg = dmg;
        pType = type;
    }

    public override void OnCollision(Collision collision)
    {
        #region If this projectile friendly
        if (pType == ProjectileType.Friendly)
        {
            //If colliding with an enemy
            if (collision.Other.GetType() == typeof(Enemy))
            {
                var enemy = (Enemy)collision.Other;
                enemy.Health -= Dmg;
                Destroy(this);
            }
        }
        #endregion

        #region If this projectile is hostile
        if (pType == ProjectileType.Hostile)
        {

        }
        #endregion
    }
}

Then I'm trying to call the OnCollision method from my Update in the GameObject class.
This is how I try to inform my objects if they are collding and who they're colliding with:

        if (GetType().IsAssignableFrom(typeof(Entity)))
        {
            Entity entity = (Entity)this;

            if (GetType() == typeof(Player))
                entity = (Player)this;
            if (GetType() == typeof(Enemy))
                entity = (Enemy)this;
            if (GetType() == typeof(Projectile))
                entity = (Projectile)this;

            var entityCol = FindCollision(entity);

            if (entityCol != null)
                entity.OnCollision(entityCol);
        }

I'm new to abstract classes & overriding, so I might have gotten the whole idea wrong.
But it seems the OnCollision method isn't reached as I've tried to Debug.WriteLine stuff but nothing shows up in the output window.

Thanks for reading & perhaps trying to help me out :)

Mediafire link to download the project in case you want to see all the code.

Body:
You should read up on interfaces. An interface provides a contract (a bunch of methods and properties) that deriving classes must implement. Abstract classes are more concrete than interfaces in that they can also provide a base implementation for deriving classes. You can only derive from one abstract class whereas you can derive from multiple interfaces. From the code in your post it looks like you are using an abstract class like an interface.

You are using reflection to do type checking. There's the is keyword for testing type compatibility. For example:

if(entity is Player)
{
    var player = (Player)entity;

    // player specific code
}

Finally; from what I can gather from your post it looks like you aren't quite using inheritance correctly. It looks like you are correctly using inheritance to build a type hierarchy but then putting all the logic in a base class.

Inheritance is meant to let you put the specialized logic in the appropriate class.

public interface IGameObject
{
    void OnCollision(IGameObject target);
}

public class Player : IGameObject
{
    public void OnCollision(IGameObject target)
    {
         Console.WriteLine("Player collision");
    }
}

public class Projectile : IGameObject
{
    public void OnCollision(IGameObject target)
    {
         Console.WriteLine("Projectile collision");
    }
}

When we then have a reference to a IGameObject and call OnCollision the appropriate OnCollision function will automatically be called. For example:

IGameObject player = new Player();
IGameObject projectile = new Projectile();

player.OnCollision(projectile);
projectile.OnCollision(player);

Output:

Player collision
Projectile collision


问:
Why the Overflow prperty doesnt work like I expect it to?
I've learned that when I use the property overflow:auto; when needed, it appends a scrollbar to the right side of the box (and if it is necessary, to the bottom too). You can see an example for that here:
https://www.w3schools.com/css/tryit.asp?filename=trycss_overflow_auto

But, in that case, the property is just getting the block to be higher:

    <!DOCTYPE html>

Add a clearfix class with overflow: auto; to the containing element, to fix this problem:

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum...

    ```

Why doesn't it add a scrollbar in the second example, as it does at the first?

答: You have to specify a width or height to use the overflow property

Body:
I've learned that when I use the property overflow:auto; when needed, it appends a scrollbar to the right side of the box (and if it is necessary, to the bottom too). You can see an example for that here:
https://www.w3schools.com/css/tryit.asp?filename=trycss_overflow_auto

But, in that case, the property is just getting the block to be higher:

    <!DOCTYPE html>

Add a clearfix class with overflow: auto; to the containing element, to fix this problem:

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum...

Why doesn't it add a scrollbar in the second example, as it does at the first?


问:
RX.Net : Use Retry but log any Exception
I am new to RX and have been investigating error handling and the use of Retry; I have the following (yes I know it's not a 'real' unit test but it gives me place to fiddle!!) and was wondering how I go about keeping the Retry but be able to log any Exception?

```<code>    [Test]
    public void Test()
    {
        var scheduler = new TestScheduler();

        var source = scheduler.CreateHotObservable(
            new Recorded<Notification<long>>(10000000, Notification.CreateOnNext(0L)),
            new Recorded<Notification<long>>(20000000, Notification.CreateOnNext(1L)),
            new Recorded<Notification<long>>(30000000, Notification.CreateOnNext(2L)),
            new Recorded<Notification<long>>(30000001, Notification.CreateOnError<long>(new Exception("Fail"))),
            new Recorded<Notification<long>>(40000000, Notification.CreateOnNext(3L)),
            new Recorded<Notification<long>>(40000000, Notification.CreateOnCompleted<long>())
        );

        source.Retry().Subscribe(
            l => Console.WriteLine($"OnNext {l}"),
            exception => Console.WriteLine(exception.ToString()), // Would be logging this in production
            () => Console.WriteLine("OnCompleted"));

       scheduler.Start(
            () => source,
            0,
            TimeSpan.FromSeconds(1).Ticks,
            TimeSpan.FromSeconds(5).Ticks);
    }
</code>```

Which results in...

```<code>OnNext 0
OnNext 1
OnNext 2
OnNext 3
OnCompleted
</code>```

...which is exactly what I want to happen apart from fact I would like to log the Exception which occurs between 2 and 3.

Is there a way to allow the Subscriber to see the Exception in OnError (and log it) and then re-subscribe so it sees 3?

答:
You could achieve that with this:

```<code>source
    .Do(_ => { }, exception => Console.WriteLine(exception.ToString()), () => {})
    .Retry()
    .Subscribe(
        l => Console.WriteLine($"OnNext {l}"),
        //      exception => Console.WriteLine(exception.ToString()), // Would be logging this in production
        () => Console.WriteLine("OnCompleted")
    );
</code>```

Just to clarify what's going on here: OnError is a terminating signal. If the error reached the subscription, that would terminate the rest of the stream. .Retry terminates the subscription, swallows the OnError, and then re-subscribes, melding the two subscriptions together. For example look at this:

```<code>source
    .StartWith(-1)
    .Retry()
    .Subscribe(
        l => Console.WriteLine($"OnNext {l}"),
        () => Console.WriteLine("OnCompleted")
    );
</code>```

Your output would be

```<code>OnNext -1
OnNext 0
OnNext 1
OnNext 2
OnNext -1
OnNext 3
OnCompleted
</code>```

The OnNext -1 shows up twice, because it shows up whenever you subscribe (which Retry does after the OnError.

Your test observable is frankly a bad test. It breaks the "Rx Contract" which is that notifications follow the following pattern:

```<code>OnNext* (OnCompleted | OnError)?
</code>```

That is, 0 or more OnNext notifications, followed by an optional OnError or an optional OnCompleted. No notifications of any type should follow either an OnError or an OnCompleted.

ContentLicense: CC BY-SA 4.0

Body:
I am new to RX and have been investigating error handling and the use of Retry; I have the following (yes I know it's not a 'real' unit test but it gives me place to fiddle!!) and was wondering how I go about keeping the Retry but be able to log any Exception?

    [Test]
    public void Test()
    {
        var scheduler = new TestScheduler();

        var source = scheduler.CreateHotObservable(
            new Recorded<Notification<long>>(10000000, Notification.CreateOnNext(0L)),
            new Recorded<Notification<long>>(20000000, Notification.CreateOnNext(1L)),
            new Recorded<Notification<long>>(30000000, Notification.CreateOnNext(2L)),
            new Recorded<Notification<long>>(30000001, Notification.CreateOnError<long>(new Exception("Fail"))),
            new Recorded<Notification<long>>(40000000, Notification.CreateOnNext(3L)),
            new Recorded<Notification<long>>(40000000, Notification.CreateOnCompleted<long>())
        );

        source.Retry().Subscribe(
            l => Console.WriteLine($"OnNext {l}"),
            exception => Console.WriteLine(exception.ToString()), // Would be logging this in production
            () => Console.WriteLine("OnCompleted"));

       scheduler.Start(
            () => source,
            0,
            TimeSpan.FromSeconds(1).Ticks,
            TimeSpan.FromSeconds(5).Ticks);
    }

Which results in...

OnNext 0
OnNext 1
OnNext 2
OnNext 3
OnCompleted

...which is exactly what I want to happen apart from fact I would like to log the Exception which occurs between 2 and 3.

Is there a way to allow the Subscriber to see the Exception in OnError (and log it) and then re-subscribe so it sees 3?

Body:
You could achieve that with this:

source
    .Do(_ => { }, exception => Console.WriteLine(exception.ToString()), () => {})
    .Retry()
    .Subscribe(
        l => Console.WriteLine($"OnNext {l}"),
        //      exception => Console.WriteLine(exception.ToString()), // Would be logging this in production
        () => Console.WriteLine("OnCompleted")
    );

Just to clarify what's going on here: OnError is a terminating signal. If the error reached the subscription, that would terminate the rest of the stream. .Retry terminates the subscription, swallows the OnError, and then re-subscribes, melding the two subscriptions together. For example look at this:

source
    .StartWith(-1)
    .Retry()
    .Subscribe(
        l => Console.WriteLine($"OnNext {l}"),
        () => Console.WriteLine("OnCompleted")
    );

Your output would be

OnNext -1
OnNext 0
OnNext 1
OnNext 2
OnNext -1
OnNext 3
OnCompleted

The OnNext -1 shows up twice, because it shows up whenever you subscribe (which Retry does after the OnError.

Your test observable is frankly a bad test. It breaks the "Rx Contract" which is that notifications follow the following pattern:

OnNext* (OnCompleted | OnError)?

That is, 0 or more OnNext notifications, followed by an optional OnError or an optional OnCompleted. No notifications of any type should follow either an OnError or an OnCompleted.