dimanche 31 janvier 2016

How to randomly generate password Rails 4?

I have completed Railstutorial.org book. Now I want to change that only admin can register a new user with name and email. Password is automactically generated and sent to user'email. I'm stuck on how to randomly generate password for user. Can someone help me ? thank a lot.

model/user.fb
class User < ActiveRecord::Base
  attr_accessor :remember_token
  before_save { self.email = email.downcase }
  validates :name,  presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, length: { maximum: 255 },
                    format: { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }
  has_secure_password
  validates :password, presence: true, length: { minimum: 6 }, on: :create // this line will be removed

  # Returns the hash digest of the given string.
  def User.digest(string)
    cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
                                                  BCrypt::Engine.cost
    BCrypt::Password.create(string, cost: cost)
  end

  # Returns a random token.
  def User.new_token
    SecureRandom.urlsafe_base64
  end

  # Remembers a user in the database for use in persistent sessions.
  def remember
    self.remember_token = User.new_token
    update_attribute(:remember_digest, User.digest(remember_token))
  end

  # Returns true if the given token matches the digest.
  def authenticated?(remember_token)
    BCrypt::Password.new(remember_digest).is_password?(remember_token)
  end

   # Forgets a user.
  def forget
    update_attribute(:remember_digest, nil)
  end

  # Returns true if the given token matches the digest.
  def authenticated?(remember_token)
    return false if remember_digest.nil?
    BCrypt::Password.new(remember_digest).is_password?(remember_token)
  end
end

controller/admin/user_controller.rb
class Admin::UsersController < ApplicationController
  before_action :admin_user 
  before_action :logged_in_user 
  def new
    @user = User.new
  end

  def index
    @users = User.where(admin: false)
  end

  def show
    @user = User.find(params[:id])
    @subjects = @user.subjects
  end

  def create
    @user = User.new(user_params)
    if @user.save
      flash[:success] = "create new user successfully"
      redirect_to admin_users_url
    else
      render 'new'
    end  
  end

  def edit
    @user = User.find(params[:id])
  end

  def update
    @user = User.find(params[:id])
    if @user.update_attributes(user_params)
      flash[:success] = "Profile updated!"
      redirect_to admin_users_url
    else
      render 'edit'
    end
  end

  def destroy
    User.find(params[:id]).destroy
    flash[:success] = "User deleted!"
    redirect_to admin_users_url
  end

  private

    def user_params
      params.require(:user).permit(:name, :email, :password, :password_confirmation, :address, :phone, :admin)
    end
end

views/admin/new.html
<% provide(:title, 'Sign up') %>
<h1>add user</h1>

<div class="row">
  <div class="col-md-6 col-md-offset-3">
    <%= form_for [:admin, @user] do |f| %>
      <%= render 'shared/error_messages', object: @user %>

      <%= f.label :name %>
      <%= f.text_field :name, class: 'form-control' %>

      <%= f.label :email %>
      <%= f.email_field :email, class: 'form-control' %>

      <%= f.label :address %>
      <%= f.text_field :address, class: 'form-control' %>

      <%= f.label :phone %>
      <%= f.text_field :phone, class: 'form-control' %>

      <%= f.label :password %> // this line will be removed
      <%= f.password_field :password, class: 'form-control' %>// this line will be removed

      <%= f.label :password_confirmation, "Confirmation" %>// this line will be removed
      <%= f.password_field :password_confirmation, class: 'form-control' %>// this line will be removed

      <%= f.label :admin, 'Is this admin?' %>
      <%= f.select :admin, options_for_select(['false', 'true']) %><br>

      <%= f.submit "Save", class: "btn btn-primary" %>
    <% end %>
  </div>
</div>




HTTP Content-type header for any file

I have a requirement where I can upload any file (any file type) and on request I should send the file back to the browser. If the file is an image, I should display the image in the browser. If the file is of any other type, I should download the file. Please let me know the content-type that should set for the above requirement in my servlet.




Safely / securely send configuration information to front-end

I am a bit curious about the best way to send configuration information to the front-end - we have a web server serving up pages and an API server serving the JSON API - currently the urls for the API server are just in an Angular service, basically hardcoded in a front-end JS file. Something slightly more "secure" would be to send the configuration as some sort of object with each request. But I get the feeling that most people would say this is just obfuscation and not really secure at all. What is the best way to do this? Maybe there's just no way to prevent someone from redirecting requests to some other server besides ours?

One way to sort of solve this would be to direct all traffic back to the web server which in turn makes requests to the API, but I am not sure if that's a great solution.




how do i change the text inside a button using a php if else statement?

Im on a dynamic webpage written in php and would like to have an if else statement that would look inside mysql database table and check if the string "description" is present inside a certain database table column. if the word "description" is present echo "Visit Discounted Venue" text inside the button, else echo "Visit venue website" string inside the button.

I currently have the code below, its in a php file.

<?php 
  if(stripos( $forum_data['venue_url_text'],"discount") == false) ?>

" class="btn" target="_blank" rel="nofollow"> VISIT VENUE WEBSITE

" class="btn" target="_blank" rel="nofollow"> VISIT DISCOUNTED VENUE


Flask app on DigitalOcean droplet 404 Error

I've been trying to setup my Flask app on DigitalOcean but keep getting a 404 error:

Not Found The requested URL / was not found on this server. Apache/2.4.12 (Ubuntu) Server at recomeal.com Port 80

I've set up the site on Ubuntu 15.10 with apache2 and put my flask application in the /var/www/recomeal/Recomeal directory. I've been following this tutorial and don't know what went wrong. I've also pointed my domain name (recomeal.com) at the virtual machine and I know that part at least is working, I just can't get rid of the 404 error. Thanks so much for your help.

/etc/apache2/sites-available/recomeal.conf

<VirtualHost *:80>
                ServerName recomeal.com
                ServerAdmin jackbrucesimpson@gmail.com
                WSGIScriptAlias / /var/www/recomeal/recomeal.wsgi
                <Directory /var/www/recomeal/Recomeal/>
                        Order allow,deny
                        Allow from all
                </Directory>
                Alias /static /var/www/recomeal/Recomeal/static
                <Directory /var/www/recomeal/Recomeal/static/>
                        Order allow,deny
                        Allow from all
                </Directory>
                ErrorLog ${APACHE_LOG_DIR}/error.log
                LogLevel warn
                CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

/var/www/recomeal/recomeal.wsgi

#!/usr/bin/python3
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/recomeal/")

from Recomeal import app as application
application.secret_key = 'my key'




Old vs new. Which backend technology to choose?

So, I encountered the following problem:

My dream is to become Full-stack developer. But I have a lot of doubts. Which language should I learn?

On the one hand, we have such experienced "players" as Ruby on Rails, C# (with its ASP.NET), PHP and Java. On the other hand, we have such things as Node.js, Scala (with Play), Clojure.

Which one is more suitable for a novice? Which one is more in demand? I know, this question may be really stupid, but I would like to hear from experienced developers. I understand that there are more vacancies for older, more popular languages, but I've tried C#, Java and Ruby and I don't feel "Yeah, I really like it!"

P.S. Sorry if there are spelling mistakes in my question, I'm not a native speaker.




ActiveViewIndex is being set to '0' during postback?

A user is supposed to enter a number click a button and have dynamically added controls with forwards and backwards arrows to switch between the views. I add a view after the btnParseInput is pressed and switch my MultiView to that view. However afterwards if a user clicks the btnBackwards or btnForwards I recieve the following error.

ActiveViewIndex is being set to '0'. It must be smaller than the current number of View controls '0'. For dynamically added views, make sure they are added before or in Page_PreInit event. Parameter name: value

Master Page:

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="Assignment03MasterPage.master.cs" Inherits="privetsl_Assignment03_Assignment03MasterPage" %>

<!DOCTYPE html>

<html xmlns="http://ift.tt/lH0Osb">
<head runat="server">
    <title></title>
    <link href="../Content/bootstrap.css" rel="stylesheet" />
    <link href="../Content/Assignment03.css" rel="stylesheet" />
    <script src="../Scripts/jquery-1.9.1.js"></script>
    <script src="../Scripts/bootstrap.js"></script>
    <asp:ContentPlaceHolder id="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">

        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>

Code behind master page:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class privetsl_Assignment03_Assignment03MasterPage : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Session["_ViewCount"] = 0;
            Session["pageOn"] = -1;
        }
    }
}

Child page:

<%@ Page Title="" Language="C#" MasterPageFile="~/privetsl_Assignment03/Assignment03MasterPage.master" AutoEventWireup="true" CodeFile="Assignment03.aspx.cs" Inherits="privetsl_Assignment03_Default" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <div class="container-fluid text-center">
        <div class="jumbotron text-center">
            <h1>Assignment 03</h1>
        </div>
        <div class="mvDiv">
            <div class="fitDiv">
                <span>
                    <asp:TextBox ID="tbUserInput" runat="server"></asp:TextBox>
                    <asp:Button ID="btnParseInput" runat="server" Text="Go!" OnClick="btnParseInput_Click" />
                </span>
            </div>
            <br />
            <asp:MultiView ID="mvFillMe" runat="server"></asp:MultiView>
            <br />
            <div class="fitDiv">
                <span>
                    <asp:Button CssClass="btnBackwards" ID="btnBackwards" runat="server" Text="<" />
                    <asp:Button CssClass="btnForwards" ID="btnForwards" runat="server" Text=">" />
                </span>
            </div>
        </div>
    </div>
</asp:Content>

