/*

@Copyright Barrett Adair 2015-2017
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)

*/

#ifndef BOOST_CLBL_TRTS_REMOVE_MEMBER_CONST_HPP
#define BOOST_CLBL_TRTS_REMOVE_MEMBER_CONST_HPP

#include <boost/callable_traits/detail/core.hpp>

namespace boost { namespace callable_traits {

//[ remove_member_const_hpp
/*`
[section:ref_remove_member_const remove_member_const]
[heading Header]
``#include <boost/callable_traits/remove_member_const.hpp>``
[heading Definition]
*/

template<typename T>
using remove_member_const_t = //see below
//<-
    detail::try_but_fail_if_invalid<
        typename detail::traits<T>::remove_member_const,
        member_qualifiers_are_illegal_for_this_type>;

namespace detail {

    template<typename T, typename = std::false_type>
    struct remove_member_const_impl {};

    template<typename T>
    struct remove_member_const_impl <T, typename std::is_same<
        remove_member_const_t<T>, detail::dummy>::type>
    {
        using type = remove_member_const_t<T>;
    };
}

//->

template<typename T>
struct remove_member_const : detail::remove_member_const_impl<T> {};

//<-
}} // namespace boost::callable_traits
//->

/*`
[heading Constraints]
* `T` must be a function type or a member function pointer type
* If `T` is a pointer, it may not be cv/ref qualified

[heading Behavior]
* A substitution failure occurs if the constraints are violated.
* Removes the member `const` qualifier from `T`, if present.

[heading Input/Output Examples]
[table
    [[`T`]                              [`remove_member_const_t<T>`]]
    [[`int() const`]                    [`int()`]]
    [[`int(foo::*)() const`]            [`int(foo::*)()`]]
    [[`int(foo::*)() const &`]          [`int(foo::*)() &`]]
    [[`int(foo::*)() const &&`]         [`int(foo::*)() &&`]]
    [[`int(foo::*)() const`]            [`int(foo::*)()`]]
    [[`int(foo::*)() const volatile`]   [`int(foo::*)() volatile`]]
    [[`int`]                            [(substitution failure)]]
    [[`int (&)()`]                      [(substitution failure)]]
    [[`int (*)()`]                      [(substitution failure)]]
    [[`int foo::*`]                     [(substitution failure)]]
    [[`int (foo::* const)()`]           [(substitution failure)]]
]

[heading Example Program]
[import ../example/remove_member_const.cpp]
[remove_member_const]
[endsect]
*/
//]

#endif // #ifndef BOOST_CLBL_TRTS_REMOVE_MEMBER_CONST_HPP

{'repo_name': 'marcosd4h/memhunter', 'stars': '246', 'repo_language': 'C++', 'file_name': 'conf.json', 'mime_type': 'text/plain', 'hash': 5644862160776152529, 'source_dataset': 'data'}


#include <opc/ua/protocol/protocol.h>

namespace OpcUa
{

ReadParameters::ReadParameters()
  : MaxAge(0)
  , TimestampsToReturn(OpcUa::TimestampsToReturn::Neither)
{

}

}

{'repo_name': 'FreeOpcUa/freeopcua', 'stars': '455', 'repo_language': 'C++', 'file_name': 'format', 'mime_type': 'text/plain', 'hash': -3422831098329871503, 'source_dataset': 'data'}


$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'reline'
require 'test/unit'

module Reline
  class <<self
    def test_mode
        remove_const('IOGate') if const_defined?('IOGate')
        const_set('IOGate', Reline::GeneralIO)
        send(:core).config.instance_variable_set(:@test_mode, true)
        send(:core).config.reset
    end

    def test_reset
      Reline.instance_variable_set(:@core, nil)
    end
  end
end

RELINE_TEST_ENCODING ||=
  if ENV['RELINE_TEST_ENCODING']
    Encoding.find(ENV['RELINE_TEST_ENCODING'])
  else
    Encoding::UTF_8
  end

class Reline::TestCase < Test::Unit::TestCase
  private def convert_str(input, options = {}, normalized = nil)
    return nil if input.nil?
    input.chars.map { |c|
      if Reline::Unicode::EscapedChars.include?(c.ord)
        c
      else
        c.encode(@line_editor.instance_variable_get(:@encoding), Encoding::UTF_8, **options)
      end
    }.join
  rescue Encoding::UndefinedConversionError, Encoding::InvalidByteSequenceError
    input.unicode_normalize!(:nfc)
    if normalized
      options[:undef] = :replace
      options[:replace] = '?'
    end
    normalized = true
    retry
  end

  def input_key_by_symbol(input)
    @line_editor.input_key(Reline::Key.new(input, input, false))
  end

  def input_keys(input, convert = true)
    input = convert_str(input) if convert
    input.chars.each do |c|
      if c.bytesize == 1
        eighth_bit = 0b10000000
        byte = c.bytes.first
        if byte.allbits?(eighth_bit)
          @line_editor.input_key(Reline::Key.new(byte ^ eighth_bit, byte, true))
        else
          @line_editor.input_key(Reline::Key.new(byte, byte, false))
        end
      else
        c.bytes.each do |b|
          @line_editor.input_key(Reline::Key.new(b, b, false))
        end
      end
    end
  end

  def assert_line(expected)
    expected = convert_str(expected)
    assert_equal(expected, @line_editor.line)
  end

  def assert_byte_pointer_size(expected)
    expected = convert_str(expected)
    byte_pointer = @line_editor.instance_variable_get(:@byte_pointer)
    assert_equal(
      expected.bytesize, byte_pointer,
      "<#{expected.inspect}> expected but was\n<#{@line_editor.line.byteslice(0, byte_pointer).inspect}>")
  end

  def assert_cursor(expected)
    assert_equal(expected, @line_editor.instance_variable_get(:@cursor))
  end

  def assert_cursor_max(expected)
    assert_equal(expected, @line_editor.instance_variable_get(:@cursor_max))
  end
