text:
Q: Proper databinding in WPF using TabControl and MVVM Just when I thought I was getting better at this, TabControl is now giving me problems.  I have read relevant posts here on StackOverflow, but have been unable to get my simple demo application to work the way I want it to.
To keep things focused, I'll start with a single question about something I don't understand.
I have a TabControl whose TabItems each host the same UserControl.  When I set the TabControl.ContentTemplate's DataTemplate to my UserControl, a rendering of that control appears, but it looks like it's the same control for each tab.  Or perhaps it's not tied to any of the tabs at all.
MainWindow.xaml
<Window x:Class="TabControlMvvm.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:localviews="clr-namespace:TabControlMvvm.Views"
    Title="MainWindow" Height="350" Width="525">
    <TabControl ItemsSource="{Binding Tabs}" SelectedIndex="{Binding Selected}">
        <TabControl.ContentTemplate>
            <DataTemplate>
               <localviews:PersonMainPanel />
            </DataTemplate>
        </TabControl.ContentTemplate>
    </TabControl>
</Window>

Code-behind just sets the ViewModel as its DataContext:
namespace TabControlMvvm {
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new TabControlMvvm.ViewModels.MainViewModel();
        }
    }
}

The TabItem's Content should be another UserControl, PersonMainPanel.xaml:
<UserControl x:Class="TabControlMvvm.Views.PersonMainPanel"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:localviews="clr-namespace:TabControlMvvm.Views"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <Border BorderBrush="Red" BorderThickness="2">
        <TabControl TabStripPlacement="Bottom">
            <TabItem Header="Tab 1">
                <localviews:MyTabItem />
            </TabItem>
            <TabItem Header="Tab 2">
                <TextBlock Text="This was left blank intentionally" />
            </TabItem>
            <TabItem Header="Tab 3">
                <TextBlock Text="This was also left blank intentionally" />
            </TabItem>
        </TabControl>
    </Border>
</UserControl>

Code-behind:
namespace TabControlMvvm.Views {
    /// <summary>
    /// Interaction logic for PersonMainPanel.xaml
    /// </summary>
    public partial class PersonMainPanel : UserControl {
        public PersonMainPanel()
        {
            InitializeComponent();
        }
    }
}

And the MainViewModel:
namespace TabControlMvvm.ViewModels {
    public class MainViewModel : ViewModelBase {
        public ICollectionView Tabs { get; set; }
        public int Selected { get; set; }

        public class Person
        {
            public string Name { get; set; }
        }

        public class DummyController {
            public List<Person> Persons { get; private set; }

            public DummyController()
            {
                Persons = new List<Person> {
                    new Person { Name = "Larry" },
                    new Person { Name = "Darryl" },
                    new Person { Name = "Other brother Darryl" }
                };
            }
        }

        public DummyController Controller { get; private set; }

        public RelayCommand HelloCommand { get; set; }

        public MainViewModel()
        {
            Controller = new DummyController();

            /*
            IEnumerable<TabItem> tabs = Enumerable.Range( 1, _controller.Persons.Count())
                                                  .Select( x => new TabItem { Header = String.Format( "Person {0}", x),
                                                                              Content = new PersonMainPanel() });
             */
            IEnumerable<TabItem> tabs = Enumerable.Range( 1, Controller.Persons.Count())
                                                  .Select( x => new TabItem { Header = String.Format( "Person {0}", x)});
            Tabs = CollectionViewSource.GetDefaultView( tabs.ToList());
            Tabs.MoveCurrentToFirst();

            InitializeCommands();
        }

        private void InitializeCommands()
        {
            HelloCommand = new RelayCommand( () => { MessageBox.Show( String.Format( "Hello, Person {0} named {1}!",
                                                                      Selected, Controller.Persons[Selected].Name)); });
        }
    }
}

PersonMainPanel hosts another TabControl, where Tab 1's Content is MyTabItem.xaml:
<UserControl x:Class="TabControlMvvm.Views.MyTabItem"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <StackPanel Orientation="Vertical">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="Name:" />
            <TextBox Text="{Binding Name}" Width="100" />
        </StackPanel>
        <Button Command="{Binding HelloCommand}" Content="Say Hello" />
    </StackPanel>
</UserControl>

Code-behind:
namespace TabControlMvvm.Views {
    /// <summary>
    /// Interaction logic for MyTabItem.xaml
    /// </summary>
    public partial class MyTabItem : UserControl {
        public MyTabItem()
        {
            InitializeComponent();
        }
    }
}

Which looks like this at runtime:

Issues I have so far:

*

*When I enter Person 1's Name and then click the Person 2 tab, Person 1's Name is still visible, hence my assumption that the controls are not databound properly.  I understand that ItemsControls do not pass their DataContext down to their children, but I am not sure how to fix this without associating the View in code-behind.

*I would have expected to get databinding errors in the Output window because of the missing DataContext, but I don't get any errors.  I assume the DataContext is null, but wouldn't this still result in a binding error?

*How can I use Snoop effectively to debug problems like this?

Here's the sample solution: http://www.filedropper.com/tabcontrolmvvm

A: Here is solution:
In MainWindow modify your TabControl template, to bind Header from your Model:
<TabControl ItemsSource="{Binding Tabs}" SelectedIndex="{Binding Selected}">
    <TabControl.ContentTemplate>
        <DataTemplate>
            <localviews:PersonMainPanel />
        </DataTemplate>
    </TabControl.ContentTemplate>
    <TabControl.ItemContainerStyle>
        <Style TargetType="TabItem">
            <Setter Property="Header" Value="{Binding Header}"/>
        </Style>
    </TabControl.ItemContainerStyle>
</TabControl>

In MyTabItem.xaml, set UpdateTrigger, because default one 'OnLostFocus' can sometimes not save your data:
 <TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" Width="100" />

In MainViewModel modify creating of your tabs, so it will have Name property too:
IEnumerable<TabItem> tabs = Enumerable.Range( 1, Controller.Persons.Count())
                                        .Select( x => new TabItem { Header = String.Format("Person {0}", x), Name = Controller.Persons[x-1].Name });

Also, the most important, create own TabItem class to contain some bounded data:
public class TabItem
{
    public string Name { set; get; }
    public string Header { set; get; }
}


text:
Q: trying to add an image in html I've just added a new widget to my blog, using a label-search url to pull up specific posts. This is working very nicely.
However, I want to add an image next to the link, and this is not working. I'm getting a nasty blue question mark on the page instead of my photo. I've looked up all the attributes I'm using and I think my syntax is OK, so I'm stumped. Would somebody please point out what I've done wrong?
thanks
MM

MY GEORGETOWN

A: You have .html on the end of your src attributes.  The image source should end in .jpg, not .jpg.html.
src="http://s1275.photobucket.com/user/MaddyMarcel/media/DCgraffiti_zps23603274.jpg.html

should be
src="http://i1275.photobucket.com/albums/y449/MaddyMarcel/DCgraffiti_zps23603274.jpg

redpajama_set_name: RedPajamaStackExchange