and the code behind the child page:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class privetsl_Assignment03_Default : System.Web.UI.Page
{
    View home = new View();
    View isThisYourNum = new View();
    View GreatestCommonDenominator = new View();
    MultiView _profileView;

    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void Page_PreInit(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            int viewTemp = (int)Session["_ViewCount"];
            if (viewTemp > 0)
            {
                View isThisYourNum = new View();

                /************** 
                 *  Question  *
                 **************/

                int temp = (int)Session["userNum"];

                Label lblYourNum = new Label();
                lblYourNum.Text = "What number did you enter?";

                RadioButton rbYourNumQ1 = new RadioButton();
                rbYourNumQ1.GroupName = "isThisYourNum";
                rbYourNumQ1.Checked = false;
                temp--;
                rbYourNumQ1.Text = (temp).ToString() + "?";

                RadioButton rbYourNumQ2 = new RadioButton();
                rbYourNumQ2.GroupName = "isThisYourNum";
                rbYourNumQ2.Checked = false;
                rbYourNumQ2.Text = Session["userNum"].ToString() + "?";

                RadioButton rbYourNumQ3 = new RadioButton();
                rbYourNumQ3.GroupName = "isThisYourNum";
                rbYourNumQ3.Checked = false;
                temp = temp + 2;
                rbYourNumQ3.Text = temp.ToString() + "?";

                isThisYourNum.Controls.Add(lblYourNum);
                isThisYourNum.Controls.Add(rbYourNumQ1);
                isThisYourNum.Controls.Add(rbYourNumQ2);
                isThisYourNum.Controls.Add(rbYourNumQ3);

                /************** 
                 * Load View  *
                 **************/
                _profileView = new MultiView();
                _profileView.ID = "ProfileView";
                _profileView.Views.Add(isThisYourNum);
            }
        }
    }

    protected void btnParseInput_Click(object sender, EventArgs e)
    {
        //I don't use the userNum var? it requires me to declare an int for it to be placed in
        if (tbUserInput.Text != "")
        {
            try
            {
                Session["userNum"] = Convert.ToInt32(tbUserInput.Text);

                //Change page first. This way we don't go back to the home page from the home page...
                Session["pageOn"] = (int)Session["pageOn"] + 1;
                InitializeViews();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
    }

    private void InitializeViews()
    {
        int pageOn = (int)Session["pageOn"];
        //Break on the page #, call a method to set active view to that view.
        switch (pageOn)
        {
            case -1: //home page
                //Method to load home(?)
                showHome();
                break;

            case 0: //isThisYourNum?
                test();
                showQuestion();
                break;

            case 1: //GreatestCommonDenominator
                //mvFillMe.SetActiveView(GreatestCommonDenominator); Should instantiate and load in the same method
                showQuestion();
                break;
        }
    }

    private void test()
    {
        /************** 
         *  Question  *
         **************/

        int temp = (int)Session["userNum"];

        Label lblYourNum = new Label();
        lblYourNum.Text = "What number did you enter?";

        RadioButton rbYourNumQ1 = new RadioButton();
        rbYourNumQ1.GroupName = "isThisYourNum";
        rbYourNumQ1.Checked = false;
        temp--;
        rbYourNumQ1.Text = (temp).ToString() + "?";

        RadioButton rbYourNumQ2 = new RadioButton();
        rbYourNumQ2.GroupName = "isThisYourNum";
        rbYourNumQ2.Checked = false;
        rbYourNumQ2.Text = Session["userNum"].ToString() + "?";

        RadioButton rbYourNumQ3 = new RadioButton();
        rbYourNumQ3.GroupName = "isThisYourNum";
        rbYourNumQ3.Checked = false;
        temp = temp + 2;
        rbYourNumQ3.Text = temp.ToString() + "?";

        isThisYourNum.Controls.Add(lblYourNum);
        isThisYourNum.Controls.Add(rbYourNumQ1);
        isThisYourNum.Controls.Add(rbYourNumQ2);
        isThisYourNum.Controls.Add(rbYourNumQ3);

        /************** 
         * Load View  *
         **************/
        mvFillMe.Views.Add(isThisYourNum);
        Session["_ViewCount"] = (int)Session["_ViewCount"] + 1;
        mvFillMe.SetActiveView(isThisYourNum);
    }

    private void showHome()
    {
        tbUserInput.Enabled = true;
        btnParseInput.Enabled = true;
        btnBackwards.Enabled = false;
        btnForwards.Enabled = false;
    }

    private void showQuestion()
    {
        tbUserInput.Enabled = false;
        btnParseInput.Enabled = false;
        btnBackwards.Enabled = true;
        btnForwards.Enabled = true;
    }
}




Fetching data from spreadsheet in script: "Data table is not defined"

I’m trying to make a script using the Google Visualization App Geomap. In the example code on the Google Developers page, they are using a hard coded table. What I want to do, is to make code use data from a Google Spreadsheet connected to a Google Form. More specifically, I want to use the data of the spreadsheet tab «countries» from the following spreadsheet: http://ift.tt/1NJRScb.

Somehow this does not work, and I get the error messages listed below.

How can I collect the data from the spreadsheet in the right format? I have attempted to use this procedure to collect the data from the spreadsheet: http://ift.tt/1M0dNkD.

Error message on web page:

"Data table is not defined"

Error message in Safari Console:

TypeError: undefined is not an object (evaluating 'new google.visualization.Query’)
drawChart help:113
(anonymous function) help:117

My code

<script type="text/javascript" src="http://ift.tt/JuZcy0"></script>
<script type="text/javascript">
  google.load("visualization", "1", {packages:["geomap"]});
  google.setOnLoadCallback(drawMap);

  function drawMap() {
    var opts = {sendMethod: 'auto'};

    // ***My code***
    var query = new google.visualization.Query('http://ift.tt/1NJRTwy', 'sheet=countries', 'headers=1');
    var data = query.send(handleQueryResponse);

    var options = {};
    options['dataMode'] = 'regions';

    var container = document.getElementById('regions_div');
    var geomap = new google.visualization.GeoMap(container);

    geomap.draw(data, options);
  };

  function handleQueryResponse(response) {
      if (response.isError()) {
        alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
        return;
      }

      return response.getDataTable();
    }

</script>

Hope there is someone out there who can help me with this (hopefully) not so hard task. Thank you very much in advance! :-)




Open AppStore from website link in IOS 9

I have a webpage that includes a link to 'Download from the AppStore' which I want to either open the AppStore app if tapped on a device or open the Apple Itunes page for the app if clicked within a desktop browser. I am not trying to open the app itself by using myApp://, just want to open the AppStore download page.

I have this working fine for iOS8 (and lower). The AppStore app is opened and lands on the app page itself. On iOS9 however an error message is shown when tapping the same link: "Safari cannot open the page because the address is invalid".

Error example

On the webpage I am using a simple a to link to the appstore page like so:

<a href="http://ift.tt/U4iR6e" class="appstore-base" target="_blank">

Note: I have replaced my app with Twitter for this example, URL format is the same.

How can I get this to open the AppStore on iOS 9?




How improve this torrent file scraping php script to reduce disk r/w operations

Here is the php script that I created for downloading torrent file using torrent hash.

It doesn't download torrent file sometimes maybe because of poor header array I created but the failed download info automatically written to a text file for later viewing and downloading mannually .

Please let me post this now. How much details do you want stackexchange.

Also tell if OOP will improve this code. And how to download torrent file reliably in this.

<?php
set_time_limit(0);
include('simple_html_dom.php');

//------------------------------------------------
function getUserAgent()
{
$agents   = array();
$agents[] = "Mozilla/5.0 (Windows NT 10.0; 
        WOW64; rv:41.0) 
        Gecko/20100101 Firefox/41.0";
$agents[] = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0";
$agents[] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36";
$agents[] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36";
$agents[] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36";
$agents[] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11) AppleWebKit/601.1.56 (KHTML, like Gecko) Version/9.0 Safari/601.1.56";
$agents[] = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36";
$agents[] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/601.2.7 (KHTML, like Gecko) Version/9.0.1 Safari/601.2.7";
$agents[] = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko";
$agents[] = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0";
$agents[] = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0";
$agents[] = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:41.0) Gecko/20100101 Firefox/41.0";
$agents[] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36";
$agents[] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36";
$agents[] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36";
$agents[] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:41.0) Gecko/20100101 Firefox/41.0";
$agents[] = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0";
$agents[] = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36";
$agents[] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36";
return $agents[rand(0, count($agents) - 1)];
}
//----------------------------------------------------------
//function for curl options
function curl_setopt_my(&$chandle)
{
$headers   = array();
$headers[] = 'Content-Type: */*';
$headers[] = 'Accept: */*';
curl_setopt($chandle, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($chandle, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($chandle, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt($chandle, CURLOPT_TIMEOUT, 50);
curl_setopt($chandle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($chandle, CURLOPT_USERAGENT, getUserAgent());
//curl_setopt($chandle, CURLOPT_COOKIESESSION, 1);
curl_setopt($chandle, CURLOPT_COOKIEJAR, 'katcook.txt');
curl_setopt($chandle, CURLOPT_COOKIEFILE, 'katcook1.txt');
curl_setopt($chandle, CURLOPT_ENCODING, "gzip");
curl_setopt($chandle, CURLOPT_HTTPHEADER, $headers);
}
   //------------------------------------------------------------------------------------
$data = "";
do {
$ch = curl_init('http://ift.tt/1PJmuMc');
curl_setopt_my($ch);
$data = curl_exec($ch);
curl_close($ch);
} while (!$data);
//file_put_contents("newtkat.html", $data);
//echo "------------------------------------------------------------------";

$html = new simple_html_dom();
$html->load($data);
//$magnet = $html->find('a[title="Torrent magnet link"]');
$torrentFile     = $html->find('a[title="Download torrent file"]');
//$magElements = array();
$torFileElements = array();
foreach ($torrentFile as $e)
$torFileElements[] = $e->href;
$countFailed = 1;
foreach ($torFileElements as $e) {
$fileName = substr($e, stripos($e, "?title=") + 7);
$hash     = substr($e, stripos($e, "/torrent/") + 9, 40);
$fp       = fopen('tors\\' . $fileName . '.torrent', 'w+');
$ch1      = curl_init('http://ift.tt/1PJmxaP' . $hash . '.torrent');
curl_setopt_my($ch1);
curl_setopt($ch1, CURLOPT_FILE, $fp);
curl_exec($ch1);
curl_close($ch1);
fclose($fp);
sleep(1);
//echo $fileName. "----completed<br />". PHP_EOL ;

if (filesize('tors\\' . $fileName . '.torrent') > 3000) {
    continue;
}
$ch2 = curl_init('http://ift.tt/1Kjx3t4' . $hash . '.torrent');
$fp2 = fopen('tors\\' . $fileName . '.torrent', 'w+');
curl_setopt_my($ch2);
curl_setopt($ch2, CURLOPT_FILE, $fp2);
curl_exec($ch2);
curl_close($ch2);
fclose($fp2);
sleep(1);

if (filesize('tors\\' . $fileName . '.torrent') > 3000) {
    continue;
}

$ch3 = curl_init('http://ift.tt/1Kjx3t6' . $hash . '.torrent');
$fp3 = fopen('tors\\' . $fileName . '.torrent', 'w+');
curl_setopt_my($ch3);
curl_setopt($ch3, CURLOPT_FILE, $fp3);
curl_exec($ch3);
curl_close($ch3);
fclose($fp3);
sleep(1);

if (filesize('tors\\' . $fileName . '.torrent') > 3000) {
    continue;
}

$ch4 = curl_init('http://ift.tt/1PJmuMe' . $hash . '.torrent');
$fp4 = fopen('tors\\' . $fileName . '.torrent', 'w+');
curl_setopt_my($ch4);
curl_setopt($ch4, CURLOPT_FILE, $fp4);
curl_exec($ch4);
curl_close($ch4);
fclose($fp4);
sleep(1);

if (filesize('tors\\' . $fileName . '.torrent') < 3000) {
    unlink('tors\\' . $fileName . '.torrent');
    file_put_contents("tors\\magnets.txt", $countFailed . ")->" . $hash . ">->" . $fileName . PHP_EOL, FILE_APPEND | LOCK_EX);
    $countFailed++;
    }

}

?> 

Reply soon. Thanks




Permitted image formats on HTML pages [duplicate]

This question already has an answer here:

Can someone please list all the image formats (.jpg, .png, .gif, etc.) that most modern browsers will accept and render?




web scraping content within tag and tag

I need to scrape data from http://ift.tt/1PJcm64 this link. Actually i want to scrape data from the table of this link. But the code of the table is written within div tag. I used php regex and file_get_content I couldn't scrape it can you help me with the script.




How to make my web chat app like omegle? [Node.js and Mongodb]

I have made a very simple chat app using Node.js and MongoDB where as soon as you enter the app you are put in the same room and all messages are emitted to all users. How can I make this like Omegle where the users are randomly allocated to another 'Stranger' and not in a group. I am new to all of this so I would appreciate it if you could try to explain in layman terms.

Thanks!




i dont see default gateway when i type commands in command prompt

i want to develop website from my pc. I have to get a static ip but when i want to know my default gateway its nothing! see here




font-awesome do not work in Flask?

I'm trying to use font-awesome to show small icons in my web pages. My project is based on Flask framework. Here is my code:

<head>
<!-- use bootstrap -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://ift.tt/1JAVNZp">
<script src="http://ift.tt/1Cva0ES"></script>
<script src="http://ift.tt/1JAVNZv"></script>
<link rel="stylesheet" href="{{url_for('static', filename='custom.css')}}" type="text/css"/>
<link rel="stylesheet" href="{{url_for('static', filename = 'css/font-awesome.min.css')}}" type="text/css">

<a href="http://ift.tt/1KjgbTh" target="_blank"><i class="icon-github"></i> </a>

However, the icon does not appear. Could anyone give me some suggestions?




iterating in two arrays in the same for loop

I'm learning php, I want to iterate in two arrays in the same for loop, how ? this is the code I have, line 8 to line 14 for example, but it gives an array instead of an element, what to do? please be easy with on me I'm still new to this field.

<tr>
<td><?php echo $val->title ?></td>
<td><?php echo $val->content?></td>
<td><?php echo $val->owner ?></td>
<?php } ?>

<?php
foreach ($users as $val) {
?>
<td><?php echo str_replace("-", "%", $val->email) ?></td>
<?php }?>
<?php foreach ($maincat as $val) {?>
<td><?php echo str_replace("-","%",$val->maincat_name) ?></td>
<?php }?>

<?php foreach ($category as $val) {?>
<td><?php echo str_replace("-","%",$val->category_name) ?></td>
<?php }?>

<?php foreach ($sub_category as $val) {?>
<td><?php echo str_replace("-","%",$val->sub_category_name) ?></td>
<?php }?>

<?php foreach ($sub_sub_category as $val) {?>
<td><?php echo str_replace("-","%",$val->sub_sub_category_name) ?></td>
<?php }?>

</tr>

can somebody help ?




How to create a web page for uploading very big files to OpenStack Swift?

I would like to set up a web page where a user could upload very big data files to OpenStack Swift. The data files have file sizes that sometimes exceed the object file size limit of Rackspace Cloud Files (5 GB). This seems to rule out the possibility to use FormPost for uploading the input files. Quoting the Rackspace Cloud Files documentation: If your users try to upload an object larger than 5 GB, they will get a file size error

How could I set up a web page where a user could upload very big data files to OpenStack Swift? We currently use the OpenStack provider Rackspace and their Open Swift service called Rackspace Cloud Files.

FormPost would have been a great solution as it doesn't rely on sending the data files through my web server. With FormPost the data files are being sent directly to Rackspace Cloud Files.

As a good general security permissions strategy, I would also like to find a way where I would give the user as little Rackspace permissions as possible.




how to become a professional webdeveloper

I would become a professional webdeveloper, now I know only HTML/CSS, how to Can I started with JS,PHP,AJAX,JSON etc.? I know a bit of JS/PHP, but I haven't logic for create script useful and cool, know only the bases as if/else,switch etc., how to Can I learn to logic of a web developer?




Yield

I came across a code in Unity's scripting guide:

    www = new WWW("SomeDirectFileUrl");
    yield www;
    newestVersion = www.text;

Called in a coroutine, I undertand the yield is used to put the method on standby until a condition is met (like waitForSeconds, or simply for a frame), but it simply passes an instance as a parameter, not a condition... So i'd really like to know how it works, and what is the program waiting after (since only a mere instance of a class was passed as a parameter, not an order),and I'd also like to know if you can actually ask the program to wait until a condition is true. Thanks a lot! -Alex




samedi 30 janvier 2016

How to Send Data in web form which has readonly attribute Using Python

Following is The Element I am trying to Send .

<input type="text" name="Date" id="Date" readonly="readonly"
                        class="calOnward"  onfocus="resetTxt(this, 'Depart On');"
                        value="Depart On"
                        /> 

I tried the Following Code :

import re
from mechanize import Browser

browser = Browser()
browser.open("Some-Site-With-Date.com")

browser.select_form(nr=0)
browser['Date']='08/04/2016'

response = browser.submit()

content = response.read()

print content

When I ran this code I am getting the Following Error:

   File "build\bdist.win32\egg\mechanize\_form.py", line 2784, in __setitem__
alueError: control 'Date' is readonly

Is there any Workaround for this to send this Date attribute? I am new to Python and any lead is appreciated.




concurrent users hitting web app

I am a business analyst and db designer who has the seed of an idea for a web/mobile app. I am doing a feasibility study on a web/mobile fitness app. I've talked to a couple of my colleagues about the idea and have hit a brick wall on dealing with a potential challenge related to costs of a app that might have a large number of users hitting the site concurrently. The question came up because I had planned to store user stats and profiles on the website. Data would be uploaded to the "mothership" whenever a user has new data to add to their profile for dash boarding. My colleagues have told me that licencing for whatever I use for data storage is going to cost me a fortune and that profiles should be maintained on the users mobile device. Is this true? This is a startup project and I am not sure I want to finance a big dollar system until we experience growth in memberships. I am an absolute neophyte with this so any help, advice or direction would be greatly appreciated. Many thanks in advance! Rob




php my admin on iis7 error HTTP Error 403.14 - Forbidden

error while trying to run PHPMyAdmin on my local host with iis7 HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents of this directory.




New Project/Opportunity [on hold]

My problem is that I have a number of projects that would fit nicely with PubNub. Except I could use some help in the development and implementation. The first project deals with Stocks subscriptions service. This is the one I wish to focus on.

Basically it would consist of two screens, one chat and the other a live stock tracker. Pubnub has both of these options readily available,

Your job (if you accept it) would be to maintain the web pages and Pubnub codes, My responsibility would be to keep our subscribers with new stock data and expert recommendation. Recommendations will be handled through Like Chat and newsletter.

The live stock screen is the question. For it will require multiple instances with different data for each instance. So each instance will have a new web page??? or they can franchise out with us and subscribe with Punub. We maintain the stock data, guaranteeing residuals.

If you're interested in developing a real world application with Pubnub, serious contacts only.




Need a Map Solution for Web and Mobile

I have been looking at Google and Mapbox, however both don't give me what I need (at least I don't think they do).

I am looking for a solution where I can have a create simple map that contains markers via a web interface and then have my website and mobile app point to it.

The kicker is, when I make a change I don't want to have to upload a new KML. I want it to be networked link so the changes are automatically viewable on my website and mobile app.

Google has network links, however they don't work with custom markers, and Mapbox is very complex and I can't figure out how to add markers without uploading a KML file of them.

I am new to this so any help would be greatly appreciated.




Calculate strike and dip from euler angles given by Javascript deviceOrientation API

The w3c specs http://ift.tt/1i2JXXi give us the necessary documenation to access the get the euler angles of a device orienation and its conversion to the direction cosine matrix, my question is about calculating the

DIP:the acute angle that a rock surface makes with a horizontal plane and STRIKE: is the direction of the line formed by the intersection of a rock surface with a horizontal plane

from the Euler angles, for any arbitrary orientation of the phone or device on a plane. strike can be done with the compass-heading + 180deg but the dip implementation is something confusing P.S. any code/algorithm explanation will suffice. thank you




Store and access data offline from a website

What is the best/easiest way to store data offline? I have a website that I only run local (it's just for personal use) so I am not using any php or sql. I have a lot of posts containing a date, a time, a description the consist of a lot of text and a few of them contain an audio file (there are very few audio files so they may be stored separately from the rest). Now I want to make a website which can show these posts at request, but since I am not using either a server or a database I'm not sure how to store them. Use of any kind of framework or library is allowed, as long as I can use it without an internet connection.




Filtering Website For Parental Control

Ce résumé n'est pas disponible. Veuillez cliquer ici pour afficher l'article.


Can't return to app after launching web page

Hi i am working on a source code and I noticed when testing that I can't return to the app once I tap on my dos and about button. Ince I tap those button I get directed to my TOS web page and no return or back button show. I did see an answer that addresses this but I am new to coding and so I don't know what code I need and where to put it on my code to fix this. My code: import UIKit

class AboutViewController: UITableViewController {

@IBOutlet weak var termsText: UILabel!
@IBOutlet weak var aboutApp: UILabel!
@IBOutlet weak var logoutt: UILabel!
@IBOutlet weak var refresh: UILabel!






override func viewDidLoad() {
    super.viewDidLoad()

    self.tableView.backgroundColor = backColor

    self.termsText.textColor  = colorText
    self.aboutApp.textColor  = colorText
    self.logoutt.textColor  = colorText
    self.refresh.textColor  = colorText

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

    // Dispose of any resources that can be recreated.
}

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if indexPath.section == 1 {
        if indexPath.row == 0 {
            PFUser.logOut()
            currentuser = nil
            let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
            let loginvc = storyb.instantiateViewControllerWithIdentifier("loginvc") as! LoginViewController
            appDelegate.window?.rootViewController = loginvc

        }
        if indexPath.row == 1 {
            currentuser.removeObjectForKey("viewedUsers")
            currentuser.saveInBackgroundWithBlock({ (done, error) -> Void in
                let alert = UIAlertView(title: "Done", message: "Now you can see all users again", delegate: self, cancelButtonTitle: "okay")
                alert.show()
            })
        }
    }
}

}

Can this resolution help me in this case and if so how do I code it After viewing web in app, cannot return to app without closing it and relaunching

Thanks so much

Kyle




TinyMCE - edit output image links

I´m using TinyMCE editor with default image plugin for content management. Everything works fine, the only problem is, that I can´t use LightBox inside links generated by TinyMCE. It is some way how to adjust output generated for images by TinyMCE for all inserted images or wrap link with ? I don´t need any checkbox or something - the solution should be for all images inserted using TinyMCE. Many thanks!




Java HTML parsing (links)

I am trying to parse a web site and get some content from it, but I am completely lost now, I am trying to get all the links from the <div class="block block--archive"> there is <a class="block_link" hrek = "/curator/christoffer-rostlund-jonsson/" I want to get these links, I have searched a lot for some guides about it, but could not find any specific answer. I have tried something but I know its in really stupid way and doesnt work:

public static void main(String[]args) throws IOException {
      Document doc = Jsoup.connect("http://ift.tt/LkcgU2").get();
      Elements articles = doc.select("body");
       Elements element2= articles.select("div");
        Elements element3 = element2.select("article");
        Elements element4 = element3.select("div");
        System.out.println(element4.toString());
        }

And here is the structure of the web site that I want to get the links from: enter image description here




custom exception handling in .asmx web service

How Can we handle or log exception occurred while calling an asmx web service? exception like desensitization, HTTP method invalid or something like these exceptions? thanks.




vendredi 29 janvier 2016

Front and Back end for web development

I want to do some web development using python. What are the front-end and back-end can be used? Please help me.

Thank you :)




How to handle rowspan while scrapping a wikitable using python?

I am trying to scrape the data stored in the table of this wikipedia page http://ift.tt/20bqqk1. However i am unable to scrape the full data stored in rowspan Hers's what i wrote so far:

from bs4 import BeautifulSoup
from urllib.request import urlopen

wiki = urlopen("http://ift.tt/20bqqk1")

soup = BeautifulSoup(wiki, "html.parser")

table = soup.find("table", { "class" : "wikitable" })
for row in table.findAll("tr"):
    cells = row.findAll("td")

    if cells:
        name = cells[0].find(text=True)
        pic = cells[1].find("img")
        strt = cells[2].find(text=True)
        end = cells[3].find(text=True)
        pri = cells[6].find(text=True)

        z=name+'\n'+pic+'\n'+strt+'\n'+end+'\n'+pri
        print z




How to remove extension .html from url?

I design my website and created many pages in website and all pages extension are .html but i want to remove this from url. I want like this xyz.com/services not like this http://.xyz.com/services.html.




Putting background color behind a fontawesome icon with paragraph

Hey guys, I tried researching and tried various techniques and this is as close as I got and I'm trying to mess with the z-index. maybe someone can advice? So I am trying to put my background color layer, behind my fontawesome icon. I will show the html, css below.

HTML img

CSS img




Basic application development advice

I'm after some basic advice. For a university project I need to develop a mobile application (for either Android, iOS, or even an online web application). It will basically display real-time stock prices, have an alerts system, calendar, contact list etc. I was just wondering what is the best approach to take? Which is the best coding language to learn, in order to create such an application and which software would you recommend? Any courses you recommend?

Any advice is much appreciated.

Thanks




How to extract all links from a website?

I wonder if there's a way to extract all website links
Ex. Example.com
Result will be like this
Example.com/help/
Example.com/user/
http://ift.tt/1WSv0Ow
And so on, I used google search, and it shows a prefect results (site:Example.com) the problem is it doesn't give me all links
Ex. Example.com
http://ift.tt/23yGuLT
http://ift.tt/1WSv0Oy




File permissions aren't APPARENTLY working the way I expected

I am using hosting provided by 000webhost.com.

Root directory is: public_html I set it's file attributes to 700 by using FileZilla ftp. Also I set individual file permissions to 600.

public_html directory has only one file which is index.html. Now even though I have set puclic permission to zero as evident from right-most zero in both 600 and 700. Still I am able to view file index.html by using web browser here is the link. Why is that? I thought last zero in 600 or 700 meant public would not be able to view file, what is happening now then?




How Doctrine 2 helps to reduce SQL Injection?

I know there are many advantages of using a ORM in general My question is specifically Doctrine 2 about SQL Injection




Wiki scraping using python

I am trying to scrape the data stored in the table of this wikipedia page http://ift.tt/20bqqk1. However i am unable to scrape the full data Hers's what i wrote so far:

from bs4 import BeautifulSoup
import urllib2
wiki = "http://ift.tt/20bqqk1"
header = {'User-Agent': 'Mozilla/5.0'} #Needed to prevent 403 error on Wikipedia
req = urllib2.Request(wiki,headers=header)
page = urllib2.urlopen(req)
soup = BeautifulSoup(page,"html.parser")

name = ""
pic = ""
strt = ""
end = ""
pri = ""
x=""
table = soup.find("table", { "class" : "wikitable" })
for row in table.findAll("tr"):
    cells = row.findAll("td")

    if len(cells) == 8:
        name = cells[0].find(text=True)
        print name`

The output obtained is: Jairamdas Daulatram, Surjit Singh Barnala, Rao Birendra Singh

Whereas the output should be: Jairamdas Daulatram followed by Panjabrao Deshmukh




How to creat an online web editor?

i want to creat an oline "WYSIWYG" web editor , so what is the best component to creat the workshop erea a canvas or a simply div .

which component should i use to identfy the Workshop ? a canvas or something else ? enter image description here




What is the purpose of 1 click installation of Drupal on Web hosting?

I am in process of making first Drupal 7 website and for that searching for the web hosting. And I found that, several hosting says 1-click Drupal installation. But as I was searching the net for standard practice of site development, many sources explains Develop the site on local environment and then transfer to the web server (which includes, transfer of database, and whole drupal with modules) which is quite convincing that you develop locally and transfer to web so it start working there as it was working on locally.

On the other hand, what is the use of 1 click drupal installation on web server, I believe it will install the fresh core drupal, so from again initially I have to start developing, installing each module so, starting from square 1.

  1. So, which is the BEST practice for making web site live, shall i develop locally first or develop directly on web server?

  2. Simultaneously, what is the best practice about maintaining site, I read that, there should be One live site where visitor will come, Second Test site which is similar to live, One local site, So what is the standard practice for this, and how to maintain?

Very thanks in advance.




I wonder if we can install and manage a web application in a remote server? [on hold]

I would like to know if it is possible to install and manage a web application from your host to a remote server on Linux or Windows, what are best tools needed to do so?




Is there any tool to get data from website?

Let's say i have this link called : http://user.com/1345, and that link returns a json. Now i want a tool that can loop from http://user.com/1 to http://user.com/1345 and save that json data to a file. Anyone knows a good tool for that?




How do I change the favicon in google's "web starter kit?"

I replaced all of the files in images/touch with my own logo, and also replaced favicon.ico in the main directory of my project, but the favicon still displays as the default asterisk that comes with web starter kit. I tried refreshing the cache of my browser, and adding in

to try and manually link the favicon. This works, only when

is also commented out. But this will change the behavior of chrome for Android so that it is incorrect. Also, "images/touch/chrome-touch-icon-192x192.png" has been replaced with MY icon now, so why does this line make the favicon revert back?




Play Framework. I cant add new template

Play Framework does not see my template even after recompilationlation. My error look like this




Restful Web service - java.lang.NoSuchMethodError concat(Ljava/lang/Iterable;Ljava/lang/Iterable;)Ljava/lang/Iterable

I am trying one restful web service example so when I am going to hit url that time I am getting below exception

java.lang.NoSuchMethodError: jersey.repackaged.com.google.common.collect.Iterables.concat(Ljava/lang/Iterable;Ljava/lang/Iterable;)Ljava/lang/Iterable;
    org.glassfish.jersey.server.internal.ConfigHelper.getContainerLifecycleListener(ConfigHelper.java:92)
    org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:172)
    org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:363)
    javax.servlet.GenericServlet.init(GenericServlet.java:158)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Thread.java:724)

Below are the Jars i am using

enter image description here




Wicket's AjaxSelfUpdatingTimerBehavior stops updating after leaving and re-entering the page

I have this behavior added to a component(MarkupContainer)

    AjaxSelfUpdatingTimerBehavior updateBehavior = new AjaxSelfUpdatingTimerBehavior(Duration.seconds(3))
    {


        @Override
        public void onEvent(Component component, IEvent<?> event) {
            // some business logic
        }

    };

Somewhere , on the same page I have an AjaxLink which redirects to another page(in whom constructor I pass the actual page as a parameter) and on that page I have a "Back" AjaxLink which redirects me back , calling setResponsePage(myFirstPage) .

The problem is that even though , when rendering the page the behavior updates once , it stops updating once at 3 seconds , as was constructed for.No problem faced with the behavior until leaving the page.




How to create google form for image upload and save in drive

I wanted to make a google form which can take an image as input and upload/save it in the google drive along with the response number.




Angular Factory Object Persisting Over Storing in Local Storage

I've got a problem that i need help with in Angular 1.4.0. I have a factory in angular which has a complex structure and method within so i am able to restore the factory back to its original state by calling the method. The factory looks like this.

 angular.module('myApp').factory('itemFcty', function(){
 var currentValues = {};
 var default values {
       a = 1,
       b = 2,
       resetData : function(){
          currentValues = angular.extend(currentValues, defaultValues);
          return currentValues 
       };
   };
   defaultValues.resetData();
   return currentValues;

}); In order to add values to 'a' i call itemFcty.a = 2; So this method works well when i want to overwrite all the values as and when required. However i have been asked could i persist the data over a refresh. So i stringify the object into JSON. Like this:

localStorage.setItem('itemFcty', JSON.parse(itemFcty);

However i have hit a snag. The only data to be stored in the local storage is the

{a = 1,b = 2,}

I can add the method back in by doing this:-

itemFcty.resetData = function(){return currentValues = angular.extend(currentValues, defaultValues);}

This is the issue that now the factory does function the same way as before as i am not able to call the function as the call and return outside the default values object is not there any more i can cannot for the life of me work out how to add it back into as everything goes directly into the object as a whole.

Your help would be greatly appreciated!




jeudi 28 janvier 2016

Mechanize Python library

I've recently started working with mechanize in python to fill forms.

br = mechanize.Browser()
retorno = br.open("http://ift.tt/1JKwtEN")
nomes = ['Subject A', 'Subject B','Subject C']
email = '********'

br.select_form(nr=0)
for f in br.forms():
    print f


br.form['nome[]'] = 'Subject A'
br.form['email'] = email
br.submit()

The problem is that I would like to enter all the names in the 'nomes' in the 'nome[]' field, but it only accepts one string at the time. When you enter the website, there is a "plus" button that adds more fields to enter other names. I would like to know if there is a way to acess this button using the script or to enter the names using a kind of list or dictionary.

Also, I would like to know if I could iterate on the 'idEvento' array, since each one is a different form.

Here are the forms:

<TextControl(nome[]=)>
<TextControl(email=)>
<SelectControl(idEvento=[335, 334, *336])>

Here are the controls of the form

text nome[] 
email email 
select idEvento ['336']
submit None 

Thanks!




Programming and Databases

I am creating a website that has a log in form. I want the user to be able to create an account with their desired email and password and let that information be stored in a database (SQL) and then be able to log back in later with that same log in credentials that they made.

I am currently using HTML, CSS, and Javascript to create my form and learning SQL for storing that information. This is my first time doing this and have no guidance in creating this. Is it just as simple as creating my form using HTML, CSS, and Javascript and linking it to my SQL database or will I have to use something else to do that?

I was looking online for this topic and found tools such as JDBC and PythonDB but not entirely sure on what they are and how to use them.




Retrieving form date with Flask Requests

I've been using Flask's requests to retrieve data from a form. It's been working perfectly except I can't get the date input type from the html forms to work

This is the code that I thought would get the data back:

dob = request.form['dob']

This is how the section of the form looks

Date of Birth <input type="date" class="" name="dob" value="{{request.form.dob}}"><br />

If I change the input type from date to text then it works without problem, but I can't seem to get the date input to work.




Google hangout / telephone / voip input to web app

I am currently building a web application and was exploring if there is a way to parse an incoming voip call information.

For e.g.: I have a list of contacts with phone numbers on my page. when I receive a call on my hangout in that browser, I need to parse the caller's phone number and search for that phone number in the list and display that contact details. I am not tied to Google Hangouts. Any similar libraries / frameworks are fine. The application I am building uses AngularJS.




Choosing Framework For Web Development

I want to jump into web development and I know I should learn HTML/CSS, Javascript, Json, Jquerry etc. However I do not know which webframework should I learn. I have made a search about that and there are many such as RoR, Django, Symfony2, Meteor and I am confused about Meteor.js because according to this website: http://ift.tt/1pLcBBB Meteor.js is not a framework, instead "Meteor is an open-source Isomorphic Development Ecosystem (IDevE) for efficiently and painlessly developing web and mobile applications". So can not I build whole website with Meteor.js and should I learn another framework such as Symfony or Laravel or Django?

Lastly can you advice any book/website(preferred) to learn fundamentals of web development such as what is back-end/front-end, what is server side language etc.

I am new and still learning things. If you illuminate my way, I would be very happy.




Exporting .txt from webpage to downloads directory

Im developing a web application (phonebook) using python and I want to be able to export my existing address books to my downloads (be able to specify download direction) the way i have it now, it exports the text file to my local webapp directory ./phone_book

What I want to accomplish is make the users able export/download the address book textfile to directory they desire on their machine.

thank you. Please ask if you need more details




Need to create a Web api to show current status of automated tests with failures in graph chart.

I need to create a WEB api which will read pass/failures for a test suite and render them to a graph.

In this graph I should be able to see bug id appended to the failure.

Also, for each failure, I need to append it to the bug id.

For graph I can use morris.js. Can someone help with chasing a good technology stack?




PHP temperature converter reloading without refreshing

I am trying to do the temperature converter in PHP without reloading the page using the jquery, but having problem......

This is the Index.php page

Jqeury function for printing data without reloading..

function SubmitFormData(){
    var first = $("#valueConvert").val();
    var operator = $("#convertType").val(); 
    $.post("temperature_calculate.php",
       {
         first:first,
         operator: operator
       },
       function(data){
          $('#results').html(data);
         $('#formcal')[0].reset();
       });
}

HTML code:

<form name="tempConvert" id="formcal" method="POST">

    <input type="text" name="valueConvert" id="valueConvert" size="15">

    Convert to:
    <select name="convertType" id="convertType" size="1">
               <option disabled> Select a measurement type</option>
               <option value="celsius">Celsius</option>
               <option value="fahrenheit">Fahrenheit</option>
        </select>

    <td><input type="submit" name="btnConvert" id="btnConvert" value="Convert">

</form>
<div id="results">
 </div>

And this is the php code that process the value:

<?php 
function tempConvert($valueConvert, $convertType) { 
    if($convertType == "fahrenheit"){ 
        $conversion = ((9/5) * $valueConvert) + (32); 
    } else if ($convertType == "celsius"){ 
        $conversion = ($valueConvert - 32) * (5/9); 
    } 
    return $conversion; 
} 
$valueConvert = $_POST['valueConvert']; 
$convertType = $_POST['convertType']; 
$conversion = tempConvert($valueConvert, $convertType); 
echo " $conversion."; 
?>




Parse Alternative - Parse just announced they are stopping the Parse service as of Jan. 2017

I know they are releasing an open source server that you can host and migrate. Parse being a wonderful SaaS I am disappointed. Is there any other services out there like Parse? I have a lot of applications running on Parse so am curious what everyone else does.

Parse Moving On




htaccess redirecting working except for the root

I have an htaccess redirect (forcing www) set for my website and it works perfectly except when I go to mydomain.com it doesn't redirect to www.mydomain.com

It works for every other page except for the root one. For example if I go to http://ift.tt/1SMKrIM it will redirect me to http://ift.tt/1PWpZz6

I have tried a ton of different options I could find online and none of them seem to work.

This is the current version I use:

RewriteBase /
RewriteCond %{HTTP_HOST} !^www\.domain-name\.com$ [NC]
RewriteRule ^(.*)$ http://ift.tt/1xCuxqV [R=301,L]




Getting 417 error for Web API POST method

I have developed WEB API service in .NET. In the service I have POST request which communicates Database through Entity Framework. This post method gets called from another application. A Continuous requests are sent to this request and post method gets called accordingly. I am getting below response from the service.

417 Expectation Failed The server cannot meet the requirements of the Expect request-header field

The service is deployed on development server.




Side bar pop-up annotations like those on Genius.com, Inset on squarespace site

A project I'm engaged in currently at work is delivery of educational code. We're trying a new approach, and one of the aspects of that is re-configuring how users view the example code on our website. Having created an ample body of content, I'm now charged with determining the method by which the display occurs.

I proposed that there be two text bodies side by side, one is the code itself and the other is the set of long annotations about that code. Someone brought up the clickable annotations used by Genius.com, which would be perfect for this project. Unfortunately, I have no web design experience at all (to my shame, I even use a drag and drop editor for my personal website) and thus don't even know how to start on something like this.

The pertinent facts are thus:

-I'd like to have the example code laid out on one half of the page. (Very easy)

-I'd like to have each line set up so that you can click it, bringing up the related explanation text for that line on the other side of the page

-We have no proper web design personnel. My supervisor builds the website with some kind of CSS voodoo and Squarespace.

I've tried Google, of course, but my search seems to be misguided. Seeking out 'Genius.com annotation code' and 'website popup annotations' are only mildly comprehensible to me. Because I need to supply this information to another person, who will implement the actual web-side part, my question proper is multi-part:

a) Genius.com has an API, and by a combination of reading the docs and viewing the source of a song, I can deduce the HTML tagging to mark an annotation and create a page from which the annotation will draw, and how the GET and PUT requests to access that data work, but can that app-style functionality be embedded on a webpage? In particular Squarespace? What would that kind of embedding even be called?

b) Are there other types of markup tricks that can be leveraged into this? Like a suite of hidden layers than only show up based on the most recently clicked line? Or a gallery of the different content pieces, from which the display is selected by clicking a line?

c) Does Squarespace have an obscure tool for something like this? Is there an applet that I'm missing? Can I iframe in or embed a page from Genius with my code 'song' and its annotations? Can I write my own thing with Python or Processing and cram that onto Squarespace?

d) Am I completely barking up the wrong tree due to ignorance?

I know this is an awfully rambling question, but I've been after it for a couple hours now and quite honestly have to admit that I'm completely out of my depth on this one. I have a sneaking suspicion that my lack of knowledge has me approaching this all wrong. Let me know if none of this makes sense.




File not found using wamp

I changed the port to 8080 on wamp in the httpd.conf file and it works, using localhost:8080. However, I don't seem to be able to open any file in wwww-folder, not even the index.php which supposedly is running when using the url localhost:8080!

localhost:8080/index gives me

Not Found

The requested URL /index was not found on this server.
Apache/2.4.9 (Win64) PHP/5.5.12 Server at localhost Port 8080

Has the path changed? How do I look this up?




How do I split recieving requests and sending responses into two functions using Python's `wsgiref` API ?`

I'm writing an extensible web framework in Python. My abstract base class for the server defines a receive and a send method. The implemented server should return a Request object when receive is called, and send should take a Response object and send it to the client. The problem is that I have to build my request from the WSGI app's environment and translate my response into a valid WSGI response object. However I fail when trying to implement this class for my WSGI server because, as far as I know, WSGI applications must do both tasks at the same time.

I have the code for my methods, but how can I access environ and start_response from those ?

Here's the code:

class WSGIServer(Server):
    def receive(self):
        url = environ['PATH_INFO']

        method_name = environ['REQUEST_METHOD']
        method = Method[method_name]

        if method is Method.GET:
            query = environ['QUERY_STRING']
        else:
            size = int(environ.get('CONTENT_LENGTH', 0))
            query = environ['wsgi.input'].read(size).decode('UTF-8')

        args = {}

        for arg in filter(bool, query.split('&')):
            name, val = arg.split('=')
            args[name] = val

        headers = Headers([])
        request = Request(url, method, headers, args)

        return request

    def send(self, response):
        start_response(response.status, list(response.headers.items()))
        wsgi_response = [response.page.as_string().encode('utf-8')]

        return wsgi_response

Thanks.




How to Format List in HttpResponseMessage in WEB API

Here, I want the list "User" as a response. But it contains Message also. I want the message to be printed only once. Currently it is printing user.count times.

for (int i = 0; i < user.Count; i++)
 {
   if (user[i].Message == "Success")
      {
        resp = new HttpResponseMessage { Content = new ObjectContent(typeof(List<GetUserList>), user, GlobalConfiguration.Configuration.Formatters.JsonFormatter) };
       }
   else
      {
        resp = new HttpResponseMessage { Content = new StringContent("[{\"Message\":\"" + user[i].Message + "\"}]", System.Text.Encoding.UTF8, "application/json") };
       }
 }

The result should be like this:

{
  "message": " Successful",
  "supervisorlist": [
  {
    " userID ": "654",
    " forename ": "John"
  },
  {
    " userID ": "655",
    " forename ": "Jack"
  }
 ]

}




How to use Selenium to get the parking price?

I'm trying to use web scraping to get the parking price at this link, http://ift.tt/1Qvzic3. It's $2 for the day which is what I'm trying to get. I'm using python+selenium, but just couldn't get the parking price. Below is the code I'm using, but sometimes I hit the target but most time I get the error selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: {"method":"class name","selector":"gwt-RadioButton"}. Can anyone help? thanks in advance

def downtownparking(driver):
driver.get("http://ift.tt/1Qvzic3")
try:
    ### driver.wait = WebDriverWait(driver, 16)
    ### driver.implicitly_wait(20)
    cr = driver.find_element_by_class_name("gwt-RadioButton")
    dayprice = cr.find_element_by_tag_name("label")
    print (dayprice.text)




Can't load web pages using swift

I use the flowing code Let url = NSURL (string: "http://www.hello.com") Let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) ->Void In

}

