问:
JMeter Dynamic Request
I need to test a web service with header-item lines with reading values from csv.

```<code><urn:Requisition_BudgetReqExportHeaderDetails_Item>
        <!--Zero or more repetitions:-->
        <urn:item>
           <urn:CompanyCode>
              <urn:UniqueName>?</urn:UniqueName>
           </urn:CompanyCode>
           <urn:ERPRequisitionID>?</urn:ERPRequisitionID>
           <urn:HoldTillDate>?</urn:HoldTillDate>
           <urn:IsServiceRequisition>?</urn:IsServiceRequisition>
           <urn:Name>?</urn:Name>
        </urn:item>
</urn:Requisition_BudgetReqExportHeaderDetails_Item>
</code>```

I can read values from CSV file but this web service is complex and items might be 1 or more than 2.

How can I handle this web service request?

答:
You can use JSR223 PreProcessor like:

Add JSR223 PreProcessor as a child of your request

Put the code to generate the XML payload into "Script" area, an example one would look like:

```<code>def writer = new StringWriter()
def xml = new groovy.xml.MarkupBuilder(writer)

xml.records() {
    car(name:'HSV Maloo', make:'Holden', year:2006) {
        country('Australia')
        record(type:'speed', 'Production Pickup Truck with speed of 271kph')
    }
    car(name:'Royale', make:'Bugatti', year:1931) {
        country('France')
        record(type:'price', 'Most Valuable Car at $15 million')
    }
}

sampler.addNonEncodedArgument("", writer.toString(), "")
</code>```

Amend it to match your requirement

When you run your test the JSR223 PreProcessor will generate the request body and set it in the HTTP Request sampler

References:

sampler  - a shorthand to HTTPSamplerProxy class, see the JavaDoc for all available methods and fields

Groovy - Creating XML - learn how to create XML data using Groovy language

Groovy is the New Black - an introduction to Groovy scripting in JMeter

Title: JMeter Dynamic Request

Body:
I need to test a web service with header-item lines with reading values from csv.

<urn:Requisition_BudgetReqExportHeaderDetails_Item>

        <urn:item>
           <urn:CompanyCode>
              <urn:UniqueName>?</urn:UniqueName>
           </urn:CompanyCode>
           <urn:ERPRequisitionID>?</urn:ERPRequisitionID>
           <urn:HoldTillDate>?</urn:HoldTillDate>
           <urn:IsServiceRequisition>?</urn:IsServiceRequisition>
           <urn:Name>?</urn:Name>
        </urn:item>
</urn:Requisition_BudgetReqExportHeaderDetails_Item>

I can read values from CSV file but this web service is complex and items might be 1 or more than 2.

How can I handle this web service request?

Body:
You can use JSR223 PreProcessor like:

Add JSR223 PreProcessor as a child of your request

Put the code to generate the XML payload into "Script" area, an example one would look like:

def writer = new StringWriter()
def xml = new groovy.xml.MarkupBuilder(writer)

xml.records() {
    car(name:'HSV Maloo', make:'Holden', year:2006) {
        country('Australia')
        record(type:'speed', 'Production Pickup Truck with speed of 271kph')
    }
    car(name:'Royale', make:'Bugatti', year:1931) {
        country('France')
        record(type:'price', 'Most Valuable Car at $15 million')
    }
}

sampler.addNonEncodedArgument("", writer.toString(), "")

Amend it to match your requirement

When you run your test the JSR223 PreProcessor will generate the request body and set it in the HTTP Request sampler

References:

sampler  - a shorthand to HTTPSamplerProxy class, see the JavaDoc for all available methods and fields

Groovy - Creating XML - learn how to create XML data using Groovy language

Groovy is the New Black - an introduction to Groovy scripting in JMeter


来源: stackexchange

问:
How to make an obstacle hit a wall not go through the wall/obstacle
I need some help figuring out how i can make the ambulance go around the obstacle rather than going through it. This is what i have so far...
My plan is to make a racing game, the red box represents my car and I'm trying to figure out how to make it so it doesn't collide with the rectangles so they can't just cheat and cross over to the finish line, they have to go through the track. This is what i want to do

https://i.stack.imgur.com/apgBf.png

So far i just have the car and one of the rectangles but can't get it to not cross over the rectangle.

I'm trying to make it so the ambulance can't just go past that obstacle but has to go around it, i want to make a track, a racing game but stuck

```<code>using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace FinalProject
{
    /// <summary>
    /// This is the main type for your game.
    /// </summary>
    public class Game1 : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        int count;
        int speed = 5;
        Texture2D background, carUp, carDown, carRight, carLeft, obstacle;
        Rectangle backgroundRec, carRec, carRecDown, carRecUp, carRecLeft, carRecRight, carRec1, obstacleRec;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();
            carRec = new Rectangle(500, 300, 100, 100);
            carRecDown = new Rectangle(500, (300 + speed), 100, 100);
            carRecLeft = new Rectangle((500 - speed), 300, 100, 100);
            carRecUp = new Rectangle(500, (300 - speed), 100, 100);
            carRecRight = new Rectangle((500 + speed), 300, 100, 100);
            backgroundRec = new Rectangle(0, 0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);
            obstacleRec = new Rectangle(100, 240, 100, 300);
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);

            carUp = Content.Load<Texture2D>("up");
            carDown = Content.Load<Texture2D>("down");
            carRight = Content.Load<Texture2D>("right");
            carLeft = Content.Load<Texture2D>("left");
            background = Content.Load<Texture2D>("background");
            obstacle = Content.Load<Texture2D>("obstacle");
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// game-specific content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();
            KeyboardState keys = Keyboard.GetState();
            GamePadState pad1 = GamePad.GetState(PlayerIndex.One);
            carRecDown.Y = carRec.Y - speed;
            carRecLeft.X = carRec.X - speed;
            carRecRight.X = carRec.X + speed;
            carRecUp.Y = carRec.X + speed;
            // Keyboard

            if (keys.IsKeyDown(Keys.Up) && !(obstacleRec.Intersects(carRecUp)))
            {
                count = 1;
                carRec.Y -= speed;
            }
            if (keys.IsKeyDown(Keys.Down) && !(obstacleRec.Intersects(carRecDown)))
            {
                count = 2;
                carRec.Y += speed;
            }
            if (keys.IsKeyDown(Keys.Right) && !(obstacleRec.Intersects(carRecRight)))
            {
                count = 3;
                carRec.X += speed;
            }
            if (keys.IsKeyDown(Keys.Left) && !(obstacleRec.Intersects(carRecLeft)))
            {
                count = 4;
                carRec.X -= speed;
            }

            /* if (obstacleRec.Intersects(carRec))
             {
                 carRec.X +=1 ;
             }*/

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin();
            spriteBatch.Draw(background, backgroundRec, Color.White);
            spriteBatch.Draw(obstacle, obstacleRec, Color.White);
            if (count == 0)
                spriteBatch.Draw(carUp, carRec, Color.White);
            if (count == 1)
                spriteBatch.Draw(carUp, carRec, Color.White);
            if (count == 2)
                spriteBatch.Draw(carDown, carRec, Color.White);
            if (count == 3)
                spriteBatch.Draw(carRight, carRec, Color.White);
            if (count == 4)
                spriteBatch.Draw(carLeft, carRec, Color.White);
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}
</code>```

答:
If you want to do path finding, You should create a graph representing your race track use BFS or Djikstra algorithm.

For the collisions, read about basic collision detection methods. If you want to do a very basic collision detection, just calculate the next location of the car twice, once for the movement on each axis, Then check if these created locations collide with the map. If so, just block the car from moving in this axis.

Here is a short pseudo code:

```<code>Vector2 movement = ...

Rectangle nextPosX = ....
Rectangle nextPosY = ....
if (IntersectingWithMap(nextPosX))
   movement.x = 0
if (IntersectingWithMap(nextPosY))
   movement.y = 0

currPos += movement;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need some help figuring out how i can make the ambulance go around the obstacle rather than going through it. This is what i have so far...
My plan is to make a racing game, the red box represents my car and I'm trying to figure out how to make it so it doesn't collide with the rectangles so they can't just cheat and cross over to the finish line, they have to go through the track. This is what i want to do

https://i.stack.imgur.com/apgBf.png

So far i just have the car and one of the rectangles but can't get it to not cross over the rectangle.

I'm trying to make it so the ambulance can't just go past that obstacle but has to go around it, i want to make a track, a racing game but stuck

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace FinalProject
{
    ///
    /// This is the main type for your game.
    ///
    public class Game1 : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        int count;
        int speed = 5;
        Texture2D background, carUp, carDown, carRight, carLeft, obstacle;
        Rectangle backgroundRec, carRec, carRecDown, carRecUp, carRecLeft, carRecRight, carRec1, obstacleRec;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        ///
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        ///
        protected override void Initialize()
        {
            base.Initialize();
            carRec = new Rectangle(500, 300, 100, 100);
            carRecDown = new Rectangle(500, (300 + speed), 100, 100);
            carRecLeft = new Rectangle((500 - speed), 300, 100, 100);
            carRecUp = new Rectangle(500, (300 - speed), 100, 100);
            carRecRight = new Rectangle((500 + speed), 300, 100, 100);
            backgroundRec = new Rectangle(0, 0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);
            obstacleRec = new Rectangle(100, 240, 100, 300);
        }

        ///
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        ///
        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);

            carUp = Content.Load<Texture2D>("up");
            carDown = Content.Load<Texture2D>("down");
            carRight = Content.Load<Texture2D>("right");
            carLeft = Content.Load<Texture2D>("left");
            background = Content.Load<Texture2D>("background");
            obstacle = Content.Load<Texture2D>("obstacle");
        }

        ///
        /// UnloadContent will be called once per game and is the place to unload
        /// game-specific content.
        ///
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        ///
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        ///
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();
            KeyboardState keys = Keyboard.GetState();
            GamePadState pad1 = GamePad.GetState(PlayerIndex.One);
            carRecDown.Y = carRec.Y - speed;
            carRecLeft.X = carRec.X - speed;
            carRecRight.X = carRec.X + speed;
            carRecUp.Y = carRec.X + speed;
            // Keyboard

            if (keys.IsKeyDown(Keys.Up) && !(obstacleRec.Intersects(carRecUp)))
            {
                count = 1;
                carRec.Y -= speed;
            }
            if (keys.IsKeyDown(Keys.Down) && !(obstacleRec.Intersects(carRecDown)))
            {
                count = 2;
                carRec.Y += speed;
            }
            if (keys.IsKeyDown(Keys.Right) && !(obstacleRec.Intersects(carRecRight)))
            {
                count = 3;
                carRec.X += speed;
            }
            if (keys.IsKeyDown(Keys.Left) && !(obstacleRec.Intersects(carRecLeft)))
            {
                count = 4;
                carRec.X -= speed;
            }

            /* if (obstacleRec.Intersects(carRec))
             {
                 carRec.X +=1 ;
             }*/

            base.Update(gameTime);
        }

        ///
        /// This is called when the game should draw itself.
        ///
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin();
            spriteBatch.Draw(background, backgroundRec, Color.White);
            spriteBatch.Draw(obstacle, obstacleRec, Color.White);
            if (count == 0)
                spriteBatch.Draw(carUp, carRec, Color.White);
            if (count == 1)
                spriteBatch.Draw(carUp, carRec, Color.White);
            if (count == 2)
                spriteBatch.Draw(carDown, carRec, Color.White);
            if (count == 3)
                spriteBatch.Draw(carRight, carRec, Color.White);
            if (count == 4)
                spriteBatch.Draw(carLeft, carRec, Color.White);
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}

Body:
If you want to do path finding, You should create a graph representing your race track use BFS or Djikstra algorithm.

For the collisions, read about basic collision detection methods. If you want to do a very basic collision detection, just calculate the next location of the car twice, once for the movement on each axis, Then check if these created locations collide with the map. If so, just block the car from moving in this axis.

Here is a short pseudo code:

Vector2 movement = ...

Rectangle nextPosX = ....
Rectangle nextPosY = ....
if (IntersectingWithMap(nextPosX))
   movement.x = 0
if (IntersectingWithMap(nextPosY))
   movement.y = 0

currPos += movement;


问:
Only allow donations from PayPal balance?
In PHP how would I allow only donations from PayPal balance and not from a credit card? Is there any example code you can provide or code out there which could help?</p>

答: You cant.  That'd be controlled on the paypal side, and Im pretty sure there is not an option for that.</p>

ContentLicense: CC BY-SA 2.5


问:
Jess considers only the last mapped instance
I have a question in Jess Tab in Protege,I am building an ontology of 1 class Message and 3 instances :message 1 message2 message 3 , each each 3 datatype properties : category , interests , class .For each message I want to classify it as ham if the category and interests are equal , spam otherwise.The classification should be done using Jess Rules by which the class slot / property should change to ham or spam so I use modify-instance for that , as the interests of a message instance could change by time so it's not a static classification (or I would need to reclassify it)
Here is an example for message1 in protege :

So I mapped the instances as shown to Jess Engine using Jess Tab :

Here are screenshots with my rules the  :

 When I type (run) the Jess engine will classify only 1 instance correctly which is message3 the last instance , I mean I thus have to send only 1 instance at a time to the engine else it won't classify all messages correctly.

I tried to otherwise print the classification value and it works correctly( in my example the 3 messages should be classified as ham )

and when I added both rules the result was that the "ham/spam" printing enters a for loop . I've asked a question before and I got an answer that infinite loop happens because the rule keeps firing as the "if " in the action (RHS) is always correct :

Is this a feature of Jess that it considers the last received instance. And is there a way to force Jess engine to consider more than 1 message at a time ? and why is the infinite loop happening ?

I am really stuck in this part and in desperate need for speed to finalize it for my thesis . So you help is appreciated .
(I have implemented these rules in swrl busing SWRL+Jess Tab in Protege and the rules worked fine the problem was the facts were asserted in the ontology and I want them to be modified not asserted so that's why I used Jess Rules , do you think I am on the write track or I should use Sweet Rules for example better ?)

I updated the rule as follows by making constraint on the fact's slot value but no change :

(defrule MAIN::test2
   (object (is-a http://www.owl-ontologies.com/Ontology1496039955.owl#Message) (OBJECT ?o))
   (object (OBJECT ?o) (http://www.owl-ontologies.com/Ontology1496039955.owl#interests $?i))
   (object (OBJECT ?o) (http://www.owl-ontologies.com/Ontology1496039955.owl#category $?c&:(eq (intersection$ $?i $?c) )))
   (object (OBJECT ?o) (http://www.owl-ontologies.com/Ontology1496039955.owl#class $?cl&:(neq $?cl "spam")))
   =>
   (modify-instance ?o (http://www.owl-ontologies.com/Ontology1496039955.owl#class spam)))

答:
This may not really be an answer, but you should consider changing your code accordingly, and if your problem continues, edit your question.

Don't use (if) on the right hand side. If there are two different situations due to values in the facts, distinguish them by rules.

Don't use (if) with just a single operand. This will always return true.

To avoid looping, either use the rule attribute no-loop or add a condition that is true unless something has been changed by the right hand side.

I would test rules in plain Jess first, before wrestling with the Protege layer.


问:
ImportError: No module named 'email.mime'; email is not a package
When running the below code, I keep getting the error:

```<code>ImportError: No module named 'email.mime'; email is not a package
</code>```

So I run:

```<code>pip install email
</code>```

And get the following error:

```<code>ImportError: No module named 'cStringIO'...
Command "python setup.py egg_info" failed with error code 1
</code>```

The internet has told me to run:

```<code>pip install --upgrade pip
</code>```

To solve this problem, which I've done many times now. I don't know what else I can do.

Python version: Python 3.3.5 | Anaconda 2.3.0 (x86_64)

```<code>import smtplib,email,email.encoders,email.mime.text,email.mime.base

smtpserver = 'email@site.com'
to = ['address@gmail.com']
fromAddr = 'email@site.com'
subject = "testing email attachments"

# create html email
html = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" '
html +='"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">'
html +='<body style="font-size:12px;font-family:Verdana"><p>...</p>'
html += "</body></html>"
emailMsg = email.MIMEMultipart.MIMEMultipart('text/csv')
emailMsg['Subject'] = subject
emailMsg['From'] = fromAddr
emailMsg['To'] = ', '.join(to)
emailMsg['Cc'] = ", ".join(cc)
emailMsg.attach(email.mime.text.MIMEText(html,'html'))

# now attach the file
fileMsg = email.mime.base.MIMEBase('text/csv')
fileMsg.set_payload(file('rsvps.csv').read())
email.encoders.encode_base64(fileMsg)
fileMsg.add_header('Content-Disposition','attachment;filename=rsvps.csv')
emailMsg.attach(fileMsg)

# send email
server = smtplib.SMTP(smtpserver)
server.sendmail(fromAddr,to,emailMsg.as_string())
server.quit()
</code>```

答: I encountered the same problem just now. Finally, I found it's because I name the python file as 'email.py'. It works after changing its name.</p>

Body:
When running the below code, I keep getting the error:

ImportError: No module named 'email.mime'; email is not a package

So I run:

pip install email

And get the following error:

ImportError: No module named 'cStringIO'...
Command "python setup.py egg_info" failed with error code 1

The internet has told me to run:

pip install --upgrade pip

To solve this problem, which I've done many times now. I don't know what else I can do.

Python version: Python 3.3.5 | Anaconda 2.3.0 (x86_64)

import smtplib,email,email.encoders,email.mime.text,email.mime.base

smtpserver = 'email@site.com'
to = ['address@gmail.com']
fromAddr = 'email@site.com'
subject = "testing email attachments"

# create html email
html = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" '
html +='"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
html +='
...
'
html += ""
emailMsg = email.MIMEMultipart.MIMEMultipart('text/csv')
emailMsg['Subject'] = subject
emailMsg['From'] = fromAddr
emailMsg['To'] = ', '.join(to)
emailMsg['Cc'] = ", ".join(cc)
emailMsg.attach(email.mime.text.MIMEText(html,'html'))

# now attach the file
fileMsg = email.mime.base.MIMEBase('text/csv')
fileMsg.set_payload(file('rsvps.csv').read())
email.encoders.encode_base64(fileMsg)
fileMsg.add_header('Content-Disposition','attachment;filename=rsvps.csv')
emailMsg.attach(fileMsg)

# send email
server = smtplib.SMTP(smtpserver)
server.sendmail(fromAddr,to,emailMsg.as_string())
server.quit()


问:
Bundle not working with rbenv
I'm trying to use bundler with rbenv. I has been working until today. The only thing I may have done to break it was gem pristine --all or gem cleanup ? When trying to install bundler i get the following error.

```<code>Antarrs-MacBook-Pro:some-app antarrbyrd$ sudo gem install bundler
Password:
Bundler gave the error "Could not find mail-2.5.4 in any of the sources" while processing "/Users/antarrbyrd/dev/some-app/Gemfile". Perhaps you forgot to run "bundle install"?
Successfully installed bundler-1.7.12
Parsing documentation for bundler-1.7.12
Done installing documentation for bundler after 3 seconds
1 gem installed
Antarrs-MacBook-Pro:some-app antarrbyrd$ bundle install
/Users/antarrbyrd/.rbenv/versions/2.1.2/lib/ruby/site_ruby/2.1.0/rubygems/dependency.rb:315:in `to_specs': Could not find 'bundler' (>= 0) among 8 total gem(s) (Gem::LoadError)
Checked in 'GEM_PATH=/Users/antarrbyrd/.gem', execute `gem env` for more information
    from /Users/antarrbyrd/.rbenv/versions/2.1.2/lib/ruby/site_ruby/2.1.0/rubygems/dependency.rb:324:in `to_spec'
    from /Users/antarrbyrd/.rbenv/versions/2.1.2/lib/ruby/site_ruby/2.1.0/rubygems/core_ext/kernel_gem.rb:64:in `gem'
    from /usr/local/bin/bundle:22:in `<main>'
</code>```

when i do rbenv rehash or rbenv bundler on it get this error

```<code>Bundler gave the error "Could not find mail-2.5.4 in any of the sources" while processing "/Users/antarrbyrd/dev/some-app/Gemfile". Perhaps you forgot to run "bundle install"?
</code>```

~/.bash_profile

```<code>export BUNDLER_EDITOR=atom
export PATH=$PATH:/usr/local/opt/android-sdk/build-tools/21.1.2
export HOMEBREW_GITHUB_API_TOKEN=...

export ANDROID_HOME=/usr/local/opt/android-sdk
export PATH="$HOME/.rbenv/bin:$PATH"
if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi

# Allow local Gem Managment
# export GEM_HOME="$HOME/.gem"
# export GEM_PATH="$HOME/.gem"
# export PATH="$HOME/.gem/bin:$PATH"
</code>```

gem env

```<code>RubyGems Environment:
  - RUBYGEMS VERSION: 2.2.2
  - RUBY VERSION: 2.1.2 (2014-05-08 patchlevel 95) [x86_64-darwin14.0]
  - INSTALLATION DIRECTORY: /usr/local/var/rbenv/versions/2.1.2/lib/ruby/gems/2.1.0
  - RUBY EXECUTABLE: /usr/local/var/rbenv/versions/2.1.2/bin/ruby
  - EXECUTABLE DIRECTORY: /usr/local/var/rbenv/versions/2.1.2/bin
  - SPEC CACHE DIRECTORY: /Users/antarrbyrd/.gem/specs
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86_64-darwin-14
  - GEM PATHS:
     - /usr/local/var/rbenv/versions/2.1.2/lib/ruby/gems/2.1.0
     - /Users/antarrbyrd/.gem/ruby/2.1.0
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => false
     - :backtrace => false
     - :bulk_threshold => 1000
     - "gem" => "-n/usr/local/bin"
  - REMOTE SOURCES:
     - https://rubygems.org/
  - SHELL PATH:
     - /usr/local/var/rbenv/versions/2.1.2/bin
     - /usr/local/Cellar/rbenv/0.4.0/libexec
     - /Users/antarrbyrd/.gem/bin
     - /usr/local/var/rbenv/shims
     - /usr/local/bin
     - /usr/bin
     - /bin
     - /usr/sbin
     - /sbin
     - /usr/local/var/rbenv/shims
     - /Users/antarrbyrd/.rbenv/bin
     - /Users/antarrbyrd/.rbenv/shims
     - /Users/antarrbyrd/.gem/bin
     - /usr/local/opt/android-sdk/build-tools/21.1.2
</code>```

update

I reinstalled rbenv via brew and now I get the following error when running bundle install.

```<code>The `bundle' command exists in these Ruby versions:
  2.1.5
</code>```

response to Joel

```<code>Antarrs-MacBook-Pro:myapp antarrbyrd$ command -v ruby
/usr/local/var/rbenv/shims/ruby
Antarrs-MacBook-Pro:myapp antarrbyrd$ command -v bundle
/usr/local/bin/bundle
Antarrs-MacBook-Pro:myapp antarrbyrd$ ruby -v
ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-darwin14.0]
Antarrs-MacBook-Pro:myapp antarrbyrd$ bundle -v
Bundler version 1.7.12
Antarrs-MacBook-Pro:myapp antarrbyrd$
</code>```

答:
Try to use:

bin/bundle

instead of

bundle

Title: Bundle not working with rbenv

Body:
I'm trying to use bundler with rbenv. I has been working until today. The only thing I may have done to break it was gem pristine --all or gem cleanup ? When trying to install bundler i get the following error.

Antarrs-MacBook-Pro:some-app antarrbyrd$ sudo gem install bundler
Password:
Bundler gave the error "Could not find mail-2.5.4 in any of the sources" while processing "/Users/antarrbyrd/dev/some-app/Gemfile". Perhaps you forgot to run "bundle install"?
Successfully installed bundler-1.7.12
Parsing documentation for bundler-1.7.12
Done installing documentation for bundler after 3 seconds
1 gem installed
Antarrs-MacBook-Pro:some-app antarrbyrd$ bundle install
/Users/antarrbyrd/.rbenv/versions/2.1.2/lib/ruby/site_ruby/2.1.0/rubygems/dependency.rb:315:in `to_specs': Could not find 'bundler' (>= 0) among 8 total gem(s) (Gem::LoadError)
Checked in 'GEM_PATH=/Users/antarrbyrd/.gem', execute `gem env` for more information
    from /Users/antarrbyrd/.rbenv/versions/2.1.2/lib/ruby/site_ruby/2.1.0/rubygems/dependency.rb:324:in `to_spec'
    from /Users/antarrbyrd/.rbenv/versions/2.1.2/lib/ruby/site_ruby/2.1.0/rubygems/core_ext/kernel_gem.rb:64:in `gem'
    from /usr/local/bin/bundle:22:in `'

when i do rbenv rehash or rbenv bundler on it get this error

Bundler gave the error "Could not find mail-2.5.4 in any of the sources" while processing "/Users/antarrbyrd/dev/some-app/Gemfile". Perhaps you forgot to run "bundle install"?

~/.bash_profile

export BUNDLER_EDITOR=atom
export PATH=$PATH:/usr/local/opt/android-sdk/build-tools/21.1.2
export HOMEBREW_GITHUB_API_TOKEN=...

export ANDROID_HOME=/usr/local/opt/android-sdk
export PATH="$HOME/.rbenv/bin:$PATH"
if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi

# Allow local Gem Managment
# export GEM_HOME="$HOME/.gem"
# export GEM_PATH="$HOME/.gem"
# export PATH="$HOME/.gem/bin:$PATH"

gem env

RubyGems Environment:
  - RUBYGEMS VERSION: 2.2.2
  - RUBY VERSION: 2.1.2 (2014-05-08 patchlevel 95) [x86_64-darwin14.0]
  - INSTALLATION DIRECTORY: /usr/local/var/rbenv/versions/2.1.2/lib/ruby/gems/2.1.0
  - RUBY EXECUTABLE: /usr/local/var/rbenv/versions/2.1.2/bin/ruby
  - EXECUTABLE DIRECTORY: /usr/local/var/rbenv/versions/2.1.2/bin
  - SPEC CACHE DIRECTORY: /Users/antarrbyrd/.gem/specs
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86_64-darwin-14
  - GEM PATHS:
     - /usr/local/var/rbenv/versions/2.1.2/lib/ruby/gems/2.1.0
     - /Users/antarrbyrd/.gem/ruby/2.1.0
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => false
     - :backtrace => false
     - :bulk_threshold => 1000
     - "gem" => "-n/usr/local/bin"
  - REMOTE SOURCES:
     - https://rubygems.org/
  - SHELL PATH:
     - /usr/local/var/rbenv/versions/2.1.2/bin
     - /usr/local/Cellar/rbenv/0.4.0/libexec
     - /Users/antarrbyrd/.gem/bin
     - /usr/local/var/rbenv/shims
     - /usr/local/bin
     - /usr/bin
     - /bin
     - /usr/sbin
     - /sbin
     - /usr/local/var/rbenv/shims
     - /Users/antarrbyrd/.rbenv/bin
     - /Users/antarrbyrd/.rbenv/shims
     - /Users/antarrbyrd/.gem/bin
     - /usr/local/opt/android-sdk/build-tools/21.1.2

update

I reinstalled rbenv via brew and now I get the following error when running bundle install.

The `bundle' command exists in these Ruby versions:
  2.1.5

response to Joel

Antarrs-MacBook-Pro:myapp antarrbyrd$ command -v ruby
/usr/local/var/rbenv/shims/ruby
Antarrs-MacBook-Pro:myapp antarrbyrd$ command -v bundle
/usr/local/bin/bundle
Antarrs-MacBook-Pro:myapp antarrbyrd$ ruby -v
ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-darwin14.0]
Antarrs-MacBook-Pro:myapp antarrbyrd$ bundle -v
Bundler version 1.7.12
Antarrs-MacBook-Pro:myapp antarrbyrd$


问:
making a table using div in HTML
I want to make a table like this by using DIV in html & CSSdesired result
but I am having a table like this gained result
I tried but could not get the desired result. where I need to change my code? can anyone help me regarding this?

.tableMain {
  display: table;
  width: 100%;
  background-color: black;
}

.tableRow {
  display: table-row;
  color: aqua;
}

.tableCell,
.tableHead {
  border: 1px solid aqua;
  display: table-cell;
  padding-left: 5px;
}

.tableHeading {
  display: table-header-group;
  font-weight: bold;
}

.tableBody {
  display: table-row-group;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="tableMain">
  <div class="tableBody">
    <div class="tableRow">
      <div class="tableCell">
        <h2>Header-1</h2>
      </div>
      <div class="tableCell">
        <h2>Header-2</h2>
      </div>
    </div>
    <div class="tableRow">
      <div class="tableCell">
        <h2>Section-1</h2>
      </div>
      <div class="tableCell">
        <h3>Title</h3>
        <h4>Description</h4>
        <ul>
          <li>item-1</li>
          <li>item-2</li>
          <li>item-3</li>
        </ul>
      </div>
    </div>
    <div class="tableRow">
      <div class="tableCell">
        <h2>Section-2</h2>
      </div>
    </div>
    <div class="tableRow">
      <div class="tableCell">
        <h2>header-1</h2>
      </div>
      <div class="tableCell">
        <h2>header-2</h2>
      </div>
      <div class="tableCell">
        <h2>header-3</h2>
      </div>
    </div>
    <div class="tableRow">
      <div class="tableCell">
        <p>A</p>
      </div>
      <div class="TableCell">
        <p>B</p>
      </div>
      <div class="tableCell">
        <p>C</p>
      </div>
    </div>
    <div class="tableRow">
      <div class="tableCell">
        <p>A</p>
      </div>
      <div class="tableCell">
        <p>B</p>
      </div>
      <div class="tableCell">
        <p>C</p>
      </div>
    </div>
    <div class="tableRow">
      <div class="tableCell">
        <p>A</p>
      </div>
      <div class="tableCell">
        <p>B</p>
      </div>
      <div class="tableCell">
        <p>C</p>
      </div>
    </div>
  </div>
</div></code>```

答:
you can try this

html

```<code><div class="table">
<div class="table-row">
<div class="table-cell">Header1</div>
  <div class="table-cell">Header2</div>
</div>
  <div class="table-row">
  <div class="table-cell">section1</div>
    <div class="table-cell">
      <div>title</div>
      <div>description</div>
      <ul>
      <li>item1</li>
      <li>item2</li>
      <li>item 3</li></ul>
    </div>
  </div>
  <div class="table-row">
  <div class="table-cell">Section2</div>
  <div class="table-cell">

    <div class="table">
    <div class="table-row">
    <div class="table-cell">

      Header 1
      <div>
        A
      </div>
      <div>
      B
      </div>
      <div>
      C
      </div>
    </div>
    <div class="table-cell">
    Header 2
       <div>
        A
      </div>
      <div>
      B
      </div>
      <div>
      C
      </div>
    </div>
    <div class="table-cell">
      header 3
       <div>
        A
      </div>
      <div>
      B
      </div>
      <div>
      C
      </div>
    </div>
    </div>
    </div>

  </div>
  </div>
</div>
</code>```