text:
Q:  coldfusion I am severely new to ColdFusion... I have searched for help on this statement and have found a bunch of material, but still don't understand what is going on.  All of the parts of this statement make sense, but when I put them all together, it's confusing...  the ColdFusion 8: IsDefined("URL.variable) and is not"" thread is the closest, but I still don't understand.  This is the 1st statement in the index.cfm file of my application.   It's not throwing an error, I just want to understand how it works.  Thank you.
I have yet to be able to successfully post code here, so here is a link to a text version of the index.cfm.
Edit:
The code below should be the relevant sections related to URL.openFile
   <cfif isdefined("URL.openFile")>
      <cfquery name="getFile" datasource="xxxxxxxx">
         SELECT filename, filename2, filecontent, filesize
         FROM Help_FooterInfo
         WHERE Help_id=5 and Section='Registration'
       </cfquery>
       <cfset sproot=#getDirectoryFromPath(getTemplatePath())#>
       <cfset newDest = #sproot#&"temp\">
       <cfoutput query="getFile">
          <cfheader name="Content-Disposition" value="attachment; filename=#getfile.FileName2#">
          <cfcontent type="application/msword" variable="#getfile.filecontent#">
       </cfoutput>
   </cfif>
   ...
   <cfquery name="getRegistration" datasource="xxxxxxxx">
      select * from help_footerinfo where help_id=5
   </cfquery>
   ....
   <cfoutput>#getRegistration.Content#</cfoutput>

   <a href="<cfif #getRegistration.filename2# neq "">index.cfm?openfile=Yes</cfif>" target="_blank">
       <cfoutput>#getRegistration.FileName#</cfoutput>

The error message I am receiving (see comment below): ORA-00942: table or view does not exist (ColdFusion application)

A: This:
<cfif IsDefined("URL.variable") and URL.variable is not "" >

means, "If url.variable actually exists and is not an empty string".
A better alternative for isDefined("URL.variable") is StructKeyExists(url,"variable").
Other alternatives for is not "" include len(trim(url.variable)) gt 0, and isNumeric(url.variable).


text:
Q: libcurl POST xml file to url I have been working on uploading a simple XML file to a specialized Web Server. This webserver only supports the use of POST or GET, so it eliminates the use of CURLOPT_UPLOAD which only provides for PUT.
I can use the command line to send the file using the following command line
    curl -H 'Content-Type: text/xml; charset=utf-8' -H 'SOAP Action:'
    -T igs_meters2.xml -X POST //url//
I tried to use CURLOPT_POST and CURLOPT_READDATA, but received a 413 Request Entity Too Large.
I know this cannot be this hard, but I am out in areas I have never work in. Thanks in advance for an idea.
SOLVED:
the tip about CUSTOMREQUEST was what I needed to find. That helped, and I also needed to add in an HTTPHEADER for CONTENT-TYPE and SOAPAction:


text:
Q: After reinstalling MAMP PRO, apps can't find databases Thanks to MAMP PRO's amazing uninstaller, which deletes all of your databases, I had to restore them from the online versions.  The only problem is now, when I take code that is working online and databases that are working online, the code can't find the databases.  With MAMP PRO running, I can see the databases via command-line as such:
+--------------------+
| Database           |
+--------------------+
| information_schema |
| donatetheweight    |
| mysql              |
| natiood8_wrd1      |
| performance_schema |
| personalprpro      |
| test               |
+--------------------+

And I have permissions:
+----------------------------------------------------------------------------------------------------------------------------------------+
| Grants for root@localhost                                                                                |
+----------------------------------------------------------------------------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY PASSWORD '*2E80906F903DA9B84678ED79A48FF414B4FDC890' WITH GRANT OPTION |
| GRANT PROXY ON ''@'' TO 'root'@'localhost' WITH GRANT OPTION                                                                           |
+----------------------------------------------------------------------------------------------------------------------------------------+

Not to mention I can use Sequel Pro to see the databases on localhost.  In my code, I am using the Fat-Free Framework, which works fine online and did before I reinstalled.  Here is the command:
$f3->db = new \DB\SQL(
      'mysql:host=localhost;port=8889;dbname=donatetheweight',
      'root',
      'notroot'
    );

My MAMP PRO is set to MAMP ports (http->8888, https->8890, mysql->8889) and I am accessing my site through the correct host on port 8888.  The error I get is an internal server error [1049] etc:

Anything else I can try?  I did notice for a while I was getting a my.cnf file conflict but I accidentally clicked "Do not show this again" so I can't be sure where to look for that error.
Just to be sure that the database existed (and that this isn't a duplicate of ERROR 1049 (42000): Unknown database, I tried to recreate the database and got this:
mysql> create database donatetheweight;
ERROR 1007 (HY000): Can't create database 'donatetheweight'; database exists

A: Verify your mysql.sock file is missing (use mysqladmin variables to see where it is looking and check there), restart your computer, start up MAMP (not PRO), then MAMP PRO.  Double check by ensuring your changes persist using two database tools (I used Sequel Pro and PHPMyAdmin).


text:
Q: VB.NET Wait a DOS shell program to terminate before continuing- doesn't work I am building a Windows Forms Application on VS2010, through which I need to execute a 3d party DOS shell program (OpenSees.exe), open a source file in it and perform an analysis. After this, some output files are created which I need to read again in my VB.NET app.
The thing is that the analysis in OpenSees may take a long time, so the VB code has to wait for it before carrying on.
For this, I have tried both "ShellandWait" sub along with "WaitForSingleObject" function and "process class" option, but neither of then works.
My DOS shell program initializes, but it closes almost immediately, not letting the analysis to complete and the required output to be created.
Here are the code snippets I used:
1st try: ShellandWait
Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess _
 As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long
Private Declare Function WaitForSingleObject Lib "kernel32" (ByVal hHandle _
    As Long, ByVal dwMilliseconds As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long

Private Sub ShellAndWait(ByVal program_name As String, _
                         Optional ByVal window_style As AppWinStyle = vbNormalFocus, _
                         Optional ByVal max_wait_seconds As Long = 0)
    Dim lngProcessId As Long
    Dim lngProcessHandle As Long
    Dim datStartTime As Date
    Const WAIT_TIMEOUT = &H102
    Const SYNCHRONIZE As Long = &H100000
    Const INFINITE As Long = &HFFFFFFFF

    ' Start the program.
    On Error GoTo ShellError
    lngProcessId = Shell(program_name, window_style)
    On Error GoTo 0
    Threading.Thread.Sleep(1500)
    'System.Windows.Forms.Application.DoEvents()

    SendKeys.Send("source " & filename & ".tcl")
    SendKeys.Send("{ENTER}")

    ' Wait for the program to finish.
    ' Get the process handle.
    lngProcessHandle = OpenProcess(SYNCHRONIZE, 0, lngProcessId)
    If lngProcessHandle <> 0 Then
        datStartTime = Now
        Do
            If WaitForSingleObject(lngProcessHandle, 250) <> WAIT_TIMEOUT Then
                Exit Do
            End If
            'DoEvents()
            If max_wait_seconds > 0 Then
                If DateDiff("s", datStartTime, Now) > max_wait_seconds Then Exit Do
            End If
        Loop
        CloseHandle(lngProcessHandle)
    End If
    Exit Sub

  ShellError:
  End Sub
  ...
  ShellAndWait("OpenSees.exe", , 3)

2nd try: ProcessStart
Dim p As New Process
Dim psi As New ProcessStartInfo("OpenSees.exe", "source " & filename & ".tcl")
p.StartInfo = psi
p.Start()

p.WaitForExit()

I don't understand why this isn't working. Any help would be much appreciated!

A: Try this:
Shell("OpenSees.exe <arguments>",, True)


text:
Q: react-css-module module not found I'm new in react and I'm trying to build a simple application. I try react-css-modules to style it. It doesn't work, and I don't find the solution since now tooooooo much time. I think I have hard time to understand webpack and how it works... I found this similar post, but it didn't help me (module not found). I hope somebody can help me.
I try to style in the following way, and I get a white page with several red errors. Most important, I guess: "react-css-modules doesn't exist".
I installed:
npm install style-loader --save-dev
npm install css-loader --save-dev
npm install --save css-modulesify

I cut the most of the code to make it easy to read:
the component:
import React from 'react';
import CSSModules from 'react-css-modules';
var styles = require('./header.css');

class Header extends  React.Component {enter code here
  render (){
    return (

{this.props.info.username}

    );
  }
}
export default CSSModules(Header, styles);

the CSS file:
.mainTitle{
    color: #aa0;
}

the package.json:
{
  "name": "Health Prover",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node server"
  },
  "keywords": [],
  "author": "Massimo Pibiri",
  "license": "ISC",
  "dependencies": {
    "css-modulesify": "^0.22.0",
    "express": "^4.13.4",
    "i": "^0.3.4",
    "lodash": "^4.6.1",
    "react": "^0.14.7",
    "react-dom": "^0.14.7"
  },
  "devDependencies": {
    "babel-core": "^6.7.2",
    "babel-loader": "^6.2.4",
    "babel-preset-es2015": "^6.6.0",
    "babel-preset-react": "^6.5.0",
    "css-loader": "^0.23.1",
    "react-hot-loader": "^1.3.0",
    "style-loader": "^0.13.0",
    "webpack": "^1.12.14",
    "webpack-dev-server": "^1.14.1"
  },
  "engines": {
    "node": "5.5.0"
  }
}

the webpack file:
var webpack = require('webpack');
var path = require('path');

module.exports = {
    devtool: 'inline-source-map',
    entry: [
        'webpack-dev-server/client?http://127.0.0.1:8080/',
        'webpack/hot/only-dev-server',
        './src'
    ],
    output: {
        path: path.join(__dirname, 'public'),
        filename: 'bundle.js'
    },
    resolve: {
        modulesDirectories: ['node_modules', 'src'],
        extensions: ['', '.js']
    },
    module: {
        loaders: [
        {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loaders: ['react-hot', 'babel?presets[]=react,presets[]=es2015']
        },
        {
            test: /\.css$/,
            loaders: [
                'style?sourceMap',
                'css?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]'
            ]
        }
        ]
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoErrorsPlugin()
    ]
};

A: The first thing to check when you get module not found is if it is in fact installed. Judging by your package json, it's not.
npm i react-css-modules --save
and your good.


text:
Q: How to cast generic types that I know to be integers? I want to check return codes of C APIs in a generic way and the result must be free from C types such as libc::c_int.  Are there any ways to write a function like
fn check<S: PartialOrd + std::num::Zero, T> (x: S) -> Option<T> {
    if std::num::zero::<S>() <= x { Some(x as T) }
    else { None }
}

when I'm sure that S and T are integral types for all usages of check()?  The compiler rejects my code complaining error: non-scalar cast: `S` as `T`

A: It is impossible to cast arbitrary type to arbitrary type, and that's exactly (almost) what you're trying to do. You need to be more specific in type constraints and conversion operations.
extern crate num;

use num::{Zero, NumCast};

fn check<S: PartialOrd + Zero + NumCast, T: NumCast>(x: S) -> Option<T> {
    if x >= S::zero() { Some(num::cast(x).unwrap()) }
    else { None }
}

fn main() {
    let x: i8 = 10;
    let y: Option<i32> = check(x);
    println!("{:?}", y);

    let x: i8 = -10;
    let y: Option<i32> = check(x);
    println!("{:?}", y);
}

Here I'm using a special trait, num::NumCast from num crate, which is implemented for all primitive types and provides a static method which converts to these types from anything which implements num::ToPrimitive. num crate also provides a function, num::cast::cast(), which gives a simple interface to perform numeric casts.
Note that cast(x) returns Option<T>; it returns None if x can't be represented in the target type. I'm using unwrap() here because in your case, according to your description, inability to convert a value correctly is likely a programming error, so failing the task feels more appropriate. It is also possible to write cast(x) directly:
if x >= S::zero() { num::cast(x) }
...

In this case check() will return None not only when its argument is negative, but also if it is impossible to convert the argument to the result type.


text:
Q: Add/Remove Roles in Discord.py Rewrite using console input I'm working on a part of a big project where I've come to a dead end with adding and removing roles due to being a noob in discord.py.
I have setup console input which asks for User ID, Role to add/remove and then it should execute a command. The console is simply a batch file or run mode of pycharm/atom etc....
The function is not used within Discord with a command, but from the input only.
Sorry if it is a double post but I've been looking for this since 2 days now and every result gave me an error code. The function is commented and should let you know what exactly is the problem:
async def rolemanager():
   await client.wait_until_ready()
   function = input("Add/Remove> ")
        if function == 'add':
            person = input("User ID> ") # Uses non-changeable User ID
            personname = client.get_user(int(person)) # Converts to Name#0000
            roleadd = input("Role-Name> ") # Asks for exact role name to add
            confi = input("Are you sure? y/n > ") # Asks for confirm input
            if confi == "y": # If its confirmed:
                await client.add_roles(name=roleadd) # Error: AttributeError: 'Bot' object has no attribute 'add_roles'
                print(f"Role {roleadd} added to user {personname}") # Prints if successful, or crashes the program
            else:
                print("Role-Add canceled.") # If canceled, shows this
                pass # Passes to restart the loop
        elif function == 'remove': # Same stuff here, but remove . .
            person = input("User ID> ")
            personname = client.get_user(int(person))
            roleremove = input("Role-Name> ")
            confi = input("Are you sure? y/n > ")
            if confi == "y":
                await client.remove_roles(name=roleremove)
                print(f"Role {roleremove} removed from user {personname}")
            else:
                print("Role-Remove canceled.")
                pass
        else:
            print(f"Wrong input, use add/remove in lower-case)

Complete Error:
   Task exception was never retrieved
future:  exception=AttributeError("'Bot' object has no attribute 'add_roles'")>
Traceback (most recent call last):
  File "bot2.py", line 42, in mainhandler
    await client.add_roles(name=roleadd)
AttributeError: 'Bot' object has no attribute 'add_roles'
Thanks in advance!

A: You shouldn't be using input at all, as it's a blocking operation.  Instead, you should get all of that information from the user as part of the command invocation.
The problem you're experiencing is that add_roles is a method of Member, not Client
from discord.ext import commands
from discord import Member, Role

bot = commands.Bot("!")

@bot.command()
async def add(ctx, member: Member, role: Role):
    await member.add_roles(role)

@bot.command()
async def remove(ctx, member: Member, role: Role):
    await member.remove_roles(role)

bot.run("token")


text:
Q: Displaying objects in page frame in foxpro How to display objects in fox-pro page frame using display objects command?
I have already tried to use display objects like * to file *.txt but it only displayed the objects in the form (main objects) all the objects contained in the page frame container didn't show in the file.
I want to know how to display the objects in container like page frame to file for development purpose.

A: Check out the Object Inspector tool that I built. It's described in this paper: http://www.tomorrowssolutionsllc.com/Conference%20Sessions/Collections--Managing%20Information%20the%20Object-Oriented%20Way.pdf and can be downloaded with the examples for that session at http://www.tomorrowssolutionsllc.com/publications/conferencepapers.
Tamar


text:
Q: apache benchmark server performance test unreasonable result I am testing the general performance of my home server using apache benchmark. However, when I test the server with 1 user and 10000 requests the reported requests per second is around 250 (on average) all the time but when I do the test with 10 users and 10000 requests then it reports that the requests per second is around 1134. I have tested these two scenarios multiple times and get this unreasonable result. What I am thinking is, why does it jump from approximately 200 req/sec to 1134 req/sec. Shouldn't the first test also give the same or close result?  Both tests send more than 1000 requests.
ab -c 1 -n 1000 http://168.192.54.8/
This is ApacheBench, Version 2.3 <$Revision: 1706008 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 168.192.54.8 (be patient)
Completed 100 requests
Completed 200 requests
Completed 300 requests
Completed 400 requests
Completed 500 requests
Completed 600 requests
Completed 700 requests
Completed 800 requests
Completed 900 requests
Completed 1000 requests
Finished 1000 requests

Server Software:        Apache/2.4.29
Server Hostname:        168.192.54.8
Server Port:            80

Document Path:          /
Document Length:        9381 bytes

Concurrency Level:      1
Time taken for tests:   3.954 seconds
Complete requests:      1000
Failed requests:        0
Total transferred:      9654000 bytes
HTML transferred:       9381000 bytes
Requests per second:    252.92 [#/sec] (mean)
Time per request:       3.954 [ms] (mean)
Time per request:       3.954 [ms] (mean, across all concurrent requests)
Transfer rate:          2384.49 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    1   0.3      1       2
Processing:     2    3   0.6      3       7
Waiting:        1    2   0.5      2       5
Total:          2    4   0.7      4       9

Percentage of the requests served within a certain time (ms)
  50%      4
  66%      4
  75%      4
  80%      4
  90%      5
  95%      5
  98%      6
  99%      6
 100%      9 (longest request)

ab -c 25 -n 10000 http://168.192.54.8/
This is ApacheBench, Version 2.3 <$Revision: 1706008 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 168.192.54.8 (be patient)
Completed 1000 requests
Completed 2000 requests
Completed 3000 requests
Completed 4000 requests
Completed 5000 requests
Completed 6000 requests
Completed 7000 requests
Completed 8000 requests
Completed 9000 requests
Completed 10000 requests
Finished 10000 requests

Server Software:        Apache/2.4.29
Server Hostname:        168.192.54.8
Server Port:            80

Document Path:          /
Document Length:        9381 bytes

Concurrency Level:      25
Time taken for tests:   8.788 seconds
Complete requests:      10000
Failed requests:        0
Total transferred:      96540000 bytes
HTML transferred:       93810000 bytes
Requests per second:    1137.91 [#/sec] (mean)
Time per request:       21.970 [ms] (mean)
Time per request:       0.879 [ms] (mean, across all concurrent requests)
Transfer rate:          10727.90 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        1    4  14.7      3    1037
Processing:     3   18   4.9     19      44
Waiting:        2    6   2.9      5      30
Total:          5   22  15.4     23    1050

Percentage of the requests served within a certain time (ms)
  50%     23
  66%     24
  75%     24
  80%     25
  90%     27
  95%     29
  98%     32
  99%     35
 100%   1050 (longest request)


text:
Q: Why Does "yes" have drastically different performance on different ditros? I tested yes using pv with following command on two different distros :
yes | pv > /dev/null

Results :
Ubuntu 16.04 : 5.83GiB/s
Centos 7.x : 100MiB/s
Here is my Specs:
1st distro : Ubuntu Ubuntu 16.04.6 LTS - VM(VMware Workstation) - 4GB ram - 4 CPU- kernel : 4.4.0-166-generic.x86_64
2nd distro : Centos 7.7.1908 (Core) - VM(Vmware Workstation) - 4GB ram
- 4 CPU- kernel : 3.10.0-1062.4.1.el7.x86_64
Vmware workstation 15.5 installed on Windows 10
I was wondering what is the cause of such difference between these two to write on the ram.
Why is Centos too slow to write on the ram?
or is Ubuntu making mistake on performance monitoring while writing on the ram?


text:
Q: camera app with collection view I am very new to XCode and Swift. Hope you guys can give me a hand here. I am having a problem that when I click the camera button, and snap a photo and click "Use Photo", the camera will be dismissed and back to the main page again.
What I actually want :
When I click "Use Photo" the main page should show the image taken just now in thumbnail size in collection view.
Camera Example
The expected output
Here is my code :
import UIKit
import CoreLocation
import Photos
import PhotosUI
import MessageUI

let albumName = "CP"

class SpeakerViewController: UIViewController,
CLLocationManagerDelegate, UIImagePickerControllerDelegate,
UINavigationControllerDelegate, UICollectionViewDataSource,
UICollectionViewDelegate, UICollectionViewDelegateFlowLayout,
MFMailComposeViewControllerDelegate {
@IBOutlet var lblLocation: UILabel!
@IBOutlet var tvNews: UITextView!
@IBOutlet var tapView: UIView!
@IBOutlet var btnAlbum: UIButton!
@IBOutlet var btnCamera: UIButton!
@IBOutlet var btnSend: UIButton!

let locationManager = CLLocationManager()
let geoCoder = CLGeocoder()

var latitude = [String]()
var longitude = [String]()
var tap : UITapGestureRecognizer! = UITapGestureRecognizer()
var assetCollection: PHAssetCollection! = PHAssetCollection()

var photoAsset : PHFetchResult<PHAsset>!

var albumFound : Bool = false
var sendLocation : String = ""
var sendContent : String = ""
var imageArray = [UIImage]()
var isCamera : Bool = false

@IBAction func btnBack(_ sender: AnyObject) {
    PHPhotoLibrary.shared().performChanges({
        PHAssetChangeRequest.deleteAssets(self.photoAsset)
        }, completionHandler: {(success, error) in
            NSLog("Delete image => %@", (success ? "Success" : "Error"))
            self.navigationController?.dismiss(animated: true, completion: nil)
    })
}

override func viewDidLoad() {
    super.viewDidLoad()
    LocalStore.setActiveView("speaker")
    self.navigationController?.navigationBar.isTranslucent = false
    self.navigationController?.navigationBar.barTintColor = UIColor(red: 255/255, green: 237/255, blue: 0/255, alpha: 1.0)

    if(locationManager.responds(to: #selector(CLLocationManager.requestAlwaysAuthorization))) {
        locationManager.requestAlwaysAuthorization()
    }
    locationManager.delegate = self

    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.startUpdatingLocation()

    tap = UITapGestureRecognizer(target: self, action: #selector(SpeakerViewController.DismissKeyboard))
    let fetchOptions = PHFetchOptions()
    fetchOptions.predicate = NSPredicate(format: "title = %@", albumName)
    let collection:PHFetchResult = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)

    if let first_Obj:AnyObject = collection.firstObject{
        //found the album
        self.albumFound = true
        self.assetCollection = first_Obj as! PHAssetCollection
    } else {
        var albumPlaceholder:PHObjectPlaceholder!
        NSLog("\nFolder \"%@\" does not exist\nCreating now...", albumName)
        PHPhotoLibrary.shared().performChanges({
            let request = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: albumName)
            albumPlaceholder = request.placeholderForCreatedAssetCollection
            },

            completionHandler: {success, error in
                if(success){
                    print("Successfully created folder")
                    self.albumFound = true
                    let collection = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [albumPlaceholder.localIdentifier], options: nil)
                    self.assetCollection = collection.firstObject as PHAssetCollection!
                } else {
                    print("Error creating folder")
                    self.albumFound = false
                }
        })
    }

    NotificationCenter.default.addObserver(self,
        selector: #selector(SpeakerViewController.keyboardShow(_:)),
        name: NSNotification.Name.UIKeyboardDidShow,
        object: nil)

    NotificationCenter.default.addObserver(self,
        selector: #selector(SpeakerViewController.keyboardHide(_:)),
        name: NSNotification.Name.UIKeyboardDidHide,
        object: nil)

    NotificationCenter.default.addObserver(self,
        selector: #selector(SpeakerViewController.applicationBecameActive(_:)),
        name: NSNotification.Name.UIApplicationDidBecomeActive,
        object: nil)

    NotificationCenter.default.addObserver(self,
        selector: #selector(SpeakerViewController.applicationBecameInactive(_:)),
        name: NSNotification.Name.UIApplicationWillResignActive,
        object: nil)
}

/* Start listening for iCloud user change notifications */
func applicationBecameActive(_ notification: Notification){
    print("did become active notification")
    if LocalStore.getPostIdMenu() != "0" {
        self.navigationController?.dismiss(animated: true, completion: nil)
        LocalStore.setPostIdMenu("0")
    }
}

func applicationBecameInactive(_ notification: Notification){
    print("did become inactive notification")
    LocalStore.setPostIdMenu("0")
}

func keyboardShow(_ notification: Notification) {
    print("Keyboard Show")
    self.view.addGestureRecognizer(tap)
}

func keyboardHide(_ notification: Notification){
    print("Keyboard Hide")
    self.view.removeGestureRecognizer(tap)
}

override func viewWillAppear(_ animated: Bool) {
    //fetch the photo from the collection
    self.navigationController?.hidesBarsOnTap = false
    self.photoAsset = PHAsset.fetchAssets(in: self.assetCollection, options: nil)
    self.collectionView.reloadData()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    let alertView = UIAlertController(title: "出现错误", message: "无法检索您的位置", preferredStyle: .alert)
    alertView.addAction(UIAlertAction(title: "好的", style: .default){ _ in})
    self.present(alertView, animated: true, completion: nil)
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    latitude.removeAll()
    longitude.removeAll()

    let currentLocation = locations.last!

    print("didUpdateToLocation: \(currentLocation)")

    latitude.append(String(format: "%.8f", currentLocation.coordinate.latitude))
    longitude.append(String(format: "%.8f", currentLocation.coordinate.longitude))

    print("Latitude \(latitude.count), Longtitude \(longitude.count)")

    geoCoder.reverseGeocodeLocation(currentLocation, completionHandler: {(placemarks, error) -> Void in
        if(error == nil && placemarks!.count > 0 ) {
            let placeMark = placemarks![0] as CLPlacemark

            if (placeMark.addressDictionary?["Thoroughfare"] as? String) != nil {

                self.lblLocation.text = "\(placeMark.thoroughfare!), \(placeMark.postalCode!), \(placeMark.administrativeArea!)"
                print("Location \(placeMark.locality!)\(placeMark.country!)")
                self.locationManager.stopUpdatingLocation()
                self.sendLocation = self.lblLocation.text!
            } else {
                print("thoroughfare not found, reupdate coordinate")
                self.locationManager.delegate = self
                self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
                self.locationManager.startUpdatingLocation()
            }
        } else {
            NSLog("%@", error.debugDescription)
        }
    })
}

func DismissKeyboard() {
    view.endEditing(true)
}

@IBOutlet var collectionView: UICollectionView!
@IBAction func btnAlbum(_ sender: AnyObject) {
    isCamera = false

    if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.savedPhotosAlbum)) {
        let imagePicker : UIImagePickerController = UIImagePickerController()
        imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
        imagePicker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
        imagePicker.delegate = self
        imagePicker.allowsEditing = false
        self.present(imagePicker, animated: true, completion: nil)
    }
}

@IBAction func btnCamera(_ sender: AnyObject) {
    isCamera = true
    if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)) {
        let imagePicker : UIImagePickerController = UIImagePickerController()
        imagePicker.sourceType = UIImagePickerControllerSourceType.camera
        imagePicker.delegate = self
        imagePicker.allowsEditing = false
        self.present(imagePicker, animated: true, completion: nil)
    } else {
        let alert = UIAlertController(title: "出现错误", message: "您的手机没有相机", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "好的", style: .default, handler: {(alertAction) in
            alert.dismiss(animated: true, completion: nil)
        }))

        self.present(alert, animated: true, completion: nil)
    }
}