Task.resume

I keep get error on let task that url cannot be used on type ViewController

Can someone help I'm lost here




WCF Client Invoking Remote Server Affects LocalHost Mongo Database

I have created a server system that uses Mongo and exposes some services. One of the services creates records in the mongo database.

Obviously I also have the same environment set up on my local dev computer for debugging and testing.

So I used the WCF Client application that comes with Visual Studio to exercise and test the services I wrote.

I created my json packet in the WCF client after attaching to the remote server service.

I hit invoke and went to look in the mongo db on the server. The record it should have created wasn't there.

Without getting into the details of why, I looked in my local mongo database on my dev computer. To my surprise I found that the record it should have created on the server got created on my local dev computer instead.

Can anyone explain to me how invoking a web service on a totally different computer that is set up to attach to and write data to its local mongo database can instead access the local mongo database on the dev computer that is running the WCF client?

How is that even possible? Does the remote service somehow run in a local context when using WCF Client that allows the remote server to access localhost:27017 on my local dev computer?




How to represent web pages in OOP

Let's say there's a web page: shop.com
Basic structure:
shop.com/search
shop.com/user

shop.com/user/cart/ needs authentication session.

I am building a parser for this web page using Jsoup, to extract piece of text from a target page. I would like to program it as a "web page as an API".
So my queston is, how should I design my program?