css

```<code>.table
{
  display:table;
  border:1px solid;
  width:100%;
  text-transform:capitalize;
}
.table-row
{
  display:table-row;
  border:1px solid;
}
.table-cell
{
  display:table-cell;
  vertical-align:middle;
  border:1px solid;
}
</code>```

here is link for reference codepen link here

Title: making a table using div in HTML

Body:
I want to make a table like this by using DIV in html & CSSdesired result
but I am having a table like this gained result
I tried but could not get the desired result. where I need to change my code? can anyone help me regarding this?

.tableMain {
  display: table;
  width: 100%;
  background-color: black;
}

.tableRow {
  display: table-row;
  color: aqua;
}

.tableCell,
.tableHead {
  border: 1px solid aqua;
  display: table-cell;
  padding-left: 5px;
}

.tableHeading {
  display: table-header-group;
  font-weight: bold;
}

.tableBody {
  display: table-row-group;
}

Header-1

Header-2

Section-1

Title

Description

item-1

item-2

item-3

Section-2

header-1

header-2

header-3

A

B

C

A

B

C

A

B

C

Body:
you can try this

html

<div class="table">
<div class="table-row">
<div class="table-cell">Header1</div>
  <div class="table-cell">Header2</div>
</div>
  <div class="table-row">
  <div class="table-cell">section1</div>
    <div class="table-cell">
      <div>title</div>
      <div>description</div>
      <ul>
      <li>item1</li>
      <li>item2</li>
      <li>item 3</li></ul>
    </div>
  </div>
  <div class="table-row">
  <div class="table-cell">Section2</div>
  <div class="table-cell">

    <div class="table">
    <div class="table-row">
    <div class="table-cell">

      Header 1
      <div>
        A
      </div>
      <div>
      B
      </div>
      <div>
      C
      </div>
    </div>
    <div class="table-cell">
    Header 2
       <div>
        A
      </div>
      <div>
      B
      </div>
      <div>
      C
      </div>
    </div>
    <div class="table-cell">
      header 3
       <div>
        A
      </div>
      <div>
      B
      </div>
      <div>
      C
      </div>
    </div>
    </div>
    </div>

  </div>
  </div>
</div>

css

.table
{
  display:table;
  border:1px solid;
  width:100%;
  text-transform:capitalize;
}
.table-row
{
  display:table-row;
  border:1px solid;
}
.table-cell
{
  display:table-cell;
  vertical-align:middle;
  border:1px solid;
}

here is link for reference codepen link here


问:
String copy using character pointers
Consider the following code, which works fine asusual for copying string

```<code>#include<stdio.h>

void strcp(char *s1, char *s2);

int main() {

    char s1[]="Hai, I am a good boy";                   //1
    char s2[]="Really I am a good boy";                 //2

    strcp(s1,s2);

    printf("%s",s1);
    return 0;
}

void strcp(char *s1, char *s2) {

    while(*s1++=*s2++);
}
</code>```

What changes I have to made if I want to declare s1, s2 as pointers to char inside main()?

```<code>char *s1="Hai, I am a good boy";                   //1
char *s2="Really I am a good boy";                 //2
</code>```

I tried to copy pointer values as shown below

```<code>void strcp(char *s1, char *s2) {

s1=s2;
}
</code>```

But it didn't work.

答:
First of all you can't modify literal strings, that are const.
Second, your function strcp() doesn't care if you pass a pointer to characters or an array of characters, it should work in both cases.When you type just s1 the array is converted in to a pointer to char which points to the first element of the array.

s1 -->(char*)&s1[0]

Since you can't modify literal strings what you can do is just switch the pointers:

```<code>void strcp(char **s1, char **s2) {
char *temp = *s1;
       *s1 = *s2;
       *s2 = temp;
}
</code>```

Title: String copy using character pointers

Body:
Consider the following code, which works fine asusual for copying string

#include<stdio.h>

void strcp(char *s1, char *s2);

int main() {

    char s1[]="Hai, I am a good boy";                   //1
    char s2[]="Really I am a good boy";                 //2

    strcp(s1,s2);

    printf("%s",s1);
    return 0;
}

void strcp(char *s1, char *s2) {

    while(*s1++=*s2++);
}

What changes I have to made if I want to declare s1, s2 as pointers to char inside main()?

char *s1="Hai, I am a good boy";                   //1
char *s2="Really I am a good boy";                 //2

I tried to copy pointer values as shown below

void strcp(char *s1, char *s2) {

s1=s2;
}

But it didn't work.

Body:
First of all you can't modify literal strings, that are const.
Second, your function strcp() doesn't care if you pass a pointer to characters or an array of characters, it should work in both cases.When you type just s1 the array is converted in to a pointer to char which points to the first element of the array.

s1 -->(char*)&s1[0]

Since you can't modify literal strings what you can do is just switch the pointers:

void strcp(char **s1, char **s2) {
char *temp = *s1;
       *s1 = *s2;
       *s2 = temp;
}


问:
Django: model testing setUp get test record insert id
I'm new on testing Django applications but I feel there should be some sort of internal framework method to retrieve last insert id.

How to get last insert id?

Sultan

答:
There is no specific way of getting the last insert id, but when inserting you get the entire object including the id.</p>

```<code>new_instance = models.SomeModel(foo='something', bar='something else')
new_instance.save()
print new_instance.pk

new_instance = models.SomeModel.objects.create(foo='something', bar='something else')
print new_instance.pk
</code>```

Body:
There is no specific way of getting the last insert id, but when inserting you get the entire object including the id.

new_instance = models.SomeModel(foo='something', bar='something else')
new_instance.save()
print new_instance.pk

new_instance = models.SomeModel.objects.create(foo='something', bar='something else')
print new_instance.pk


问:
How to loop indices of .formula/.formulaR1C1
I am stuck with a problem i cannot get my head around currently.

I have a checklist that has to update automatically when adding lines to my excel worksheet so that the checklist is applied to all rows.
I tried to use a "for loop" to modify the formula but excel returns Error 1004, when starting the string with "=".

No error but no functionality as well:

```<code> ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("AB9").FormulaLocal = "Wenn(Oder(AB" & firstRow & "=""x"""
</code>```

Returns error 1004:

```<code> ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("AB9").FormulaLocal = "=Wenn(Oder(AB" & firstRow & "=""x"""
</code>```

My first solution
Loop FormulaR1C1, or Formula and use nothing but english Function names eg. sum() instead of Summe() and follow english syntax , instead of ;.

Problem
When testing the syntax without a loop and actual indices it works like a charm. As soon as I try to loop it, Excel does not recognize R[i]C as cell anymore but just returns plain text.

no issues:

```<code>ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("AB9").Formula = "IF(OR( R[1]C = ""x"""
</code>```

issues:

```<code>ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("AB9").Formula = "IF(OR( R[i]C = ""x"""
</code>```

Splitting it like this did not solve my problem either
    ..R[" & i & "]C =..

Any tips?

// For i=  ... to .. next i
// Excel 2007

答:
@UGP: that is what i thought the code might look like after implementing your tips with intersect etc.
What do you think of it, I guess you might not like the loops too much?
Typical beginner approach to loop everything?

I would have to do this for every column accordingly?
If so it would be wise to create a sub () for every column with an exit condition so that i save computing time?

Unless it is possible to hand over the columnadress to the sub_worksheet_change()?

Private Sub Worksheet_Change(ByVal Target As Range, selected_column)

_
_

_
_

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
   Dim KeyCells As Range
   Dim i As Integer
   Dim check As Boolean

   frstRow = 1
   lastRow = 1
   i = 1

'Rowcount
    Do Until firstRow <> 1 And lastRow <> 1

          If ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("D" & i) = "Länge" Then
             firstRow = i + 2
             i = i + 1
          End If
          If ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("G" & i) = "Gesamt-h" Then
             lastRow = i - 2
         End If

    i = i + 1
    Loop

   ' check column AB fo "x" and modify header
   Set KeyCells = Range("AB" & firstRow, "AI" & lastRow)
   check = False
   i = firstRow
   If Not Application.Intersect(KeyCells, Range(Target.Address)) _
          Is Nothing Then
            Do While i <= lastRow And check = False
               If ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("AB" & i).Value = "x" Then
                  check = True
                  ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("AB9").Value = "x"
               ElseIf i = lastRow And check = False Then
                  ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("AB9").Value = " "
               End If
            i = i + 1
            Loop
    End If