@IBAction func btnSend(_ sender: AnyObject) {
    var count : Int = 0
    if(self.photoAsset != nil) {
        count = self.photoAsset.count
    }

    if (tvNews.text != "" && count > 0) {
        sendContent = tvNews.text

        if (MFMailComposeViewController.canSendMail()) {
            let emailTitle = "App"
            let messageBody = "位置: \(sendLocation) \n\n \(sendContent) \n\n "
            let toReceipients = ["test@com"]
            let mc : MFMailComposeViewController = MFMailComposeViewController()
            mc.mailComposeDelegate = self
            mc.setSubject(emailTitle)
            mc.setMessageBody(messageBody, isHTML: false)
            mc.setToRecipients(toReceipients)
}
            for image in self.imageArray {
                let photoData : Data = UIImagePNGRepresentation(image)!
                mc.addAttachmentData(photoData, mimeType: "image/png", fileName: "CP.png")
            }

            self.present(mc, animated: true, completion: nil)
        } else {
            print("No email account found")
        }
    } else {
        let alertView = UIAlertController(title: "出现错误", message: "没有内容或照片", preferredStyle: .alert)
        alertView.addAction(UIAlertAction(title: "好的", style: .default, handler: {(alertAction) in
            alertView.dismiss(animated: true, completion: nil)
        }))
        self.present(alertView, animated: true, completion: nil)
    }
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    var count : Int = 0
    if(self.photoAsset != nil) {
        count = self.photoAsset.count
    }

    return count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell: PhotoCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell", for: indexPath) as! PhotoCollectionViewCell
    let asset : PHAsset = self.photoAsset[(indexPath as NSIndexPath).item] as PHAsset

    PHImageManager.default().requestImage(for: asset, targetSize: PHImageManagerMaximumSize, contentMode: .aspectFill, options: nil, resultHandler: {(result, info) in
        if let image = result {
            cell.setThumbnailImage(image)
            self.imageArray.append(image)
        }
    })

    return cell
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if(segue.identifier == "viewLargePhoto") {
        if let controller:ViewPhotoViewController = segue.destination as? ViewPhotoViewController {
            if let cell = sender as? UICollectionViewCell {
                if let indexPath: IndexPath = self.collectionView.indexPath(for: cell) {
                    controller.index = (indexPath as NSIndexPath).item
                    controller.photoAsset = self.photoAsset
                    controller.assetCollection = self.assetCollection
                }
            }
        }
    }
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 4
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 1
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if(isCamera) {
        let image = info["UIImagePickerControllerOriginalImage"] as! UIImage
        PHPhotoLibrary.shared().performChanges({
            let createAssetRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
            let assetPlaceholder = createAssetRequest.placeholderForCreatedAsset
            if let albumChangeRequest = PHAssetCollectionChangeRequest(for: self.assetCollection,
                assets: self.photoAsset as PHFetchResult<PHAsset>) {

                let enumeration: NSArray = [assetPlaceholder!]
                albumChangeRequest.addAssets(enumeration)
            }
            //CORRECTION Error : App crashes
            }, completionHandler: {(success, error) in
                NSLog("Adding Image to Library => %@",(success ? "Success" : "Error!"))
                //Relocated1

        })
        //CORRECTION Relocated1

        picker.dismiss(animated: true, completion: nil)

    } else {
        let image = info["UIImagePickerControllerOriginalImage"] as! UIImage
        PHPhotoLibrary.shared().performChanges({
            let createAssetRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
            let assetPlaceholder = createAssetRequest.placeholderForCreatedAsset
            if let albumChangeRequest = PHAssetCollectionChangeRequest(for: self.assetCollection,

                assets: self.photoAsset as PHFetchResult<PHAsset>) {

                let enumeration: NSArray = [assetPlaceholder!]
                albumChangeRequest.addAssets(enumeration)
            }
            }, completionHandler: {(success, error) in
                NSLog("Adding Image to Library => %@",(success ? "Success" : "Error!"))
                picker.dismiss(animated: true, completion: nil)
                //self.navigationController?.dismiss(animated: true, completion: nil)
        })
    }
}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    picker.dismiss(animated: true, completion: nil)
}