Right now I have something like this:
Shop shop = new Shop(username, login) // instantiating the user session
Document shoppingCart = shop.getShoppingCart(); // returns org.jsoup.nodes.Document

The problem here is that what if I need more data from many different pages, e.x.:
shop.findBestDeals() // would not need login session
shop.getUsedSearchTerms() // would need login session
All the parsing weight would be on Shop class. Plus logging the user in for no reason, if page doesn't need it.
So I thought of using static methods like this, where each page would be a class:
Document cart = Cart.getShoppingCart(usersession)
Document deals = Shop.findBestDeals()
Document dealsForUser = Shop.findBestDeals(usersession) // if web page would display special items for logged in users

So basically, have web pages as classes, and they would all have static methods for data retrieval. As I now think about it, each "page-class" would require lots of (the same) imports (as other classes), would it be okay, or is there a design pattern to prevent this from happening?
This is the best I can come up with as a first year student for "web page as an API" problem.
English is not my first language, so feel free to ask further questions! :)

PS: not a homework, my personal project!




Make No Response status for http calls

I have implement Get() for http get requests. And I am making a rest call to that function with some authentication headers. When supplied with valid authentication headers, it works. But When I use invalid header, I should get "No Response" in my rest client. This needs to implement. Could anyone say what should do for this. I am using DHC ReST client chrome extension as my Rest client. Given below the GET implementation