End Sub
</code>```

Body:
I am stuck with a problem i cannot get my head around currently.

I have a checklist that has to update automatically when adding lines to my excel worksheet so that the checklist is applied to all rows.
I tried to use a "for loop" to modify the formula but excel returns Error 1004, when starting the string with "=".

No error but no functionality as well:

 ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("AB9").FormulaLocal = "Wenn(Oder(AB" & firstRow & "=""x"""

Returns error 1004:

 ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("AB9").FormulaLocal = "=Wenn(Oder(AB" & firstRow & "=""x"""

My first solution
Loop FormulaR1C1, or Formula and use nothing but english Function names eg. sum() instead of Summe() and follow english syntax , instead of ;.

Problem
When testing the syntax without a loop and actual indices it works like a charm. As soon as I try to loop it, Excel does not recognize R[i]C as cell anymore but just returns plain text.

no issues:

ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("AB9").Formula = "IF(OR( R[1]C = ""x"""

issues:

ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("AB9").Formula = "IF(OR( R[i]C = ""x"""

Splitting it like this did not solve my problem either
    ..R[" & i & "]C =..

Any tips?

// For i=  ... to .. next i
// Excel 2007

Body:
@UGP: that is what i thought the code might look like after implementing your tips with intersect etc.
What do you think of it, I guess you might not like the loops too much?
Typical beginner approach to loop everything?

I would have to do this for every column accordingly?
If so it would be wise to create a sub () for every column with an exit condition so that i save computing time?

Unless it is possible to hand over the columnadress to the sub_worksheet_change()?

Private Sub Worksheet_Change(ByVal Target As Range, selected_column)

_
_

_
_

Private Sub Worksheet_Change(ByVal Target As Range)
   Dim KeyCells As Range
   Dim i As Integer
   Dim check As Boolean

   frstRow = 1
   lastRow = 1
   i = 1

'Rowcount
    Do Until firstRow <> 1 And lastRow <> 1

          If ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("D" & i) = "Länge" Then
             firstRow = i + 2
             i = i + 1
          End If
          If ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("G" & i) = "Gesamt-h" Then
             lastRow = i - 2
         End If

    i = i + 1
    Loop

   ' check column AB fo "x" and modify header
   Set KeyCells = Range("AB" & firstRow, "AI" & lastRow)
   check = False
   i = firstRow
   If Not Application.Intersect(KeyCells, Range(Target.Address)) _
          Is Nothing Then
            Do While i <= lastRow And check = False
               If ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("AB" & i).Value = "x" Then
                  check = True
                  ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("AB9").Value = "x"
               ElseIf i = lastRow And check = False Then
                  ActiveWorkbook.Sheets("Kalkulation Änderungen").Range("AB9").Value = " "
               End If
            i = i + 1
            Loop
    End If
End Sub


问:
C++ generate random number based on mathematical equations.
I have three positive integers

distance1

distance2

distnace3

that sum up to 100.

distance1 + distance2 + distance3 = 100 (EQ1)

I have  additional information that

20 < distance2 < 90 (EQ2) and

distance1 + distance3 > 8 (EQ3)

I need in C++ to calculate fast three positive random values for distance1, distance2 and distance3 in order to support the equations EQ1, EQ2 and EQ3.

My first approach was to do the following

```<code>    std::list<...> solutions;
    //i for distance1, j for distance2, z for distance3
    for (int i = 1; i < 101; i++) {

       for (int j = 1; j < 101; j++)  {

           for (int z = 1; z < 101; z++)  {

              evaluate if i, j, z satisfy EQ1, EQ2,EQ3
              if ( evaluate == true )
                solutions.push_back(...i,j,z...); //pseudocode

           }
       }

    }
// when all iterations are finished select a random from std::<list>
</code>```

Any better approach to do this? Is there any library that can help? Is this the correct way to perform combinations?

答:
Mathematically you have stated that these are your conditions:

I have three positive integers

```<code>• distance1
• distance2
• distnace3

that sum up to 100.

distance1 + distance2 + distance3 = 100 (EQ1)
</code>```

I have additional information that

```<code>•20 < distance2 < 90 (EQ2) and
•distance1 + distance3 > 8 (EQ3)
</code>```

Let's first use mathematics to find the range & domain of the values. Let these be A, B & C for your three distances. From what you stated we can see that:

```<code>For A We don't have enough information without first finding B & C
A = [Depends On B & C]
B = [21,89]

For C; Since A+C > 8 then:
C > 8 - A
We Know that both A & C are both positive so let's make a small table setting values to A
C > 8 - 1   |  C > 7
C > 8 - 2   |  C > 6
C > 8 - 3   |  C > 5
C > 8 - 4   |  C > 4
C > 8 - 5   |  C > 3
C > 8 - 6   |  C > 2
C > 8 - 7   |  C > 1
C > 8 - 8   |  C > 0 still holds true
C > 8 - 9   |  C > -1  ... ? Still true

How Large can A go? This depends on B & C so we need to use B's domain.

100 = (C > 8 - A) + B[21,89]

We can use B's min and max values or the
floor & ceiling function to determine the domains of A & C.

If B = 21 (min) then the range of combinations between A & C are
100 - 21 = 79
A[1-78]  &  C[1-78] since you have A+B

If B = 89 (max) then the range of combinations between A & C are
100 - 89 = 21
A[1-20] & C[1-20] since you have A+B

So both A & C have a valid domain of [1,78] since
B has a domain of [21,89] and that A+B+C = 100 and all three are + integers

However the Domains of Both A & C depend on the initial value of B.
If B is small then either A or C or A & C can be large
If B is large then both A & C should be small.

Let's say that the first random value for B is its max 89
Then A or C would be 100 - 89 - 1 giving a range of values [1,10] for either A or C's domain

Let's say that the first random value for B is its min 21
Then A or C would be 100 - 21 - 1 giving a range of values [1,78] for either A or C's domain

We can combine these domains to look as such: [1, 10...78]

We can see above that in both calculations we have 100 - 1 that is constant

The final pseudo mathematical code would be:
99 - B[21,89] = A[1,10...78] + C[1,10...78] where A + C > 8
</code>```

We can now use the above assessments of their full domains to design an algorithm as others have already stated:

```<code>// First use a random number generated to find B in the range of [21,89]
// Then you can find a random number for either A or C in the Range of [1,10...78]
// depending on what B is. Remember if B is small then either A or C can be large.
// And if B is large then A & C should be fairly small.
// Once you have the 2nd value just calculate the third.
</code>```

Body:
I have three positive integers

distance1

distance2

distnace3

that sum up to 100.

distance1 + distance2 + distance3 = 100 (EQ1)

I have  additional information that

20 < distance2 < 90 (EQ2) and

distance1 + distance3 > 8 (EQ3)

I need in C++ to calculate fast three positive random values for distance1, distance2 and distance3 in order to support the equations EQ1, EQ2 and EQ3.

My first approach was to do the following

    std::list<...> solutions;
    //i for distance1, j for distance2, z for distance3
    for (int i = 1; i < 101; i++) {

       for (int j = 1; j < 101; j++)  {

           for (int z = 1; z < 101; z++)  {

              evaluate if i, j, z satisfy EQ1, EQ2,EQ3
              if ( evaluate == true )
                solutions.push_back(...i,j,z...); //pseudocode

           }
       }

    }
// when all iterations are finished select a random from std::<list>

Any better approach to do this? Is there any library that can help? Is this the correct way to perform combinations?

Body:
Mathematically you have stated that these are your conditions:

I have three positive integers

• distance1
• distance2
• distnace3

that sum up to 100.

distance1 + distance2 + distance3 = 100 (EQ1)

I have additional information that

•20 < distance2 < 90 (EQ2) and
•distance1 + distance3 > 8 (EQ3)

Let's first use mathematics to find the range & domain of the values. Let these be A, B & C for your three distances. From what you stated we can see that:

For A We don't have enough information without first finding B & C
A = [Depends On B & C]
B = [21,89]

For C; Since A+C > 8 then:
C > 8 - A
We Know that both A & C are both positive so let's make a small table setting values to A
C > 8 - 1   |  C > 7
C > 8 - 2   |  C > 6
C > 8 - 3   |  C > 5
C > 8 - 4   |  C > 4
C > 8 - 5   |  C > 3
C > 8 - 6   |  C > 2
C > 8 - 7   |  C > 1
C > 8 - 8   |  C > 0 still holds true
C > 8 - 9   |  C > -1  ... ? Still true

How Large can A go? This depends on B & C so we need to use B's domain.

100 = (C > 8 - A) + B[21,89]

We can use B's min and max values or the
floor & ceiling function to determine the domains of A & C.

If B = 21 (min) then the range of combinations between A & C are
100 - 21 = 79
A[1-78]  &  C[1-78] since you have A+B

If B = 89 (max) then the range of combinations between A & C are
100 - 89 = 21
A[1-20] & C[1-20] since you have A+B

So both A & C have a valid domain of [1,78] since
B has a domain of [21,89] and that A+B+C = 100 and all three are + integers

However the Domains of Both A & C depend on the initial value of B.
If B is small then either A or C or A & C can be large
If B is large then both A & C should be small.

Let's say that the first random value for B is its max 89
Then A or C would be 100 - 89 - 1 giving a range of values [1,10] for either A or C's domain

Let's say that the first random value for B is its min 21
Then A or C would be 100 - 21 - 1 giving a range of values [1,78] for either A or C's domain

We can combine these domains to look as such: [1, 10...78]

We can see above that in both calculations we have 100 - 1 that is constant

The final pseudo mathematical code would be:
99 - B[21,89] = A[1,10...78] + C[1,10...78] where A + C > 8

We can now use the above assessments of their full domains to design an algorithm as others have already stated:

// First use a random number generated to find B in the range of [21,89]
// Then you can find a random number for either A or C in the Range of [1,10...78]
// depending on what B is. Remember if B is small then either A or C can be large.
// And if B is large then A & C should be fairly small.
// Once you have the 2nd value just calculate the third.


问:
How to get a List of Base class objects, from x number of child classes lists?
For the sake of explanation I made an example

```<code>public class Base {
    public string Name { get; set; }
    public string Surname { get; set; }

    public Base(string name, string surname) {
        Name = name;
        Surname = surname;
    }
}

public class Student : Base {

    public int StudentID { get; set; }

    public Student(string name, string surname, int studentID)
                          : base(name, surname) {
        Name = name;
        Surname = surname;
        StudentID = studentID;
    }

    public override string ToString() {
        return string.Format("Name is {0}, surname is {1}, ID is {2}",
                              Name, Surname, StudentID);
    }
}

public class Teacher : Base {

    public string TeachingSubject { get; set; }

    public Teacher(string name, string surname, string teachingSubject)
                          : base(name, surname) {
        Name = name;
        Surname = surname;
        TeachingSubject = teachingSubject;
    }