func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
    switch result {
    case .cancelled:
        let alertView = UIAlertController(title: "取消电邮", message: "您已经取消电邮", preferredStyle: .alert)
        alertView.addAction(UIAlertAction(title: "好的", style: .default, handler: {(alertAction) in
            alertView.dismiss(animated: true, completion: nil)
        }))
        self.present(alertView, animated: true, completion: nil)
    case .saved:
        let alertView = UIAlertController(title: "保存电邮", message: "您已经保存电邮", preferredStyle: .alert)
        alertView.addAction(UIAlertAction(title: "好的", style: .default, handler: {(alertAction) in
            alertView.dismiss(animated: true, completion: nil)
        }))
        self.present(alertView, animated: true, completion: nil)
    case .sent:
        let alertView = UIAlertController(title: "发送电邮", message: "您已经发送您的电邮", preferredStyle: .alert)
        alertView.addAction(UIAlertAction(title: "好的", style: .default, handler: {(alertAction) in
            alertView.dismiss(animated: true, completion: nil)
        }))
        self.present(alertView, animated: true, completion: nil)
    case .failed:
        let alertView = UIAlertController(title: "发送失败", message: "请检查您的电邮设定", preferredStyle: .alert)
        alertView.addAction(UIAlertAction(title: "好的", style: .default, handler: {(alertAction) in
            alertView.dismiss(animated: true, completion: nil)
        }))
        self.present(alertView, animated: true, completion: nil)
    //CORRECTION default:
      //  break
    default :
        break
    }

    self.dismiss(animated: false, completion: nil)
  }
}

Thanks in advance!


text:
Q: URLDecoder in android Please see this link.We will be able to send the data by the following code:
String data = URLEncoder.encode("name", "UTF-8")
                         + "=" + URLEncoder.encode(Name, "UTF-8");

            data += "&" + URLEncoder.encode("email", "UTF-8") + "="
                        + URLEncoder.encode(Email, "UTF-8");

            data += "&" + URLEncoder.encode("user", "UTF-8")
                        + "=" + URLEncoder.encode(Login, "UTF-8");

            data += "&" + URLEncoder.encode("pass", "UTF-8")
                        + "=" + URLEncoder.encode(Pass, "UTF-8");

and then when the php file tries to send the string variables using the echo command, How can I get the variable values in php separately in java variables?
As a visual description, I want such a thing:
//in java-> String name = echo "$name" //in php
//in java-> String pass = echo "$pass" //in php and etc.

in existing code in the link we can assign the all input strings only in the one variable java such as text = sb.toString();. I want assign for each echo $variable in php, one specific variable in java that as the result I can display each of them in arbitrary places in activity. Please explain me on based the link to prevent bewilderment. Thank you.