end

{'repo_name': 'pmq20/ruby-packer', 'stars': '992', 'repo_language': 'C', 'file_name': 'test_rubyc.rb', 'mime_type': 'text/x-ruby', 'hash': -2963583006329197257, 'source_dataset': 'data'}


import * as React from 'react';
import * as settings from 'electron-settings';
import { ipcRenderer, remote } from 'electron';
import {
  getAuthUrl,
  refreshAccessToken,
  AuthData,
  setTokenRetrievedCallback,
} from '../../../main/auth';
import {
  CONTAINER,
  MAX_SIDE_LENGTH,
  MIN_SIDE_LENGTH,
} from '../../../constants';
import Cover from './Cover';
import Settings from './Settings';
import About from './About';
import Welcome from './Welcome';
import WindowPortal from '../util/WindowPortal';

import './style.scss';

enum SIDE {
  LEFT,
  RIGHT,
}

class Lofi extends React.Component<any, any> {
  constructor(props: any) {
    super(props);

    this.state = {
      access_token: settings.getSync('access_token'),
      refresh_token: settings.getSync('refresh_token'),
      showSettings: false,
      showAbout: false,
      lofiSettings: settings.getSync('lofi'),
      side_length: settings.getSync('lofi.window.side'),
      window_side: (() => {
        if (
          (remote.getCurrentWindow().getBounds().x +
            remote.getCurrentWindow().getBounds().width) /
            2 -
            remote.screen.getDisplayMatching(
              remote.getCurrentWindow().getBounds()
            ).bounds.x <
          remote.screen.getDisplayMatching(
            remote.getCurrentWindow().getBounds()
          ).bounds.width /
            2
        ) {
          return SIDE.LEFT;
        }
        return SIDE.RIGHT;
      })(),
      auth_url: '',
    };

    // Allow to open settings via IPC channel (e.g. triggered by a taskbar click)
    ipcRenderer.on('show-settings', () => {
      this.showSettingsWindow();
    });

    // Allow to open settings via IPC channel (e.g. triggered by a taskbar click)
    ipcRenderer.on('show-about', () => {
      this.showAboutWindow();
    });
  }

  reloadSettings() {
    this.setState({ lofiSettings: settings.getSync('lofi') });
  }

  async handleAuth() {
    try {
      setTokenRetrievedCallback(this.updateTokens.bind(this));

      // always get the auth url in case refreshing the token fails
      const authUrl = await getAuthUrl();
      this.setState({ auth_url: authUrl });

      if (this.state.refresh_token) {
        await refreshAccessToken(this.state.refresh_token);
      }
    } catch (err) {
      console.error(err);
      this.updateTokens({ access_token: null, refresh_token: null });
    }
  }

  updateTokens(data: AuthData) {
    if (!data || !data.access_token || !data.refresh_token) {
      settings.deleteSync('access_token');
      settings.deleteSync('refresh_token');
    } else {
      settings.setSync('access_token', data.access_token);
      settings.setSync('refresh_token', data.refresh_token);
    }

    this.setState({ access_token: data?.access_token });
    this.setState({ refresh_token: data?.refresh_token });
  }

  componentDidMount() {
    this.handleAuth();

    // Move the window when dragging specific element without cannibalizing events
    // Credit goes out to @danielravina
    // See: https://github.com/electron/electron/issues/1354#issuecomment-404348957

    const that = this;
    let animationId: number;
    let mouseX: number;
    let mouseY: number;
    let mouseDeltaX: number;
    let mouseDeltaY: number;

    function onMouseMove(e: any) {
      mouseDeltaX = e.clientX;
      mouseDeltaY = e.clientY;
    }

    function onMouseDown(e: any) {
      if (
        leftMousePressed(e) &&
        !e.target['classList'].contains('not-draggable')
      ) {
        // Cancel old animation frame, fixes mouse getting "stuck" in the drag state
        cancelAnimationFrame(animationId);
        mouseX = e.clientX;
        mouseY = e.clientY;
        document.addEventListener('mouseup', onMouseUp);
        if (e.target['classList'].contains('grab-resize')) {
          requestAnimationFrame(
            resizeWindow.bind(
              that,
              e.target['classList'].contains('top'),
              e.target['classList'].contains('right')
            )
          );
          document.body.classList.remove('click-through');
        } else {
          requestAnimationFrame(moveWindow);
        }
      }
    }

    function onMouseUp(e: MouseEvent) {
      if (leftMousePressed(e)) {
        ipcRenderer.send('windowMoved', { mouseX, mouseY });
        document.removeEventListener('mouseup', onMouseUp);
        cancelAnimationFrame(animationId);
        document.body.classList.add('click-through');
      }
    }

    let resizeWindow = function (top: boolean, right: boolean) {
      let length = that.state.side_length;

      // TODO: The math here can be simplified, but leaving it explicit for now
      if (top && right) {
        const handleX = CONTAINER.HORIZONTAL / 2 + that.state.side_length / 2;
        const handleY = CONTAINER.VERTICAL / 2 - that.state.side_length / 2;
        const dX = handleX + mouseDeltaX;
        const dY = handleY - mouseDeltaY;
        if (Math.abs(dX) >= Math.abs(dY)) {
          length += dY;
        } else {
          length += dX;
        }
      } else if (top && !right) {
        const handleX = CONTAINER.HORIZONTAL / 2 - that.state.side_length / 2;
        const handleY = CONTAINER.VERTICAL / 2 - that.state.side_length / 2;
        const dX = handleX - mouseDeltaX;
        const dY = handleY - mouseDeltaY;
        if (Math.abs(dX) >= Math.abs(dY)) {
          length += dY;
        } else {
          length += dX;
        }
      } else if (!top && right) {
        const handleX = CONTAINER.HORIZONTAL / 2 + that.state.side_length / 2;
        const handleY = CONTAINER.VERTICAL / 2 + that.state.side_length / 2;
        const dX = mouseDeltaX - handleX;
        const dY = mouseDeltaY - handleY;
        if (Math.abs(dX) >= Math.abs(dY)) {
          length += dY;
        } else {
          length += dX;
        }
      } else if (!top && !right) {
        const handleX = CONTAINER.HORIZONTAL / 2 - that.state.side_length / 2;
        const handleY = CONTAINER.VERTICAL / 2 + that.state.side_length / 2;
        const dX = handleX - mouseDeltaX;
        const dY = handleY + mouseDeltaY;
        if (Math.abs(dX) >= Math.abs(dY)) {
          length += dY;
        } else {
          length += dX;
        }
      }

      // Maximum side length constraints
      if (length <= MAX_SIDE_LENGTH && length >= MIN_SIDE_LENGTH) {
        ipcRenderer.send('windowResizing', length);
        that.setState({ side_length: length });
      }

      animationId = requestAnimationFrame(resizeWindow.bind(that, top, right));
    };

    let moveWindow = function () {
      ipcRenderer.send('windowMoving', { mouseX, mouseY });
      if (
        remote.screen.getCursorScreenPoint().x -
          remote.screen.getDisplayMatching(
            remote.getCurrentWindow().getBounds()
          ).bounds.x <
        remote.screen.getDisplayMatching(remote.getCurrentWindow().getBounds())
          .bounds.width /
          2
      ) {
        that.setState({ window_side: SIDE.LEFT });
      } else {
        that.setState({ window_side: SIDE.RIGHT });
      }
      animationId = requestAnimationFrame(moveWindow);
    }.bind(that);

    function leftMousePressed(e: MouseEvent) {
      var button = e.which || e.button;
      return button === 1;
    }

    document
      .getElementById('visible-ui')
      .addEventListener('mousedown', onMouseDown);
    document
      .getElementById('app-body')
      .addEventListener('mousemove', onMouseMove);
  }