public stream Get()
{
  if(WebOperationContext.Current.IncomingRequest.Headers.AllKeys.Contains("Authorization"))
  {
    //Validating the header
    ...
    if( valid header)
    {
       WebOperationContext.Current.OutgoingResponse.ContentType = "application/xml";
       byte[] bytes = Encoding.UTF8.GetBytes(xml);
       var stream = new MemoryStream(bytes);

       stream.Seek(0, SeekOrigin.Begin);
       return stream;
    }

    if(invalid header)
    {
      //I need to handle the no resposen code here.
      //I tried, throw exception, change status code, return null stream but nothing worked.
    }
  }
}




mercredi 27 janvier 2016

how to create website without html and css

I think html and css is terrible.
How can I create a website without html and css?

like android

<LinearLayout>something</LinearLayout>




Need to highlight particular pattern of text

I have a file with some paragraphs, what i want to do is to highlight certain pattern of text/words occurring in the text file with background yellow and text color black.

pattern = ["enough", "too much"];
Text file = "text.txt";

and show it on a webpage with highlighted text for enough and too much words in the text file.

I want to use perl to do this task. Please tell me how i can do this in optimized way.




Web server not displayng image on html page

I am trying to show an image on an HTML page using an HTTP web server, but only simple text shows. The image does not show.