A: Do following in php:
echo "{";
echo "\"name\":\"$name\",\"pass\":\"$pass\"";
echo "}";

Use following in java code:
String response = ""; // response from php page.
    String name,pass;
    try
    {
        JSONObject obj = new JSONObject(response);
        name = obj.getString("name"); // value of $name
        pass = obj.getString("pass"); // value of $pass
    } catch (JSONException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Do read about JSON to have better understanding about it.


text:
Q: Как сделать так чтобы змейка не образовала бесконечную линию Я создавал игру змейка. При написании кода столкнулся с проблемой. Змея образовала бескончную линию. Написал snake.pop() для удаления последнего элемента массива но ничего не вышло.
Вот код:

var canvas        =document.getElementById('game')
var ctx           =canvas.getContext('2d')
var box           =10
var snake         =[]
var px            =(canvas.width/2)
var py            =(canvas.height/2)
var dir           ='right'
var maxCell       =10

function direction(){
  document.addEventListener("keydown",function(e){
    if(e.keyCode==37){
      dir='left'
      console.log('left')
    }
    else if(e.keyCode==38){
      dir='up'
      console.log('up')
    }
    else if(e.keyCode==39){
      dir='right'
      console.log('right')
    }
    else if(e.keyCode==40){
      dir='down'
      console.log('down')
    }
  })

  if(dir=='right' && dir!=='left'){px+=box }
  else if(dir=='left' && dir!=='right'){px-=box}
  else if(dir=='up' && dir!=='down'){py-=box}
  else if(dir=='down' &&dir!=='up'){py+=box}
}
function Snake(){
  direction()
  snake[0]={
    x:px,
    y:py,
  }
  if(px>canvas.width){
    px=0
  }
  else if(px<0){
    px=canvas.width
  }
  if(py>canvas.height){
    py=0
  }
  else if(py<0){
    py=canvas.height
  }
  snake.forEach( function(element, index) {
    ctx.fillRect(px,py,box,box)
    if(index==0){
      ctx.fllStyle='red'
      ctx.fillRect(px,py,box,box)
    }
  });
  if(snake.length>maxCell){
    snake.shift()
  }
}
function loop(){
  setInterval(()=>{
    Snake()
  },1000/60)
}

loop()
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      canvas{
        border: 1px solid #000; /*elevate our canvas and add shadow*/
      }
    </style>
  </head>
  <body>
    <canvas id="game" width="450" height="450">
    </canvas>
    <script src="./snake.js"></script>
  </body>
</html>

A: Необходимо очищать canvas перед отрисовкой следующего положения ctx.clearRect(0, 0, canvas.width, canvas.height). Слушатель document.addEventListener навешивать вне функции direction()..

var canvas = document.getElementById('game')
var ctx = canvas.getContext('2d')
var box = 10
var snake = []
var px = (canvas.width / 2)
var py = (canvas.height / 2)
var dir = 'right'
var maxCell = 10
var can = canvas.getBoundingClientRect()

document.addEventListener("keydown", function(e) {
  if (e.keyCode == 37) {
    dir = 'left'
    //console.log('left')
  } else if (e.keyCode == 38) {
    dir = 'up'
    //console.log('up')
  } else if (e.keyCode == 39) {
    dir = 'right'
    //console.log('right')
  } else if (e.keyCode == 40) {
    dir = 'down'
    //console.log('down')
  }
})

function direction() {
  if (dir == 'right') {
    px += box;
  } else if (dir == 'left') {
    px -= box;
  } else if (dir == 'up') {
    py -= box;
  } else if (dir == 'down') {
    py += box;
  }
}

function Snake() {

  ctx.clearRect(0, 0, canvas.width, canvas.height);

  direction();
  snake[0] = {
    x: px,
    y: py,
  }
  if (px >= canvas.width) {
    px = 0
  } else if (px < 0) {
    px = canvas.width
  }
  if (py >= canvas.height) {
    py = 0
  } else if (py < 0) {
    py = canvas.height
  }
  snake.forEach(function(element, index) {
    ctx.fillRect(px, py, box, box)
    if (index == 0) {
      ctx.fllStyle = 'red'
      ctx.fillRect(px, py, box, box)
    }
  });
  if (snake.length > maxCell) {
    snake.shift()
  }

}

function loop() {
  setInterval(() => {
    Snake()
  }, 1000 / 60)
}

loop()
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
  <style>
    canvas {
      border: 1px solid #000;
      /*elevate our canvas and add shadow*/
    }
  </style>
</head>

<body>
  <canvas id="game" width="450" height="450">
    </canvas>
  <script src="./snake.js"></script>
</body>

</html>


text:
Q: How to create a Spring Boot Actuator endpoint that delegates all calls to a different port? I'm using Spring Boot 2.7.5 and I want to create an actuator endpoint, that acts as a proxy, and forwards all requests to a different server, running on the same JVM instance, but on a different port (say 8082). Here's the gist of it:
@Component
@RestControllerEndpoint(id = "myEndpoint", enableByDefault = true)
public class MyEndpoint {

    @RequestMapping("**")
    public Object myEndpoint() {
        // TODO Forward everything to port 8082
        return ...
    }
}

What do I need to do in order to achieve this?
Update 1:
The port (8082) is not available from the internet so I can't do a simple redirect.
Update 2:
I don't want to forward the request to a Spring Controller or Spring Bean. Port 8082 is a separate server started in the same process.

A: What if instead of a redirect (as suggested in other replies) your actuator would perform a call to localhost:8082 and return it's return it's response? You could also return a ResponseEntity instead of just an Object to cascade the HTTP codes of the performed request.
    @Component
    @RestControllerEndpoint(id = "myEndpoint", enableByDefault = true)
    public class MyEndpoint {
        private static final String TARGET_HOST = "localhost";
        private static final int TARGET_PORT = 8082;

        @RequestMapping("**")
        public Object myEndpoint(HttpServletRequest originalRequest) {
            Uri targetUri = UriComponentsBuilder.fromHttpRequest(originalRequest)
                .host(TARGET_HOST)
                .port(TARGET_PORT)
                .build();
            Object responseBody = /* code to perfom the call using your preferred HTTP client*/;
            return responseBody;
        }
    }

A:
Spring Boot Actuator endpoint that delegates all calls to a different port.

*

*For different port use this in your application.properties file
management.server.port=8081
management.endpoints.web.exposure.include=*

This will expose all actuator endpoints on port 8081.

A: The official document describes :

Base path for Web endpoints. Relative to the servlet context path (server.servlet.context-path) or WebFlux base path (spring.webflux.base-path) when the management server is sharing the main server port. Relative to the management server base path (management.server.base-path) when a separate management server port (management.server.port) is configured.

You can configure the following
management:
  server:
    port: 8081
    servlet:
      context-path:
  endpoints:
    web:
      base-path: /
      path-mapping:
        prometheus: metrics
      exposure:
        include: [ "prometheus" ]

Tip : This configuration must be different with the server.ports must be different.
For more details, please check appendix.application-properties.actuator


text:
Q: How do I solve a Cannot read property error? The following is a code block that's throwing an error in the console. The function is implemented in the service of my angular application.
    lastEmployeeID()  //code block that's throwing error
    {
     let temp= this._http.get(this._employeesUrl).subscribe((employees:any)
      =>  temp = employees,err => console.log(err));
     let last=temp[temp.length-1].id;
     return last;
    }

Here is the error:

ERROR TypeError: Cannot read property 'id' of undefined at
  EmployeesService.lastEmployeeID (employees.service.ts:43) at
  AddEmployeeFormComponent.onSubmit (addemployee-form.component.ts:19)
  at Object.eval [as handleEvent] (AddEmployeeFormComponent.html:3) at
  handleEvent (core.js:13542) at callWithDebugContext (core.js:15051) at
  Object.debugHandleEvent [as handleEvent] (core.js:14638) at
  dispatchEvent (core.js:9957) at eval (core.js:12296) at
  SafeSubscriber.schedulerFn [as _next] (core.js:4339) at
  SafeSubscriber.__tryOrUnsub (Subscriber.js:240)

A: I'll try to explain the issues here:
lastEmployeeID() {
  // Here you're assigning the subscription to the get request to temp
  let temp= this._http.get(this._employeesUrl).subscribe(
    (employees:any) =>  temp = employees, // This will only happen when the get request completes
    err => console.log(err)
  );

  // By the time you get here, the get request will most likely not
  // have finished and so "temp = employees" will not have been called.
  // So you are trying to get temp[temp.length-1] where temp is not an
  // array but rather a subscription.
  let last=temp[temp.length-1].id;
    return last;
  }

Here is one way you could approach this:
lastEmployeeID(): Observable<any> {
  return new Observable(observer => {
    this._http.get(this._employeesUrl).subscribe(employees => {
      observer.next(employees[employees.length-1].id)
    }, err => {
      console.log(err))
      observer.error(err)
    }
  })
}


text:
Q: How to solve an abstract model using Pyomo in Google Colab I am learning how to use Pyomo in Google Colab and I created an Abstract model, but I dont know the coding to read the data file and solve the model. The documentation gives instructions about the command prompt but it is not the case as I am working with Google Colab.
I will highly appreaciate your help.

A: !pip install pyomo
from pyomo.environ import *
import matplotlib.pyplot as plt
!wget -N -q "https://ampl.com/dl/open/ipopt/ipopt-linux64.zip"
!unzip -o -q ipopt-linux64

model = AbstractModel()
model.x = Var(bounds=(0,1.2), within=Reals)
model.obj1 = Objective(expr=model.x**2, sense=maximize)
#opt = SolverFactory('ipopt')
opt=SolverFactory('ipopt', executable='/content/ipopt')
instance = model.create_instance()
results = opt.solve(instance) # solves and updates instance
print('OF= ',value(instance.obj1))


text:
Q: Where do I find logs for x2go windows client? I am tring to connect from Windows x2go client to linux server with x2go, black window splashes and goes away, I can't catch the error message. Where can I find a log file?

A: Was about to answer on your other question but it's now closed.

There's no dedicated x2go log file. This is because x2go server uses SSH (that's the answer I was given when I had to troubleshoot my X2Go).

You can still browse /var/log/auth.log and there you should be able to find why you're thrown out.


