text:
Q: ASP.NET GridView - Prevent Word-Wrapping in Column On an ASP.NET GridView, I have a field that prints a string from the database.  This data can range from 10 to 100 characters.  When it is longer than normal, the field word-wraps the data, making the row take up more vertical space than the others.  I want to truncate any data that does not fit on the row, and then have a "..." next to it to indicate there is more.  I don't need to allow them to resize, I just don't want any rows of different height.  I'm hoping this can be done dynamically on the client-side, for SEO purposes.
See the ActiveWIdgets Grid here, and resize the company name so that it does not fit.  You will notice that it does not wrap the contents, but it instead does exactly what I want to do.
How can I apply this technique to an ASP.NET GridView?  I assume some Javascript is involved.  If that is true, I would prefer to NOT use a library like jQuery (don't ask why -- I am not allowed to use an external dependency for this project).

A: Table of contents

*

*Illustration of problem

*Illustration of one solution

Illustration of problem
Copy the following HTML into your browsers (at least Firefox and Internet Explorer 7, but you should try Opera too):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

        content content content content content content

                    content content content content content content

Notice that the td element does not hide the overflowing content. Only the div element nows how to do this. Internet Explorer's td element does not even know how to stop wrapping the content.
Strictly speaking, according to the standard, the td element does not support the white-space rule. The div and th elements do.
Illustration of one solution
This is one solution to the problem (Tested in Opera, Firefox and Internet Explorer 7):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

                        content content content content content content

A: If you know your user is using Internet Explorer, you can use the following IE only CSS:
td.nooverflow
{
  text-overflow:ellipsis;
}

Then set the ItemStyle for the column you want to fix the width of as <ItemStyle CssClass='nooverfolow'/> (you'll need to play with the CSS to get it right for your application)
Unfortunately since this is IE only, for other browsers, there are some hacks available to simulate the same thing:

*

*Here's one for Firefox.

*Here's another for Firefox

*Here's one using jQuery


text:
Q: read, search, capture, store in MySQl using PHP? Table1 has got two columns names and details with FUll TEXT SEARCH enabled
names | details
----------------------------
Mathew | car,home,insurance,job
levin  | home,business,shop
john   | car,home,insurance
abin   | home,insurance,job
neil   | shop,car,home,tax
yancy  | computer,consultant,engineer

First step:
read each name and its details in table1
Second step:
Search in the table1 with details of each names
third step:
capture the search result of names
fourth step:
Store it into table2 with name in first step and captured names in third step.
fianlly table2 look like
 name   | names
 -----------------------
 Mathew | john,abin,neil

How can I do this in PHP with MySQL?? I want do this for upto 250k approx.

A: Do you have the option to break those details out into a child table?  Cuz if you can, then it is trivial.
Assuming they have been broke out, you have:
name   detail
-------------
john   car
john   insurance
neil   car
neil   home
...etc...

Your desired output is much easier to read than your step-wise explanation, it looks like you want, for any given person, all the other people who have at least one detail in common, no?  If so, the query is:
-- the strange CASE WHEN eliminates transitive closure
-- where you will get john,bill and bill,john
select case when t1.name < t2.name then t1.name else t2.name end as name1
     , case when t1.name < t2.name then t2.name else t1.name end as name2
  from childTable t1
  join childtable t2 on t1.detail = t2.detail
                    and t1.name   <>t2.name
 group by case when t1.name < t2.name then t1.name else t2.name end
        , case when t1.name < t2.name then t2.name else t1.name end
 order by case when t1.name < t2.name then t1.name else t2.name end
        , case when t1.name < t2.name then t2.name else t1.name end

The ORDER BY is not strictly necessary, but if you run this in a console it makes it easier to inspect the results.
All of those CASE...WHEN statements eliminate the problem of duplicate pairs.  Without them the query will double every answer, you'll get "joe,bill" and "bill,joe" and "suzy,john" and "john,suzy".  Those CASE..WHENs cause them to always have the alphabetically lower name first so they can be collapsed and dupes eliminated.
After that, you can use a Common Table Expression to combine these on the server, or just loop through them in PHP.  The php might look like this:
 <?php
 # Assuming rows have been retrieved...
 $matches = array();
 foreach($rows as $row) {
     $matches[$row['name1']][] = $row['name2'];
 }
 foreach($matches as $name1=>$names) {
     echo "$name1 has details in common with ".implode(",",$names);
 }
 ?>

One last note.  I don't want to think about trying to do this without first normalizing that list of details :(

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I play a sound on iOS? I have built a random number generator, I want it to play a sound when the button is pressed. Xcode doesn't give me any errors and when I simulate my app it generates numbers no problem but there is no sound. I have my sound in a sound folder.
Here is my code.
import UIKit
import AVFoundation

class ViewController: UIViewController {

    var player: AVAudioPlayer!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBOutlet weak var operations: UIImageView!
    @IBOutlet weak var bottomRightNumber: UIImageView!
    @IBOutlet weak var bottomMiddleNumber: UIImageView!
    @IBOutlet weak var bottomLeftNumber: UIImageView!
    @IBOutlet weak var topRightNumber: UIImageView!
    @IBOutlet weak var topMiddleNumber: UIImageView!
    @IBOutlet weak var topLeftNumber: UIImageView!

    @IBAction func buttonPressed(_ sender: UIButton) {

        let numberArray = [#imageLiteral(resourceName: "RN1"), #imageLiteral(resourceName: "RN2"), #imageLiteral(resourceName: "RN3"), #imageLiteral(resourceName: "RN4"),#imageLiteral(resourceName: "RN5"), #imageLiteral(resourceName: "RN6"), #imageLiteral(resourceName: "RN7"), #imageLiteral(resourceName: "RN8"), #imageLiteral(resourceName: "RN9"), #imageLiteral(resourceName: "RN0")]

        bottomRightNumber.image = numberArray.randomElement()
        bottomLeftNumber.image = numberArray.randomElement()
        bottomMiddleNumber.image = numberArray.randomElement()
        topRightNumber.image = numberArray.randomElement()
        topMiddleNumber.image = numberArray.randomElement()
        topLeftNumber.image = numberArray.randomElement()

        let operationArray = [#imageLiteral(resourceName: "-"), #imageLiteral(resourceName: "+")]

        operations.image = operationArray.randomElement()

            func playSound() {
                guard let url = Bundle.main.url(forResource: "A", withExtension: "wav") else { return }

             do { /* The following line is required for the player to work on iOS 11. Change the file type accordingly*/
                    player = try! AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.wav.rawValue)
                player.play()

                }
            }
        }
}

A: Looks like you just copied and pasted someone else's code. But you pasted it into some other code, so the problem now is that your code that plays sound has ended up wrapped in a nested function declaration, inside your func buttonPressed code:
func playSound() {
    guard let url = Bundle.main.url(forResource: "A", withExtension: "wav") else { return }
    do {
        player = try! AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.wav.rawValue)
        player.play() // this is where sound _would_ play
    }
}

Nothing ever calls that function, so it never runs.
Just delete those two lines that wrap the code, and now the code can run as part of what buttonPressed does. I would also suggest removing the pointless do construct as well, so you will end up with this:
    guard let url = Bundle.main.url(forResource: "A", withExtension: "wav") else { return }
    player = try! AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.wav.rawValue)
    player.play() // this is where sound _would_ play

Your sound still might not play, or you might crash, but at least the code will now actually run!

Having said all that, let me change the code a little more to demonstrate best practices:
    guard let url = Bundle.main.url(forResource: "A", withExtension: "wav") else {
        print("the URL was not valid") // tell yourself what went wrong
        return
    }
    do {
        player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.wav.rawValue)
        player.play()
    } catch { print(error) } // tell yourself what went wrong

In that version, I've put the do construct back, but this time it actually does something useful.

A: you can do 2 things:
1. Take the function playSound() out of the buttonPressed action and call the playSound() function - because I see that you have not called the function to play the sound.
2. you can just take the audio code out of the function playSound() if you are eventually going to use it there itself.

A: If you want to play sounds in your iOS application, stop what you are doing. Throw away the manual on swifts built in audio services and use a framework.
AudioKit is an incredible powerful framework built by some very competent audio programmers. This library has a nice API, is well documented and is very powerful. They have plenty of example apps, including sample code to help get you started. If you just want to play a sound, you will be covered. If you wanted to build a granular synth, you will also be covered.
Especially if you are new to programming, usually someone has done the hard work for you. Don't reinvent the wheel!

A: Here is the sample class to play sounds,
import Foundation
import AudioToolbox
import AVKit

class SoundManager {

    static var objPlayer: AVAudioPlayer?
    class func playAppLaunchSound() {

        registerAndPlaySoundForFile(fileName: "AppLaunchSound", fileExtension: "mp3")
    }

    class func playEnterButtonSound() {

        registerAndPlaySoundForFile(fileName: "EnterButtonSound", fileExtension: "mp3")
    }

    private class func registerAndPlaySoundForFile(fileName: String, fileExtension: String, withVibration: Bool = true) {

        let bundle = Bundle.main
        guard let url = bundle.url(forResource: fileName, withExtension: fileExtension) else {
            return
        }
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.ambient)
            try AVAudioSession.sharedInstance().setActive(true)
                        objPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
            guard let aPlayer = objPlayer else { return }
            aPlayer.play()

        } catch let error {
            print(error.localizedDescription)
        }
    }
}

registerAndPlaySoundForFile is the main method responsible to play sound!
You can use it like SoundManager.playEnterButtonSound(). You can create multiple methods in this class like this.


text:
Q: Use TLS certificate from a domain owned, and use it at URL given by AWS Elastic Beanstalk I'm building a websockets application that runs on:

*

*NodeJS
Environment with:

*

*Nginx.

Using library at app.js:
...
const https = require('https');
...

And the websockets at app.js:
...
const webSocket = require('ws');
...

It works if I use a self signed certificate and force the client not to authenticate server certificate with CAs...
But there's a client application that doesn't support self signed certificates.
So, I came across here and here...
I'm thinking about issuing a certificate for a subdomain of a domain I own. And use the files to run the websockets application at AWS Elastic Beanstalk environment.

*

*Is that idea possible?

*Do I need to have a domain name for the beanstalk application?

*Am I missing something?

Thanks a lot!
Kind regards,
Jon.

A: Thanks @t.niese for the  feedback. Thanks @Abhyudit for your proposal for out traffic to domain-server of my own.
Tried to setup Route53. But come to realize that I was trying to impersonate my domain using elastic beanstalk AWS provided resource URL. So it was not possible as the docs say.
Then, tried the management of certificates with Amazon Certificate Manager, by importing the information from a domain I truly own, setup URLs, wildcards, in order to call elastic beanstalk environment. And it did the trick. Just make sure to call the right URL with the right port.
Kind regards all! :D
Jon.