    public override string ToString() {
        return string.Format("Name is {0}, surname is {1}, TeachingSubject is {2}",
                              Name, Surname, TeachingSubject);
    }
}
</code>```

In my case, there are 4 child classes, but 2 is enough to keep it simple and still hit the point. Keep in mind that Student and Teacher classes contain their own property, so each object from the Base list should be different, according to the derived class properties.

Somewhere in the project I need to have a Method that returns List of Base objects

```<code>List<Base> GetAllLists() {

    return allLists; //Lets name the return list of Base objects like this
}
</code>```

So I need to put lists of objects from derived classes to a Base class List and use it somewhere.

I already did something like this

```<code>List<Base> GetAllLists() {

    var allLists = new List<Base>();

    var studentList = new StudentService().GetList();  //Service class that populates the list of students from a csv file
    foreach (var item in studentList) {
        allLists.Add(new Student(item.Name, item.Surname, item.StudentID));
    }
    var teacherList = new TeacherService().GetList();  //Service class that populates the list of teachers from a csv file
    foreach (var item in teacherList) {
        allLists.Add(new Teacher(item.Name, item.Surname, item.TeachingSubject));
    }

    return allLists;
}
</code>```

I got a comment:

there's no need to iterate all of the lists and instantiate a new
  object of each entity, since all of them inherit from the same base
  class

So how to achieve this in some other way?

答:
I would do the following, if it is allowed to create a new instance of a list when the GetAllLists method is called

```<code>public List<Base> GetAllLists() {
    var studentList = new StudentService().GetList();
    var teacherList = new TeacherService().GetList();

    return studentList.Cast<Base>()
        .Concat(teacherList.Cast<Base>())
        .ToList();
}
</code>```

Body:
For the sake of explanation I made an example

public class Base {
    public string Name { get; set; }
    public string Surname { get; set; }

    public Base(string name, string surname) {
        Name = name;
        Surname = surname;
    }
}

public class Student : Base {

    public int StudentID { get; set; }

    public Student(string name, string surname, int studentID)
                          : base(name, surname) {
        Name = name;
        Surname = surname;
        StudentID = studentID;
    }

    public override string ToString() {
        return string.Format("Name is {0}, surname is {1}, ID is {2}",
                              Name, Surname, StudentID);
    }
}

public class Teacher : Base {

    public string TeachingSubject { get; set; }

    public Teacher(string name, string surname, string teachingSubject)
                          : base(name, surname) {
        Name = name;
        Surname = surname;
        TeachingSubject = teachingSubject;
    }

    public override string ToString() {
        return string.Format("Name is {0}, surname is {1}, TeachingSubject is {2}",
                              Name, Surname, TeachingSubject);
    }
}

In my case, there are 4 child classes, but 2 is enough to keep it simple and still hit the point. Keep in mind that Student and Teacher classes contain their own property, so each object from the Base list should be different, according to the derived class properties.

Somewhere in the project I need to have a Method that returns List of Base objects

List<Base> GetAllLists() {

    return allLists; //Lets name the return list of Base objects like this
}

So I need to put lists of objects from derived classes to a Base class List and use it somewhere.

I already did something like this

List<Base> GetAllLists() {

    var allLists = new List<Base>();

    var studentList = new StudentService().GetList();  //Service class that populates the list of students from a csv file
    foreach (var item in studentList) {
        allLists.Add(new Student(item.Name, item.Surname, item.StudentID));
    }
    var teacherList = new TeacherService().GetList();  //Service class that populates the list of teachers from a csv file
    foreach (var item in teacherList) {
        allLists.Add(new Teacher(item.Name, item.Surname, item.TeachingSubject));
    }

    return allLists;
}

I got a comment:

there's no need to iterate all of the lists and instantiate a new
  object of each entity, since all of them inherit from the same base
  class

So how to achieve this in some other way?

Body:
I would do the following, if it is allowed to create a new instance of a list when the GetAllLists method is called

public List<Base> GetAllLists() {
    var studentList = new StudentService().GetList();
    var teacherList = new TeacherService().GetList();

    return studentList.Cast<Base>()
        .Concat(teacherList.Cast<Base>())
        .ToList();
}


问:
Mailjet Campaign API : How to set a unique CustomName value?
I want to set a unique alphanumeric name to my campaign to retrieve it later from that name.

I use to set Headers => 'X-Mailjet-Campaign' but now i am using the API and can't make it work.

And API doc doesn't help at all cause there is no exemple given.

Does anyone know how i can set this CustomName value ?

I tried CampaignID And CampaignALT during my post on "CampaignDraft/Create" but none is working (it tells me this is not integer).

答:
I lead the API at Mailjet.

I assume you're referring to our Send API as documented here. As you'll find here, I believe you're looking for the Mj-campaign property in the JSON payload. The full reference of fields is available at https://dev.mailjet.com/guides/#send-api-json-properties.

Since I do not know which programming language you're using, I won't be able to give you a valid sample code but I think the doc should contain all you need to move forward.

Let me know.


问:
Form Dynamic JSON array in C#
For a web service, I need to create dynamic JSON array to be sent as response based on the data given by a stored procedure.

```<code>var t = new Dictionary<string, dynamic>();
for (int i = 0; i < reader.FieldCount; i++)
{
  columnName = reader.GetName(i);
  fieldValue = reader.GetValue(i).ToString();
  t[columnName] = fieldValue;
}
_response.data.Add(t);
</code>```

But the response received is data: [[{"key": "name", "value": "123"}, {"date": "01-Jun-2017"}],[{"key": "name", "value": "abc"}]]

whereas the response needed is : [{ "name": "abc", "date": "01-Jun-2017"},{ "name": "123"}]

Can anyone let me know what could the issue be?

Thanks in Advance.

答:
You can use an anonymous type in C#.

```<code>new { key = value, ...};
</code>```

e.g.

```<code>List<object> lst = new List<object>();
lst.Add(new { Name = "Andrey", Age = 31 });
lst.Add(new { Name = "Martha" });

// print [{"Name":"Andrey","Age":31},{"Name":"Martha"}]
Console.WriteLine(JsonConvert.SerializeObject(lst));
</code>```

Title: Form Dynamic JSON array in C#

Body:
For a web service, I need to create dynamic JSON array to be sent as response based on the data given by a stored procedure.

var t = new Dictionary<string, dynamic>();
for (int i = 0; i < reader.FieldCount; i++)
{
  columnName = reader.GetName(i);
  fieldValue = reader.GetValue(i).ToString();
  t[columnName] = fieldValue;
}
_response.data.Add(t);

But the response received is data: [[{"key": "name", "value": "123"}, {"date": "01-Jun-2017"}],[{"key": "name", "value": "abc"}]]

whereas the response needed is : [{ "name": "abc", "date": "01-Jun-2017"},{ "name": "123"}]

Can anyone let me know what could the issue be?

Thanks in Advance.

Body:
You can use an anonymous type in C#.

new { key = value, ...};

e.g.

List<object> lst = new List<object>();
lst.Add(new { Name = "Andrey", Age = 31 });
lst.Add(new { Name = "Martha" });

// print [{"Name":"Andrey","Age":31},{"Name":"Martha"}]
Console.WriteLine(JsonConvert.SerializeObject(lst));


问:
How do I refresh Netbeans workspace?
In Eclipse, there is something called refresh workspace or F5 that refreshes the files, to make sure to pick-up any files that are changed outside eclipse.

How do i do that in Netbeans ? I am using 6.9.1 for PHP/Java development?

I don't see any refresh nor F5 works?

any hints? any plugins??

答: Never Mind, found ScanOnDemand plugin and also there is source-->Scan for External Changes menu.</p>

Title: How do I refresh Netbeans workspace?


问:
Why does Python optimize out "if 0", but not "if None"?
Why is it that if you compile a conditional expression like

```<code>def f():
    if None:
        print(222)
    if 0:
        print(333)
</code>```

the branches that use numbers get optimized out, but those that use None don't? Example:

```<code> 3        0 LOAD_CONST               0 (None)
          3 POP_JUMP_IF_FALSE       14

 4        6 LOAD_CONST               1 (222)
          9 PRINT_ITEM
         10 PRINT_NEWLINE
         11 JUMP_FORWARD             0 (to 14)

 5  >>   14 LOAD_CONST               0 (None)
         17 RETURN_VALUE
</code>```

In which scenarios could if 0 and if None behave differently?

答:
Disclaimer: This is not really an answer, but just a report of my succeeded
  attempt to override None in CPython 2.7 despite the protection by the
  compiler.

I found a way of overriding None in CPython 2.7, though it involves a dirty trick and could similarly be done to literals. Namely, I replace the constant entry #0 in the co_consts field of a code object:

```<code>def makeNoneTrueIn(func):
    c = func.__code__
    func.__code__ = type(c)(c.co_argcount,
                            c.co_nlocals,
                            c.co_stacksize,
                            c.co_flags,
                            c.co_code,
                            (True, ) + c.co_consts[1:],
                            c.co_names,
                            c.co_varnames,
                            c.co_filename,
                            c.co_name,
                            c.co_firstlineno,
                            c.co_lnotab,
                            c.co_freevars,
                            c.co_cellvars)

def foo():
    if None:
        print "None is true"
    else:
        print "None is false"