text:
Q: Word or a phrase for finance sharing in groups? Is there a word or a phrase for a financial scenario where all participants put money in one pile and then the organizer uses that money to buy whatever the group agreed upon (eg. airplane tickets, concert tickets, birthday gift...)?
Some examples:

*

*Let's _____, it'll be much more efficient.

*One benefit of _____ is getting a discount for a larger purchase.

*Skyler plans to organize _____ for our trip to London.
Let me make an analogy with carpooling:

*

*Let's carpool, it'll be much more efficient.

*One benefit of carpooling is bypassing the traffic by using the carpool lane.

*Skyler plans to carpool for the next three months.

A: You've almost given the answer yourself with "carpooling": a pool is

3: an aggregation of the interests or property of different persons made to further a joint undertaking by subjecting them to the same control and a common liability

(source: Merriam-Webster)
Since pool has some other meanings as well (a swimming pool, a billiard game) you might need to specify what you're pooling to avoid ambiguation.
A related concept is group buying or collective buying, but there you usually don't know the other participants; there is usually some third party service trying to make the group as large as possible. (I assume you do know the other participants, given the examples you mention.) It would fit perfectly in sentence 2 though.


text:
Q: How to write find clause using where user_id =current_user.id I have a one to many relationship between 1 user and many challenges. I am using rails 4 with Devise
I would like to list the challenges for the current user.
So far I have
@challenge = User.find(current_user.id).challenges

and I've also tried
@challenge = User.find(current_user).challenges

and I also tried @challenge = current_user.challenges
but it doesn't work. I get the error "undefined methodeach' for nil:NilClass"`  which usually means @challenge isn't being passed over to the view Have I made some kind of syntax error?
if I do User.find(1).challenges in the rails console it works fine so presumably I'm not using current_user.id correctly

A: It looks like when you are trying to access the page user is not logged in and hence current_user is set to nil.
current_user.challenges will do the job of fetching all challenges associated to this user. You can use user_signed_in? method from devise before calling this code to ensure current_user is always available.


text:
Q: How to show toast in extjs at the top of the screen? By default Ext.toast shows messages at the bottom of the screen. However, this is not very practical because toast might not be visible when virtual keyboard is shown.
How can Ext.toast be configured to pops up at the top of the screen?

A: You can use aligment property:
Ext.toast({
    message: "Hallo Welt!",
    alignment: 'tc-tc',
    timeout: 2000
});

Aligment values are described here.


text:
Q: Insert on ObservableCollection causes Win32Exception I'd like to Insert an item into an ObservableCollection which is bound using a ComboBox on the dispatcher thread (ensured by using a DispatcherTimer). The insert call will cause the application to crash with a non-debuggable Win32Exception (looking like this), if an item is selected in the ComboBox. When the item is Added instead of Inserted, the code will run as expected.
Minimal code example:
<Page
x:Class="App1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <ComboBox x:Name="comboBox" HorizontalAlignment="Left" Margin="77,59,0,0" VerticalAlignment="Top" Width="120"
              ItemsSource="{Binding Data}">

        <ComboBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Text}" />
            </DataTemplate>
        </ComboBox.ItemTemplate>

    </ComboBox>

    <Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="202,58,0,0" VerticalAlignment="Top" Click="button_Click"/>

</Grid>

</Page>

And the code behind:
public class MyData
{
    public string Text { get; set; }
}

public sealed partial class MainPage : Page
{
    public ObservableCollection<MyData> Data { get; set; }

    public MainPage()
    {
        DataContext = this;

        Data = new ObservableCollection<MyData>()
        {
            new MyData { Text = "Lorem" }
        };

        this.InitializeComponent();
    }

    private void button_Click(object sender, RoutedEventArgs e)
    {
        var timer = new DispatcherTimer();
        timer.Interval = TimeSpan.FromSeconds(1);
        timer.Tick += (_, __) => { Data.Insert(0, new MyData { Text = "Ipsum" }); /* crash */ };
        timer.Start();
    }

}

Is there a way to insert the item without causing the app to crash?

A: The problem seems to occur once you try to 'touch' selected item - ObservableCollection uses List.Insert method, which as you can see at reference uses Array.Copy. The selected item is copied and then replaced at old index with new item, this probably is not handeled by Combobox and causes exception.
Note that when you select item at 0 position and then insert items at 1st index, there will be no exception. Similar - if no item is selected, there will be no exception while inserting at any position. So as a workaround, if appliciable, you may try to set Combobox.Selected item to null before starting inserting, what may work.


text:
Q: Theano Tutorial Computing the Jacobian with Scan In the Theano Tutorial:
http://deeplearning.net/software/theano/tutorial/gradients.html
or
>>> import theano
>>> import theano.tensor as T
>>> x = T.dvector('x')
>>> y = x ** 2
>>> J, updates = theano.scan(lambda i, y,x : T.grad(y[i], x), sequences=T.arange(y.shape[0]), non_sequences=[y,x])
>>> f = theano.function([x], J, updates=updates)
>>> f([4, 4])
array([[ 8.,  0.],
       [ 0.,  8.]])

"theano.scan" is used to compute the Jacobian. I understand how to compute the Jacobian by hand but I do not quite understand how the function scan is calculating it iteratively; specifically, I don't understand how the "zeroes" are obtained in the Jacobian.
Can someone show me, for each iteration, how this is calculated? Thanks!


text:
Q: Calling a method from within a function passed as an argument I have a classlike thing (button). When instantiating it, I pass an onClick function as an argument to its constructor. In response to a click, I want the button instance's "deactivate()" method to be called. How do I properly refer to that method from within that function-passed-as-argument?
button = function(onclick){
  this.deactivate = function(){
    activeButton = null;
  }
  this.onclick = function(){onclick()};
}

var makeMainMenu = function(){
  this.multiplayerButton = new button(function(e){
    //onClick function of multiplayerButton:
    mainMenu.multiplayerButton.deactivate(); //HELP HERE
    selectDifficultyMenu = makeSelectDifficultyMenu();
    mainMenu.all.hide();
  });
}

mainMenu = makeMainMenu();


text:
Q: Use Long value as drop and take in a quill query I have a simple endpoint which returns some records from a database. The endpoint supports pagination.
Therefor i have the following quill-query
query[HandbookModule].drop(lift(offset)).take(lift(limit))
I want to support int64/Long values for the pagination but quill only supports Int values as far as i know.
Did I just miss how to do this or is this not possible with quill.

A: 32-bit integer max value is well over 2 billion. Are you sure your database will actually ever have that volume? Maybe narrowing that long to int will do the job?
Anyway, you can customize quill to some extent with infix dsl:
def find(..., take: Long, ...) = {
    implicit class LongTake[T](q: Query[T]) {
      def lTake(l: Long) = quote(infix"$q take $l".as[Query[T]])
    }
    query[HandbookModule].drop(lift(offset)).lTake(lift(limit))
}


text:
Q: Intersecting Circles. Let $O_1$ , $O_2$ be the centers of circles $C_1$ , $C_2$ in a plane respectively, and the circles meet at two distinct points $A$ , $B$ . Line $O_1$$A$ meets the circle $C_1$ at point $P_1$ , and line $O_2$$A$ meets the circle $C_2$ at point $P_2$. Determine the maximum number of points lying in a circle among these 6 points $A$, $B$, $O_1$ , $O_2$ , $P_1$ and $P_2$.
I drew the two circles, but both the points $P_1$ and $P_2$ coincide with the point $A$.   Is this method of solving the question correct?

A: Analysis & Solution
Notice that $\angle ABP_1+\angle ABP_2=90^o+90^o=180^o$. Hence, $P_1, B, P_2$ are collinear. Thus, we have three groups of collinear points, which are $(A, O_1, P_1), (A, O_2, P_2)$ and $(P_1, B,P_2).$
On one hand,we may claim that, no matter what $5$ points we pick among the given $6$ points, or we pick all of them, there necessarily exists at least one group of collinear points, which is not concylic. For this reason, we obtain the fact,there exists no more than $4$ concyclic points  among the given $6$ points.
One the other hand, we may pick $4$ points such that they are concylic, for example, we want $O_1, O_2, P_1, P_2$ are concylic. For this purpose, we only need $c_1$ and $c_2$ are equal circles. (Can you prove this?)
Now, we may conclude, the maximum number of points lying in a circle among the six is $4.$

A: If the correction as described in the comments is taken to be true, then you can prove that $P_1, B$ and $P_2$ are collinear. (Sketch it out and first prove that $ABP_1$ is a right angle.)
After proving this, you can reason that a maximum of four of the six points can lie on a circle.


text:
Q: Is it possible to host an iframe in one domain and target it to a different domain? I have a web application which tries to make a http request using jQuery to another API in a different domain which I don't have the control. That API does not return Origin in the response header so the browser prevents from sending response to the application with an error "Origin not found in Access-Control-Allow-Origin header". So I am trying to implement an iFrame through which the web application can send a message to API.
Is it possible to have (host) the iFrame in my web application domain and target it to the API domain? Or do I have to ask the third party API to host the iFrame in their domain? Is there any way at all to do it without dealing with the third party?
Thanks for any advice.


text:
Q: How to use spark streaming from a file system input I want to use spark streaming and give the input from file system (say HDFS ).How will I do it

A: For instance, when using JavaStreamingContext there are appropriate methods methods, e.g. textFileStream() to read any text files, fileStream() to read files from Hadoop-compatible filesystem. The directory you pass as a parameter of the API will be monitored for changes. In case you are going to move any file there it will be picked up by Streaming application depending on batch interval.
Please have a look at my simple samples at github to read data either from Twitter or from file system.
Hope that will help.


text: Q: Как получить тип размером на 1 больше, чем данный? Как получить тип размером на 1 больше, чем данный T (в смысле минимальный по размеру тип, больше данного)? Для T = int, например, long int, если первый 4 байта, а второй 8. Или long long int, если long int тоже 4 байта, а long long int 8 байтов. Если бОльшего типа нет, то тот же самый тип вернуть (либо substitution failure). Можно ли это сделать без явного перечисления всех комбинаций через std::conditional?