  showAboutWindow() {
    if (!this.state.showAbout) {
      this.setState({ showAbout: true });
    }
  }

  hideAboutWindow() {
    this.setState({ showAbout: false });
  }

  showSettingsWindow() {
    if (!this.state.showSettings) {
      this.setState({ showSettings: true });
    }
  }

  hideSettingsWindow() {
    this.setState({ showSettings: false });
  }

  render() {
    return (
      <div
        id="visible-ui"
        className="click-on"
        style={{
          height: this.state.side_length,
          width: this.state.side_length,
          left: `calc(50% - ${this.state.side_length / 2}px)`,
        }}>

        {this.state.showSettings ? (
          <WindowPortal
            fullscreen
            onUnload={this.hideSettingsWindow.bind(this)}
            name="settings">
            <Settings lofi={this} className="settings-wnd" />
          </WindowPortal>
        ) : null}
        {this.state.showAbout ? (
          <WindowPortal
            fullscreen
            onUnload={this.hideAboutWindow.bind(this)}
            name="about">
            <About lofi={this} className="about-wnd" />
          </WindowPortal>
        ) : null}
        {this.state.access_token ? (
          <Cover
            visualizationId={this.state.lofiSettings.visualization}
            settings={this.state.lofiSettings.window}
            side={this.state.window_side}
            lofi={this}
            token={this.state.access_token}
          />
        ) : (
          <Welcome lofi={this} />
        )}

    );
  }
}

export default Lofi;

{'repo_name': 'dvx/lofi', 'stars': '478', 'repo_language': 'TypeScript', 'file_name': 'settings.json', 'mime_type': 'text/plain', 'hash': 2913254053940663816, 'source_dataset': 'data'}


<?php
/**
 * NOTICE OF LICENSE.
 *
 * UNIT3D Community Edition is open-sourced software licensed under the GNU Affero General Public License v3.0
 * The details is bundled with this project in the file LICENSE.txt.
 *
 * @project    UNIT3D Community Edition
 *
 * @author     HDVinnie <hdinnovations@protonmail.com>
 * @license    https://www.gnu.org/licenses/agpl-3.0.en.html/ GNU Affero General Public License v3.0
 */