A: You can add a CNAME record in Route53 for the URL given by Elastic Beanstalk and then your domain will point to your Elastic Beanstalk application.
Refer to this link: https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-to-beanstalk-environment.html


text:
Q: Cast a nullable DateTime in a lambda expression Using EF6 I want to get all objects of the year 2019 from my database CALENDRIER, but EF6 generates nullables DateTimes "DateTime?" instead of usual DateTimes. Because I want only the year, I could use the Year field from the DateTime to filter my List, but it isn't available with a nullable DateTime. Basically I want to use it like this :
_db.CALENDRIERs.Where(c => c.CALE_DATE.Year == year).ToList();

But I get the following error :

'DateTime?' does not contain a definition for 'Year' and no accessible extension method 'Year' accepting a first argument of type 'DateTime?' could be found...

How can I cast them implicitely inside my lambda expression ?

A: First check to see if CALE_DATE has a value, and then use the .Value
_db.CALENDRIERs.Where(c => c.CALE_DATE.HasValue && c.CALE_DATE.Value.Year == year).ToList();

A: You have to access the Value field of the nullable type:
DateTime? nullableDt = DateTime.Now;
int year = nullableDt.Value.Year;

A: You can first check whether the DateTime object is not null i.e. it has value and then you can fetch the Year property from it
_db.CALENDRIERs.Where(c => c.CALE_DATE.HasValue && c.CALE_DATE.Year == year).ToList();


text:
Q: Who are attacking sanctuary, and why? I've played all the games and I like the gameplay, never really got the lore.
So far I understand that there are demons and angels, and those are in an eternal battle. Inarius, a great angel, was captured by the demons and released by Lilith, a great demon, daughter of Mephisto, one of the three prime evils.
They together created sanctuary and had a bunch of babies(?). Angels and demons had babies and those are called Nephilims. I'm a nephilim in the game.
However it seems Sanctuary keeps getting targeted and attacked, I guess mostly by the demons as it seems I ally myself with the angels(?).
Why do they keep wanting to destroy sanctuary? And why is it only the demons and not the angels?

A: The story is long and detailed, but here is a brief explanation.  It's been a while, so some of recollection is a bit hazy.
The war between heaven and hell has been waged for an eternity.  Some of the angels and demons became tired of fighting.  Lilith used the Worldstone (a fragment of Anu's eye - their version of God who is now dead) and created the world of Sanctuary.  She and her lover, the angel Inarius hid it from everyone else.  the angels and demons who were tired of fighting settled on Sanctuary and started having children with each other.  Eventually, heaven and hell found out about Sanctuary, but agreed it was off limits.  However, the Prime Evils, like Diablo were not going to keep that agreement.  In order for Diablo to come to the world he started influencing a priest to find a host for him to possess.  This is why the story takes place under the church.
I won't go on, as it spoils the game.


text:
Q: Loop data from 2 different model php codeigniter 4 I have table to display data from 2 of my model

    <?php $numbering = 1;
     foreach ($data1 as $row) :
         foreach ($data2 as $rowData) : ?>

               <?= $numbering++; ?>
               <?= $row["id"]; ?>
               <?= $row["name"]; ?>
               <?= $rowData["question"]; ?>
               <?= $rowData["indicator 1"]; ?>
               <?= $rowData["indicator 2"]; ?>
               <?= $rowData["indicator 3"]; ?>
               <?= $rowData["indicator 4"]; ?>
               <?= $rowData["indicator 5"]; ?>

          <?php endforeach;
          endforeach; ?>

data 1 and data 2 from my controller
public function index()
{
    $display1 = $this->model1->findAll();
    $display2 = $this->model2->findAll();
    $data = [
        'title' => 'Page Title',
        'data1' => $display1 ,
        'data2' => $display2 ,
        'content'    => 'Backend/viewDisplay'
    ];

    return view('layouts/v_wrapper', $data);
}

displayed like this

How to display it so question 1 doesn't repeat on user 1 and question 2 doesn't repeat on user 1 and so on. In total it should only have 4 column.

*

*User 1

*

*Question 1

*Question 2

*User 2

*

*Question 1

*Question 2

A: I Solve it
my view

    <?php $numbering = 1;
     foreach ($data1 as $key => $value) : ?>

           <?= $key + 1 ?>
           <?= $value->id?>
           <?= $value->name?>
           <?= $value->question?>
           <?= $value->indicator 1?>
           <?= $value->indicator 2?>
           <?= $value->indicator 3?>
           <?= $value->indicator 4?>
           <?= $value->indicator 5?>

     <?php endforeach; ?>

my model (join function)
function getAll()
{
    $builder = $this->db->table('table2');
    $builder->select('*');
    $builder->join('table1', 'table1.id = table2.id');
    $builder->orderBy('name', 'ASC');
    $query = $builder->get();

    return $query->getResult();
}

my controller
public function index()
{
    $display2= $this->model2->getAll();
    $data = [
        'title' => 'Page Title',
        'data2' => $display2,
        'content'    => 'Backend/viewDisplay'
    ];

    return view('layouts/v_wrapper', $data);
}

i change findAll() to getAll()
thanks to Guido Faecke in comment


text:
Q: JPA foreign key is null in the child table I have below classes i am trying to get onetomany relationship using JPA. When the xml message sent to restcontroller, the message is stored both parent and child table but foreign key is always null. Please let me know if any issue.
Rest Service which i am using to persist the data and the below is the sample xml which i am posting to this rest method.
@RequestMapping(value="/team/", method = RequestMethod.POST , headers="Accept=application/xml")
@ResponseStatus(value = HttpStatus.OK)
public void createTeam(@RequestBody Team team) throws Exception {
    teamService.createTeam(team);
}

Child class
   @XmlRootElement
    @Entity
    public class Player {

        @Id
        @GeneratedValue
        @Column(name = "player_id")
        private long player_id;

        @Column(unique=true , nullable = false)
        private String name;

        @ManyToOne
        @JoinColumn(name = "team_id")
        private Team team;

and setter and getters....
}

and my parent class
   @XmlRootElement
    @Entity(name ="team")
    public class Team {

        @Id
        @GeneratedValue
        @Column(name = "team_id")
        private long team_id;

        @Column(unique=true , nullable = false)
        private String name;

        @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "team")
        private List<Player> player;

and setter and getter
}

@Service
@Transactional
public class TeamServiceImpl implements TeamService{

protected EntityManager entityManager;

    public EntityManager getEntityManager() {
        return entityManager;
    }

    @PersistenceContext
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @Override
    public List<Team> getTeam() {
         Query query = getEntityManager().createQuery("select a from team a");
          List<Team> resultList = query.getResultList();
          return resultList;
    }

    @Override
    public void createTeam(Team team) {
        getEntityManager().persist(team);
    }

}

@Service
@Transactional
public class PlayerServiceImpl implements PlayerService {

    protected EntityManager entityManager;

    public EntityManager getEntityManager() {
        return entityManager;
    }

    @PersistenceContext
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @Override
    public List<Player> getPlayer() {
         Query query = getEntityManager().createQuery("select a from Player a");
          List<Player> resultList = query.getResultList();
          return resultList;
    }

    @Override
    public void createPlayer(Player player) {
        getEntityManager().persist(player);
    }

}

and my xml
<team>
<name>CSK</name>
<Players>
<player>
    <name>kholi</name>
</player>
<player>
    <name>king</name>
</player>
<player>
    <name>raja</name>
</player>
</Players>
</team>

Below is the result i am seeing in the table after creating entry in team. Please note team_id field in player table is null. this is my issue. Need to know how i can fix it so that this field will get team_id value.
mysql> select * from team;
+---------+-------+
| team_id | name  |
+---------+-------+
|       1 | Delhi |
+---------+-------+
1 row in set (0.00 sec)

mysql> select * from player;
+-----------+--------+---------+
| player_id | name   | team_id |
+-----------+--------+---------+
|         1 | kholi1 |    NULL |
|         2 | king   |    NULL |
|         3 | raja   |    NULL |
|         4 | kholi  |    NULL |
|         5 | a      |    NULL |
|         6 | b      |    NULL |
|         7 | c      |    NULL |
|         8 | d      |    NULL |
|         9 | e      |    NULL |
|        10 | f      |    NULL |
|        11 | g      |    NULL |
|        12 | h      |    NULL |
|        13 | i      |    NULL |
|        14 | j      |    NULL |
|        15 | k      |    NULL |
|        16 | l      |    NULL |
|        17 | m      |    NULL |
|        18 | n      |    NULL |
|        20 | sdsdsd |    NULL |
+-----------+--------+---------+
19 rows in set (0.00 sec)

A: Looks like you've saved players, but didn't set Team for them.
You should perform like this:
for (Player player: team.getPlayers())
    player.setTeam(team);

In another way only one property for player is set - its name. JPA is unable to automagically detect that if the player is in players collection than it is in the team.


text:
Q: Body background sourced from PHP variable So I'm trying to set the body background tag to a php variable I created, however I can't get it to correctly work.
Here is the simple PHP:
<?php
$backGround = "images/backgrounds/grey.png";
?>

and here is the HTML I tried which none worked.
<body background="<?php echo $backGround; ?>">
<body background="<?php echo htmlspecialchars($backGround); ?>">

I found these from preview stack overflow questions but they were about setting PHP variables to image sources. I would have thought it would apply to this as well.
Here's my entire PHP page using some of the suggestions but yet to still work.
<?php
$backGround = "images/backgrounds/grey.png";
?>

<title>Exodus</title>
<link rel=StyleSheet href="styles/main.css" type="text/css" media=screen>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<link href='https://fonts.googleapis.com/css?family=Quicksand' rel='stylesheet' type='text/css'>

<body style= 'background-image: url("<?php echo $backGround; ?>")'>

Test

A: First of all - using backgound attribute is not recommended by W3C.
What you really need is inline style:
<body style="background-image: url('<?php echo $backGround; ?>')">

A: check this it will work
   <body style= 'background-image: url("<?php echo $backGround; ?>")'>
     <body style= 'background-image: url("<?php echo htmlspecialchars($backGround); ?>")'>


text:
Q: How to add multiple Y-Values to one X-Value in OxyPlot I need to add several DataPoints with three y-Values and one y-Value. Setting multiple yaxiskeys does not work.
OxyPlots DataPoint only accepts two values (x,y)
I've already tried adding multiple DataPoints with the same x-Value...didnt work fine
plot.Points.Add(new DataPoint(X, Y));
plot.YAxisKey = "y";
plot.XAxisKey = "x";

plot.Points.Add(new DataPoint(X, Y1));
plot.YAxisKey = "y1";

plot.Points.Add(new DataPoint(X, Y2));
plot.YAxisKey = "y2";

Any ideas?