text:
Q: MongoDB aggregation results This is probably a really easy answer, but I am just not quite understanding aggregation results. Whenever I see anything about aggregation it is defined with only results, it doesn't specify where the results are going, some places make it seem like they are being directly output in the console while other places make it seem like it is being placed into a new collection or something like that. I have been working with Mongo but I've been trying to learn as I go while I'm working on things. when I actually try and use an aggregation within my own code I get nothing in the console, so since I'm not sure where the results are actually going I'm not sure if something is wrong by not getting anything in the console. the entire idea of aggregation seems straightforward, I'm just confused about where and how I can manipulate the data of the aggregation.
SoundSpot.aggregate([
{
$geoNear: {
 near: { type: "Point", coordinates: [ longitude , latitude ] },
//coordinates: [longitude, latitude]
 distanceField: "location.calculated",
 maxDistance: 200, //Meters
 includeLocs: "location.location",
 num:3 ,
 spherical: true
 }
}]);


text:
Q: openshift form sendgrid ajax form html5 PHP BootStrap I am trying to use an HTML form on openshift. The form controlled by Ajax. I can successfully send from OpenShift using a seperate page for the form, but I would like to use the BootStrap form. Bootstrap template is freelancer at Start BootStrap
I tried replacing the sendgrid code where the send php command was and moved return true to the end of the file.
working now-I must have had something wrong in my configuration. leaving here in case someone else wants to get a form working with openshift and sendgrid.

<?php
// Check for empty fields
if(empty($_POST['name'])    ||
   empty($_POST['email'])   ||
   empty($_POST['phone'])   ||
   empty($_POST['message']) ||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
 echo "No arguments Provided!";
 return false;
   }

// Create the email and send the message
$to = 'xxxx'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
//mail($to,$email_subject,$email_body,$headers);

// use actual sendgrid username and password in this section
$url = 'https://api.sendgrid.com/';
$user = 'xxxxx'; // place SG username here
$pass = 'xxxxx'; // place SG password here

// grabs HTML form's post data; if you customize the form.html parameters then you will need to reference their new new names here
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['phone'];
$message = $_POST['message'];

// note the above parameters now referenced in the 'subject', 'html', and 'text' sections
// make the to email be your own address or where ever you would like the contact form info sent
$params = array(
    'api_user'  => "$user",
    'api_key'   => "$pass",
    'to'        => "xxxxx", // set TO address to have the contact form's email content sent to
    'subject'   => "Contact Form Submission", // Either give a subject for each submission, or set to $subject
    'html'      => "<title> Contact Form</title>
    Name: $name\n

    Email: $email\n

    Subject: $subject\n

    Message: $message </title>", // Set HTML here.  Will still need to make sure to reference post data names
    'text'      => "
    Name: $name\n
    Email: $email\n
    Subject: $subject\n
    $message",
    'from'      => "xxxxxx", // set from address here, it can really be anything
  );

$request =  $url.'api/mail.send.json';

// Generate curl request
$session = curl_init($request);
// Tell curl to use HTTP POST
curl_setopt ($session, CURLOPT_POST, true);
// Tell curl that this is the body of the POST
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);

// obtain response
$response = curl_exec($session);
curl_close($session);
return true;
?>

contact_me php from bootstrap theme

<?php
// Check for empty fields
if(empty($_POST['name'])    ||
   empty($_POST['email'])   ||
   empty($_POST['phone'])   ||
   empty($_POST['message']) ||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
 echo "No arguments Provided!";
 return false;
   }

$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];

// Create the email and send the message
$to = 'yourname@yourdomain.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>

The working mailer.php

<?php
// use actual sendgrid username and password in this section
$url = 'https://api.sendgrid.com/';
$user = 'xxxxx'; // place SG username here
$pass = 'xxxxx'; // place SG password here

// grabs HTML form's post data; if you customize the form.html parameters then you will need to reference their new new names here
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];

// note the above parameters now referenced in the 'subject', 'html', and 'text' sections
// make the to email be your own address or where ever you would like the contact form info sent
$params = array(
    'api_user'  => "$user",
    'api_key'   => "$pass",
    'to'        => "xxxxx", // set TO address to have the contact form's email content sent to
    'subject'   => "Contact Form Submission", // Either give a subject for each submission, or set to $subject
    'html'      => "<title> Contact Form</title>
    Name: $name\n

    Email: $email\n

    Subject: $subject\n

    Message: $message </title>", // Set HTML here.  Will still need to make sure to reference post data names
    'text'      => "
    Name: $name\n
    Email: $email\n
    Subject: $subject\n
    $message",
    'from'      => "xxxxxxxx", // set from address here, it can really be anything
  );

$request =  $url.'api/mail.send.json';

// Generate curl request
$session = curl_init($request);
// Tell curl to use HTTP POST
curl_setopt ($session, CURLOPT_POST, true);
// Tell curl that this is the body of the POST
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);

// obtain response
$response = curl_exec($session);
curl_close($session);

// Redirect to thank you page upon successfull completion, will want to build one if you don't alreday have one available
header('Location: thanks.html'); // feel free to use whatever title you wish for thank you landing page, but will need to reference that file name in place of the present 'thanks.html'
exit();

// print everything out
print_r($response);

?>

the ajax file from the bootstrap template