return [
    'aboutus-advantage'     => 'Prednost',
    'aboutus-advantage1'    => 'Imamo iskusne članove i osoblje koje dobro poznaje svijet HD video / audio i tehničke podrške.',
    'aboutus-advantage2'    => 'Uz našu veliku strast prema filmovima i TV emisijama, nudimo i jednu od najboljih selekcija nečega što najviše - FANRES! VELIKO HVALA našim donositeljima sadržaja.',
    'aboutus-advantage3'    => 'Iako prihvaćamo donacije kako bismo zadržali web-lokaciju i pokrenuli web-lokaciju, neće biti nikakvih gnjavitelja ili banera na licu mjesta. Ne moliti od nas.',
    'aboutus-advantage4'    => 'Naša zajednica nema premca za ranu dob. Između našeg osoblja i korisničke baze, uvijek smo bili tu da vam pomognemo. Bili smo strastveni u osiguravanju vašeg iskustva na: naslov je ništa manje od nevjerojatna.',
    'aboutus-advantage5'    => 'Naše usluge svakodnevno koriste mnogi ljudi širom svijeta. Dokazali smo da nam je stalo do funkcionalnosti i sigurnosti našeg koda i da se može pouzdati i osloniti se na njega. Naši programeri svakodnevno rade kako bi pružili doista nex-gen kodnu bazu.',
    'aboutus-header'        => 'bok tamo',
    'aboutus-rules'         => 'Ono što trebamo od vas',
    'aboutus-rules1'        => 'Biti aktivan član zajednice! To znači produktivno uključivanje u razgovore, dodavanje odobrenog sadržaja i pomoć drugim korisnicima ako možete.',
    'aboutus-rules2'        => 'Pročitati pravila u cijelosti i poštovati ih!',
    'aboutus-rules3'        => 'Davati prijedloge! Nastojimo svaki dan poboljšati: titulu. Mi ne tvrdimo da će se svaki prijedlog koristiti, ali nikada ne boli vidjeti nove ideje.',
    'aboutus-welcome'       => 'Pričajmo o',
    'aboutus-welcome-desc'  => ': title je baza filmova / TV-a / FANRES -a izgrađena u zajednici . Svaki dio podataka dodan je našoj izvanrednoj zajednici od 2017. godine: naslovi snažan fokus su na HD sadržaju, proaktivnoj korisničkoj bazi, strašnoj / sigurnoj bazi koda i uslužnom timu.',
    'blacklist-browsers'    => 'Preglednici',
    'blacklist-btclient'    => 'BitTorrent klijent',
    'blacklist-clients'     => 'klijenti',
    'blacklist-desc'        => 'Sljedeći preglednici i bittorrent klijenti su na crnoj listi / zabranjeni iz objavljivanja na: naslov',
    'blacklist-webbrowser'  => 'Web-preglednik',
    'blacklist-emaildomain' => 'Blokirana domena',
    'email-blacklist-desc'  => 'Sljedeće domene e-pošte blokirane su od upotrebe. Ne možete se registrirati ili poslati pozivnicu na sljedeće.',
    'email-whitelist-desc'  => 'Sljedeće e-mail domene su jedine domene koje se mogu koristiti. Možete samo registrirati ili poslati pozivnicu pomoću sljedećeg.',
    'staff-group'           => 'Skupina',
    'staff-title'           => 'Titula',
    'whitelist-emaildomain' => 'Pouzdana domena',
];

{'repo_name': 'HDInnovations/UNIT3D-Community-Edition', 'stars': '1172', 'repo_language': 'PHP', 'file_name': 'web.config', 'mime_type': 'text/plain', 'hash': -5685025995787718661, 'source_dataset': 'data'}


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="search.css"/>

Loading...

Searching...

No Matches

{'repo_name': 'apache/guacamole-website', 'stars': '148', 'repo_language': 'JavaScript', 'file_name': 'LocalEnvironment.html', 'mime_type': 'text/html', 'hash': -4919431694934131770, 'source_dataset': 'data'}


---
layout: daily
title: DataTables使用入门-国际化 Internationalisation 博客 DataTables中文网
short: DataTables使用入门-国际化 Internationalisation
date: 2020-09-10
group: 2020-9
caption: DataTables 中文网博客
categories: blog
tags: [博客,DataTables使用经验,第二季视频]
author: DataTables中文网
hot: 1
---

本节为Datatables入门第二期 —— [《使用Datatables"武装"你的html表格》][index]的第十一章，主要讲Datatables的[国际化处理][i18n]，即Datatables如何自定义显示语言。

## 课程简介
---

默认情况下，我们可能只需要一种语言显示给最终用户。比如Datatables默认的就是用英语显示，显然对于中国开发者来说这不是第一选择，所以就需要对软件做语言替换，通过配置的方式来替换显示的语言。当然如果是做国际化的项目，还可能需要在多种语言之间切换，根据当前系统的语言环境来决定用那一套语言显示给最终用户。国际化处理就是为了解决这个问题而存在的。

<!--more-->

### 本节课程通过以下几个方面进行讲述：
---

- 什么是国际化？
- 如何配置显示的语言？
    - 直接配置
    - 通过ajax读取配置文件
- 数字类型的排序？

### 学完本节课程可以解决哪些疑惑？
---

- 自定义Datatables显示语言
- 根据系统环境使用对应的语言

## 课程视频
---

由于源码托管在GitHub上，不方便传大文件，观看视频请加群20779435，视频在群文件里可以查阅，或者查看我的[bilibili频道][bilibili]、[Youtube频道][youtube]和[微博视频][weibo]在线播放

<iframe flag="bilibili" src="//player.bilibili.com/player.html?aid=839501955&bvid=BV1C54y127rs&cid=234137904&page=1" scrolling="no" border="0" frameborder="no" framespacing="0" allowfullscreen="true"></iframe>

## 课程代码
---

课程中所有代码都已经放在GitHub上了，[点我查看][github]

最后，谢谢大家的支持，如有错误的地方还望指出，如果您还有其他的建议或要求，欢迎在下方留言

[youtube]: https://www.youtube.com/playlist?list=PLfl1Raz12t6s43Fb--qDoIsBPKHEme7FO
[bilibili]: https://space.bilibili.com/618644465/channel/detail?cid=133983
[github]: https://github.com/ssy341/datatables-season2/tree/master/example11
[index]: {{ site.baseurl }}/blog/2020/06/21/how-to-make-your-table-stronger.html
[weibo]: https://weibo.com/2957561617/profile?topnav=1&wvr=6&is_all=1
[i18n]: {{ site.baseurl }}/manual/i18n

{'repo_name': 'ssy341/datatables-cn', 'stars': '456', 'repo_language': 'HTML', 'file_name': 'deployto_site.bat', 'mime_type': 'text/plain', 'hash': 6600842879336366123, 'source_dataset': 'data'}


package com.jaychang.sa.google

import com.jaychang.sa.AuthCallback
import com.jaychang.sa.AuthData
import com.jaychang.sa.AuthDataHolder
import com.jaychang.sa.Initializer