This is the request:

GET /Settings.html HTTP/1.1
Host: 192.168.0.34:8080
Connection: keep-alive
Cache-Control: max-age=0
Authorization: Digest username="vax", realm="testrealm@host.com", nonce="Ny8", uri="/Settings.html", response="e15dc422afc6f9a7ccdfe3b5dfe2b56d"
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8

This is the response:

HTTP/1.0 200 OK 
Date: Thu, 28 Jan 2016 06:16:39 GMT
Server: HTTP SERVER
content-Type: image/gif
content-Lenght: 164724




How to Change ModX 1.0.4J-r1 Language from Japanese to English?

I basically cannot understand all whats written in the interface because its all japanese. Google translate wont work.

I tried upgrading (doing the http://url.com/install) but it does not work. it just directing me to the website




Some problems when using swfupload+ftp

Recently i am using swfupload in my web project. What i want to do is to upload files to remote ftp server instead of my local web server.The problem is that when the swfupload progress bar percentage shows my uploading is completed,but the file is only upload to my local web server,not excatlly to the remote ftp server.how can i show the correct percentage in the progress bar.




ASP.NET education advice needed [on hold]

I am looking for advice about my further education in web developement. I graduated at computer engeneering faculty 5 years ago where I have learned programming in ASP.NET C#. After my graduation i found job as a teacher, where i was teaching courses mostly not related with programming. Since than I made just couple of ASP.NET C# websites, and now I think in some way I am disconnected from the latest technologies in web developement. At faculty i had subjects where i have learned many different things in different technologies but without big practical experience: HTML, ASP.Net, JavaScript, XML, C/C++, C#, Java, Visual Studio 2010/12, NetBeans, Eclipse, C# ASP .NET, Google Android, Microsoft SQL, ADO .NET,UML. Next, I am looking to work with ASP.NET C# web developement and for beginning I plan to start learning MVC.NET. I would be thankful if someone could give me an advice for my further steps as a web developer and latest .NET technologies from which I can expect a lot !

Thanks, Zoran




Finding similar application

I have little problem and i hope that u help me. My teacher gived me the task for my project. I have to find similar web application to mine subject, and my subject is: "Free time organizer". It will be application which gives u information about event in your city and u can plan u free time just like in organizer. What's more u will be able to create group events and ivite friends. I know its nothin original but i really cant find anything similar on Google. I would be grateful if u could send me some links or name of similar apps.




gearman php callback,how to use the gearman

I has the problem like this: Now I need to use the PHP to call the gearman to download the picture async and give it my callback function.And when it done its job,the gearman will return me the data by using my callback function.(My first time to use the gearman) the problem is that:when I call the doBackGround,and echo the $result,it return the info:"H:ip:xxx.xxx.xxx.xxx:number",it seems work,but the file I create in the callback function can not find in my web service.I do not where is wrong? in PHP,how can I make the code work?these are my code:

    public function tryGearman() {
    $url = "url1\n";
    $url1 = "url2\n";
    $url2 = "url3\n";

    $urlFile = fopen("url.txt","w") or die("can not open the file");
    fwrite($urlFile,$url);
    fwrite($urlFile,$url1);
    fwrite($urlFile,$url2);
    fclose($urlFile);

    $gmclient = new GearmanClient();

    $gmclient->addServer();

    $gmclient->setCompleteCallback('getProData');

    $result = $gmclient->doBackground('upload','{"callback_url":"https://my_web_app_realm_name/index.php?c=Game&a=getProData","input_file":"/usr/local/test/url.txt"}');

    echo $result;
}

public function getProData($data) {
    $urlFile = fopen("result.txt","w") or die("can not open the file");
    fwrite($urlFile,$data);
    fclose($urlFile);
}




Azure Pricing Tiers - Cores Per Instance or Plan?

I'm trying to fully understand the Azure pricing model and just need a little clarification.

If I choose the standard tier for an Azure web app, I know that I can have any number of web apps / websites, and 10 instances at 1 core and 1.75gb of ram.

Now, what I'd like to know is if that means EACH instances gets 1 core and 1.75gb of ram, or that the total hardware power is 1 core and 1.75gb over all instances? There's a huge difference. Also, I'm assuming that each of these instances could potentially be running on different machines in different locations (though all in the same region). And I believe I understand that all of my websites under this pricing tier will be duplicated to all of the instances, based on the number I specify.

I'm pretty sure it means that each instance will get the stated physical hardware specs, so in essence I am getting the power of a maximum of 10 machines (though maybe not technically). Is this understanding correct?

As a secondary question: why are cloud services so much cheaper? They still have a domain and can be used for a website / web app.

Thanks, Sam




kindly example these responsive website points

i am writing my assignment for university, kindly help me to explain these point just write 2 line for all.

What is responsive website

One url, Single content, One code, CSS3 media Queries, Multiple devices

Advantages of responsive website

Saves money, Improved SEO, Better performance, Wider browser Support




I have a folder of HTML and CSS documents as well as many images that my HTML documents reference. Can I upload the folder somewhere online?

So my HTML files link to my CSS files by <link type="text/css" rel="stylesheet" href="stylesheet.css" /> so if the HTML file is not in the same folder as stylesheet.css, there will be no link.

Similarly, whenever I put images in the HTML files, I reference them with <img src="image.jpg" />. So, again, if image.jpg is not in the same folder as the HTML file, there will be no link.

I have a folder with 30 different HTML files and a bunch of pictures and CSS files. Each HTML file has a dropdown menu with hyperlink references to get to all the other HTML files (<a href="file.html"></a>). So, again, if all the HTML files are not in the same folder, there will be no link.

I am looking for a way to basically upload the entire folder to some free web hosting service so that the functionality that I have set up in the folder will remain on the web.

Any ideas?




How to distinguish pre-rendered and regular page visits on server-side analytic tool?

Pre-rendering seems to be a great tool but it distorted statistics.

<link rel="prerender" href="http://google.com" />

How can I make a distinct between pre-rendering and actual visits?

Thanks.




Google Sign-In button doesn't show up

I tried to add Google Sing-In button to my website, but the button doesn't show up. I was following these instructions:

http://ift.tt/1DSdwfV

Firstly I added reCAPTCHA button and it is working fine.

Here is my login.php page:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login</title>
<link rel="stylesheet" href="css/style.css" />

<script src='http://ift.tt/1xQsaAf'></script>

<script src="http://ift.tt/1bMh26W" async defer></script>
<meta name="google-signin-client_id" content="[Generated Client ID]">

<script>
function onSignIn(googleUser) {
  var profile = googleUser.getBasicProfile();
  console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
  console.log('Name: ' + profile.getName());
  console.log('Image URL: ' + profile.getImageUrl());
  console.log('Email: ' + profile.getEmail());
}
</script>
</head>
<body>

<div class="form">
<h1>Log In</h1>
<form name="login" action="login_post.php" method="post">
    <input type="text" name="username" placeholder="Username" required />
    <input type="password" name="password" placeholder="Password" required />
    <div class="[reCAPTCHA ID]"></div>
    <input name="submit" type="submit" value="Login" />
</form>
<p>Not registered yet? <a href='registration.php'>Register Here</a></p>
</div>

<div class="g-signin2" data-onsuccess="onSignIn"></div>

</body>
</html> 

Do you have any ideas?




Giving folder permission as apache owner

I have setup the AWS Linux instance and deployed web project and for that project I need folder permission only by apache user I have ssh for root user

How can I do this which will show apache as a owner of web project?




First post, go easy! Trying to determine development technique for a final year university computing project?

I'm approximately halfway through my undergraduate dissertation, which is 25,000 words, and requires the build of a computer system (in order to demonstrate computer skills). Important to note at this stage, I do not consider myself as a technical person, so please consider this when responding.

I have decided to go down the route of attendance monitoring within higher education (yawn zZzZzZ) as the literature available was vast. Initially I thought to build the system with Microsoft Visual Basic 2013 and link it to a back-end MS Access DB, as the system is not required to run online, it can be ran locally on a desktop. However, research conducted through interviews and self-completion questionaries' raised probing questions as to why the system was not being developed using a web-based application (i.e PHP, HTML, CSS).

A database must exist, to allow system users (Student & Staff), to add/retrieve/modify/delete attendance records. The system should have restricted views in place, to prevent students viewing the attendance record of their cohort. The database will contain dummy data, therefor storage is not a concern. Ideally, I would like for the user to generate a report of their attendance, and export this to a printable format (word, excel, pdf).

To summarise; I have three questions today for the stack overflow community. 1) Should I use MS VB, and MS Access? 2) Should I create a web application, using PHP for database retrieval;? 3) If option 2 is selected, can anyone recommend a suitable database?