$(function() {

    $("input,textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
            // additional error messages or events
        },
        submitSuccess: function($form, event) {
            event.preventDefault(); // prevent default submit behaviour
            // get values from FORM
            var name = $("input#name").val();
            var email = $("input#email").val();
            var phone = $("input#phone").val();
            var message = $("textarea#message").val();
            var firstName = name; // For Success/Failure Message
            // Check for white space in name for Success/Fail message
            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            $.ajax({
                url: "././mail/contact_me.php",
                type: "POST",
                data: {
                    name: name,
                    phone: phone,
                    email: email,
                    message: message
                },
                cache: false,
                success: function() {
                    // Success message
                    $('#success').html("
");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-success')
                        .append("Your message has been sent. ");
                    $('#success > .alert-success')
                        .append('
');

                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
                error: function() {
                    // Fail message
                    $('#success').html("
");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-danger').append("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                    $('#success > .alert-danger').append('
');
                    //clear all fields
                   // $('#contactForm').trigger("reset");
                },
            })
        },
        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});

/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
    $('#success').html('');
});

The bootstrap index.html form

Contact Me

                    <form name="sentMessage" id="contactForm" novalidate>

                                Name
                                <input type="text" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name.">

                                Email Address
                                <input type="email" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address.">

                                Phone Number
                                <input type="tel" class="form-control" placeholder="Phone Number" id="phone" required data-validation-required-message="Please enter your phone number.">

                                Message
                                <textarea rows="5" class="form-control" placeholder="Message" id="message" required data-validation-required-message="Please enter a message."></textarea>

                                <button type="submit" class="btn btn-success btn-lg">Send</button>

                    </form>

A: Pardon me. The script works as is! I am not sure why it was not working, but I must have somehow corrupted my installation. I am leaving this up in case someone else wants to get emails working with openshift.


text:
Q: Excel VBA Macro: Importing Workbooks, Copying Columns, And Looping Through Imported Workbooks I am trying to create a copy tool for my Finance VBA course group that allows a user to import a series of workbooks, copy the same several columns from each workbook, and aggregate those columns into a single workbook.
For convenience, I have attached a set of sample import files and the desired output for those files.
It is also import to note that in Q1 and Q2, it is simply column B being copied. However, in Q3, it is column B and C being copied.
This is my current code below. Currently, it is only copying from 1 workbook and is simply repeating the same column throughout the rest of the workbook (though I am able to import more than 1 workbook). Any help at all would be appreciated! Thank you!
Sub import()
Dim OutputWorkbook As Workbook, InputWorkbook As Workbook, lInputWorkbookName As String, fDialog As Office.FileDialog, _
varFile As Variant, i As Long, sheet As Worksheet, cell As Range, _
Interest_Income As Range, temp As String, sourceColumn As Range,  targetColumn As Range _

ThisWorkbook.Activate

On Error GoTo handler

Set OutputWorkbook = ThisWorkbook
Set targetColumn = OutputWorkbook.Sheets("Taxable Income Aggregate").Columns("C:XED")

ThisWorkbook.Activate

  ' Set up the File Dialog.
   Set fDialog = Application.FileDialog(msoFileDialogOpen)

   With fDialog
      Application.DisplayAlerts = False
      Application.ScreenUpdating = False
      Application.AskToUpdateLinks = False
      Application.CutCopyMode = False
  ' Allow user to make multiple selections in dialog box
      .AllowMultiSelect = True

  .Title = "Import Your Workbooks"

  .Filters.Clear
  .Filters.Add "Excel 97-2003 Workbook", "*.xls"
  .Filters.Add "Excel Workbook", "*.xlsx"
  .Filters.Add "Excel Binary Workbook", "*.xlsb"
  .Filters.Add "Macro-Enabled Workbook", "*.xlsm"
  .Filters.Add "All", "*.*"

  ' Show the dialog box.
      If .Show = True Then
        Application.ScreenUpdating = False

        For Each varFile In .SelectedItems
            Workbooks.Open (varFile)
            lInputWorkbookName = Mid(varFile, InStrRev(varFile, "\") + 1)
            Set sheet = varFile.Sheets("Taxable Income Summary").Columns("B")
            For Each sheet In Workbooks(lInputWorkbookName).Sheets("Taxable Income Summary").Columns("B")
                sourceColumn.Copy Destination:=targetColumn

                'For populating Taxable Income Aggregate
                'If sheet.Name Like "Taxable Income Summary" Then
                'End If
            Next

            Workbooks(lInputWorkbookName).Close
         Next

         OutputWorkbook.Sheets("Taxable Income Aggregate").Activate

         Application.ScreenUpdating = True
         Application.DisplayAlerts = True
         Application.AskToUpdateLinks = True
         Application.CutCopyMode = True
      Else
         MsgBox "You clicked Cancel in the file dialog box."
      End If
   End With

Exit Sub
handler:
    MsgBox Err.Description
End Sub

Copy Tool -> https://drive.google.com/file/d/0B-QauGO0OicTMEFEUlFvY28wNFU/view?usp=sharing
Input 3 -> https://drive.google.com/open?id=0B-QauGO0OicTUHJuMUs5UlVuU2s

A: Except for the "Q3 is column B and C" which I don't get (how to know when to do it), this should work:
Sub import()
  On Error GoTo handler
  ThisWorkbook.Activate

  Dim OutputWorksheet As Object
  Set OutputWorksheet = ThisWorkbook.Sheets("Taxable Income Aggregate")

  Dim actCol As Long
  actCol = 3

  With Application.FileDialog(msoFileDialogOpen)

    Application.DisplayAlerts = False
    Application.ScreenUpdating = False
    Application.AskToUpdateLinks = False
    Application.CutCopyMode = False

    .AllowMultiSelect = True
    .Title = "Import Your Workbooks"

    .Filters.Clear
    .Filters.Add "All Excel Files", "*.xl*"
    .Filters.Add "All Files", "*.*"

    If .Show = True Then
      Application.ScreenUpdating = False

      Dim varFile As Variant
      For Each varFile In .SelectedItems
        With Workbooks.Open(varFile)

          Dim xSheet As Object
          For Each xSheet In .Sheets
            If xSheet.Name Like "*Taxable Income Summary*" Then

              'Don't know how to ckeck for Q3
              'You still need to add that code

              xSheet.Columns("B").Copy OutputWorksheet.Column(actCol)
              actCol = actCol + 1
            End If
          Next
          .Close 0

        End With
      Next

      OutputWorksheet.Activate

    Else
      MsgBox "You clicked Cancel in the file dialog box."
    End If
  End With

  Application.AskToUpdateLinks = True

  Exit Sub

handler:
  MsgBox Err.Description
  Application.AskToUpdateLinks = True
End Sub

DisplayAlerts and ScreenUpdating will automatically set to True (so there is no need to do it manualy) and CutCopyMode never need to be turned to "True" (actually: it can not be turned to True at all)
I also "skipped" some of your variables.
The target to copy to is set via actCol
The rest should be self explaining to you.
If you still have questions or trouble, just write a comment.


text:
Q: issue on my recyclerview I'm trying to show up recyclerview and retrieve data from firebase but I got problem after adding images which I saved on firebase storage. It closed after scrolling. I have another recyclerview which is using the same database but it doesnt have issue. can you give me solution for this?
AllLaundries.java
   package com.example.rizkafs.laundrize;

            import android.content.Context;
            import android.os.Bundle;
            import android.support.annotation.Nullable;
            import android.support.v7.app.AppCompatActivity;
            import android.support.v7.widget.LinearLayoutManager;
            import android.support.v7.widget.RecyclerView;
            import android.util.Log;
            import android.view.View;
            import android.widget.ImageView;
            import android.widget.TextView;

            import com.bumptech.glide.Glide;
            import com.firebase.ui.database.FirebaseRecyclerAdapter;
            import com.firebase.ui.storage.images.FirebaseImageLoader;
            import com.google.firebase.database.DatabaseReference;
            import com.google.firebase.database.FirebaseDatabase;
            import com.google.firebase.database.Query;
            import com.google.firebase.storage.FirebaseStorage;
            import com.google.firebase.storage.StorageReference;

            /**
             * Created by Abi FS on 29.5.17.
             */
            public class AllLaundries extends AppCompatActivity {

                private Context context;

                @Override
                protected void onCreate(@Nullable Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_all_laundries);
                    DatabaseReference myRef = FirebaseDatabase.getInstance().getReference().child("places");
                    Query queryRef = myRef.orderByChild("jenis").equalTo("Laundry Kiloan");
                    RecyclerView rvView = (RecyclerView) findViewById(R.id.rv_main);
                    rvView.setHasFixedSize(true);
                    rvView.setLayoutManager(new LinearLayoutManager(this));

                    FirebaseRecyclerAdapter<DataLaundry, DataViewHolder> recyclerAdapter = new FirebaseRecyclerAdapter<DataLaundry, DataViewHolder>(
                            DataLaundry.class,
                            R.layout.laundry_card,
                            DataViewHolder.class,
                            queryRef
                    ) {
                        @Override
                        protected void populateViewHolder(DataViewHolder viewHolder, DataLaundry model, int position) {
                            viewHolder.setNamaTempat(model.getNama());
                            viewHolder.setAlamat(model.getAlamat());
                            viewHolder.setJenis(model.getJenis());
                            viewHolder.setImage(model.getImage_placeholder(), AllLaundries.this);
                        }
                    };
                    rvView.setAdapter(recyclerAdapter);
                }

                public static class DataViewHolder extends RecyclerView.ViewHolder {
                    View mView;
                    TextView txt_namaTempat;
                    TextView txt_alamat;
                    TextView txt_jenis;
                    ImageView imageView;

                    public DataViewHolder(View itemView) {
                        super(itemView);
                        mView = itemView;
                        txt_namaTempat = (TextView) itemView.findViewById(R.id.txt_judul);
                        txt_alamat = (TextView) itemView.findViewById(R.id.alamat);
                        txt_jenis = (TextView) itemView.findViewById(R.id.jenis);
                        imageView = (ImageView) itemView.findViewById(R.id.imageView);
                    }

                    public void setNamaTempat(String namaTempat) {
                        txt_namaTempat.setText(namaTempat);
                    }

                    public void setAlamat(String alamat){
                        txt_alamat.setText(alamat);
                    }

                    public void setJenis(String jenis) {
                        txt_jenis.setText(jenis);
                    }

                    public void setImage(String image, Context context) {
                        Log.d("DEBUG_", "Load image ");
                        FirebaseStorage storage = FirebaseStorage.getInstance();
                        StorageReference storageRef = storage.getReferenceFromUrl("gs://laundrize-68cee.appspot.com/");
                        StorageReference pathReference = storageRef.child(image);
                        Glide.with(context)
                                .using(new FirebaseImageLoader())
                                .load(pathReference)
                                .into(imageView);
                    }
                }
            }

Android Monitor
        06-19 00:30:35.736 14636-15761/com.example.rizkafs.laundrize E/AndroidRuntime: FATAL EXCEPTION: FirebaseStorage-Download-1
                                                                           Process: com.example.rizkafs.laundrize, PID: 14636
                                                                           java.lang.NoSuchMethodError: No static method zzax(Z)V in class Lcom/google/android/gms/common/internal/zzac; or its super classes (declaration of 'com.google.android.gms.common.internal.zzac' appears in /data/app/com.example.rizkafs.laundrize-1/base.apk)
                                                                               at com.google.firebase.storage.StreamDownloadTask.onCanceled(Unknown Source)
                                                                               at com.google.firebase.storage.StorageTask.zzf(Unknown Source)
                                                                               at com.google.firebase.storage.StreamDownloadTask.run(Unknown Source)
                                                                               at com.google.firebase.storage.StorageTask$8.run(Unknown Source)
                                                                               at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                                               at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                                               at java.lang.Thread.run(Thread.java:818)


text:
Q: How do I round a decimal result up in Thymeleaf (same behavior as Math.ceil)? I am doing table pagination logic for my project using Thymeleaf.
I have two values:

*

*int totalRows

*int rowsPerPage

The operation I want to do is something along the lines of Math.ceil((1.0 + totalRows) / rowsPerPage) to store in a variable that represents the total number of pages necessary.
However, I'm not sure how to do that ceil() operation to convert it from a decimal to an integer.

A: If you are working with Spring then you can add a bean that has the method you want Math.ceil. Then call this method in the template. Something like
@Component
public class ThymeMath {
    public int ceil(int a, int b) {
        return Math.ceil....
    }
}

Then in the template
${@thymeMath.ceil(a, b)}

That is in the case you really need to do it in Thymeleaf. In the more general case you can calculate the variable in the Java code and add it to the model.

A: You can just call Math.ceil with thymeleaf, use:
${T(Math).ceil(yourNumber)}

Since Math.ceil returns a double type, you can also encapsulate that in the following expression to remove the trailing ".0" if you wish (the last "1" is the min number of integer digits):
${#numbers.formatInteger(T(Math).ceil(yourNumber),1)}


text:
Q: Python Selenium - NoSuchElementException. Why do I keep getting this? I am trying to paste values into a form using Selenium in Python, but I keep getting NoSuchElementException as shown in the picture below.
I tried various find_element_by_xx but keep getting the same error.
Can anyone advise what I am doing wrong?
The form I'm filling in is a custom querying Cognos report. The ID is visible of the block (shown in the pic below), but it does not seem to be working.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
browser = webdriver.Chrome()
browser.get("website") #"website" is placeholder
elem = browser.find_element_by_id("PRMT_TB_N0000000016B521C0x000000002552DDD8_NS_")
elem.send_keys(Keys.CONTROL,'v')

Form:

Code:

Exception:

A: I figured it out.
Copy Full Xpath when inspecting the element and use find_element_by_xpath.


text:
Q: mysqli_fetch_array parameter error I have this problem where I am trying to get input from the user and then display information. The user is meant to insert an ID number, obtained by $_POST[PID], then I catch that in result and when I try to get the result and print their info. This is the code:
 $result = mysqli_query($connection, $_POST[PID]);

 while($row = mysqli_fetch_array($result))
 {
    echo some info
    echo "<br>";
 }

However such code yields this error:
mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given
How can I fix such error such that I am able to obtain the input and use it in mysqli_fetch_array

A: The second argument for mysqli_query() must be a query.
For instance:
$var = "insert into tbl where field = '{$_POST['PID']}'";
$result = mysqli_query($connect, $var);

Read it here:
http://www.w3schools.com/php/func_mysqli_query.asp

A: Refer to my answer from your previous question(similar to this question)
Obtain resource from POST php

A: Please learn about these functions to properly use them (Link here)
Instead of $_POST[PID] in mysqli_query() there must be some query string like
"select * from tablename where id ='". $_POST['PID']."'
Also, you need to enclose the key name within single quotes like $_POST['PID']


text:
Q: how many non-isomorphic group of order 15 are there? Let $G$ be group of order $15 = 3 \cdot 5  = p \cdot q$ , where $p < q$ are primes. I know that there exists a unique non abelian group of order $pq$ and one abelian non isomorphic group of order $pq$. I think here are two non isomorphic of order $15$
Am i right or wrong ?


text: Q: Full background color for chart.js version 2 I need to get the result in the answer given in this post How to set a full length background color for each bar in chartjs bar but with version 2. Basically it is to fill up the full length of the bar with a background color. Any ideas? Thanks in advance