object SimpleAuth {
  @JvmStatic
  fun connectGoogle(scopes: List<String> = listOf(), listener: AuthCallback) {
    AuthDataHolder.getInstance().googleAuthData = AuthData(scopes, listener)
    GoogleAuthActivity.start(Initializer.context)
  }

  @JvmStatic
  fun disconnectGoogle() {
    AuthDataHolder.getInstance().googleAuthData = null
    GoogleAuthActivity.setGoogleDisconnectRequested(Initializer.context,true)
  }

  @JvmStatic
  fun revokeGoogle() {
    GoogleAuthActivity.setGoogleRevokeRequested(Initializer.context,true)
  }
}

{'repo_name': 'jaychang0917/SimpleAuth', 'stars': '214', 'repo_language': 'Java', 'file_name': 'FacebookAuthActivity.java', 'mime_type': 'text/x-java', 'hash': -5685965419896988611, 'source_dataset': 'data'}


%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 2008-2020. All Rights Reserved.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%%     http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%

%%

-module(ssh_client_channel).

-include("ssh.hrl").
-include("ssh_connect.hrl").

-callback init(Args :: term()) ->
    {ok, State :: term()} | {ok, State :: term(), timeout() | hibernate} |
    {stop, Reason :: term()} | ignore.
-callback handle_call(Request :: term(), From :: {pid(), Tag :: term()},
                      State :: term()) ->
    {reply, Reply :: term(), NewState :: term()} |
    {reply, Reply :: term(), NewState :: term(), timeout() | hibernate} |
    {noreply, NewState :: term()} |
    {noreply, NewState :: term(), timeout() | hibernate} |
    {stop, Reason :: term(), Reply :: term(), NewState :: term()} |
    {stop, Reason :: term(), NewState :: term()}.
-callback handle_cast(Request :: term(), State :: term()) ->
    {noreply, NewState :: term()} |
    {noreply, NewState :: term(), timeout() | hibernate} |
    {stop, Reason :: term(), NewState :: term()}.

-callback terminate(Reason :: (normal | shutdown | {shutdown, term()} |
                               term()),
                    State :: term()) ->
    term().
-callback code_change(OldVsn :: (term() | {down, term()}), State :: term(),
                      Extra :: term()) ->
    {ok, NewState :: term()} | {error, Reason :: term()}.

-callback handle_msg(Msg ::term(), State :: term()) ->
    {ok, State::term()} | {stop, ChannelId::ssh:channel_id(), State::term()}.

-callback handle_ssh_msg(ssh_connection:event(),
 			 State::term()) -> {ok, State::term()} |
 					   {stop, ChannelId::ssh:channel_id(),
 					    State::term()}.
-behaviour(gen_server).

%%% API
-export([start/4, start/5, start_link/4, start_link/5, call/2, call/3,
	 cast/2, reply/2, enter_loop/1]).

%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
	 terminate/2, code_change/3]).

%% Internal application API
-export([cache_create/0, cache_lookup/2, cache_update/2,
	 cache_delete/1, cache_delete/2,  cache_foldl/3,
	 cache_info/2,  cache_find/2,
	 get_print_info/1]).

-behaviour(ssh_dbg).
-export([ssh_dbg_trace_points/0, ssh_dbg_flags/1, ssh_dbg_on/1, ssh_dbg_off/1, ssh_dbg_format/2]).

-record(state, {
	  cm,
	  channel_cb,
	  channel_state,
	  channel_id,
	  close_sent = false
	 }).

%%====================================================================
%% API
%%====================================================================

call(ChannelPid, Msg) ->
    call(ChannelPid, Msg, infinity).

call(ChannelPid, Msg, TimeOute) ->
    try gen_server:call(ChannelPid, Msg, TimeOute) of
	Result ->
	    Result
    catch
 	exit:{noproc, _} ->
 	    {error, closed};
	exit:{normal, _} ->
	    {error, closed};
	exit:{shutdown, _} ->
	    {error, closed};
	exit:{{shutdown, _}, _} ->
	    {error, closed};
 	exit:{timeout, _} ->
 	    {error, timeout}
    end.

cast(ChannelPid, Msg) ->
    gen_server:cast(ChannelPid, Msg).

reply(From, Msg) ->
    gen_server:reply(From, Msg).

%%====================================================================
%% Internal application API
%%====================================================================

%%--------------------------------------------------------------------
%% Function: start_link() -> {ok,Pid} | ignore | {error,Error}
%% Description: Starts the server
%%--------------------------------------------------------------------
start(ConnectionManager, ChannelId, CallBack, CbInitArgs) ->
    start(ConnectionManager, ChannelId, CallBack, CbInitArgs, undefined).

start(ConnectionManager, ChannelId, CallBack, CbInitArgs, Exec) ->
    Options = [{channel_cb, CallBack},
	       {channel_id, ChannelId},
	       {init_args, CbInitArgs},
	       {cm, ConnectionManager},
	       {exec, Exec}],
    gen_server:start(?MODULE, [Options], []).

start_link(ConnectionManager, ChannelId, CallBack, CbInitArgs) ->
    start_link(ConnectionManager, ChannelId, CallBack, CbInitArgs, undefined).

start_link(ConnectionManager, ChannelId, CallBack, CbInitArgs, Exec) ->
    Options = [{channel_cb, CallBack},
	       {channel_id, ChannelId},
	       {init_args, CbInitArgs},
	       {cm, ConnectionManager},
	       {exec, Exec}],
    gen_server:start_link(?MODULE, [Options], []).

enter_loop(State) ->
    gen_server:enter_loop(?MODULE, [], State).

%%====================================================================
%% gen_server callbacks
%%====================================================================