I hope I have provided sufficient information to warrant a response.

One final note, I have approximately 13 weeks till deadline.

Thanks, Andy




Why the youtube video can't be fullscreen on my web page?

Just check this page http://ift.tt/1NAYBF5 open the book, you will see the youtube video, when you click fullscreen button, the video will not show up, but then when you open the chrome developer tool, the fullscreen video will display as normal.

I'm not sure the reason. please help!

Thanks in advanced!




Show language in WordPress web

I had a mqtranslate in my WordPress but mqtranslate remained deprecated and I install qtranslate and before when I had mqtranslate I show in one corner of my web "eng" and "esp" to change the language but with qtranslate I don't show "eng" and "esp" in my web, someone have any idea?

Thanks in advance,

Sorry for my English.




Send HTML snippet in the generated page or in JavaScript and then load on the page?

In an application, a user stores some HTML snippets in the DB. Later when the user requests a resource, a snippet need to be part of the representation. There are two approaches: 1. Insert the snippet into the representation when generating it on the server, and send the page to the client 2. Leave the node empty when generating, but put it into the JavaScript variable. The page then fill the snippet in the node on the client side

I like the first more, because it is easy to cache the page. It is kind of ugly to have a JS viable with a long HTML snippet in the second. The processing of the page has to wait until the snippet loads.

Is there any general good practice guideline for this? Or what is your thinking?

Thanks.




Changing attribute with .load()

Here is my code:

setInterval(function(){
            $('#elementtochange').load('ajax/getdata.php #elementtoget');
        }, 500)

setInterval(function(){
            $('#ajaxplayers').attr('value').load('ajax/getdata.php #players');
        }, 500)

I know you can use the jquery function .load() to load elements from an external php file, which I do from the first function in the code in an interval.

Now I want to do the same thing but instead of loading it into an element I want to load it into an atribute 'value' and change it dynamically with .load() and in the external php file load it from my mysql database. But the code as i wrote it doesn't work so does anyone have a solution for this?




how to know the server address using ip address and to upload a file on that server

I have got IP adress of a website by pinging. Now i want to know the server site for that IP adress also want to upload some files on that server.




How to get value text as result for result button after clicking Show button?

I'm here to ask a question regarding JavaScript. I'm new to JavaScript so please forgive if I'm going wrong. Could someone help me to get the values as result. After I select any State from Drop down list, the Show button should give me the value of the States as result. Is it possible?

  <h1>Please select a State</h1>

  <select id = "district">
   <option value = "Tiruvanandapuram">Kerala</option>
   <option value = "Chennai">Tamil Nadu</option>
   <option value = "New Delhi">Delhi</option>
  </select>
  
  <input type = "button" value = "Show" onclick = "" />
  <INPUT type="text" ID="add"  id="txtresult" NAME="result" VALUE="">
    