text:
Q: Possible for input/useState not to be set on button click? Do I need to worry that fetchClassesSearchedByName(searchName); will not have a searchName value? Is it possible my button click is faster than searchName being set?
// On input
const [searchName, setSearchName] = useState('');

// Text input
<input
    type='text'
    value={searchName}
    onChange={(e) => setSearchName(e.target.value)}
/>

// On button click
const searchNameBtn = (e) => {
        fetchClassesSearchedByName(searchName);
}

Thank you

A: setState is asynchronous, so it is possible if you've got the reflexes of an old west gunslinger.
Your default value is '', though, so I don't think you'll need any error handling as long as fetchClassesSearchedByName can take an empty string.

A:
Do I need to worry that fetchClassesSearchedByName(searchName); will
not have a searchName value?

You have defined initial searchName state and all the setSearchName calls pass valid defined values. And so long as all state updates are valid defined values, there's no chance for fetchClassesSearchedByName to be called without a defined searchName value.

Is it possible my button click is faster than searchName being set?

Yes, this is entirely possible, BUT also entirely unrealistic. It's possible because React state updates are not immediate, but are enqueued and asynchronously processed.
Consider the follow example. There are two inputs with onChange handlers.

*

*Input and handler #1: The first input attempts to simulate clicking the button immediately after enqueueing a state update, but due to the way Javascript enclosures and the event loop work, the button's onClick event is processed before React processes the state update because it's synchronous within the onChange handler function's scope. The fetchClassesSearchedByName appears to be a "render cycle behind" because it's logging the unupdated state.

*Input and handler #2: The second input attempts to simulate clicking the button immediately after enqueueing a state update, but uses a setTimeout of 0. This places the click event callback at the end of the event queue. Note that this is the earliest possible the button can even be clicked after the state update was enqueued. React's state update is processed, then the click event is processed. Note here that the fetchClassesSearchedByName now always sees the updated React state.

const fetchClassesSearchedByName = (value) => console.log(value);