%%--------------------------------------------------------------------
%% Function: init(Args) -> {ok, State} |
%%                         {ok, State, Timeout} |
%%                         ignore               |
%%                         {stop, Reason}
%% Description: Initiates the server
%%--------------------------------------------------------------------
init([Options]) ->
    Cb = proplists:get_value(channel_cb, Options),
    ConnectionManager =  proplists:get_value(cm, Options),
    ChannelId = proplists:get_value(channel_id, Options),
    process_flag(trap_exit, true),
    try Cb:init(channel_cb_init_args(Options)) of
	{ok, ChannelState} ->
	    State = #state{cm = ConnectionManager,
			   channel_cb = Cb,
			   channel_id = ChannelId,
			   channel_state = ChannelState},
	    self() ! {ssh_channel_up, ChannelId, ConnectionManager},
	    {ok, State};
	{ok, ChannelState, Timeout} ->
	    State = #state{cm = ConnectionManager,
			   channel_cb = Cb,
			   channel_id = ChannelId,
			   channel_state = ChannelState},
	    self() ! {ssh_channel_up, ChannelId, ConnectionManager},
	    {ok, State, Timeout};
	{stop, Why} ->
	    {stop, Why}
    catch
        _:undef ->
            {stop, {bad_channel_callback_module,Cb}};
	_:Reason ->
	    {stop, Reason}
    end.

channel_cb_init_args(Options) ->
    case proplists:get_value(exec, Options) of
        undefined ->
            proplists:get_value(init_args, Options);
        Exec ->
            proplists:get_value(init_args, Options) ++ [Exec]
    end.

%%--------------------------------------------------------------------
%% Function: %% handle_call(Request, From, State) -> {reply, Reply, State} |
%%                                      {reply, Reply, State, Timeout} |
%%                                      {noreply, State} |
%%                                      {noreply, State, Timeout} |
%%                                      {stop, Reason, Reply, State} |
%%                                      {stop, Reason, State}
%% Description: Handling call messages
%%--------------------------------------------------------------------
handle_call(get_print_info, _From, State) ->
    Reply =
	{{State#state.cm,
	  State#state.channel_id},
	 io_lib:format('CB=~p',[State#state.channel_cb])
	},
    {reply, Reply, State};

handle_call(Request, From, #state{channel_cb = Module,
				  channel_state = ChannelState} = State) ->
   try Module:handle_call(Request, From, ChannelState) of
       Result ->
	   handle_cb_result(Result, State)
   catch
       error:{undef, _} ->
	   {noreply, State}
   end.

%%--------------------------------------------------------------------
%% Function: handle_cast(Msg, State) -> {noreply, State} |
%%                                      {noreply, State, Timeout} |
%%                                      {stop, Reason, State}
%% Description: Handling cast messages
%%--------------------------------------------------------------------
handle_cast(Msg, #state{channel_cb = Module,
			channel_state = ChannelState} = State) ->

    try Module:handle_cast(Msg, ChannelState) of
	Result ->
	    handle_cb_result(Result, State)
    catch
       error:{undef, _} ->
	    {noreply, State}
   end.

%%--------------------------------------------------------------------
%% Function: handle_info(Info, State) -> {noreply, State} |
%%                                       {noreply, State, Timeout} |
%%                                       {stop, Reason, State}
%% Description: Handling all non call/cast messages
%%--------------------------------------------------------------------
handle_info({ssh_cm, ConnectionManager, {closed, _ChannelId}},
	    #state{cm = ConnectionManager,
		   close_sent = true} = State) ->
    {stop, normal, State};
handle_info({ssh_cm, ConnectionManager, {closed, ChannelId}},
	    #state{cm = ConnectionManager,
		   close_sent = false} = State) ->
    %% To be on the safe side, i.e. the manager has already been terminated.
    (catch ssh_connection:close(ConnectionManager, ChannelId)),
    {stop, normal, State#state{close_sent = true}};

handle_info({ssh_cm, _, _} = Msg, #state{cm = ConnectionManager,
			channel_cb = Module,
			channel_state = ChannelState0} = State) ->
    case Module:handle_ssh_msg(Msg, ChannelState0) of
	{ok, ChannelState} ->
	    adjust_window(Msg),
	    {noreply, State#state{channel_state = ChannelState}};
	{ok, ChannelState, Timeout} ->
	    adjust_window(Msg),
	    {noreply, State#state{channel_state = ChannelState}, Timeout};
	{stop, ChannelId, ChannelState} ->
	    catch ssh_connection:close(ConnectionManager, ChannelId),
	    {stop, normal, State#state{close_sent = true,
				       channel_state = ChannelState}}
    end;

handle_info(Msg, #state{cm = ConnectionManager, channel_cb = Module,
			channel_state = ChannelState0} = State) ->
    case Module:handle_msg(Msg, ChannelState0) of
	{ok, ChannelState} ->
	    {noreply, State#state{channel_state = ChannelState}};
	{ok, ChannelState, Timeout} ->
	    {noreply, State#state{channel_state = ChannelState}, Timeout};
	{stop, Reason, ChannelState} when is_atom(Reason)->
	    {stop, Reason, State#state{close_sent = true,
				       channel_state = ChannelState}};
	{stop, ChannelId, ChannelState} ->
	    Reason =
		case Msg of
		    {'EXIT', _Pid, shutdown} ->
			shutdown;
		    _ ->
			normal
		end,
	    (catch ssh_connection:close(ConnectionManager, ChannelId)),
	    {stop, Reason, State#state{close_sent = true,
				       channel_state = ChannelState}}
    end.