foo()
makeNoneTrueIn(foo)
foo()
</code>```

Output:

```<code>None is false
None is true
</code>```

Body:
Why is it that if you compile a conditional expression like

def f():
    if None:
        print(222)
    if 0:
        print(333)

the branches that use numbers get optimized out, but those that use None don't? Example:

 3        0 LOAD_CONST               0 (None)
          3 POP_JUMP_IF_FALSE       14

 4        6 LOAD_CONST               1 (222)
          9 PRINT_ITEM
         10 PRINT_NEWLINE
         11 JUMP_FORWARD             0 (to 14)

 5  >>   14 LOAD_CONST               0 (None)
         17 RETURN_VALUE

In which scenarios could if 0 and if None behave differently?

Body:
Disclaimer: This is not really an answer, but just a report of my succeeded
  attempt to override None in CPython 2.7 despite the protection by the
  compiler.

I found a way of overriding None in CPython 2.7, though it involves a dirty trick and could similarly be done to literals. Namely, I replace the constant entry #0 in the co_consts field of a code object:

def makeNoneTrueIn(func):
    c = func.__code__
    func.__code__ = type(c)(c.co_argcount,
                            c.co_nlocals,
                            c.co_stacksize,
                            c.co_flags,
                            c.co_code,
                            (True, ) + c.co_consts[1:],
                            c.co_names,
                            c.co_varnames,
                            c.co_filename,
                            c.co_name,
                            c.co_firstlineno,
                            c.co_lnotab,
                            c.co_freevars,
                            c.co_cellvars)

def foo():
    if None:
        print "None is true"
    else:
        print "None is false"

foo()
makeNoneTrueIn(foo)
foo()

Output:

None is false
None is true


问:
Find is not a function error
I have an array of objects in javascript like this:

```<code>array=[{label: 1, value:e}, {label:1, value: i}, {label: 2, value:l}]
</code>```

I want to find the label when value is l so I'm writing:

```<code>array.map((i) => i.find(item => item.value === 'l').label)
</code>```

But an error is returning

i.find is not a function

What am I missing?

答:
I don't understand why you are using map- based on your question you are just trying to find the label of the element with a particular value, so all you need is find. This works fine:

array.find(item => item.value === 'l').label

Returns 2.

You should handle the case where find returns undefined, for example:

```<code>var found = array.find(item => item.value === 'l')
if(found){
  var label = found.label;
  // use label
}else{
  // nothing found
}
</code>```

Title: Find is not a function error

Body:
I have an array of objects in javascript like this:

array=[{label: 1, value:e}, {label:1, value: i}, {label: 2, value:l}]

I want to find the label when value is l so I'm writing:

array.map((i) => i.find(item => item.value === 'l').label)

But an error is returning

i.find is not a function

What am I missing?

Body:
I don't understand why you are using map- based on your question you are just trying to find the label of the element with a particular value, so all you need is find. This works fine:

array.find(item => item.value === 'l').label

Returns 2.

You should handle the case where find returns undefined, for example:

var found = array.find(item => item.value === 'l')
if(found){
  var label = found.label;
  // use label
}else{
  // nothing found
}


问:
Retrieving data from code mirror after merge
I am using code mirror instance to merge data. I want to retrieve the left hand side data from code mirror after performing the merge.
Code below:</p>

```<code>$timeout(function () {
 var a = document.getElementById("diffView");
 dv = CodeMirror.MergeView(a, {
        value: repositoryData,
        orig: workspaceData,
        lineNumbers: true,
        mode: "javascript",
        highlightDifferences: true
    });
},1);
</code>```

答: I got the way out by using dv.editor().getValue();</p>

Body:
I am using code mirror instance to merge data. I want to retrieve the left hand side data from code mirror after performing the merge.
Code below:

$timeout(function () {
 var a = document.getElementById("diffView");
 dv = CodeMirror.MergeView(a, {
        value: repositoryData,
        orig: workspaceData,
        lineNumbers: true,
        mode: "javascript",
        highlightDifferences: true
    });
},1);


问:
heap pollution for simple parameter
I have following function:

```<code>public static <T> List<T> list(T... xs) {
    final List<T> lst = new ArrayList<T>();
    for (final T x : xs) {
        lst.add(x);
    }

    return lst;
}
</code>```

Its usage is simple:

```<code>   List<Integer> ints = list(1, 2, 3, 4)
</code>```

Compiler gives me following warning for this list

"TypeSafety: potential heap pollution for via varargs parameter

I tried to find what it means but all explanastions I found were for functions of parameters that are themselves parametrized e.g.

f(List<T>... xss).

While I have function of generic non parametrized parameter.

Please explain me what is the potential problem with my function because I can not find any.

答:
Varargs in Java is a syntatic sugar. T... xs is the same as T[] xs. Therefore actually you have a function with parametrized parameter (the array).

Back to your question. Let's consider the situation, when you pass List<String> as generic type to the method. Then you have an array of elements of List<String> as an argument to your method. Two important issues arise because of this and lead to possible flaw in the code.

Arrays are covariant and it means that the compilator will allow this assignment: Object[] arr = xs

Because of generic erasure during compile time the array contains raw List elements and, unfortunately, there is no way in Java to guarantee, that the element you put in the array is exactly List<String>. So if you put List<Integer> java.lang.ArrayStoreException will not be thrown at runtime.

This alltogether leads to a situation when you may produce heap polution. Please, see the following example:

```<code>public static <T> List<T> list(T... xs) {
    final List<T> lst = new ArrayList<T>();
    for (final T x : xs) {
        lst.add(x);
    }
    Object[] arr = xs; //arrays are covariant, we can do this
    arr[0] = Arrays.asList(4); //<--------heap pollution
    return lst;
}
public static void main(String[] args) {
    List[] arr = { Arrays.asList("one"), Arrays.asList("two"), Arrays.asList("three") };
    List<List<String>> l = list(arr);
    for (List list : arr) {
        System.out.println(list.get(0));
    }
}
</code>```

Output:

```<code>4
two
three
</code>```

Here is a really good one explanation on the topic:
http://www.angelikalanger.com/GenericsFAQ/FAQSections/ProgrammingIdioms.html#FAQ300

Official Java Guide:
https://docs.oracle.com/javase/8/docs/technotes/guides/language/non-reifiable-varargs.html

Title: heap pollution for simple parameter

Body:
I have following function:

public static <T> List<T> list(T... xs) {
    final List<T> lst = new ArrayList<T>();
    for (final T x : xs) {
        lst.add(x);
    }

    return lst;
}

Its usage is simple:

   List<Integer> ints = list(1, 2, 3, 4)

Compiler gives me following warning for this list

"TypeSafety: potential heap pollution for via varargs parameter

I tried to find what it means but all explanastions I found were for functions of parameters that are themselves parametrized e.g.

f(List<T>... xss).

While I have function of generic non parametrized parameter.

Please explain me what is the potential problem with my function because I can not find any.

Body:
Varargs in Java is a syntatic sugar. T... xs is the same as T[] xs. Therefore actually you have a function with parametrized parameter (the array).

Back to your question. Let's consider the situation, when you pass List<String> as generic type to the method. Then you have an array of elements of List<String> as an argument to your method. Two important issues arise because of this and lead to possible flaw in the code.

Arrays are covariant and it means that the compilator will allow this assignment: Object[] arr = xs

Because of generic erasure during compile time the array contains raw List elements and, unfortunately, there is no way in Java to guarantee, that the element you put in the array is exactly List<String>. So if you put List<Integer> java.lang.ArrayStoreException will not be thrown at runtime.

This alltogether leads to a situation when you may produce heap polution. Please, see the following example:

public static <T> List<T> list(T... xs) {
    final List<T> lst = new ArrayList<T>();
    for (final T x : xs) {
        lst.add(x);
    }
    Object[] arr = xs; //arrays are covariant, we can do this
    arr[0] = Arrays.asList(4); //<--------heap pollution
    return lst;
}
public static void main(String[] args) {
    List[] arr = { Arrays.asList("one"), Arrays.asList("two"), Arrays.asList("three") };
    List<List<String>> l = list(arr);
    for (List list : arr) {
        System.out.println(list.get(0));
    }
}

Output:

4
two
three

Here is a really good one explanation on the topic:
http://www.angelikalanger.com/GenericsFAQ/FAQSections/ProgrammingIdioms.html#FAQ300

Official Java Guide:
https://docs.oracle.com/javase/8/docs/technotes/guides/language/non-reifiable-varargs.html


问:
Fail to send data to server using device
I'm new to Android and after a long time I finally manage to create a database using PHP scripts and MySQL.

While I'm using the Android Studio emulator I do succeed sending data to the database but when I run the application on my device I failed to do so.
I don't get any error and the app keeps running (not crushing) but the database doesn't get the data.

This is the doInbackground method in my BackgroundTask class:

```<code>@Override
// send info to MySQL DB
// it gets 4 parameters - the first if the opertaion should be "register" and the others are
// user info (name,pass,gender)
protected String doInBackground(String... params) {
    // the ip is default for localhost
    String reg_url = "http://**MyIP**/webapp/register.php";
    String login_url = "http://**MyIP**/webapp/login.php";
    String method = params[0];
    if (Objects.equals(method, "register")){
        String userName = params[1];
        String userPass = params[2];
        String gender = params[3];
        try {
            URL url = new URL(reg_url);
            // run the register php script.
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            OutputStream OS = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
            // applied the "userName,"userPass" and "gender" that I define in the POST (at the register.php)
            // the info the user typed.
            String data = URLEncoder.encode("userName", "UTF-8") + "=" + URLEncoder.encode(userName,"UTF-8") + "&" +
                    URLEncoder.encode("userPass", "UTF-8") + "=" +URLEncoder.encode(userPass,"UTF-8") + "&" +
                    URLEncoder.encode("gender", "UTF-8") + "=" +URLEncoder.encode(gender,"UTF-8");
            // write the data to server
            bufferedWriter.write(data);
            bufferedWriter.flush();
            bufferedWriter.close();
            OS.close();
            InputStream IS = httpURLConnection.getInputStream();
            IS.close();
            return "Registration Successs";
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}
</code>```

答:
Connect your PC and android device to same wifi network.

If your running on windows enter ipconfig on cmd and if it is ubuntu run ifconfig on terminal to get ip address

it'll be like 192.168.0.*. If **MyIP** and IP Address which you've got are same then ignore it.

Be Sure that you've given permissions to access internet in manifest file.

Body:
I'm new to Android and after a long time I finally manage to create a database using PHP scripts and MySQL.

While I'm using the Android Studio emulator I do succeed sending data to the database but when I run the application on my device I failed to do so.
I don't get any error and the app keeps running (not crushing) but the database doesn't get the data.

This is the doInbackground method in my BackgroundTask class:

@Override
// send info to MySQL DB
// it gets 4 parameters - the first if the opertaion should be "register" and the others are
// user info (name,pass,gender)
protected String doInBackground(String... params) {
    // the ip is default for localhost
    String reg_url = "http://**MyIP**/webapp/register.php";
    String login_url = "http://**MyIP**/webapp/login.php";
    String method = params[0];
    if (Objects.equals(method, "register")){
        String userName = params[1];
        String userPass = params[2];
        String gender = params[3];
        try {
            URL url = new URL(reg_url);
            // run the register php script.
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            OutputStream OS = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
            // applied the "userName,"userPass" and "gender" that I define in the POST (at the register.php)
            // the info the user typed.
            String data = URLEncoder.encode("userName", "UTF-8") + "=" + URLEncoder.encode(userName,"UTF-8") + "&" +
                    URLEncoder.encode("userPass", "UTF-8") + "=" +URLEncoder.encode(userPass,"UTF-8") + "&" +
                    URLEncoder.encode("gender", "UTF-8") + "=" +URLEncoder.encode(gender,"UTF-8");
            // write the data to server
            bufferedWriter.write(data);
            bufferedWriter.flush();
            bufferedWriter.close();
            OS.close();
            InputStream IS = httpURLConnection.getInputStream();
            IS.close();
            return "Registration Successs";
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}


问:
Do you recommend using semicolons after every statement in JavaScript?
In many situations, JavaScript parsers will insert semicolons for you if you leave them out. My question is, do you leave them out?

If you're unfamiliar with the rules, there's a description of semicolon insertion on the Mozilla site. Here's the key point:

If the first through the nth tokens of a JavaScript program form are grammatically valid but the first through the n+1st tokens are not and there is a line break between the nth tokens and the n+1st tokens, then the parser tries to parse the program again after inserting a virtual semicolon token between the nth and the n+1st tokens.

That description may be incomplete, because it doesn't explain @Dreas's example. Anybody have a link to the complete rules, or see why the example gets a semicolon? (I tried it in JScript.NET.)

This stackoverflow question is related, but only talks about a specific scenario.

答:
Yes, you should always use semicolons. Why? Because if you end up using a JavaScript compressor, all your code will be on one line, which will break your code.

Try http://www.jslint.com/; it will hurt your feelings, but show you many ways to write better JavaScript (and one of the ways is to always use semicolons).

OwnerDisplayName: anon

LastEditorDisplayName: anon


问:
Given an array of uint8_t what is a good way to extract any subsequence of bits as a uint32_t?
I have run into an interesting problem lately:

Lets say I have an array of bytes (uint8_t to be exact) of length at least one. Now i need a function that will get a subsequence of bits from this array, starting with bit X (zero based index, inclusive) and having length L and will return this as an uint32_t. If L is smaller than 32 the remaining high bits should be zero.

Although this is not very hard to solve, my current thoughts on how to do this seem a bit cumbersome to me. I'm thinking of a table of all the possible masks for a given byte (start with bit 0-7, take 1-8 bits) and then construct the number one byte at a time using this table.

Can somebody come up with a nicer solution? Note that i cannot use Boost or STL for this - and no, it is not a homework, its a problem i run into at work and we do not use Boost or STL in the code where this thing goes. You can assume that: 0 < L <= 32 and that the byte array is large enough to hold the subsequence.

One example of correct input/output:

array: 00110011 1010 1010 11110011 01 101100

subsequence: X = 12 (zero based index), L = 14

resulting uint32_t = 00000000 00000000 00 101011 11001101

答:
I would be thinking something like loading a uint64_t with a cast and then shifting left and right to lose the uninteresting bits. </p>

```<code>uint32_t extract_bits(uint8_t* bytes, int start, int count)
{
    int shiftleft =  32+start;
    int shiftright = 64-count;
    uint64_t *ptr = (uint64_t*)(bytes);
    uint64_t hold = *ptr;
    hold <<= shiftleft;
    hold >>= shiftright;
    return (uint32_t)hold;
}
</code>```

Body:
I would be thinking something like loading a uint64_t with a cast and then shifting left and right to lose the uninteresting bits.

uint32_t extract_bits(uint8_t* bytes, int start, int count)
{
    int shiftleft =  32+start;
    int shiftright = 64-count;
    uint64_t *ptr = (uint64_t*)(bytes);
    uint64_t hold = *ptr;
    hold <<= shiftleft;
    hold >>= shiftright;
    return (uint32_t)hold;
}


问:
Spring @Autowire on non-setter methods
I just came across some samples where the @Autowire is used on non-setter methods.

```<code>@Autowired
public void doSomething(MyType t){
     System.out.println(t);
}
</code>```

how will i call this method ? like objectReference.doSomething(); does the parameter is not required while calling these methods ?

when do we use @Autowire on non-setter methods

can anybody share some samples on the same ?

答:
```<code>@Target(value={CONSTRUCTOR,METHOD,PARAMETER,FIELD,ANNOTATION_TYPE})
 @Retention(value=RUNTIME)
 @Documented
public @interface Autowired
</code>```

as we see from official docs @Autowired Marks a constructor, field, setter method or config method as to be autowired by Spring's dependency injection facilities. - https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/annotation/Autowired.html

But, how spring will know that you method is or is not a config method? When Spring finds @Autowired it will try to find beans matching to method parameters and will invoke that method.

Title: Spring @Autowire on non-setter methods

Body:
I just came across some samples where the @Autowire is used on non-setter methods.

@Autowired
public void doSomething(MyType t){
     System.out.println(t);
}

how will i call this method ? like objectReference.doSomething(); does the parameter is not required while calling these methods ?

when do we use @Autowire on non-setter methods

can anybody share some samples on the same ?

Body:
@Target(value={CONSTRUCTOR,METHOD,PARAMETER,FIELD,ANNOTATION_TYPE})
 @Retention(value=RUNTIME)
 @Documented
public @interface Autowired

as we see from official docs @Autowired Marks a constructor, field, setter method or config method as to be autowired by Spring's dependency injection facilities. - https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/annotation/Autowired.html

But, how spring will know that you method is or is not a config method? When Spring finds @Autowired it will try to find beans matching to method parameters and will invoke that method.


问:
Array Comparision
I have a array with 8 columns and 42 rows B2 TO I43. I have to compare this array with other arrays in the same sheet so that every array have same values. I defined array1 Rang('B2;I43") and need to compare every other array of same size. how to that in VBA.
My code is

```<code>Sub driver()
Dim array1, array2, m, n
Set array1 = Range("B2,I43")
total_rows = 42
total_cols = 8
Set array2 = Range("B44:I85")

For i = 1 To total_rows
For j = 1 To total_cols
    If array1(i, j) = array2(i, j) Then
    array2.Cells(i, j).Interior.ColorIndex = 0
    ElseIf array1(i, j) <> array2(i, j) Then
    array2.Cells(i, j).Interior.ColorIndex = 3
    End If
    Next j
    Next i
End Sub
</code>```

I want array2 to point to other set of values. Every array start after 42 rows.

答:
Have you tried to use Conditional formatting instead? Your suggested VBA code can easily be solved with conditional formatting by comparing each cell in array2 with the same cell in array1 and use colours to mark if the cells are equal or not

Edit
I have modified your code. Instead of using two ranges I have used an "row offset" for each array you have on your sheet. It then compares the cells from your source array (array1 in your code) with the cells that are found next_array_offset rows down. When the comparison has been made, the offset is increased with 42. The loop ends when there are no more values to be found.

Is this what you was looking for?

```<code>Sub driver()
    Dim r As Integer
    Dim c As Integer
    Dim source_row As Integer
    Dim source_col As Integer
    Dim total_rows As Integer
    Dim total_cols As Integer
    Dim next_array_offset As Integer

    source_row = 2   ' row B
    source_col = 2   ' col 2
    total_rows = 42
    total_cols = 8
    next_array_offset = 42  ' distance in rows to next array

    Do Until IsEmpty(Cells(source_row + next_array_offset, source_col).Value)
        For r = 0 To total_rows - 1
            For c = 0 To total_cols - 1
                If Cells(source_row + r, source_col + c) = Cells(source_row + next_array_offset + r, source_col + c) Then
                    Cells(source_row + next_array_offset + r, source_col + c).Interior.ColorIndex = 0
                Else
                    Cells(source_row + next_array_offset + r, source_col + c).Interior.ColorIndex = 3
                End If
            Next
        Next
        next_array_offset = next_array_offset + 42
    Loop
End Sub
</code>```

Title: Array Comparision

Body:
I have a array with 8 columns and 42 rows B2 TO I43. I have to compare this array with other arrays in the same sheet so that every array have same values. I defined array1 Rang('B2;I43") and need to compare every other array of same size. how to that in VBA.
My code is

Sub driver()
Dim array1, array2, m, n
Set array1 = Range("B2,I43")
total_rows = 42
total_cols = 8
Set array2 = Range("B44:I85")

For i = 1 To total_rows
For j = 1 To total_cols
    If array1(i, j) = array2(i, j) Then
    array2.Cells(i, j).Interior.ColorIndex = 0
    ElseIf array1(i, j) <> array2(i, j) Then
    array2.Cells(i, j).Interior.ColorIndex = 3
    End If
    Next j
    Next i
End Sub

I want array2 to point to other set of values. Every array start after 42 rows.

Body:
Have you tried to use Conditional formatting instead? Your suggested VBA code can easily be solved with conditional formatting by comparing each cell in array2 with the same cell in array1 and use colours to mark if the cells are equal or not

Edit
I have modified your code. Instead of using two ranges I have used an "row offset" for each array you have on your sheet. It then compares the cells from your source array (array1 in your code) with the cells that are found next_array_offset rows down. When the comparison has been made, the offset is increased with 42. The loop ends when there are no more values to be found.

Is this what you was looking for?

Sub driver()
    Dim r As Integer
    Dim c As Integer
    Dim source_row As Integer
    Dim source_col As Integer
    Dim total_rows As Integer
    Dim total_cols As Integer
    Dim next_array_offset As Integer

    source_row = 2   ' row B
    source_col = 2   ' col 2
    total_rows = 42
    total_cols = 8
    next_array_offset = 42  ' distance in rows to next array

    Do Until IsEmpty(Cells(source_row + next_array_offset, source_col).Value)
        For r = 0 To total_rows - 1
            For c = 0 To total_cols - 1
                If Cells(source_row + r, source_col + c) = Cells(source_row + next_array_offset + r, source_col + c) Then
                    Cells(source_row + next_array_offset + r, source_col + c).Interior.ColorIndex = 0
                Else
                    Cells(source_row + next_array_offset + r, source_col + c).Interior.ColorIndex = 3
                End If
            Next
        Next
        next_array_offset = next_array_offset + 42
    Loop
End Sub


问:
Bash error not recognizing asterisk
Hello I am trying to write a Bash Script that will loop through a directory, and run the files in that directory through a command line program.

Unfortunately when I run it I keep getting

/home/user/Documents/Original_Files/*.fastq.gz: No such file or directory

Here's my code

```<code>Origin=/home/user/Documents/Original_Files/*.fastq.gz

for a in "$Origin"
do
BASE=basename "$a"
nohup java -jar $
done
</code>```

答:
Use an array if you want to keep several values in a variable.</p>

```<code>Origin=(/home/user/Documents/Original_Files/*.fastq.gz)
for a in "${Origin[@]}" ; do
    BASE=$(basename "$a")
    nohup java -jar "$BASE"...
</code>```

Title: Bash error not recognizing asterisk

Body:
Hello I am trying to write a Bash Script that will loop through a directory, and run the files in that directory through a command line program.

Unfortunately when I run it I keep getting

/home/user/Documents/Original_Files/*.fastq.gz: No such file or directory

Here's my code

Origin=/home/user/Documents/Original_Files/*.fastq.gz

for a in "$Origin"
do
BASE=basename "$a"
nohup java -jar $
done

Body:
Use an array if you want to keep several values in a variable.

Origin=(/home/user/Documents/Original_Files/*.fastq.gz)
for a in "${Origin[@]}" ; do
    BASE=$(basename "$a")
    nohup java -jar "$BASE"...


问:
How to export content starting with "$" without cell content transformation to a number?
When I am trying to export data like "$101" in cells, am getting just numbers (number format) in resulted excel document.

How to prevent excel from interpreting such data as numbers, but just make it show these values as text?

答:
As discussed ands discribed here and in the documentation, datatables allow to change display format for Excel cells,
there is an example.</p>