function App() {
  const buttonRef = React.useRef();
  const [searchName, setSearchName] = React.useState("");

  const changeHandler1 = (e) => {
    setSearchName(e.target.value);
    buttonRef.current.click();
  };

  const changeHandler2 = (e) => {
    setSearchName(e.target.value);
    setTimeout(() => {
      buttonRef.current.click();
    }, 0);
  };

  const searchNameBtn = (e) => {
    fetchClassesSearchedByName(searchName);
  };

  return (

          Input 1 w/ synchronous button click
          <input type="text" value={searchName} onChange={changeHandler1} />

          Input 2 w/ asynchronous button click
          <input type="text" value={searchName} onChange={changeHandler2} />

        <button ref={buttonRef} type="button" onClick={searchNameBtn}>
          Click me
        </button>

  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(
  <App />,
  rootElement
);


text:
Q: Laravel unable to retrieve the correct current page no. which result pagination is not working(showing the first page result only) Let us consider an example
https://www.example.net/xyz?page=2
Route::get('/xyz', 'controller@getpages');

public function getpages() {
  $variable=Model::paginate(10);
  dd($variable);
}

i have done "dd($variable);" in function . which gives the result of
LengthAwarePaginator {#1209 ▼
#total: 4341
#lastPage: 435
#items: Collection {#1211 ▶}
#perPage: 10
#currentPage: 1
#path: "www.example.net/xyz"
#query: []
#fragment: null
#pageName: "page"
}

dd($request);
Request {#38 ▼
  #json: null
  #convertedFiles: null
  #userResolver: Closure {#1028 ▶}
  #routeResolver: Closure {#1029 ▶}
  +attributes: ParameterBag {#40 ▶}
  +request: ParameterBag {#46 ▶}
  +query: ParameterBag {#46 ▶}
  +server: ServerBag {#42 ▶}
  +files: FileBag {#43 ▶}
  +cookies: ParameterBag {#41 ▶}
  +headers: HeaderBag {#44 ▶}
  #content: null
  #languages: null
  #charsets: null
  #encodings: null
  #acceptableContentTypes: null
  #pathInfo: "/xyz"
  #requestUri: "/xyz?page=2"
  #baseUrl: ""
  #basePath: null
  #method: "GET"
  #format: null
  #session: Store {#112 ▶}
  #locale: null
  #defaultLocale: "en"
  -isForwardedValid: true
}

dd($request->all());
it is showing
array:1 [▼
  "/xyz" => null
]

in the site which have error. but rest of the sites whose pagination working properly . gives the below output.
array:1 [▼
 "page" => "2"
]

instead of #currentPage: 2 . it was working properly, But from yesterday it is happening like this through all our site. so how can I fix this?
Note: I have used this same code in multipage sites. but it is not working in it only
i got the proper issue here.In our whole site the passing to controller . and in validation . it is not mention how can i resolve this.

A: Defected htaccess file
   RewriteEngine On
    RewriteCond %{HTTP:X-Forwarded-Proto} !https
    RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

    #RewriteEngine On
    #RewriteCond %{REQUEST_FILENAME} !-f
    #RewriteCond %{REQUEST_FILENAME} !-d
    #RewriteRule ^(.*)$ /index.php?/$1 [L]

    RewriteEngine On
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

    #RewriteCond %{THE_REQUEST} ^.*/index\.php
    #RewriteRule ^(.*)index.php$ /$1 [R=301,L]
    ##Redirect 301 /index.php https://www.example.net/
    #RewriteEngine On
    #RewriteCond %{HTTP:X-Forwarded-Proto} !https [OR]
    #RewriteCond %{HTTP_HOST} !^www. [NC]
    #RewriteRule ^(.*)$ https://www.example.net/$1 [L,R=301]

    <IfModule mod_rewrite.c>
        <IfModule mod_negotiation.c>
            Options -MultiViews
        </IfModule>

        RewriteEngine On
        RewriteBase /
        RewriteRule ^api/(.*)?$ http://127.0.0.1:8888/$1 [P,L]
        # Redirect Trailing Slashes If Not A Folder...
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)/$ /$1 [L,R=301]

        # Handle Front Controller...
        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)$ /index.php?/$1 [L]

        # Handle Authorization Header
        RewriteCond %{HTTP:Authorization} .
        RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
    </IfModule>

corrected htaccess file
    RewriteEngine On
    RewriteCond %{HTTP:X-Forwarded-Proto} !https
    RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

    RewriteEngine On
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

    #RewriteEngine On
    #RewriteCond %{REQUEST_FILENAME} !-f
    #RewriteCond %{REQUEST_FILENAME} !-d
    #RewriteRule ^(.*)$ /index.php?/$1 [L]

    #RewriteCond %{THE_REQUEST} ^.*/index\.php
    #RewriteRule ^(.*)index.php$ /$1 [R=301,L]
    ##Redirect 301 /index.php https://www.example.net/
    #RewriteEngine On
    #RewriteCond %{HTTP:X-Forwarded-Proto} !https [OR]
    #RewriteCond %{HTTP_HOST} !^www. [NC]
    #RewriteRule ^(.*)$ https://www.example.net/$1 [L,R=301]

    <IfModule mod_rewrite.c>
        <IfModule mod_negotiation.c>
            Options -MultiViews
        </IfModule>

        RewriteEngine On
        RewriteBase /
        RewriteRule ^api/(.*)?$ http://127.0.0.1:8888/$1 [P,L]
        # Redirect Trailing Slashes If Not A Folder...
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)/$ /$1 [L,R=301]

        # Handle Front Controller...
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^ index.php [L]

        # Handle Authorization Header
        RewriteCond %{HTTP:Authorization} .
        RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
    </IfModule>

A: I have tried your code, working fine for me. couldn't able to find out the problem with your code based on the information given. if it is not working, please set the currentPage manullay in you controller. so you controller would be like
 public function getpages(Request $request) {
   Paginator::currentPageResolver(function() use ($request){
       return $request->page;
   });
   $variable=Model::paginate(10);
   dd($variable);
 }


text:
Q: Apache Camel - method shortcut to jump to aggregator when exception thrown in the middle of a multiple step split route I'd like to ask if there is some way to skip rest of the split route and jump directly to aggregator part, when in the exception handler I mark the split route to continue.
I have a route like this:

*

*receive a message

*fetch config for 3 endpoints

*merge config and message as a tuple for each endpoint, and create a list of it

*.split(), and in the split route I convert message according to config for each endpoint(s1), fetch oauth token(s2), send to final endpoint with token(s3), collect response for each endpoint(s4), aggregate(split aggregator; splitting ends here, let's call it sa)

*return as a whole one result

*stop

You can see, in the split route there are 4 steps(s1-s4); if any of these step fails I want to jump to aggregation(sa). For example, it does not make sense to continue the split route, if s1 or s2 fails.
I define an onException() clause to handle the exception and mark it to continue(continued(true)),because anyway I want to reach aggregator. Also, if I mark continue(false), not only split route, but the whole route(meaning the main route even before splitting) will be rolled back. I want to decide rollback after getting all the causes/exceptions in each split branch.
I have a workaround for a simple case, which is, in exception handler for errors in s2, I add a property in the exchange oauth_failed to be true, and add a condition check choice().when() after s2; if this prop is null, then go to s3 (continue sending). Solely for this purpose I must isolated s3 as a separate route(direct:s3).
.bean(S2Bean.class)
.choice()
    .when(simple("${exchangeProperty.oauth_failed} == null")) // null = continue the flow
        .to("direct:s3")
    .endChoice()
    // otherwise, it will skip s3 and s4, and jump to aggregator directly
.end()

But, what can I do if s1 throws exception? Do I need to isolate s2 as a direct endpoint too? Then each step in the pipeline should be a separate endpoint. I don't like that.

A: Find a solution: use doTry and doCatch in split route and don't .stop().
from("direct:split")
    .doTry()
        .bean(S1Bean.class)
        .bean(S2Bean.class)
        .bean(S3Bean.class)
        .bean(S4Bean.class)
    .endDoTry()
    .doCatch(javax.ws.rs.ProcessingException.class) // oauth timeout
        .log(LoggingLevel.ERROR, "Time out, never retry, just aggregate")
        .bean(MyGenericExceptionHandler.class)
    .doCatch(Exception.class)
        .log(LoggingLevel.ERROR, "Other exceptions, mark as failed, aggregate")
        .bean(MyGenericExceptionHandler.class)
    .end();

And in the MyGenericExceptionHandler, exchange.getIn().setBody(xxx) to set body to the expected type which my aggregator needs. The exception is in exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class), response code is null. (I create a dto to contain both status code and/or exception, so that either success or failure, I aggregate with same class)
Don't call stop().


text:
Q: jQuery CSS 'display: none' issue sometimes on PageLoad I am loading some text from a database via $.post. Sometimes on page load the screen is just blank, when I inspect element the div it is set to
, I don't know why this is happening, though before the $.post I am fading out the div and when the $.post gets an output, I bring back the div.
$('#panel').html(output).show();
I am using $("#panel").fadeOut(100); so I can make my loading.gif work.
Is there any way to check if #panel's style is set to display:none and if it is, then remove it.
Thanks.
EDIT: My function I call on checkbox change and page load
$("#loading").show();
$("#panel").fadeOut(100);
$('#options :input').prop('disabled', true);
$('#loading').html("");
var langSelected = $('input[name=text]:checked').map(function() {return $(this).parent().text();}).get().join(",");

$.post('http://mywebsite.com/data.php', { value: languages.url.value, mycheckboxes: langSelected},
function(output) {
    $('#panel').html(output).show();
    $('#loading').hide();
    $('#options :input').removeAttr('disabled');

});

A: Try this:
if ($('#panel').is(':hidden')) {
     $('#panel').remove()
}

or:
$('#panel:hidden').remove()

However instead of removing the div you can use the error method:
$.post("example.php", function() {
      // success
}).error(function() {
      $('#panel').show()
      // error
})


text:
Q: Define custom model/architecture in TensorFlow From the little I have played around with TensorFlow I see it has already-implemented architectures like RNN/LSTM cells, ConvNets, etc. Is there a way to define one's "custom" architecture (e.g. an "enhanced" LSTM network with a few convolutional layers)?

A: Yes, it is totally possible. The output of LSTM or any network are tensors which cab used as input of another network.
See how to combine them at https://github.com/jazzsaxmafia/show_and_tell.tensorflow.
You can find more examples at https://github.com/TensorFlowKR/awesome_tensorflow_implementations.


text:
Q: How to detect screen change in class component with navigation v6? I just want to clear the state when you move to any other screen in my class component when I'm using navigation v6 (I saw some coments about function component but not class), so I will explain briefly
I did a clean state function in my Body component
class InputBody extends Component {
  constructor(props) {
    super(props);
    this.state = {
      fields: JSON.parse(this.props.route).message,
    };
  }

  reset () {
    this.setState({});
  }

  render() {
    return (
      <Fragment>
        {Object.keys(JSON.parse(this.props.route).message).length > 0 ? (
          <FieldArraysForm all={JSON.parse(this.props.route).message} resetForm={reset} native={this.props} />
        ) : (
          <ActivityIndicator size="large" color="#eb6b09" />
        )}
      </Fragment>
    );
  }
}

And then I call it in my fields array component
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
class FieldArraysForm extends Component {
  render() {
    const {handleSubmit} = this.props.native;
    // event listener
    const getFields = async (values) => {
      return sleep(500).then(() => {
        console.log(JSON.stringify(values))
        this.props.resetForm();
      })
    }
    return (
      <Form>
        {this.props.all.map((item) => (
          <Field
            key={item._id}
            name={`customInput.${item._id}`}
            component={RenderField}
            label={item.field}
            type={item.typeFieldAltText}
          />
        ))}
        <View>
          <TouchableOpacity onPress={handleSubmit(getFields)}>
            <Text>Save Form</Text>
          </TouchableOpacity>
        </View>
      </Form>
    );
  }
}

Render field function component
   class RenderField extends Component {
      render() {
        return (
          <Fragment>
            <Texto>{this.props.label}</Texto>
            <TextInput
              onChangeText={this.props.input.onChange}
              {...this.props.input}
              keyboardType={this.props.type}
            />
          </Fragment>
        );
      }
    }

So how can I call this.prop.reset() on screen change using class component with react navigation v6 ?


text:
Q: Reversing a hash to find something which works, but hashcat seems to have issues I saw some unfamiliar code on a project i was working on.
I saw a function which said:
var salt = 1514691869198;
var result hex_hmac_sha1(salt, hmac_sha1(password))
# result is: 462435F34EAD6BB7C70751D90984DADD90EED9A4

I was having some issues with hashcat though. It seems to be getting killed early because of a driver or something.
It seems that option -m160 would be the one I would want to use since 160 = HMAC-SHA1 (key = $salt) in the man page for it.
Given the sha1.js file i was looking at, which gave me the code above, it showed the salt as the key which makes me think the 160 code as the most relevant.
Obviously this is a nested sha, but trying to find something to reverse it would be ideal.
I am aware reversing a hash would not return the actual password, but I figured I could run a wordlist and attempt to find a hash which matches this one.
That being said, I was thinking I can find a string which works.  I am having issues though building either the hashcat command or finding this answer in general.  I was not sure how i would want to put the hash in the command.  I was thinking it would be along the lines of:
hashcat -m160 462435F34EAD6BB7C70751D90984DADD90EED9A4: 1514691869198 mywordlist.txt

but it seems to fail for me with the following:
* Device #1: Not a native Intel OpenCL runtime. Expect massive speed loss.
         You can use --force to override, but do not report related errors.
No devices found/left.

Started: Sat Dec 30 22:52:33 2017
Stopped: Sat Dec 30 22:52:33 2017

and if i used --force it would say:
hashcat (pull/1273/head) starting...

OpenCL Platform #1: The pocl project
====================================
* Device #1: pthread-Intel(R) Core(TM) i7-4770HQ CPU @ 2.20GHz,
2656/2656 MB allocatable, 1MCU

Hashes: 1 digests; 1 unique digests, 1 unique salts
Bitmaps: 16 bits, 65536 entries, 0x0000ffff mask, 262144 bytes, 5/13
rotates
Rules: 1

Applicable optimizers:
* Zero-Byte
* Not-Iterated
* Single-Hash
* Single-Salt

Watchdog: Hardware monitoring interface not found on your system.
Watchdog: Temperature abort trigger disabled.
Watchdog: Temperature retain trigger disabled.

* Device #1: build_opts '-I /usr/share/hashcat/OpenCL -D VENDOR_ID=64 -D CUDA_ARCH=0 -D VECT_SIZE=1 -D DEVICE_TYPE=2 -D DGST_R0=3 -D DGST_R1=4 -D DGST_R2=2 -D DGST_R3=1 -D DGST_ELEM=5 -D KERN_TYPE=160 -D _unroll -cl-std=CL1.2'
* Device #1: Kernel m00160_a0.0bbec6e5.kernel not found in cache! Building may take a while...
Kernel library file /usr/share/pocl/kernel-i686-pc-linux-gnu.bc doesn't exist.

A: Try reading How to use hashcat on CPU only
Relevant parts:

*Download latest OpenCL Drivers and Runtimes for CPU:
  https://software.intel.com/en-us/articles/opencl-drivers#latest_CPU_runtime
  Latest release (16.1.1) – at time of writing


text: Q: Representing a Number as the Sum of Powers of Form $k^k$. So I was wondering if it would be useful to instead of writing a number in base $2$ or $3$, we use functions in general as bases. So like writing it as the sum of squares or other increasing functions. So for a number $N$, its base $f(n)$ representation could be found basically in the same way that you would find the base $2$ representation of $N$. The representation could be written as a "string" of characters and each character could be written in its binary representation. For example, $8153 = [1000][1][101][11]$ which took $10$ bits to write out. I wanted to see if there was a function that would dramatically reduce the number of bits required to store a number.


text:
Q: Which Programming Language have a best image filter? Which programming language has best possible image filter and also provide art photo effect and oil paint effect. I've also tried in php-imagick, python-opencv, css, and javascript but they do not exactly provide art effect and oil paint effect.
Prisma app also provide art and oil paint effect but they use neural network and ai technology so how can I use this both technology for my project.

A: As you have mentioned php-imagick and python-opencv, what you need is a library that provides you the tools you want, the programming language is irrelevant.
Have a look at G'MIC and the image gallery.


text:
Q: How to get li chechbox checked status in jquery How to get li checkbox checked status in jquery.
I want like this one, but its throw me undefined.
$('#ul'+$Id+' li:nth-child('+_index+') span input:checkbox').attr("checked")

can anyone help from out of this one.

A: Use .is(':checked') on your jQuery object.
$('#ul'+$Id+' li:nth-child('+_index+') span input:checkbox').is(':checked');

A: Why variable $id in javascript??
   Is _index variable?
You can check a check-box like
$(selector).prop('checked', true);
$(selector).prop('checked', false);
$(selector).attr('checked','checked');
$(selector).removeAttr('checked');
alert($(selector).is(':checked'));


text:
Q: Same content shared between multiple posts? I want to have some cotent shared between various posts.
Why?
I am writing a series of posts on backbone js. The thing is every post has some common content ie from where you can download the source code etc. Now everytime I  want to make a new post, I just copy paste that same content. Now one problem is: modifying the content. Today I want to modify the content in all the post. Now I have to manually edit the content in each post.
It will be great if I can use a shared copy something like partial in ruby on rails and just edit that shared copy and all the post having that shared copy get modified.
Any suggestions, plugins etc.

A: Register a custom taxonomy, filter the_content, and add the term description.


text:
Q: ASP.NET MVC : dropdown positioning and save I have this in my view :
@Html.DropDownList("LookupTypeImmobilier", new SelectList(Model.LkpTypeImmobilier, "Code", "Value", Model.LookupTypeImmobilier.Code))

The lookup class has the properties : Id, FR, NL, Value and Code. The Value is text show in the dropdown.
LkpTypeImmobilier is the list and LookupTypeImmobilier is the selected, the values are correct (see the pictures) but the dropdown is not setted.
When I select and I post like this :
var jqxhr = $.post("Controller/Action", $("form").serialize(),
function (data) {
});

The values coming from textbox, textarea are posted and I get them in the controller but not the dropdown.
Do you have an idea ?
Thanks,

Update 1 (ShankarSangoli request)
<select id="LookupTypeImmobilier" name="LookupTypeImmobilier"><option value="0">----</option>
<option value="1">habitation principale / logement familial</option>
<option value="2">résidence secondaire</option>
<option value="3">immeuble de rapport</option>
<option value="4">terrain à bâtir</option>
<option value="5">terre agricole</option>
<option value="6">bois</option>
</select>

Update 2
Tried with this but not work (null when I post and no positioning)
@Html.DropDownListFor(m => m.LookupTypeImmobilier, new SelectList(Model.LkpTypeImmobilier, "Code", "Value", Model.LookupTypeImmobilier))

Update 3
No solution then I use a workaround. I post with jQuery field by field and not the model. In edition I set the dropdown list position by jQuery. It's really not the right way but work, I hope find a solution.

A: Explain please, "The lookup class has the properties : Id, FR, NL, Value and Code", but your view has @Html.DropDownList("LookupTypeImmobilier"...
can you write something like:
@Html.DropDownListFor(m => m.Value,new SelectList(/**/))

Sorry, maybe I understand something wrong :)

A: The following should work:
@Html.DropDownListFor(
    m => m.LookupTypeImmobilier,
    new SelectList(Model.LkpTypeImmobilier, "Code", "Value")
)

Now in order to set a default value for the dropdownlist ensure that your controller action sets a value of the LookupTypeImmobilier on the view model:
var model = new MyViewModel
{
    // Preselect the third element which in the rendered HTML has value="3"
    LookupTypeImmobilier = "3",
    LkpTypeImmobilier = ...
}
return View(model);

Make sure that the value you are setting the LookupTypeImmobilier property to exists in the LkpTypeImmobilier collection. This will automatically preselect the corresponding element of the dropdownlist. And it should correspond to the Code property, not the Value.
As far as getting the selected value back in your POST controller action is concerned, simply use this same view model as action argument:
[HttpPost]
public ActionResult Foo(MyViewModel model)
{
    // model.LookupTypeImmobilier will contain the selected value here
    ...
}


text:
Q: Does one get any set of positive roots by "cutting" with a hyperplane? If $\Phi$ is the root system of a complex semisimple Lie algebra $\mathfrak{g}$, then one way to choose a set $\Phi^+$ of positive roots is by choosing a hyperplane which does not contain any root, which will partition (by looking at the corresponding two half-spaces) the set of roots $\Phi$ into two subsets. Either one of these two subsets can be taken to be $\Phi^+$.
My question is about the converse. Can any set $\Phi^+$ of positive roots be obtained by this construction?
I am mostly interested in $A_n$ but the question makes sense in general.

A: Let $V$ be the real vector space spanned by the root system, and let $L: V \rightarrow \mathbb R$ be any linear functional with the property that $L(\Phi^+) \subset \mathbb R_{> 0}$; then $\ker(L)$ is a hyperplane that does the job.
One obvious choice for $L$ is as follows: From your $\Phi^+$, choose a set of simple roots $\alpha_i$, $1 \le i \le n$. It is well known that the $\alpha_i$ are a basis of $V$, and a root $\alpha = \sum_{i=1}^n c_i \alpha_i$ is in $\Phi^+$ if and only if all $c_i \in \mathbb Z_{\ge 0}$. Now set $L(\sum_{i=1}^n c_i \alpha_i) := \sum_{i=1}^n c_i$.
(With respect to the basis $(\alpha_i)_i$, this is the functional $(1,1, ...,1)^{tr}$. Notice that because of the fact that for all roots, the coefficients $c_i$ are either all $\ge 0$ or all $\le 0$, one actually has a lot of "wiggle room": any $(\ell_1, ..., \ell_n)^{tr}$ with all $\ell_i > 0$ gives another suitable hyperplane.)


text:
Q: Inner Join & PHP So this is my first time properly approaching INNER JOIN Statements and I have been trying my hand at it, needless to say it isnt going well. Below is my page code:
<?php require_once('Connections/reps.php'); ?>
<?php

if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

mysql_select_db($database_reps, $reps);
$query_orders = "SELECT * FROM orders";
$orders = mysql_query($query_orders, $reps) or die(mysql_error());
$row_orders = mysql_fetch_assoc($orders);
$totalRows_orders = mysql_num_rows($orders);

mysql_select_db($database_reps, $reps);
$query_staff = "SELECT * FROM staff";
$staff = mysql_query($query_staff, $reps) or die(mysql_error());
$row_staff = mysql_fetch_assoc($staff);
$totalRows_staff = mysql_num_rows($staff);

mysql_select_db($database_reps, $reps);
$query_products = "SELECT * FROM products";
$products = mysql_query($query_products, $reps) or die(mysql_error());
$row_products = mysql_fetch_assoc($products);
$totalRows_products = mysql_num_rows($products);

mysql_select_db($database_reps, $reps);
$join = "SELECT
orders.ID AS id,
orders.CustomerName AS customerName,
orders.StaffMember AS staffMember,
orders.SalesPrice AS salesPrice,
orders.ListPrice AS listPrice,
orders.AgeOfPayment AS productAge,
orders.Product AS productName,
orders.Quantity AS orderQuantity,
orders.DateOfOrder AS orderDate,
staff.Bonus AS staffBonus,
products.Price AS productPrice
FROM
orders AS orders
INNER JOIN staff AS staff ON orders.StaffMember = staff.StaffName
INNER JOIN products AS products ON orders.Product = products.ProductName
ORDER BY
orderDate ASC";

$joinresult = mysql_query($join);

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<?php

require_once("models/config.php");
if (!securePage($_SERVER['PHP_SELF'])){die();}
require_once("models/header.php");

?>

Change This

    <?php include("left-nav.php"); ?>

          Order ID
          Customer Name
          Product
          Quantity
          Sales Price (€)
          Total Sale (€)
          List Price (€)
          Price Difference (€)
          % Difference
          Sold By
          Order Date
          Age of Payment
          Bonus %
          Bonus Amount

        <?php do { ?>
        <?php do { ?>

            <?php echo $row_orders['ID']; ?>
            <?php echo $row_join['customerName']; ?>
            <?php echo $row_join['product']; ?>
            <?php echo $row_orders['Quantity']; ?>
            <?php echo $row_orders['SalesPrice']; ?>
            <?php $first_multiply = $row_orders['Quantity'];
                                               $second_multiply = $row_orders['SalesPrice'];
                                               $multiply_total = $first_multiply *  $second_multiply;
                                               echo ($multiply_total); ?>
            <?php echo $row_orders['Price']; ?>
            <?php $first_number = $row_orders['Price'];
                                                $second_number = $row_orders['SalesPrice'];
                                                $sum_total = $first_number - $second_number;
                                                echo ($sum_total); ?>
            as
            <?php echo $row_join['staffMember']; ?>
            <?php echo date('d/m/Y', $row_orders['orderDate']); ?>

            <?php echo $row_orders['bonus']; ?>%

          <?php } while ($row_orders = mysql_fetch_assoc($orders));?>
          <?php } while ($row_join = mysql_fetch_array($join));?>

<?php
mysql_free_result($orders);

mysql_free_result($staff);

mysql_free_result($products);
?>

What I am basically trying to do is the following:

*

*An order is submitted from a page before this. The data is stored on the table in the database and echoed out.

*The three tables in question are the staff, orders and products tables

*I saved the form based on the ID and not the value. I have googled and researched INNER JOIN and I tried the below which didn't work.

Anyone able to point me in the right direction as to what I am doing wrong?

A: I would do the join like this:
$join = "SELECT  o.ID id,
                 o.CustomerName customerName,
                 o.StaffMember staffMember,
                 o.SalesPrice salesPrice,
                 o.ListPrice listPrice,
                 o.AgeOfPayment productAge,
                 o.Product productName,
                 o.Quantity orderQuantity,
                 o.DateOfOrder orderDate,
                 s.Bonus staffBonus,
                 p.Price productPrice
         FROM
                 orders o,
                 staff s,
                 products p
         WHERE
                 o.StaffMember = s.StaffName
         AND
                 o.Product = p.ProductName
         ORDER BY
                 orderDate";

since you have 2 conditions when joining 3 tables, you will get all results.  You can put in another AND where you present something unique to the orders table and get this information about a specific order.

A: One thing to note is that mysql_ functions are deprecated in PHP now. You may want to switch to mysqli_ (is very comparable to the mysql_ class) or PDO.

A: SELECT
o.ID,
o.CustomerName,
o.StaffMember,
o.SalesPrice,
o.ListPrice,
o.AgeOfPayment,
o.Product,
o.Quantity,
o.DateOfOrder,
s.Bonus,
p.Price
FROM
`orders` o
INNER JOIN staff AS s ON o.StaffMember = s.StaffName
INNER JOIN products AS p ON o.Product = p.ProductName
WHERE o.StaffMember = s.StaffName
AND o.Product = p.ProductName
ORDER BY
orderDate ASC";

However, I have a feeling that your tables are not constructed well. I would suggest using IDs instead of Product = ProductName etc.


text:
Q: Error while implementing Google Play Games I am getting an error on an import statement that I am using in order to try and implement Play Games with my app.
-The import com.google.android.gms.games.GamesClient cannot be resolved
I have BaseGameUtils referecncing google-play-services_lib, and my project references BaseGameUtils as a library.
It's my understanding that GameClient was to have been deprecated as of February 7, 2014 but when looking at Google's sample code (e.g. ButtonClicker) it still uses this import and some of the method calls from the import.
I got the code I am using from Google's GitHub sample app repository  for the ButtonClicker2000, some of that code has been recycled and used in the program I'm having errors with as well.
This is all the info I can think to provide, if anything more would help please let me know.

A: I was struggling with the ButtonClicker2000 example for a couple days and I was having the same problem as yours.
I think the problem in the sample code is having some lines being not updated. If you look at that page, you can easily see that the updated versions of those lines are lying there. However the codes in GitHub page are not updated completely.
Because GamesClient class is removed permanently, those statements
GamesClient.EXTRA_PLAYERS
GamesClient.EXTRA_MIN_AUTOMATCH_PLAYERS
GamesClient.EXTRA_MAX_AUTOMATCH_PLAYERS
GamesClient.EXTRA_INVITATION
GamesClient.STATUS_OK

must be replaced with
Games.EXTRA_PLAYERS_IDS
Multiplayer.EXTRA_MIN_AUTOMATCH_PLAYERS
Multiplayer.EXTRA_MAX_AUTOMATCH_PLAYERS
Multiplayer.EXTRA_INVITATION
GamesStatusCodes.STATUS_OK

Also that line can be removed:
import com.google.android.gms.games.GamesClient;

There is no need for importing GoogleApiClient because it is already imported in GameHelper.java.
After changing these lines manually and importing Multiplayer and GamesStatusCodes classes, I was successful to compile the code. I hope that solves your problem as well.


text:
Q: problema recorrer un Array y sacar el dato correcto Php Buenas tengo este Array:
   $array  = array (
    'id' => 457243060,
    'album_id' => -3,
    'owner_id' => 208428341,
    'sizes' => array (
      array (
        'type' => 's',
        'url' => 'https://sun9-67.userapi.com/c857616/v857616133/1a62f4/eS7hlSZYlHE.jpg',
        'width' => 75,
        'height' => 75
      ),
      array (
        'type' => 'm',
        'url' => 'https://sun9-29.userapi.com/c857616/v857616133/1a62f5/oYJdSRKPbfY.jpg',
        'width' => 130,
        'height' => 130
      ),
      array (
        'type' => 'x',
        'url' => 'https://sun9-16.userapi.com/c857616/v857616133/1a62f6/-NHOu25XkDk.jpg',
        'width' => 604,
        'height' => 604
      ),
      array (
        'type' => 'y',
        'url' => 'https://sun9-14.userapi.com/c857616/v857616133/1a62f7/34fwsN3EFEc.jpg',
        'width' => 807,
        'height' => 807
      ),
      array (
        'type' => 'z',
        'url' => 'https://sun9-64.userapi.com/c857616/v857616133/1a62f8/8jDB0yaqEk4.jpg',
        'width' => 1080,
        'height' => 1080
      ),
      array (
        'type' => 'w',
        'url' => 'https://sun9-40.userapi.com/c857616/v857616133/1a62f9/ToyJjVZXaUg.jpg',
        'width' => 1280,
        'height' => 1280
      ),
      array (
        'type' => 'o',
        'url' => 'https://sun9-32.userapi.com/c857616/v857616133/1a62fa/7z-veU2v_1o.jpg',
        'width' => 130,
        'height' => 130,
      ),
      array (
        'type' => 'p',
        'url' => 'https://sun9-56.userapi.com/c857616/v857616133/1a62fb/dD_sshumBxE.jpg',
        'width' => 200,
        'height' => 200
      ),
      array (
        'type' => 'q',
        'url' => 'https://sun9-62.userapi.com/c857616/v857616133/1a62fc/qkCjR4c_k_M.jpg',
        'width' => 320,
        'height' => 320
      ),
      array (
        'type' => 'r',
        'url' => 'https://sun9-48.userapi.com/c857616/v857616133/1a62fd/NuONkTQdEkE.jpg',
        'width' => 510,
        'height' => 510
      )
    ),
    'text' => '',
    'date' => 1584084929,
    'access_key' => 'b97d42f1637ed7d825'
  );

Necesito ayuda para obtener la imagen más grande de este array, e provado de varias maneras, como por ejemplo:
$contenido="";
foreach($array["items"] as $row){
    $contenido .= $row["id"].PHP_EOL;
}

Pero no me funciona espero alguna idea.

A: Una forma simple de hacerlo sería:

*

*Obtener el mayor width en el array general mediante el uso de max() combinado con array_column()

*Buscar dentro del sub-array sizes el sub-array completo que tenga el width encontrado en (1)

Veamos:
#(1) Obtenemos el mayor width
$max=max(array_column($mData["sizes"], 'width'));
#Array que tendrá los datos del mayor
$maxSize=array();

foreach ($mData["sizes"] as $size) {
    #(2) Verificamos si es el width que encontramos en (1)
    if ($size["width"] == $max) {
        $maxSize=$size;
        #Salimos del bucle porque ya encontramos lo que queríamos
        break;
    }
}
#Test ... bórralo luego
var_dump($maxSize);

Salida:
array(4) {
  ["type"]=>
  string(1) "x"
  ["url"]=>
  string(18) "https://sun......."
  ["width"]=>
  int(1280)
  ["height"]=>
  int(1280)
}

DEMOSTRACIÓN

PD: Si te interesara hacer algo parecido con otra clave, convendría incorporar el código a una función que reciba en parámetro el nombre de las claves, tanto del padre (sizes)  como del hijo (width).

A: Prueba con esto haber si te funciona:
function maxImageSize ($array) {
  $max = 0;
  $maxImage = null;
  foreach ($array['sizes'] as $image) {
    if ($max < $image['width']) {
      $max = $image['width'];
      $maxImage = $image;
    }
  }
  return $maxImage;
}

A: Para éste caso y otros poco mas complejos como imágenes que no son cuadradas ó si necesitas otro valor del mismo elemento, la función map_reduce reduce a un solo valor un arreglo usando una función de llamada de retorno:
$masGrande = array_reduce( $array['sizes']
                         , function($max, $size){
                                return ( !isset($max)
                                       ? $size
                                       : ( $max['width']*$max['height'] > $size['width']*$size['height']
                                         ? $max
                                         : $size
                                        )
                                       );
                           }
                        );
print_r($masGrande);

Aquí la función simplemente compara las dimensiones (área) y regresa el mayor (no-nulo) con ayuda de un par de ifs en línea.
Resultado:
Array
(
    [type] => w
    [url] => https://sun9-40.userapi.com/c857616/v857616133/1a62f9/ToyJjVZXaUg.jpg
    [width] => 1280
    [height] => 1280
)


text:
Q: Overlapping Grouping in Crystal reports I have a dataset with some numbers for each month.
For example:
1/1/2009   param1 param2
2/1/2009   param1 param2
3/1/2009   param1 param2
What I need is to show 4 lines of summary:

*

*last 6 months

*this year (last 12 months)

*last year (12 to 24 months ago)

*total

I was thinking of adding a parameter for each record that assings each record to a specific time frame (6 months ago, 12 months ago, etc.). But groups 1 and 2 are overlapping, so some records would belong to both.
Do you have any suggestions on how to display such a summary?
Thanks a lot!
Irene

A: You can use Running Totals with an evaluate formula to only total certain rows. Assuming you have an {asofdate} parameter and the {month} data field...

*

*last 6 months
datediff("m", {month}, {asofdate}) <= 6

*this year (last 12 months)
datediff("m", {month}, {asofdate}) <= 12

*last year (12 to 24 months ago)
datediff("m", {month}, {asofdate}) >= 13
and datediff("m", {month}, {asofdate}) <= 24

*total
just use a sum


text:
Q: How to redirect to a view controller based on the status of location services in iOS I'm using the following code to check to see if the user's location services for the app have changed. If they change they should view a different view controller. It really only needs to run each time the app launches and then redirect based on the [CLLocationManager authorizationStatus] status
the problem with my  code is that everytime the location updates the segue is ran.
thanks for any help
- (void)locationUpdate:(CLLocation *)location {
//locLabel.text = [location description];

NSLog(@"auth status is %u", [CLLocationManager authorizationStatus]);

if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized) {
    [self performSegueWithIdentifier: @"SegueOffersGPS" sender: self];

} else {

    [self performSegueWithIdentifier: @"SegueOffersNoGPS" sender: self];

}

A: If you want to stop updating location then write below code
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
     [self.locationManger stopUpdatingLocation];
}


text:
Q: Simple Pie "set_item_limit" doesn't I'm struggling to get set_item_limit to work. The feed comes in fine, but just renders every post. Here's the code I'm using:
// Make sure SimplePie is included. You may need to change this to match the location of autoloader.php
// For 1.0-1.2:
#require_once('../simplepie.inc');
// For 1.3+:
require_once('php/autoloader.php');
// process this feed with all of the default options.
$feed = new SimplePie();
// Set which feed to process.   http://simplepie.org/blog/feed/
$feed->set_feed_url('https://api.twitter.com/1/statuses/user_timeline.rss?screen_name=Tweet_Yourself');
// Run SimplePie.
$feed->set_item_limit(5);
$feed->init();
// This makes sure that the content is sent to the browser as text/html and the UTF-8 character set (since we didn't change it).
$feed->handle_content_type();

And here's the HTMLy bit:
<?php
//loop through all of the items in the feed, and $item represents the current item in the loop.
foreach ($feed->get_items() as $item): ?>

<a href="<?php echo $item->get_permalink(); ?>"><?php echo $item->get_title(); ?>

                <?php echo $item->get_description(); ?>

Posted on <?php echo $item->get_date('j F Y | g:i a'); ?>

<?php endforeach; ?>

The table isn't the issue!
Any ideas?

A: The issue is
$feed->set_item_limit(5);

Is for merging feeds and not for a single feed.... you need to
change
foreach ($feed->get_items() as $item): ?>

to
foreach ($feed->get_items(0, 5) as $item): ?>

This would limit it to 5 items
SimplePIE Get_ITEMS


text:
Q: Vector space function question Q:
Let $X$ be a set and $\Bbb F$ be a field. Consider the vector space $V=Fun(X,\Bbb F)$ of functions from $X$ to $\Bbb F$ with operations of addition and mult.
(i) Describe the zero element of V and show that it holds the condition of axiom vs3 (which is the existence of zero in vector space).
(ii) for each function f in V, describe the additive inverse -f and show that it satisfies the conditions of axiom vs4 ( which is the existence of an inverse vector)

I am unsure how to do both parts but this is what I have. Please tell me what I'm doing wrong.
For i) I put if V has the operations of addition and mult then let there be f,-f in V and then (f+(-f))(x)=f(x)+(-f(x))=0 which is an element of V. So the axiom vs3 holds since there exists a 0 in V.
For ii) I have no idea...

A: Your answer for i) is a valid answer for (ii).  For (i), it is enough to state that $f(x) = 0$ gives you the zero-vector.

A: To describe a function, you must define its value $f(x)$ for any $x$.
Since $\mathbb F$ is a Field, it has a zero, which is the neutral element of the sum of $\mathbb F$. So, you can define the zero function
$$z(x)=0 \ \ \forall x\in X$$
Clearly $z$ is the neutral element of the sum of $V$ as
$$(f+z)(x)=f(x)+z(x)=f(x)+0=f(x)\qquad \forall x\in X$$
For $-f$ you need to find a function such that
$$(-f+f)=z\qquad i.e. \qquad (-f+f)(x)=z(x)\ \  \forall x\in X$$
Since $\mathbb F$ is field, any element has an additive inverse.
Thus, for any $f\in V$ you can define
$$g_f(x)=-f(x)$$
Now you have $$(g_f+f)(x)=-f(x)+f(x)=0=z(x)\qquad \forall x\in X$$
Therefore $g_f=-f$ as elements of $V$.
Note that you can do all the above because of the properties of $\mathbb F$. If you try replace $\mathbb F$ with $\mathbb N$...


text:
Q: Importing my own python module
Can I import the test01.py like os, sys module?
I want to import the test01.py like:
import test01.py

In this case now, I only can import it like this:
from testDemo02 import test01

Is it possible to reach it?

A: It looks like test01 is in the package testDemo02 - you can tell because there is a file __init__.py in the directory testDemo02. Given that, there are a couple possibilities:

*

*If the parent directory of testDemo02 is in the module search path (sys.path), but testDemo02 itself is not, you can import your test01 module using either
import testDemo02.test01

or
from testDemo02 import test01

I suspect this is the case since you tried the latter one and it works. This is what I would expect because I see that __init__.py file there.

*If testDemo02 itself is in the search path, you will be able to import your module with just
import test01

I would find it strange for a directory to be in the search path when it also contains an __init__.py file, but it is possible.

A: You can use sys module's path property to append your path:
>>> import sys
>>> sys.path.append("/testDemo02/test01")
>>> import test01


text:
Q: Nginx. Server directive inheritance. Is there any way to reduce construction like:
server {
  server_name regular_site;
  location /api/ {
     proxy_pass 127.0.0.1:5000;
  }
  location / {
     proxy_pass 127.0.0.1:3000;
  }
}

server {
  server_name mobile_site;
  location /api/ {
     proxy_pass 127.0.0.1:5000;
  }
  location / {
     proxy_pass 127.0.0.1:3001;
  }
}

to
server api {
  location /api/ {
     proxy_pass 127.0.0.1:5000;
  }
}

server extends api {
  server_name regular_site;
  location / {
     proxy_pass 127.0.0.1:3000;
  }
}

server extends api {
  server_name mobile_site;
  location / {
     proxy_pass 127.0.0.1:3001;
  }
}

Any other advices for getting rid of api section are welcome.

A: You could do it quite easily with a include statement.
In /etc/nginx/conf/api_defaults.conf:
location /api/ {
  proxy_pass 127.0.0.1:5000;
}

Then in your main vhost config.
/etc/nginx/sites-enabled/my_new_api.conf

server my_new_api {
  server_name mobile_site;

  include "/etc/nginx/conf/api_defaults.conf";

  location / {
    proxy_pass 127.0.0.1:3001;
  }
}


text:
Q: C++ regex equivalent for string::find I'm trying to edit an open source C++ program to make a simple adjustment so that one of the input's accepts a regexp string instead of a string. I'm a complete C++ noob (never written anything) so I'm hoping someone can point me to a function that will work. Take the following code:
#include <iostream>
#include <string>

int main() {
    std::string str1("ABCDEABCABD");
    std::string pattern("A");

    int count1 = 0;

    size_t p1 = str1.find(pattern, 0);
    while(p1 != std::string::npos)
    {
        p1 = str1.find(pattern,p1+pattern.size());
        count1 += 1;
    }

    std::cout << count1 << std::endl;
}

I would like 'pattern' to accept a regular expression of several patterns seperated by the pipe sign, eg 'A|D' (which would output 5 in this case).
From what I gather from this C++ reference page, you cannot supply a regular expression like this to the string::find function. What function can I put here instead?

A: You may leverage the following C++ code:
#include <iostream>
#include <regex>
using namespace std;

int main() {
    std::string pattern("A|D");         // Regex expression
    std::regex rx(pattern);             // Getting the regex object

    std::string s("ABCDEABCABD");       // Defining the string input
    std::ptrdiff_t number_of_matches = std::distance(  // Count the number of matches inside the iterator
        std::sregex_iterator(s.begin(), s.end(), rx),
        std::sregex_iterator());

    std::cout << number_of_matches << std::endl;  // Displaying results
    return 0;
}

See IDEONE demo
Note that:

*

*If pattern can contain literal strings with special characters they might need escaping.

*std::distance is a function that returns the number of elements between first and last, the number of elements the iterator yields.


text:
Q: Kaazing websocket EXCEPTION: java.lang.ClassNotFoundException: Didn't find class "com.kaazing.net.ws.impl.DefaultWebSocketFactory" on path: DexPathList[[directory "."],nativeLibraryDirectories=[/vendor/lib, /data/cust/lib, /system/lib, /data/datalib]]

Using Android Studio and the demo activity
I have the jars set in the dependencies
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.google.android.gms:play-services:+'
    provided files('libs/com.kaazing.gateway.client.android.jar')
    provided files('libs/com.kaazing.gateway.jms.client.android.jar')
    provided files('libs/geronimo-jms_1.1_spec.jar')

}

--
 if (connectionFactory == null) {
            try {
-------->       connectionFactory = JmsConnectionFactory.createConnectionFactory();
                WebSocketFactory webSocketFactory = connectionFactory.getWebSocketFactory();
                webSocketFactory.setDefaultChallengeHandler(createChallengehandler());
            } catch (JMSException e) {
                e.printStackTrace();
                logMessage("EXCEPTION: " + e.getMessage());
            }
        }

A: Here are the steps we followed, and worked:

*

*Downloaded Android Studio 1.0

*Downloaded JMS 4.0.6 from Kaazing website

*Used Import Non-Android Studio project

*Pointed to the [GATEWAY_HOME]/demo/android/src/jms

*Ran the app on device


text:
Q: HTML5 - unwanted  autofocus on mobile browsers My signup page has two forms; when you go to the page on a mobile browser (confirmed on Android and iOS), it autofocuses on the first input element in the second form and opens the keyboard, jumping past the first form.
All I want is to stop the autofocus entirely because it skips past some pre-signup instructions. (Though it would also be good to understand why/how this happens, and why it chooses the second form to focus on!)

*

*Neither form has the autofocus attribute set

*I've tried adding an id="top" and linking to /signup#top - no difference

*I have $(window).scrollTop(0) running after the page is rendered (for an unrelated reason) - no difference

*I'm using Meteor / Blaze with Semantic UI

*The first form is my own, the second form is the userAccounts package signup form

Information that is skipped past

  <form class="ui form" id="welcomeFormEmail">
    <input type="email" name="preLaunchEmail" placeholder="Your email address">
    <button type="submit">Submit</button>
  </form>

  <form id="at-pwd-form" action="#" method="POST" class="ui large form">

          <input type="email" id="at-field-email" name="at-field-email" placeholder="Email" autocapitalize="none" autocorrect="off">

    <input type="submit" class="at-btn ui fluid large primary button" id="at-btn" value="Register">

</form>

Any ideas why this is happening and what to do to stop it?

A: You can use blur
if you have just one text input you can get it using getElementById and set it to blur
 document.getElementById("myAnchor").blur();

but if you have multiple text inputs this loop gets every input on your page and disable focus on all of them
var elelist = document.getElementsByTagName("input"); for(var i = 0; i < elelist.length; i++){
    elelist[i].addEventListener("focus", function(){
        this.blur();
    }); }


text:
Q: Calculate time duration value from 2 select time options in a form I have a form that has select values TIME FROM: and TIME TO:.
They are in the format TIME FROM:, select time hour, then select am or pm
The select TIME TO: is in the format , select time hour, then select am or pm
How could I get the duration between the selected values and have the duration input field filled
Example
1) 1:00 pm  - 5:00 pm = 4 hours duration / duration input filled with 4 hours
2) 9:00 am  - 3:30 pm = 6.5 hours duration / duration input filled with 6.5 hours

            From:

                    <select id="time_from" name="time_from" class="form-control">
                        <option value="1">1:00</option>
                        <option value="130">1:30</option>
                        <option value="2">2:00</option>
                        <option value="230">2:30</option>
                        <option value="3">3:00</option>
                        <option value="330">3:30</option>
                        <option value="4">4:00</option>
                        <option value="430">4:30</option>
                        <option value="5">5:00</option>
                        <option value="530">5:30</option>
                        <option value="6">6:00</option>
                        <option value="630">6:30</option>
                        <option value="7">7:00</option>
                        <option value="730">7:30</option>
                        <option value="8">8:00</option>
                        <option value="830">8:30</option>
                        <option value="9">9:00</option>
                        <option value="930">9:30</option>
                        <option value="10">10:00</option>
                        <option value="1030">10:30</option>
                        <option value="11">11:00</option>
                        <option value="1130">11:30</option>
                        <option value="12">12:00</option>
                        <option value="1230">12:30</option>
                    </select>

                    <select id="time_from_am_pm" name="time_from_am_pm" class="form-control">
                        <option value="pm">pm</option>
                        <option value="am">am</option>
                    </select>

            To:

                    <select id="time_to" name="time_to" class="form-control">
                        <option value="1">1:00</option>
                        <option value="130">1:30</option>
                        <option value="2">2:00</option>
                        <option value="230">2:30</option>
                        <option value="3">3:00</option>
                        <option value="330">3:30</option>
                        <option value="4">4:00</option>
                        <option value="430">4:30</option>
                        <option value="5">5:00</option>
                        <option value="530">5:30</option>
                        <option value="6">6:00</option>
                        <option value="630">6:30</option>
                        <option value="7">7:00</option>
                        <option value="730">7:30</option>
                        <option value="8">8:00</option>
                        <option value="830">8:30</option>
                        <option value="9">9:00</option>
                        <option value="930">9:30</option>
                        <option value="10">10:00</option>
                        <option value="1030">10:30</option>
                        <option value="11">11:00</option>
                        <option value="1130">11:30</option>
                        <option value="12">12:00</option>
                        <option value="1230">12:30</option>
                    </select>

                    <select id="time_to_am_pm" name="time_to_am_pm" class="form-control">
                        <option value="pm">pm</option>
                        <option value="am">am</option>
                    </select>