%%--------------------------------------------------------------------
%% Function: terminate(Reason, State) -> void()
%% Description: This function is called by a gen_server when it is about to
%% terminate. It should be the opposite of Module:init/1 and do any necessary
%% cleaning up. When it returns, the gen_server terminates with Reason.
%% The return value is ignored.
%%--------------------------------------------------------------------
terminate(Reason, #state{cm = ConnectionManager,
 			 channel_id = ChannelId,
 			 close_sent = false} = State) ->
    catch ssh_connection:close(ConnectionManager, ChannelId),
    terminate(Reason, State#state{close_sent = true});
terminate(Reason, #state{channel_cb = Cb, channel_state = ChannelState}) ->
    catch Cb:terminate(Reason, ChannelState),
    ok.

%%--------------------------------------------------------------------
%% Func: code_change(OldVsn, State, Extra) -> {ok, NewState}
%% Description: Convert process state when code is changed
%%--------------------------------------------------------------------
code_change(OldVsn, #state{channel_cb = Module,
			   channel_state = ChannelState0} = State, Extra) ->
    {ok, ChannelState} = Module:code_change(OldVsn, ChannelState0, Extra),
    {ok, State#state{channel_state = ChannelState}}.

%%====================================================================
%% Internal application API
%%====================================================================
cache_create() ->
    ets:new(cm_tab, [set,{keypos, #channel.local_id}]).

cache_lookup(Cache, Key) ->
    case ets:lookup(Cache, Key) of
	[Channel] ->
	    Channel;
	[] ->
	    undefined
    end.

cache_update(Cache, #channel{local_id = Id} = Entry) when Id =/= undefined ->
    ets:insert(Cache, Entry).

cache_delete(Cache, Key) ->
    ets:delete(Cache, Key).

cache_delete(Cache) ->
    ets:delete(Cache).

cache_foldl(Fun, Acc, Cache) ->
    ets:foldl(Fun, Acc, Cache).

cache_info(num_entries, Cache) ->
    proplists:get_value(size, ets:info(Cache)).

cache_find(ChannelPid, Cache) ->
   case ets:match_object(Cache, #channel{user = ChannelPid}) of
       [] ->
	   undefined;
       [Channel] ->
	   Channel
   end.

get_print_info(Pid) ->
    call(Pid, get_print_info, 1000).

%%--------------------------------------------------------------------
%%% Internal functions
%%--------------------------------------------------------------------
handle_cb_result({reply, Reply, ChannelState}, State) ->
    {reply, Reply, State#state{channel_state = ChannelState}};
handle_cb_result({reply, Reply, ChannelState, Timeout}, State) ->
    {reply, Reply,State#state{channel_state = ChannelState}, Timeout};
handle_cb_result({noreply, ChannelState}, State) ->
    {noreply, State#state{channel_state = ChannelState}};
handle_cb_result({noreply, ChannelState, Timeout}, State) ->
    {noreply, State#state{channel_state = ChannelState}, Timeout};
handle_cb_result({stop, Reason, Reply, ChannelState}, State) ->
    {stop, Reason, Reply,  State#state{channel_state = ChannelState}};
handle_cb_result({stop, Reason, ChannelState}, State) ->
    {stop, Reason, State#state{channel_state = ChannelState}}.

adjust_window({ssh_cm, ConnectionManager,
	       {data, ChannelId, _, Data}}) ->
    ssh_connection:adjust_window(ConnectionManager, ChannelId, size(Data));
adjust_window(_) ->
    ok.

%%%################################################################
%%%#
%%%# Tracing
%%%#

ssh_dbg_trace_points() -> [terminate, channels, channel_events].

ssh_dbg_flags(channels) -> [c];
ssh_dbg_flags(terminate) -> [c];
ssh_dbg_flags(channel_events) -> [c].

ssh_dbg_on(terminate) -> dbg:tp(?MODULE,  terminate, 2, x);
ssh_dbg_on(channels) -> dbg:tp(?MODULE,  init, 1, x),
                        ssh_dbg_on(terminate);
ssh_dbg_on(channel_events) -> dbg:tp(?MODULE,  handle_call, 3, x),
                              dbg:tp(?MODULE,  handle_cast, 2, x),
                              dbg:tp(?MODULE,  handle_info, 2, x).

ssh_dbg_off(terminate) -> dbg:ctpg(?MODULE, terminate, 2);
ssh_dbg_off(channels) -> dbg:ctpg(?MODULE, init, 1),
                         ssh_dbg_off(terminate);
ssh_dbg_off(channel_events) -> dbg:ctpg(?MODULE,  handle_call, 3),
                               dbg:ctpg(?MODULE,  handle_cast, 2),
                               dbg:ctpg(?MODULE,  handle_info, 2).

ssh_dbg_format(channels, {call, {?MODULE,init, [[KVs]]}}) ->
    ["Server Channel Starting:\n",
     io_lib:format("Connection: ~p, ChannelId: ~p, CallBack: ~p\nCallBack init args = ~p",
                   [proplists:get_value(K,KVs) || K <- [cm, channel_id, channel_cb]]
                   ++ [channel_cb_init_args(KVs)])
    ];
ssh_dbg_format(channels, {return_from, {?MODULE,init,1}, {stop,Reason}}) ->
    ["Server Channel Start FAILED!\n",
     io_lib:format("Reason = ~p", [Reason])
    ];

ssh_dbg_format(channels, F) ->
    ssh_dbg_format(terminate, F);

ssh_dbg_format(terminate, {call, {?MODULE,terminate, [Reason, State]}}) ->
    ["Server Channel Terminating:\n",
     io_lib:format("Reason: ~p,~nState:~n~s", [Reason, wr_record(State)])
    ];
ssh_dbg_format(terminate, {return_from, {?MODULE,terminate,2}, _Ret}) ->
    skip;

ssh_dbg_format(channel_events, {call, {?MODULE,handle_call, [Call,From,State]}}) ->
    [hdr("is called", State),
     io_lib:format("From: ~p~nCall: ~p~n", [From, Call])
    ];
ssh_dbg_format(channel_events, {return_from, {?MODULE,handle_call,3}, Ret}) ->
    ["Server Channel call returned:\n",
     io_lib:format("~p~n", [ssh_dbg:reduce_state(Ret,#state{})])
    ];

ssh_dbg_format(channel_events, {call, {?MODULE,handle_cast, [Cast,State]}}) ->
    [hdr("got cast", State),
     io_lib:format("Cast: ~p~n", [Cast])
    ];
ssh_dbg_format(channel_events, {return_from, {?MODULE,handle_cast,2}, Ret}) ->
    ["Server Channel cast returned:\n",
     io_lib:format("~p~n", [ssh_dbg:reduce_state(Ret,#state{})])
    ];

ssh_dbg_format(channel_events, {call, {?MODULE,handle_info, [Info,State]}}) ->
    [hdr("got info", State),
     io_lib:format("Info: ~p~n", [Info])
    ];
ssh_dbg_format(channel_events, {return_from, {?MODULE,handle_info,2}, Ret}) ->
    ["Server Channel info returned:\n",
     io_lib:format("~p~n", [ssh_dbg:reduce_state(Ret,#state{})])
    ].

hdr(Title, S) ->
    io_lib:format("Server Channel (Id=~p, CB=~p) ~s:\n", [S#state.channel_id, S#state.channel_cb, Title]).

?wr_record(state).

{'repo_name': 'erlang/otp', 'stars': '8441', 'repo_language': 'Erlang', 'file_name': 'vxworks_resolv.c', 'mime_type': 'text/x-c', 'hash': -933375464459564385, 'source_dataset': 'data'}


Summary: Simple DirectMedia Layer
Name: SDL2
Version: 2.0.10
Release: 2
Source: http://www.libsdl.org/release/%{name}-%{version}.tar.gz
URL: http://www.libsdl.org/
License: zlib
Group: System Environment/Libraries
BuildRoot: %{_tmppath}/%{name}-%{version}-buildroot
Prefix: %{_prefix}
%ifos linux
Provides: libSDL2-2.0.so.0
%endif

%define __defattr %defattr(-,root,root)
%define __soext so

%description
This is the Simple DirectMedia Layer, a generic API that provides low
level access to audio, keyboard, mouse, and display framebuffer across
multiple platforms.

%package devel
Summary: Libraries, includes and more to develop SDL applications.
Group: Development/Libraries
Requires: %{name} = %{version}

%description devel
This is the Simple DirectMedia Layer, a generic API that provides low
level access to audio, keyboard, mouse, and display framebuffer across
multiple platforms.

This is the libraries, include files and other resources you can use
to develop SDL applications.

%prep
%setup -q

%build
%ifos linux
CFLAGS="$RPM_OPT_FLAGS" ./configure --prefix=%{prefix} --disable-video-directfb
%else
%configure
%endif
make

%install
rm -rf $RPM_BUILD_ROOT
%ifos linux
make install prefix=$RPM_BUILD_ROOT%{prefix} \
             bindir=$RPM_BUILD_ROOT%{_bindir} \
             libdir=$RPM_BUILD_ROOT%{_libdir} \
             includedir=$RPM_BUILD_ROOT%{_includedir} \
             datadir=$RPM_BUILD_ROOT%{_datadir} \
             mandir=$RPM_BUILD_ROOT%{_mandir}
%else
%makeinstall
%endif

%clean
rm -rf $RPM_BUILD_ROOT

%files
%{__defattr}
%doc README*.txt COPYING.txt CREDITS.txt BUGS.txt
%{_libdir}/lib*.%{__soext}.*

%files devel
%{__defattr}
%doc docs/README*.md
%{_bindir}/*-config
%{_libdir}/lib*.a
%{_libdir}/lib*.la
%{_libdir}/lib*.%{__soext}
%{_includedir}/*/*.h
%{_libdir}/cmake/*
%{_libdir}/pkgconfig/SDL2/*
%{_datadir}/aclocal/*

%changelog
* Thu Jun 04 2015 Ryan C. Gordon <icculus@icculus.org>
- Fixed README paths.

* Sun Dec 07 2014 Simone Contini <s.contini@oltrelinux.com>
- Fixed changelog date issue and docs filenames

* Sun Jan 22 2012 Sam Lantinga <slouken@libsdl.org>
- Updated for SDL 2.0

* Tue May 16 2006 Sam Lantinga <slouken@libsdl.org>
- Removed support for Darwin, due to build problems on ps2linux

* Sat Jan 03 2004 Anders Bjorklund <afb@algonet.se>
- Added support for Darwin, updated spec file

* Wed Jan 19 2000 Sam Lantinga <slouken@libsdl.org>
- Re-integrated spec file into SDL distribution
- 'name' and 'version' come from configure
- Some of the documentation is devel specific
- Removed SMP support from %build - it doesn't work with libtool anyway

* Tue Jan 18 2000 Hakan Tandogan <hakan@iconsult.com>
- Hacked Mandrake sdl spec to build 1.1

* Sun Dec 19 1999 John Buswell <johnb@mandrakesoft.com>
- Build Release

* Sat Dec 18 1999 John Buswell <johnb@mandrakesoft.com>
- Add symlink for libSDL-1.0.so.0 required by sdlbomber
- Added docs

* Thu Dec 09 1999 Lenny Cartier <lenny@mandrakesoft.com>
- v 1.0.0

* Mon Nov  1 1999 Chmouel Boudjnah <chmouel@mandrakesoft.com>
- First spec file for Mandrake distribution.

# end of file

{'repo_name': 'klaussilveira/qengine', 'stars': '748', 'repo_language': 'C', 'file_name': 'Doxyfile.in', 'mime_type': 'text/plain', 'hash': 8566609502671823378, 'source_dataset': 'data'}