`




What is the best practice to protect my website from thieves?

I would like to sell custom made html templates on my site, but I'm affraid of thieves. What is the best way to keep my stuff safe? Disable the right click or put it into an iframe? Is there any solution to hide the source code of the site? These templates are hide from search engines so any suggestion can be good.

Thanks for any suggestion




Android devices connected with NSD, how to send messages using web sockets / page

I am creating one android device as master and other android devices are connected with NSD how can I sent message to master and receive message from master with web-page or web-socket.




Create Random image slideshow

i have a website live at the moment and the images desplay in sequence i want to add a little dynamics with the slider and make it so it randomly displays the images instead this is the basic code:

    <div class="container slideshowContainer" style="width: 100%;">
        <!-- BEGIN REVOLUTION SLIDER -->    
        <div class="fullwidthbanner-container slider-main margin-bottom-10">
            <div class="fullwidthabnner">
                <ul id="revolutionul" style="display:none;">                                                                                       
                    <!-- OUTPUT THE SLIDES -->
                    <?php
                        foreach($slides as $d){
                    ?>

                        <li data-transition="fade" data-slotamount="8" data-masterspeed="700" data-delay="9400" data-thumb="assets/img/sliders/revolution/thumbs/thumb2.jpg">
                                        <?php if($d['slideshow_image_sub_title_4'] != ""){ ?>
                                <a href="<?php echo $d['slideshow_image_sub_title_4']; ?>">
                                    <img src="uploads/images/<?php echo $d['slideshow_image_file']; ?>" title="<?php echo $d['slideshow_image_title']; ?>" style="width: 100%;" />
                                </a>                                
                            <?php } else { ?>
                                    <img src="uploads/images/<?php echo $d['slideshow_image_file']; ?>" title="<?php echo $d['slideshow_image_title']; ?>" style="width: 100%;" />
                            <?php } ?>
                        </li>
                        <?php
                        }
                    ?>                      
                </ul>
                <div class="tp-bannertimer tp-bottom"></div>
            </div>
        </div>
        <!-- END REVOLUTION SLIDER -->
    </div>    

how can i modify this to help randomly display images please ask if i need to provide more info

Thanks in advance




Guru Meditation: Error 502 XID: 3047196358

I am getting Guru Meditation: Error 502 XID: 3047196358 I didn't understand what exactly it is. Everything was working fine, then suddenly it showed up. Though I got a reference here: Varnish: Guru Meditation

I need to know why/when this happens? How to fix this issue?

Thanks




HRemoving Duplicate Tag Content Using BeautifulSoup

I made a Script for Getting every H1 Tag from all 76 pages of a website. But in this process my Program copy a very specific line "Current Affairs January 2015" as this line is present in every page. Can I edit the Code to just print it 1 time ?

Here's my code:

from bs4 import BeautifulSoup as bs
import urllib


for i in range(2,77):
    url1="http://ift.tt/1UpFh3f"+"page/"+str(i)
    soup = bs(urllib.urlopen(url1))
    for link in soup.findAll('h1'):
        print link.string

Here is the Screenshot of the output

Thanks in advance.




How do u handle large traffic load?

We are working for a project that has huge traffic load on Chinese new year eve. Our target throughput is up to 20w pqs and we did not ever have experience handling such large traffic before.

We are using springmvc backend and mysql with Percona cluster as database layer and redis for cache. Our network infrastructure is LVS->nginx->tomcat ->mysql/redis.

What will u do when you working on such scenario?




Is it secure to make adobe flash website?

I am making a website using adobe flash and action script. but I heard a lot about flash vulnerabilities.

Is it secure to make a website using adobe flash, comparably to ordinary tools like wordpress and joomla?




Platform/web application for task/project logger

I want a free web platform, to write logs for a group project. Furthermore it is possible to register multiple accounts to write these log. thanks




Looking to trace code from chrome devtools elements to where it came from

I am looking to trace code from chrome devtools elements to where it came from. I am modifying a wordpress website and I use phpstorm with xdebug. Thank you.




mardi 26 janvier 2016

Difference between website and web service

What is the difference between normal website and a web service? could you please explane with in an example




i need to input text ""how it work"" web browser vb.net

hi i need to input text ""how it work"" vb.net how it work this code not work ** WebBrowser1.Document.GetElementById("t").SetAttribute("value", how it work) ** plz hrlp me




Python Torando No such file or directory:

I am using Tornado to create a website using python. I have a JSON file that contains a list of dictionaries (or not if the app is running for the first time) and I am trying to insert a new dictionary to it after running a query to the DB.

In summary, my problem is that I run a code that inserts the data to my json file and works perfectly when I test it by running my python file and calling the method at the end of it. However, when I run my Tornado server and call the method in my Tornado request handler by clicking un a button, I get this error "IOError: [Errno 2] No such file or directory". I am new to Tornado so I don't have a clue of what the problem may be. Here are the details:

My project has the following structure:

Project/
|-- connector/
|   |-- DBConnector.py
|
|-- data/
|   |-- history.json (does not exist when the app runs for the 1st time)
|
|-- web
|   |-- css
|   |-- fonts
|   |-- js
|   |-- views
|-- server.py

My history.json file can be empty or can contain a list of dictionaries as follows:

[
 {"a":"a", "b":"b", "c":"c", "d":"d"},
 {"e":"e", "f":"f", "g":"g", "h":"h"}
]

Now, I have the following method in my MyMySQLConnection class that is contained in my DBConnector.py file. This method executes a mysql select and insert query and then appends a dictionary that contains the selected values to my history.json JSON file:

class MyMySQLConnection():

    def insert_history_data(self, s_id):
        #MySQL Select occurs by s_id and result is used for insertion
        #MySQL insert occurs. j, k ,l, m are the same values as inserted.
        insert_dict = {"j":"j", "k":"k", "l":"l", "m":"m"
        if(os.path.isfile("../data/history.json")):
            try:
                with open("../data/history.json", "r") as f:
                    json_file = json.load(f)
                    json_file.append(insert_dict)
                    f.close()
                    with open('../data/history.json', 'w') as f:
                        f.write(json.dumps(json_file, indent=4))
                    return True
            except:
                print "Something went wrong (history.json existed)."
                return False
        else:
            try:
                f = file("../data/history.json", "w")
                f.close()
                with open('../data/history.json', 'a+') as outfile:
                    arr = []
                    arr.append(insert_dict)
                    json.dump(arr, outfile, indent=4)
                return True
            except:
                print "Something went wrong.(history.json did not existed)"
                return False

At the end of my DBConnection file, I have the following code (I didn't included the DB connection methods or queries as I tested DB methods and they work fine):

my_con = MyMySQLConnection("user", "pwd")
result = my_con.insert_history_data()

So, when I run DBConnector.py as a python script, that is I simply use the run option over the DBConnector.py in my PyCharm IDE, It works perfectly fine. The first time I run it, the history.json file is created in the "'../data/history.json'" directory and the first dictionary is appended to it. The next times I run it, each dictionary is appended to the history.json file that exists in the '../data/history.json' path.

However, when I run my server and call the method by clicking a button in my web interface, I get the following error (I had to remove the try: except: tags in my code to get the error):

IOError: [Errno 2] No such file or directory: '../data/history.json'

The error is generated by the codeline that contains the line:

f = file("../data/history.json", "w")

When the file exists (I created it by running the DBConnector.py python file) and I call the method, I get the same error in the same line (so, the path should be the problem).

So, why I am getting this error if the code works perfectly fine by running the DBConnector.py class as a python script? My only guess is that Tornado has problems finding the path "../data/history.json" when calling my method on the MyMySQLConnector class instantiated in my Tornado server Handler, however, this does not make any sense to me as I all my files are contained in the same project.

This is how I Init my Tornado server:

if __name__ == "__main__":
    logging.log(logging.INFO, 'Deploying service...')
    app = tornado.web.Application([
        (r"/", MainHandler),
        (r"/add-translate", AddTransHandler),
        (r"/static/(.*)", tornado.web.StaticFileHandler,{"path": settings["static_path"]})
    ], **settings)
    app.listen("8888")

This are my settings:

settings = {"template_path": os.path.dirname(__file__),
            "static_path": os.path.join(os.path.dirname(__file__),"web"),
            "debug": True
            }

And this is the Handler I am using where the :

class AddTransHandler(tornado.web.RequestHandler):
    def get(self):
        s_id= self.get_argument("s_id")
        #my_con is a MyMySQLConnection instance that another method initializes.
        global my_con
        answer = []

        if my_con is None:
            answer.append([{"connection": "False"}])
        else:
            result = my_con.insert_history_data(s_id)
            answer.append(result)
        logging.log(logging.INFO, "Sending insert result...")
        self.write(json.dumps(answer))

Thanks!




Logging in to a website, second time does not return cookie hash key?

I'm programmatically logging in to a website, using HttpWebRequest, POST method. The first time I successfully authenticate, via HttpWebResponse I receive cookie hash key. The second time I perform the same action, I don't receive it anymore.

Does that mean I'm already "Logged in", or does it store my session somewhere, I don't quite understand it, if someone could explain, thank you!

Here's my code and simply said, running this twice, do not return same cookie result.

        HttpWebRequest http = (HttpWebRequest)WebRequest.Create("URL");

        string cookie = string.Empty;
        string values = "vb_login_username=" + username + "&vb_login_password=" + password + "securitytoken=guest&" + "cookieuser=checked&" + "do=login";

        http.Method = "POST";
        http.ContentType = "application/x-www-form-urlencoded";
        http.ContentLength = values.Length;

        CookieContainer cookies = new CookieContainer();
        http.CookieContainer = cookies;

        ServicePointManager.Expect100Continue = false;


        using (var stream = new StreamWriter(http.GetRequestStream(), Encoding.ASCII))
        {
            stream.Write(values);
        }



        HttpWebResponse response = (HttpWebResponse)http.GetResponse();

        foreach (var c in response.Cookies)
        {
            cookie = cookie + c.ToString() + ";";
        }

        return cookie;