Duration:

    <input type="text" name="booking_duration" class="form-control">

A: Using momentjs you can write a change event handler for the four fields:
$('#time_from, #time_from_am_pm, #time_to, #time_to_am_pm').on('change', function(e) {
  var timeFrom = moment($('#time_from option:selected').text() +
              $('#time_from_am_pm option:selected').text(), 'HH:mma');
 var timeTo = moment($('#time_to option:selected').text() +
              $('#time_to_am_pm option:selected').text(), 'HH:mma');
 var dif = timeTo.diff(timeFrom);
 if (dif < 0) {
    timeTo = timeTo.add(1, 'days');
    dif = timeTo.diff(timeFrom);
 }
 var d = moment.duration(dif);
 var result = +d.get('hours') + (+d.get('minutes') / 60);
 $('[name="booking_duration"]').val(result);

});
The snippet:

$('#time_from, #time_from_am_pm, #time_to, #time_to_am_pm').on('change', function(e) {
  var timeFrom = moment($('#time_from option:selected').text() + $('#time_from_am_pm option:selected').text(), 'HH:mma');
  var timeTo = moment($('#time_to option:selected').text() + $('#time_to_am_pm option:selected').text(), 'HH:mma');
  var dif = timeTo.diff(timeFrom);
  if (dif < 0) {
    timeTo = timeTo.add(1, 'days');
    dif = timeTo.diff(timeFrom);
  }
  var d = moment.duration(dif);
  var result = +d.get('hours') + (+d.get('minutes') / 60);
  $('[name="booking_duration"]').val(result);
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        From:

            <select id="time_from" name="time_from" class="form-control">
              <option value="1">1:00</option>
              <option value="130">1:30</option>
              <option value="2">2:00</option>
              <option value="230">2:30</option>
              <option value="3">3:00</option>
              <option value="330">3:30</option>
              <option value="4">4:00</option>
              <option value="430">4:30</option>
              <option value="5">5:00</option>
              <option value="530">5:30</option>
              <option value="6">6:00</option>
              <option value="630">6:30</option>
              <option value="7">7:00</option>
              <option value="730">7:30</option>
              <option value="8">8:00</option>
              <option value="830">8:30</option>
              <option value="9">9:00</option>
              <option value="930">9:30</option>
              <option value="10">10:00</option>
              <option value="1030">10:30</option>
              <option value="11">11:00</option>
              <option value="1130">11:30</option>
              <option value="12">12:00</option>
              <option value="1230">12:30</option>
            </select>

            <select id="time_from_am_pm" name="time_from_am_pm" class="form-control">
              <option value="pm">pm</option>
              <option value="am">am</option>
            </select>

        To:

            <select id="time_to" name="time_to" class="form-control">
              <option value="1">1:00</option>
              <option value="130">1:30</option>
              <option value="2">2:00</option>
              <option value="230">2:30</option>
              <option value="3">3:00</option>
              <option value="330">3:30</option>
              <option value="4">4:00</option>
              <option value="430">4:30</option>
              <option value="5">5:00</option>
              <option value="530">5:30</option>
              <option value="6">6:00</option>
              <option value="630">6:30</option>
              <option value="7">7:00</option>
              <option value="730">7:30</option>
              <option value="8">8:00</option>
              <option value="830">8:30</option>
              <option value="9">9:00</option>
              <option value="930">9:30</option>
              <option value="10">10:00</option>
              <option value="1030">10:30</option>
              <option value="11">11:00</option>
              <option value="1130">11:30</option>
              <option value="12">12:00</option>
              <option value="1230">12:30</option>
            </select>

            <select id="time_to_am_pm" name="time_to_am_pm" class="form-control">
              <option value="pm">pm</option>
              <option value="am">am</option>
            </select>

  Duration:

    <input type="text" name="booking_duration" class="form-control">

A: you can use jquery-timepicker time pickers to get a valid date object with the time and use the following code to calculate duration
//this returns duration in hours
var calculateDuration = function(timefrom,timeto){
      var d = (timeto.getTime()-timefrom.getTime())/60000;
      return d<0?0:d;
}


text:
Q: The name 'GroupforA' does not exist in the current context Here is the code:
class Program
{
    static void Main(string[] args)
    {

      List<Item> cont1 = new List<Item>();
      cont1.Add(objA); //objA is local varible that has been defined.
      cont1.Add(objB); //objB is local varible that has been defined.
      cont1.Add(objC); //objC is local varible that has been defined.
      cont1.Add(objD); //objD is local varible that has been defined.
      cont1.Add(objE); //objE is local varible that has been defined.

      int count = cont1.Count;

      List<Item> cont2 = GroupingA(cont1, count);

      for (int i = 0; i < cont1.Count; i++)
      {
         Console.Write(cont1[i].Name + " ");//output the item's name.

      }
      Console.WriteLine();
      Console.Write("Container 2: ");
      for (int i = 0; i < cont2.Count; i++)
      {
         Console.Write(cont2[i].Name + " ");//output the item's name.
      }
    }
}

public class GroupItem
{
    public List<Item> GroupingA (List<Item> obj, int count)
    {
        List<Item> temp = new List<Item>();
        for (int i = 0; i < count; i++)
        {
            if (i == count - 1)
            {
                break;
            }
            else if (temp.Count > 0 )
            {
                break;
            }
            else
            {
                for (int j = i + 1; j < count; j++)
                {
                    bool equal = obj[i].EqualFirstPhase(obj[j]);
                    if (equal == true)
                    {
                        if (temp.Exists(element => element == temp[j]))
                        {
                            continue;
                        }
                        else
                        {
                            temp.Add(obj[j]);
                            if (temp.Exists(element => element == obj[i]))
                            {
                                continue;
                            }
                            else
                            {
                                temp.Insert(0, obj[i]);
                            }
                            i--;

                        }

                    }
                }

            }
            for (int k = 0; k < count; k++)
            {
                for (int l = 0; l < temp.Count; l++)
                {
                    if (obj[k].Name.Contains(temp[l].Name))
                    {
                        obj.RemoveAt(k);
                        count--;

                    }
                }
                if (obj.Count < count)
                {
                    k = 0;

                }
            }

        }
        return temp;
    }
}

I want to use GroupingA method to regroup the cont1 into cont2. However, there is an error.

The name 'GroupingA ' does not exist in the current context.

Anyone can help me??? Really weak in OOP, especially naming.

A: YOu need to use :-
GroupItem grpItem  = new GroupItem();
List<Item> cont2 = grpItem.GroupingA(cont1, count);

Reason:-
Your GroupingA method is non-static and defined in the class GroupingItem. And you are trying to access it from your Program class as if the method GroupingA is a part of that class. For accessing non-static methods from other classes you need to Instantiate that class and use that object to get access to the class. In case of static method you can directly access them with the . operator on that particular class. ex Class.Method(...)

A: The line
List<Item> cont2 = GroupingA(cont1, count); is being called in the class Program.
Without a class name or object identifier that says where a method is located, it will look in the current class, which in your case is Program.
You have several choices.

*

*Make the GroupingA method static and replace the line with List<Item> cont2 = GroupItem.GroupingA(cont1, count);

*Make an instance of GroupItem and refer to that instead:
GroupItem g = new GroupItem();
List<Item> cont2 = your.GroupingA(cont1, count);

*Move the method GroupingA out of the GroupItem class and place it within the Program class so your line knows where to find it.


text:
Q: Is it possible to have multiple version of php working on the same lamp?
Possible Duplicate:
Can I run PHP 5.3 and PHP 5.2 on the same server with Apache?

Is it possible to have multiple version of php working on the same lamp?Maybe using different ports?i'm thinking of having php. 5.2 when i call port 81 and php 5.3 an port 82.
Sorry if the question is stupid but i'm a newbie!
Edit - Sorry it's a dupe.Close it (i had checked before, anyway)

A: The only way I know to do this would be to have two different apache instances running, each loading a different php module.


text:
Q: Show and fadout images in jquery With the blur event in jquery I want to show and image in a div for 1 second (fade it out) and then show in the same div another image. How can I do it in jquery. Thank for you help! This is what I've tried.
    <form name="field" method="post" id="form">
        Username:

        <input name="username" id="username" type="text"/>

        <input name="submit" type="button" value="Register" id="submit"/>

    </form>

$(document).ready(function(){

$("#username").blur(test);

function test(){
    $("#img").empty();
        $('').prependTo("#img").fadeOut(1000,     function(){
            $("#img").prepend('');
        });

}
});

A: Sorry, let me be more clear. Use one of jQuery's various animate methods.
$(document).ready(function() {
    $('#username').blur(test);

    function test() {
        $('#img').fadeOut(1000, function() {
            $('#img2').fadeIn(1000);
        });
    }

});

Your HTML:
<form name="field" method="post" id="form">
    Username:

    <input name="username" id="username" type="text"/>

    <input name="submit" type="button" value="Register" id="submit"/>

</form>

In your CSS, you can set the visibility of image 2 to be hidden by default so that it will fade in at the appropriate time.
#img2 {
    display: none;
}

A: This might help http://jsfiddle.net/m4xbf/
HTML
<form name="field" method="post" id="form">
    Username:

    <input name="username" id="username" type="text" />

    <input name="submit" type="button" value="Register" id="submit" />

</form>

jQuery
$(document).ready(function(){
$("input[type=text]").blur(function () {
    $("#img").append("").fadeIn(500).delay(1000).fadeOut(500, function () {
        $("#img").empty().append("").fadeIn(500).delay(1000).fadeOut(500);
    });
});
});


text:
Q: Feature-wise Normalization of Predictor Variables in R So I want to fit a neural network later to predict the continous numeric variable Outstate in the College dataset from the ISLR packagage as a function of the 17 other (predictor) variables in the dataset. Before I fit the neural network I need to do feature-wise normalization of only the predictor variables. Since there are 17 predictors I don't want to have to explicitly type out every variable I wanna standardize. Is there any feasible way of doing this in R? The scale function scales all variables in the dataset from what I understand.
library(ISLR)

set.seed(1)
College$Private = as.numeric(College$Private)
train.ind = sample(1:nrow(College),0.5*nrow(College))
college.train = College[train.ind,]
college.test = College[-train.ind,]

A: This code will standardise each feature with base R scale() which centres data based on the columns means and then divides by the standard deviations i.e. Z-score standardisation.
preds = colnames(college.test)[-9]

college.test[,preds] = lapply(college.test[,preds], scale)


text:
Q: Facebook apps: 'How to ad app page description for like button I have a facebook app with a like button embedded in it. Now when a user clicks 'like',
it displays on their timeline right. The problem is that only my app's Title and image shows up. how do I add/show a description as well? Maybe an attribute for the like button?
My like button  below:
<script src="http://connect.facebook.net/en_US/all.js#appId=353195451398908&xfbml=1">
</script><fb:like href="http://apps.facebook.com/e-phoneapp" layout="button_count"
width="90" height="24px" show_faces="false" action="like" font="lucida grande"></fb:like>

Thanks


text:
Q: Add sub categories to a Dependency Property in a Workflow Activity I wish to create an workflow activity that has a dependancy property structure like this

*

*Setting

*

*Wait Period

*

*Days

*Hours

*Mins

At the moment the code below will show Setting with the Wait Period as an Integer, but now need to expand it out to 3 sub child properties for Days, Hours and Mins.
I understand i will have to change the Wait Period, but i'm not sure how to go about attaching the other 3 properties to it.
Any help would be appreciated... Thanks.
public static DependencyProperty WaitPeriodProperty = DependencyProperty.Register("WaitPeriod", typeof(int), typeof(CheckActivity));
/// <summary>
/// Dependency property for 'Wait Period'
/// </summary>
///
[DescriptionAttribute("The email of the sender")]
[CategoryAttribute("Settings")]
public int WaitPeriod
{
    get
    {
        return (int)(base.GetValue(CheckActivity.WaitPeriodProperty));
    }
    set
    {
        base.SetValue(CheckActivity.WaitPeriodProperty, value);
    }
}

A: First of all you should definitely change the type from int to TimeSpan.  That has Days, Hours, Minutes, Seconds and Milliseconds.
The input UI may not be to your liking though its just a string:  d.hh:mm:ss.msecs
However personally I would put up with that for the simplicity of using a Type specifically designed for the task.  It might be possible to create a Custom editor for it though.


text:
Q: how can some apps be small in size even though having lots of images? I have an android app which is 35 MB in size. I am using around 50 images in that app because of that scrolling is not smooth and sometimes app crashes with errors like out of memory, whereas there are other apps which are using 100 images but are smaller in size, like 2 MB or so and these app work offline also.
I want to ask why these apps are small in size? are they using any library?

A: Try this it may work for you
convert all your jpeg ,png,etc etc images into " webp" it may take less space and
same quality of your picture...
https://developer.android.com/studio/write/convert-webp.html#convert_images_to_webp
Don't store all images in drawable rather make  small json file and fetch all the data from your app so you can get a apk with smaller size and fast
some code is also their how to get data from offline also..

A: Try this:
1) Reduce Images size from this website.
Tiny PNG

TinyPNG uses smart lossy compression techniques to reduce the file
  size of your PNG files

2) Put images in different drawable folder.
Using this website to generate different drawable:
https://romannurik.github.io/AndroidAssetStudio/icons-launcher.html
3) Use SVG or 9 patch if it is possible.