问:
How to create plugins in swift
I found article describing how to create plugin using Swift and Cocoa. It uses NSBundle to load plugin, but that, as far as I know, is not available in pure swift (no Cocoa). Is there way how to achieve same result without using Cocoa?

More info:

In case it's relevant, here is what I want to achieve. I create app in swift that runs on linux server. User can connect to it using their browser. I want to be able to have other people write "plugins" that will implement functionality itself (what user can see and do once they connect), from printing out hello world, through chat programs to games without having to worry about low level stuff provided by my app. Some sort of dll, that my server application loads and runs.

答:
Solution to this is not trivial, but it's not impossible to do either. I prefer to use swift package manager to manage dependencies and Xcode as IDE. This combination is not perfect as it needs a lot of tinkering but there is not any other useable free swift IDE as of now.

You will need to set up two projects, let's call them Plugin (3rd party library) and PluginConsumer (app that uses other people plugins). You will also need to decide on API, for now we will use simple

```<code>TestPluginFunc()
</code>```

Create Plugin.swift file with TestPluginFunc implementation in your Plugin project:

```<code>public func TestPluginFunc() {
    print("Hooray!")
}
</code>```

Set the project to build framework, not executable and build[1]. You will get Plugin.framework file which contains your plugin.

Now switch to your PluginConsumer project

Copy Plugin.framework from your Plugin project somewhere where you can easily find it. To actually load the framework and use it:

```<code>// we need to define how our plugin function looks like
typealias TestPluginFunc = @convention(c) ()->()
// and what is its name
let pluginFuncName = "TestPluginFunc"

func loadPlugin() {
    let pluginName = "Plugin"
    let openRes = dlopen("./\(pluginName).framework/\(pluginName)", RTLD_NOW|RTLD_LOCAL)
    if openRes != nil {
        // this is fragile
        let symbolName = "_TF\(pluginName.utf8.count)\(pluginName)\(initFuncName.utf8.count)\(initFuncName)FT_T_"
        let sym = dlsym(openRes, symbolName)
        if sym != nil {
            // here we load func from framework based on the name we constructed in "symbolName" variable
            let f: TestPluginFunc = unsafeBitCast(sym, to: TestPluginFunc.self)

            // and now all we need to do is execute our plugin function
            f()

        } else {
            print("Error loading \(realPath). Symbol \(symbolName) not found.")
            dlclose(openRes)
        }
    } else {
        print("error opening lib")
    }
}
</code>```

If done correctly, you should see "Hooray!" being printed to your log.

There is a lot of room for improvement, first thing you should do is replace Plugin.framework string with parameter, preferably using some file library (I am using PerfectLib). Another thing to look at is defining plugin API in your PluginConsumer project as a protocol or base class, creating framework out of that, importing that framework in your plugin project and basing your implementation on that protocol/base class. I am trying to figure out exactly how to do that. I will update this post if I mange to do it properly.

[1]: I usually do this by creating Package.swift file and creating xcode project out of it using swift package generate-xcodeproj. If your project doesn't contain main.swift, xcode will create framework instead of executable

Title: How to create plugins in swift

Body:
Solution to this is not trivial, but it's not impossible to do either. I prefer to use swift package manager to manage dependencies and Xcode as IDE. This combination is not perfect as it needs a lot of tinkering but there is not any other useable free swift IDE as of now.

You will need to set up two projects, let's call them Plugin (3rd party library) and PluginConsumer (app that uses other people plugins). You will also need to decide on API, for now we will use simple

TestPluginFunc()

Create Plugin.swift file with TestPluginFunc implementation in your Plugin project:

public func TestPluginFunc() {
    print("Hooray!")
}

Set the project to build framework, not executable and build[1]. You will get Plugin.framework file which contains your plugin.

Now switch to your PluginConsumer project

Copy Plugin.framework from your Plugin project somewhere where you can easily find it. To actually load the framework and use it:

// we need to define how our plugin function looks like
typealias TestPluginFunc = @convention(c) ()->()
// and what is its name
let pluginFuncName = "TestPluginFunc"

func loadPlugin() {
    let pluginName = "Plugin"
    let openRes = dlopen("./\(pluginName).framework/\(pluginName)", RTLD_NOW|RTLD_LOCAL)
    if openRes != nil {
        // this is fragile
        let symbolName = "_TF\(pluginName.utf8.count)\(pluginName)\(initFuncName.utf8.count)\(initFuncName)FT_T_"
        let sym = dlsym(openRes, symbolName)
        if sym != nil {
            // here we load func from framework based on the name we constructed in "symbolName" variable
            let f: TestPluginFunc = unsafeBitCast(sym, to: TestPluginFunc.self)

            // and now all we need to do is execute our plugin function
            f()

        } else {
            print("Error loading \(realPath). Symbol \(symbolName) not found.")
            dlclose(openRes)
        }
    } else {
        print("error opening lib")
    }
}

If done correctly, you should see "Hooray!" being printed to your log.

There is a lot of room for improvement, first thing you should do is replace Plugin.framework string with parameter, preferably using some file library (I am using PerfectLib). Another thing to look at is defining plugin API in your PluginConsumer project as a protocol or base class, creating framework out of that, importing that framework in your plugin project and basing your implementation on that protocol/base class. I am trying to figure out exactly how to do that. I will update this post if I mange to do it properly.

[1]: I usually do this by creating Package.swift file and creating xcode project out of it using swift package generate-xcodeproj. If your project doesn't contain main.swift, xcode will create framework instead of executable


来源: stackexchange

问:
Push new table to heroku without having to reset existing database
I'm at the early stages of learning RoR and working with Heroku.  So i have a fledging app with local and production databases.  I've used pg:push to create the initial production database but I appreciate this requires you to reset the db every time.  I now have a new table in my local db that I wish to push to production, but I don't want to reset and lose the data.

It seems I could create a back up from production and then reload that.  Or could if run pg:pull to get the data into my local db, and then run a pg:push so that when I add the new table I'm also reloading my existing data.

All of this seems a little long winded.  From some knowledge of php and mysql, I would have simply ran an SQL query to add the new table, is there not a similar way?

答:
I think what you are searching for is migrations:

```<code>class CreateProducts < ActiveRecord::Migration[5.0]
  def change
    create_table :products do |t|
      t.string :name
      t.text :description

      t.timestamps
    end
  end
end
</code>```

You can create migrations on your local development environment and then run them on the production server once you are satisfied. You can read about migrations more here:

Active Record Migrations

ContentLicense: CC BY-SA 3.0

Body:
I think what you are searching for is migrations:

class CreateProducts < ActiveRecord::Migration[5.0]
  def change
    create_table :products do |t|
      t.string :name
      t.text :description

      t.timestamps
    end
  end
end

You can create migrations on your local development environment and then run them on the production server once you are satisfied. You can read about migrations more here:

Active Record Migrations


问:
An issue with limiting a while loop
My table auto increments the value KundeID and on the form that confirms the input of data I want to show the person inputting it what their ID is when they're done. I'm using this code currently and while I get the correct ID, it loops forever, but I only want it to tell the ID once. What can I do to fix this?

```<code>$sq="SELECT MAX(KundeID) AS max_ID FROM kunder";
while   ($result=mysqli_query($kobling,$sq)) {
    $row=mysqli_fetch_array($result);
    echo "Ditt kundenummer er ".$row["max_ID"]."<br>";
}
</code>```

答:
Your solution is:

```<code>$sq="SELECT MAX(KundeID) AS max_ID FROM kunder";
$result = mysqli_query($kobling,$sq);
$row = mysqli_fetch_array($result);
echo "Ditt kundenummer er " . $row["max_ID"] . "<br>";
</code>```

You don't need to use while here.

Title: An issue with limiting a while loop

Body:
My table auto increments the value KundeID and on the form that confirms the input of data I want to show the person inputting it what their ID is when they're done. I'm using this code currently and while I get the correct ID, it loops forever, but I only want it to tell the ID once. What can I do to fix this?

$sq="SELECT MAX(KundeID) AS max_ID FROM kunder";
while   ($result=mysqli_query($kobling,$sq)) {
    $row=mysqli_fetch_array($result);
    echo "Ditt kundenummer er ".$row["max_ID"]."
";
}

Body:
Your solution is:

$sq="SELECT MAX(KundeID) AS max_ID FROM kunder";
$result = mysqli_query($kobling,$sq);
$row = mysqli_fetch_array($result);
echo "Ditt kundenummer er " . $row["max_ID"] . "<br>";

You don't need to use while here.


问:
Why is it possible to declare a variable without an initial value?
I'm reading Gilles Dowek's Principles of Programming Languanges:

He says that it's also possible to declare a variable without giving it an initial value and also that we must be careful not to use a variable which has been declared without an initial value and that has not been assigned a value. This produces an error.

Note: The book's author mentions the possibility of declaring variables without an initial value on Java.

So, why is this declaration of variables valid? When am I going to use it?

答:
Ok here is an example.  I am currently setting global values that are set to persistent on a PDF forums.  For this application I want to uses these values as data storage much like a text field.  Not the best method but it works for this example.  Rather than populated my forum with hundreds of hidden text fields I can set the values as a persistent global variables.

If my initial deceleration is set to 0 or "" as a value of the variable than it will not keep data between sessions.  The initialization of the forum will reset the value to nothing.  Much like Scrips, forums operated in order.  It will recognize all of the scripts in the document first, before assigning values to carry over variables. Thus it is necessary to declare the variable without a value, so that the initialization does not replace the values.

In general it is also good house keeping to declare all of your variables at the top.  It is possible to declare them as you go, but I have found that when a new element is added to a Script I have to move lines up and down to keep my code clean.  If the variable is declared when it is used, than it also becomes very easy to use a variable before it is declared, which does not work.

Additionally

It is efficient to assign value when declaring, But not generic place holder values.  In most scripts int is not as simple as saying int x = 5;  More often we call on data such as this.getField("TextBox3").value; or some other line code.  By assigning a generic value such as "" or 0 or true your function may work even if you failed to properly utilize a value.  By not assigning a value, if you fail to utilize your variable, than your function will fail allowing you to narrow the possibilities when problem solving.  If int x; is still NaN by the time you utilize x than your data collection and validations are likely the source of the problem.

In general declare all values at the top and avoid setting generic values unless you have to.  If you are going to define the values of x later than don't set it to int x = 0;.


问:
Connection timeout on query on large table
I have a problem with a script timing out while fetching data form a query on large table.

The table have 9,521,457 rows.

The query I'm trying to preform is:

```<code>SELECT *
FROM `dialhistory`
WHERE `customerId` IN (22606536, 22707251, 41598836);
</code>```

This query runs without problems on HeidiSQL and take about 171 seconds and returns 434 rows.

But when I run my C# script dose it timeout after 161 rows.

```<code>16:54:55: Row 1
...
16:54:55: Row 161
16:55:32: Error -> Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
</code>```

Here is the code

```<code>public MySqlDatabase(string server, string database, string username, string password)
{
    ConnectionString = "SERVER=" + server + ";DATABASE=" + database + ";UID=" + username + ";PASSWORD=" + password + ";";

}

public IQueryable<DailHistory> GetHistory(IList<int> customerIds)
{
    IList<DailHistory> list = new List<DailHistory>();
    var connection = new MySqlConnection(ConnectionString);
    connection.Open();
    var command = connection.CreateCommand();
    command.CommandText = "SELECT * FROM `dialhistory` WHERE `customerId` in ("+string.Join(",", customerIds.ToArray())+")";
    var reader = command.ExecuteReader();
    int i = 1;
    while (reader.Read())
    {
        Console.WriteLine(DateTime.Now.ToLongTimeString() + ": Row " + i);
        i++;
        try
        {
            var d = new DailHistory();
            d.CustomerId = int.Parse((string) reader["customerId"]);
            d.Agent = ParseNullAbleString(reader["agent"].ToString());
            d.CallBackReason = ParseNullAbleString(reader["callBackReason"].ToString());
            d.CallState = ParseCallSate(reader["callState"].ToString());
            d.ContactResponse = ParseNullAbleString(reader["contactResponse"].ToString());
            d.DailTime = new DailTime(reader["dialStart"].ToString(), reader["dialEnd"].ToString());
            d.HistoryIndex = int.Parse(reader["historyIndex"].ToString());
            d.Note = ParseNullAbleString(reader["note"].ToString());
            d.OldDialNo = ParseNullAbleInt(reader["oldDialNo"].ToString());
            d.ProjectJob = ParseNullAbleString(reader["projectJob"].ToString());
            list.Add(d);
        }
        catch(Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
    reader.Close();
    return list.AsQueryable();
}
</code>```

答:
Set the CommandTimeout on the command object</p>

```<code>var command = connection.CreateCommand();
command.CommandTimeout = 0;
//zero specifies never timeout.
//Any number greater than zero is the number of seconds before
//the command will time out.
</code>```

Body:
I have a problem with a script timing out while fetching data form a query on large table.

The table have 9,521,457 rows.

The query I'm trying to preform is:

SELECT *
FROM `dialhistory`
WHERE `customerId` IN (22606536, 22707251, 41598836);

This query runs without problems on HeidiSQL and take about 171 seconds and returns 434 rows.

But when I run my C# script dose it timeout after 161 rows.

16:54:55: Row 1
...
16:54:55: Row 161
16:55:32: Error -> Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.

Here is the code

public MySqlDatabase(string server, string database, string username, string password)
{
    ConnectionString = "SERVER=" + server + ";DATABASE=" + database + ";UID=" + username + ";PASSWORD=" + password + ";";

}

public IQueryable<DailHistory> GetHistory(IList<int> customerIds)
{
    IList<DailHistory> list = new List<DailHistory>();
    var connection = new MySqlConnection(ConnectionString);
    connection.Open();
    var command = connection.CreateCommand();
    command.CommandText = "SELECT * FROM `dialhistory` WHERE `customerId` in ("+string.Join(",", customerIds.ToArray())+")";
    var reader = command.ExecuteReader();
    int i = 1;
    while (reader.Read())
    {
        Console.WriteLine(DateTime.Now.ToLongTimeString() + ": Row " + i);
        i++;
        try
        {
            var d = new DailHistory();
            d.CustomerId = int.Parse((string) reader["customerId"]);
            d.Agent = ParseNullAbleString(reader["agent"].ToString());
            d.CallBackReason = ParseNullAbleString(reader["callBackReason"].ToString());
            d.CallState = ParseCallSate(reader["callState"].ToString());
            d.ContactResponse = ParseNullAbleString(reader["contactResponse"].ToString());
            d.DailTime = new DailTime(reader["dialStart"].ToString(), reader["dialEnd"].ToString());
            d.HistoryIndex = int.Parse(reader["historyIndex"].ToString());
            d.Note = ParseNullAbleString(reader["note"].ToString());
            d.OldDialNo = ParseNullAbleInt(reader["oldDialNo"].ToString());
            d.ProjectJob = ParseNullAbleString(reader["projectJob"].ToString());
            list.Add(d);
        }
        catch(Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
    reader.Close();
    return list.AsQueryable();
}

Body:
Set the CommandTimeout on the command object

var command = connection.CreateCommand();
command.CommandTimeout = 0;
//zero specifies never timeout.
//Any number greater than zero is the number of seconds before
//the command will time out.

ContentLicense: CC BY-SA 2.5


问:
Directive not refreshing after scope change
I have a custom directive to apply background-image on elements and I want it to refresh UI on scope changes.

After reading how to do it I added $watch to observe scope changes, but I was using the directive inside a ng-repeat so I cant pass a scope var to it.

When item.Url changes, the directive does not refresh background-url.

My directive:

```<code>.directive('bgImage', function () {
        function applyBackgroundImage(element, url) {
            if (!element || !url) { return; }
            element.css({ 'background-image': ['url(', url, ')'].join('') });
        };

        return {
            restrict: 'A',
            link: function ($scope, element, attrs) {
                if (!attrs.bgImage) { return; }

                if ($scope.hasOwnProperty(attrs.bgImage)) {
                    $scope.$watch(attrs.bgImage,
                        function(newValue, oldValue) {
                            if (newValue == oldValue) { return; }
                            if (!newValue) { return; }

                            applyBackgroundImage(element, newValue);
                        });
                } else {
                    applyBackgroundImage(element, attrs.bgImage);
                }
            }
        };
    })
</code>```

Usage:

```<code><div class="item-box" ng-repeat="item in items">
    <div bg-image="{{item.PictureUrl}}">
    </div>
</div>
</code>```

答:
Probably this will help.</p>

```<code>$scope.$watch(function() {
    return attrs.bgImage
    },
    function(newValue, oldValue) {
        if (newValue == oldValue) { return; }
        if (!newValue) { return; }
        applyBackgroundImage(element, newValue);
    });
</code>```

Body:
I have a custom directive to apply background-image on elements and I want it to refresh UI on scope changes.

After reading how to do it I added $watch to observe scope changes, but I was using the directive inside a ng-repeat so I cant pass a scope var to it.

When item.Url changes, the directive does not refresh background-url.

My directive:

.directive('bgImage', function () {
        function applyBackgroundImage(element, url) {
            if (!element || !url) { return; }
            element.css({ 'background-image': ['url(', url, ')'].join('') });
        };

        return {
            restrict: 'A',
            link: function ($scope, element, attrs) {
                if (!attrs.bgImage) { return; }

                if ($scope.hasOwnProperty(attrs.bgImage)) {
                    $scope.$watch(attrs.bgImage,
                        function(newValue, oldValue) {
                            if (newValue == oldValue) { return; }
                            if (!newValue) { return; }

                            applyBackgroundImage(element, newValue);
                        });
                } else {
                    applyBackgroundImage(element, attrs.bgImage);
                }
            }
        };
    })

Usage:

Body:
Probably this will help.

$scope.$watch(function() {
    return attrs.bgImage
    },
    function(newValue, oldValue) {
        if (newValue == oldValue) { return; }
        if (!newValue) { return; }
        applyBackgroundImage(element, newValue);
    });


问:
Find how many times team has won and loss the matches?
Find how many times team has won and loss the matches ?

 Find how many times team has won and loss the matches ?
My Table Structure

TeamA | TeamB | Won
A     | D     | D
B     | A     | A
A     | D     | A

Result should be like below

TeamName | Won | Lost
A        | 2   | 1
B        | 0   | 1
D        | 1   | 1```

答:
Conditional aggregation in combination with a union to normalize the data.</p>

```<code>SELECT A.Team as TeamName,
 SUM(CASE WHEN A.TeamA=A.Won then 1 else 0 end) as Won
 SUM(CASE WHEN A.TeamA<>A.Won then 1 else 0 end) as Lost
FROM (SELECT TeamA as Team, Won
      FROM TABLE
      UNION ALL
      SELECT TeamB as Team, Won
      FROM Table
     ) A
GROUP BY A.Team
</code>```

Body:
Conditional aggregation in combination with a union to normalize the data.

SELECT A.Team as TeamName,
 SUM(CASE WHEN A.TeamA=A.Won then 1 else 0 end) as Won
 SUM(CASE WHEN A.TeamA<>A.Won then 1 else 0 end) as Lost
FROM (SELECT TeamA as Team, Won
      FROM TABLE
      UNION ALL
      SELECT TeamB as Team, Won
      FROM Table
     ) A
GROUP BY A.Team


问:
Is there a way of fixing a maximum value for an element in an array?
```<code>list = [5, 10, 20, 40, 50, 42, 35, 26, 18]
</code>```

So in this example, I don't want an element to exceed the value 40 and if it does, I want the element to have a value of 40, e.g. the element with the value 50 will become 40.

答:
If you're using Ruby 2.4 or newer, you can make use of Comparable#clamp:

```<code>list.map { |n| n.clamp(0, 40) }
# => [5, 10, 20, 40, 40, 40, 35, 26, 18]
</code>```

Note that this will also fix the minimum value to 0. This may or may not be useful in your case, and only applies if all items are expected to be non-negative numbers.

Body:
list = [5, 10, 20, 40, 50, 42, 35, 26, 18]

So in this example, I don't want an element to exceed the value 40 and if it does, I want the element to have a value of 40, e.g. the element with the value 50 will become 40.

Body:
If you're using Ruby 2.4 or newer, you can make use of Comparable#clamp:

list.map { |n| n.clamp(0, 40) }
# => [5, 10, 20, 40, 40, 40, 35, 26, 18]

Note that this will also fix the minimum value to 0. This may or may not be useful in your case, and only applies if all items are expected to be non-negative numbers.


问:
react native google signin return status code: 12501
I need to have google sign in my react native app. So i google it a lot an i find react-native-google-signin that seems awesome, but im stuck with one error.

I follow all the steps in the READ.me and Androide Guide

i have the following code:

```<code> componentDidMount() {

     GoogleSignin.hasPlayServices({autoResolve: true}).then(() => {
        // play services are available. can now configure library
        GoogleSignin.configure({
            scopes: [
                'email', 'profile', 'https://www.googleapis.com/auth/plus.profile.emails.read', 'https://www.googleapis.com/auth/plus.login'
            ],
            webClientId: 'web-clientid from the console developper',
            offlineAccess: true
        }).then(() => {
            // you can now call currentUserAsync()
            GoogleSignin.currentUserAsync().then((user) => {
                console.log('USER', user);
            }).done();
        });
     });
}

signIn() {
    GoogleSignin.signIn()
        .then((user) => {
            console.log(user);
        })
        .catch((err) => {
            console.log('WRONG SIGNIN', err);
        })
        .done();
}

 render() {
    return (
        <Image source={BACKGROUND} style={styles.container}>
            <Image source={ICON}></Image>
            <Text style={styles.welcome}>
                APP TEST
            </Text>

            <GoogleSigninButton
                style={{width: 230, height: 48}}
                size={GoogleSigninButton.Size.Standard}
                color={GoogleSigninButton.Color.Light}
                onPress={this.signIn}
            />
        </Image>
    );
</code>```

When i click in the sign in button, pops up a window for i choose which  google account i want to use. but when i choose the account, i have the follow error : WRONG SIGNIN Error: unknown status code: 12501(…)

So i look in the faqs that hare in the bottom of Androide Guide
and confirm that my certificate_hash in  android/app/google-services.json are the same.
I also check that the aplication id in my app/build.graddle are the same that i enter in the google cloud.

I think that the problem are with the WebclientId that i pass in my scope, i'm passin the web type one, but already try the two clients id that are in  the oauth 2

I search in githubs issues and i find someone told to download the google-services again. i do that, but the file is equal to the file i previous download.
pretty sure, i'm  missing something, but dont no what.
Can anyone helping me?

I open an issue in the github, but i dont get much action.

Thanks in advance

答:
Might this will help you, try this:

Check your google-services.json cirtificate_hash code.
 match it with your Android Signing Certificate SHA-1.
 use this link to reach their https://developers.google.com/mobile

I have tested it on emulator but emulator don't have google play services so I tested it on my android mobile phone.

Use the fallowing code

```<code>import {GoogleSignin, GoogleSigninButton} from 'react-native-google-signin';
</code>```

then

```<code>componentDidMount() {
    GoogleSignin.configure({
        scopes: [
            'email', 'profile', 'https://www.googleapis.com/auth/plus.profile.emails.read', 'https://www.googleapis.com/auth/plus.login'
        ],
        webClientId: 'use here oauth_client[{client_id}]',//refer this given below example:
        offlineAccess: true
    }).then(() => {
        // you can now call currentUserAsync()
        GoogleSignin.currentUserAsync().then((user) => {
             //user = GoogleSignin.currentUser();
            console.log('USER', user);
            this.setState({user: user});
        }).done();
    });
}

_signIn() {
    GoogleSignin.signIn()
        .then((user) => {
            console.log('this1' + JSON.stringify(user));
        })
        .catch((err) => {
            console.log('WRONG SIGNIN', err);
        })
        .done();
}

_signOut(){
    GoogleSignin.signOut()
        .then(() => {
            console.log('out');
        })
        .catch((err) => {

        });
}

render() {

    return (
        <View style={styles.container}>
            <Text style={styles.welcome}>
                Welcome to React Native!
            </Text>
            <Text style={styles.instructions}>
                To get started, edit index.android.js
            </Text>
            <Text style={styles.instructions}>
                Double tap R on your keyboard to reload,{'\n'}
                Shake or press menu button for dev menu
            </Text>
            <GoogleSigninButton
                style={{width: 48, height: 48}}
                size={GoogleSigninButton.Size.Icon}
                color={GoogleSigninButton.Color.Dark}
                onPress={this._signIn.bind(this)}/>
            <TouchableHighlight>
                <Text onPress={this._signOut.bind(this)}>
                    signout
                </Text>
            </TouchableHighlight>
        </View>
    );
}
</code>```

:example   -->   webClientId: '1059..........googleusercontent.com' Their are two client Id  in google-services.json  oauth_client[] use first one. You can compare it with credential link given below https://console.developers.google.com/apis/credentials here... Name:Web client Type:web application client Id:1059........googleusercontent.com

This solve my problem.
Have a great day.
Thank You.:)

Body:
I need to have google sign in my react native app. So i google it a lot an i find react-native-google-signin that seems awesome, but im stuck with one error.

I follow all the steps in the READ.me and Androide Guide

i have the following code:

 componentDidMount() {

     GoogleSignin.hasPlayServices({autoResolve: true}).then(() => {
        // play services are available. can now configure library
        GoogleSignin.configure({
            scopes: [
                'email', 'profile', 'https://www.googleapis.com/auth/plus.profile.emails.read', 'https://www.googleapis.com/auth/plus.login'
            ],
            webClientId: 'web-clientid from the console developper',
            offlineAccess: true
        }).then(() => {
            // you can now call currentUserAsync()
            GoogleSignin.currentUserAsync().then((user) => {
                console.log('USER', user);
            }).done();
        });
     });
}

signIn() {
    GoogleSignin.signIn()
        .then((user) => {
            console.log(user);
        })
        .catch((err) => {
            console.log('WRONG SIGNIN', err);
        })
        .done();
}

 render() {
    return (
        <Image source={BACKGROUND} style={styles.container}>
            <Image source={ICON}></Image>
            <Text style={styles.welcome}>
                APP TEST
            </Text>

            <GoogleSigninButton
                style={{width: 230, height: 48}}
                size={GoogleSigninButton.Size.Standard}
                color={GoogleSigninButton.Color.Light}
                onPress={this.signIn}
            />
        </Image>
    );

When i click in the sign in button, pops up a window for i choose which  google account i want to use. but when i choose the account, i have the follow error : WRONG SIGNIN Error: unknown status code: 12501(…)

So i look in the faqs that hare in the bottom of Androide Guide
and confirm that my certificate_hash in  android/app/google-services.json are the same.
I also check that the aplication id in my app/build.graddle are the same that i enter in the google cloud.

I think that the problem are with the WebclientId that i pass in my scope, i'm passin the web type one, but already try the two clients id that are in  the oauth 2

I search in githubs issues and i find someone told to download the google-services again. i do that, but the file is equal to the file i previous download.
pretty sure, i'm  missing something, but dont no what.
Can anyone helping me?

I open an issue in the github, but i dont get much action.

Thanks in advance

Body:
Might this will help you, try this:

Check your google-services.json cirtificate_hash code.
 match it with your Android Signing Certificate SHA-1.
 use this link to reach their https://developers.google.com/mobile

I have tested it on emulator but emulator don't have google play services so I tested it on my android mobile phone.

Use the fallowing code

import {GoogleSignin, GoogleSigninButton} from 'react-native-google-signin';

then

componentDidMount() {
    GoogleSignin.configure({
        scopes: [
            'email', 'profile', 'https://www.googleapis.com/auth/plus.profile.emails.read', 'https://www.googleapis.com/auth/plus.login'
        ],
        webClientId: 'use here oauth_client[{client_id}]',//refer this given below example:
        offlineAccess: true
    }).then(() => {
        // you can now call currentUserAsync()
        GoogleSignin.currentUserAsync().then((user) => {
             //user = GoogleSignin.currentUser();
            console.log('USER', user);
            this.setState({user: user});
        }).done();
    });
}

_signIn() {
    GoogleSignin.signIn()
        .then((user) => {
            console.log('this1' + JSON.stringify(user));
        })
        .catch((err) => {
            console.log('WRONG SIGNIN', err);
        })
        .done();
}

_signOut(){
    GoogleSignin.signOut()
        .then(() => {
            console.log('out');
        })
        .catch((err) => {

        });
}

render() {

    return (
        <View style={styles.container}>
            <Text style={styles.welcome}>
                Welcome to React Native!
            </Text>
            <Text style={styles.instructions}>
                To get started, edit index.android.js
            </Text>
            <Text style={styles.instructions}>
                Double tap R on your keyboard to reload,{'\n'}
                Shake or press menu button for dev menu
            </Text>
            <GoogleSigninButton
                style={{width: 48, height: 48}}
                size={GoogleSigninButton.Size.Icon}
                color={GoogleSigninButton.Color.Dark}
                onPress={this._signIn.bind(this)}/>
            <TouchableHighlight>
                <Text onPress={this._signOut.bind(this)}>
                    signout
                </Text>
            </TouchableHighlight>
        </View>
    );
}

:example   -->   webClientId: '1059..........googleusercontent.com' Their are two client Id  in google-services.json  oauth_client[] use first one. You can compare it with credential link given below https://console.developers.google.com/apis/credentials here... Name:Web client Type:web application client Id:1059........googleusercontent.com

This solve my problem.
Have a great day.
Thank You.:)


问:
How to use fscanf to reads any character into a string until a tab is reached?
How to use fscanf to reads any character into a string until a tab is reached?

My data file have only 1 row:

```<code>123'\t'(Tab)345'\t'Le Duc Huy'\t'567
</code>```

and i use fscanf like this:

```<code>fscanf(fin,"%d %d %d %[^\t]%s %d",&m,&n,&k,s,&q);
</code>```

it return q with wrong value. Anybody can tell me what made it failed?

答:
Instead of fscanf I would just use fgetc (though my syntax may be off a bit):

```<code>int c;
string s = "";
for (;;)
{
    c = fgetc(somefile);
    if (c == '\t' || c == EOF) break;
    s += c;
    // ...
}
</code>```

Body:
How to use fscanf to reads any character into a string until a tab is reached?

My data file have only 1 row:

123'\t'(Tab)345'\t'Le Duc Huy'\t'567

and i use fscanf like this:

fscanf(fin,"%d %d %d %[^\t]%s %d",&m,&n,&k,s,&q);

it return q with wrong value. Anybody can tell me what made it failed?

Body:
Instead of fscanf I would just use fgetc (though my syntax may be off a bit):

int c;
string s = "";
for (;;)
{
    c = fgetc(somefile);
    if (c == '\t' || c == EOF) break;
    s += c;
    // ...
}


问:
Delete query working in PgAdmin 3 but not working on Java JDBC
I am trying to delete a list of times saved in a database where the date (end_time - timestamp) is bigger that my reference day for a specific employee (employeeId - integer).
The query works perfectly on pgAdmin III. However I cannot make it work in JDBC.
It works, but it deletes everything from that particular employee and not just the dates I want. I looks like it ignores the date in the Where clause. Also, I do not get any exception.
The variable nextDayTimestamp comes out like: '2017-03-31 12:00:00.0'
Could anybody please help?

```<code> public void deleteBigListOfPeriodOfWorkFutureOnly(int employeeId, LocalDate referenceDate) {
        Connection myConn = null;
        PreparedStatement myStmt = null;

        try {

            myConn = dataSource.getConnection();

            LocalDate nextDay = referenceDate.plusDays(1);
            Timestamp nextDayTimestamp = Timestamp.valueOf(LocalDateTime.of(nextDay, LocalTime.NOON));
            String sql = "delete from working_time where working_time.end_time > ? and employee_id = ?";

            myStmt = myConn.prepareStatement(sql);

            myStmt.setTimestamp(1, nextDayTimestamp);
            myStmt.setInt(2, employeeId);

            myStmt.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {

            CloseConnection.close(myConn, myStmt, null);
        }

    }
}
</code>```

答:
I found out the answer! I made a mistake calling "delete from employee where employeeId=?" from another method that I was not taking notice. It was at a higher level. That is why it was deleting every employee.
I just removed that method and THE CODE MENTIONED IN MY QUESTION ABOVE DO WORKS!
Thanks a lot for the effort and time trying to help me! THANK YOU!</p>

Body:
I am trying to delete a list of times saved in a database where the date (end_time - timestamp) is bigger that my reference day for a specific employee (employeeId - integer).
The query works perfectly on pgAdmin III. However I cannot make it work in JDBC.
It works, but it deletes everything from that particular employee and not just the dates I want. I looks like it ignores the date in the Where clause. Also, I do not get any exception.
The variable nextDayTimestamp comes out like: '2017-03-31 12:00:00.0'
Could anybody please help?

 public void deleteBigListOfPeriodOfWorkFutureOnly(int employeeId, LocalDate referenceDate) {
        Connection myConn = null;
        PreparedStatement myStmt = null;

        try {

            myConn = dataSource.getConnection();

            LocalDate nextDay = referenceDate.plusDays(1);
            Timestamp nextDayTimestamp = Timestamp.valueOf(LocalDateTime.of(nextDay, LocalTime.NOON));
            String sql = "delete from working_time where working_time.end_time > ? and employee_id = ?";

            myStmt = myConn.prepareStatement(sql);

            myStmt.setTimestamp(1, nextDayTimestamp);
            myStmt.setInt(2, employeeId);

            myStmt.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {

            CloseConnection.close(myConn, myStmt, null);
        }

    }
}


问:
SSH -X "Warning: untrusted X11 forwarding setup failed: xauth key data not generated"
Hey I'm having an issue getting ssh X forwarding to work. The setup is I'm sshing into my ubuntu VM off OSX Yosemite host machine.

I already installed xQuartz on OSX, xauth on ubuntu, and I believe I've have all the correct options set in ssh_config files.

I get the

```<code>Warning: untrusted X11 forwarding setup failed: xauth key data not generated
X11 forwarding request failed on channel 0
</code>```

message when opening a connection with ssh -X, and when I tried to run an X application:

```<code>xterm: Xt error: Can't open display:
xterm: DISPLAY is not set
</code>```

I have the identical setup on my other machine except running Mavericks and it works fine, is there something specific to Yosemite specific I have to worry about?

答: I already had the latest XQuartz 2.7.11 installed, but I think I've also updated the OS a few times since then.  I reinstalled XQuartz 2.7.11, and now it is working fine.</p>

Body:
Hey I'm having an issue getting ssh X forwarding to work. The setup is I'm sshing into my ubuntu VM off OSX Yosemite host machine.

I already installed xQuartz on OSX, xauth on ubuntu, and I believe I've have all the correct options set in ssh_config files.

I get the

Warning: untrusted X11 forwarding setup failed: xauth key data not generated
X11 forwarding request failed on channel 0

message when opening a connection with ssh -X, and when I tried to run an X application:

xterm: Xt error: Can't open display:
xterm: DISPLAY is not set

I have the identical setup on my other machine except running Mavericks and it works fine, is there something specific to Yosemite specific I have to worry about?


问:
Type intersection in typescript
I am trying to understand Type Relations in type script.
What is the intersection of the types denoted by the following two expressions:

```<code>{a:number}[] & {b:string}[]
</code>```

Is that

```<code>{a:number,b:string}[]
</code>```

?
Thanks,

答:
Yeah, the documentation is not crystal clear as to the operator precedence in the type definition. But it is fairly easy to test:

```<code>type Z = { a: number }[] & { b: string }[];

let a: Z = [];
a = [{ a: 1, b: "q" }]; // Cannot assign because `b` does not exist in `{ a: number }`.
a = [{ a: 1 }]; // Cannot assign because `a` does not exist in `{ b: string }`.
a = [{b: "foo"}]; // Cannot assign because `b` does not exist in `{ a: number }`.
a = []; // Ok.

let x: { a: number, b: string }[] = a; // Cannot assign either.
</code>```

The above shows that the hypothesis that it resolves to {a:number,b:string}[] is not correct. I had initially hypothesized that it would resolve to ({ a: number } | { b: string })[], but that's not correct either.

The intersection means "an array of elements where each element satisfies the type { a: number } and at the same time satisfies the type { b: string }. Since, a is not in the second type and b is not in the first, no element can satisfy the intersection. So you can only assign empty arrays to variables that are typed with the intersection.

To get the result you were hypothesizing, you'd need a different intersection:

```<code>type Z2 = { a: number, b?: string }[] & { a?: number, b: string }[];

let a2: Z2 = [];
a2 = [{ a: 1, b: "q" }];
</code>```

This works as you expect because the first type in the intersection accepts elements that optionally have b and the 2nd type accepts elements that optionally have a.

Title: Type intersection in typescript

Body:
I am trying to understand Type Relations in type script.
What is the intersection of the types denoted by the following two expressions:

{a:number}[] & {b:string}[]

Is that

{a:number,b:string}[]

?
Thanks,

Body:
Yeah, the documentation is not crystal clear as to the operator precedence in the type definition. But it is fairly easy to test:

type Z = { a: number }[] & { b: string }[];

let a: Z = [];
a = [{ a: 1, b: "q" }]; // Cannot assign because `b` does not exist in `{ a: number }`.
a = [{ a: 1 }]; // Cannot assign because `a` does not exist in `{ b: string }`.
a = [{b: "foo"}]; // Cannot assign because `b` does not exist in `{ a: number }`.
a = []; // Ok.

let x: { a: number, b: string }[] = a; // Cannot assign either.

The above shows that the hypothesis that it resolves to {a:number,b:string}[] is not correct. I had initially hypothesized that it would resolve to ({ a: number } | { b: string })[], but that's not correct either.

The intersection means "an array of elements where each element satisfies the type { a: number } and at the same time satisfies the type { b: string }. Since, a is not in the second type and b is not in the first, no element can satisfy the intersection. So you can only assign empty arrays to variables that are typed with the intersection.

To get the result you were hypothesizing, you'd need a different intersection:

type Z2 = { a: number, b?: string }[] & { a?: number, b: string }[];

let a2: Z2 = [];
a2 = [{ a: 1, b: "q" }];

This works as you expect because the first type in the intersection accepts elements that optionally have b and the 2nd type accepts elements that optionally have a.


问:
Toolbar haven't the full size
Hey Guys I want to make a Custom Toolbar. I tried so many things but nothing works.... So I have this in my manifest.xml:

```<code><application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true">
    <activity android:name=".HomeActivity"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar">
        <!--android:theme="@style/HomeActionBar">-->
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</code>```

And here my activity_home.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_home"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.iiiii.iiiii.HomeActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/my_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="enterAlways|scroll" />

</android.support.design.widget.CoordinatorLayout>```

But look! I didn't get the full size of the ActionBar:

答:
Move paddings to inner layout</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_home"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.iiiii.iiiii.HomeActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/my_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="enterAlways|scroll" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
    />

</android.support.design.widget.CoordinatorLayout>
</code>```

Title: Toolbar haven't the full size

Body:
Hey Guys I want to make a Custom Toolbar. I tried so many things but nothing works.... So I have this in my manifest.xml:

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true">
    <activity android:name=".HomeActivity"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar">

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

And here my activity_home.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_home"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.iiiii.iiiii.HomeActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/my_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="enterAlways|scroll" />

</android.support.design.widget.CoordinatorLayout>

But look! I didn't get the full size of the ActionBar:

Body:
Move paddings to inner layout

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_home"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.iiiii.iiiii.HomeActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/my_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="enterAlways|scroll" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
    />

</android.support.design.widget.CoordinatorLayout>


问:
what is better , WITH statement or left join 3 tables?
Plz tell me what is better between 2 query in mssql ?

```<code>;with ab as (select a.*,b.CategoryName from Products a
left join Categories b on a.CategoryID = b.CategoryID where b.CategoryID = 2)
select * from ab left join Suppliers c on ab.SupplierID = c.SupplierID
</code>```

or

```<code>select * from Products a left join Categories b on a.CategoryID = b.CategoryID
left join Suppliers c on a.SupplierID = c.SupplierID
where b.CategoryID = 2
</code>```

答:
are the same, WITH only help to make the code more readable.

You can test it  with EXPLAIN QUERY How do I obtain a Query Execution Plan?

Body:
Plz tell me what is better between 2 query in mssql ?

;with ab as (select a.*,b.CategoryName from Products a
left join Categories b on a.CategoryID = b.CategoryID where b.CategoryID = 2)
select * from ab left join Suppliers c on ab.SupplierID = c.SupplierID

or

select * from Products a left join Categories b on a.CategoryID = b.CategoryID
left join Suppliers c on a.SupplierID = c.SupplierID
where b.CategoryID = 2


问:
Get the value of the lowest array key
I have an array which returns this:

```<code>    Array (
            [122] => value
            [43] => value1
            [654645] => value2
            [34634] => value3
            [3] => value4  // I want this
            [550] => value5
    )
</code>```

How can I return value4 from the lowest key [3], I have read http://php.net/manual/en/array.sorting.php and attempted some of the sort by key examples with no luck.

答:
With one-liner:

```<code>echo $array[min(array_keys($array))];
</code>```

Explanation:

array_keys($array) gets keys of your source array as new array, ie. [122, 43, 654645, /*etc*/]

min() gets the lowest value of this array - 3

passing lowest value 3 as index will give your the value of a source array

Title: Get the value of the lowest array key

Body:
I have an array which returns this:

    Array (
            [122] => value
            [43] => value1
            [654645] => value2
            [34634] => value3
            [3] => value4  // I want this
            [550] => value5
    )

How can I return value4 from the lowest key [3], I have read http://php.net/manual/en/array.sorting.php and attempted some of the sort by key examples with no luck.

Body:
With one-liner:

echo $array[min(array_keys($array))];

Explanation:

array_keys($array) gets keys of your source array as new array, ie. [122, 43, 654645, /*etc*/]

min() gets the lowest value of this array - 3

passing lowest value 3 as index will give your the value of a source array


问:
How to make data inside a particular item show while using ng-repeat in angularjs?
I'm trying to make a quiz application with angular js.
When a user selects the correct answer i want to show an icon inside that item.
Problem is that icon is beign applied to every item in the list.
How can i fix this.?

here's the code

```<code>   <md-radio-group ng-model="test.selected" ng-change="test.onChange(test.selected)">
   <md-radio-button ng-repeat="item in test.items" value="{{item}}" class="md-accent" ng-click="test.validate($index)">
   {{item}}
   <md-icon class="material-icons md-secondary right" ng-show="test.isCorrect">done</md-icon>
   <md-icon class="material-icons md-secondary wrong" ng-show="test.isNotCorrect">clear</md-icon>
   </md-radio-button>
   </md-radio-group>
</code>```

Here's a plunker demo plunkr

答:
A quick way could be to add the following styles:

```<code>md-icon {
  display: none !important;
}

.md-checked md-icon {
  display: inline-block !important;
}
</code>```

They ensure that an icon is only shown under md-checked element.

Body:
I'm trying to make a quiz application with angular js.
When a user selects the correct answer i want to show an icon inside that item.
Problem is that icon is beign applied to every item in the list.
How can i fix this.?

here's the code

   <md-radio-group ng-model="test.selected" ng-change="test.onChange(test.selected)">
   <md-radio-button ng-repeat="item in test.items" value="{{item}}" class="md-accent" ng-click="test.validate($index)">
   {{item}}
   <md-icon class="material-icons md-secondary right" ng-show="test.isCorrect">done</md-icon>
   <md-icon class="material-icons md-secondary wrong" ng-show="test.isNotCorrect">clear</md-icon>
   </md-radio-button>
   </md-radio-group>

Here's a plunker demo plunkr

Body:
A quick way could be to add the following styles:

md-icon {
  display: none !important;
}

.md-checked md-icon {
  display: inline-block !important;
}

They ensure that an icon is only shown under md-checked element.


问:
Ocaml List: Implement append and map functions
I'm currently trying to extend a friend's OCaml program. It's a huge collection of functions needed for some data analysis.. Since I'm not really an OCaml crack I'm currently stuck on a (for me) strange List implementation:

```<code>type 'a cell = Nil
    | Cons of ('a * 'a llist)
and 'a llist = (unit -> 'a cell);;
</code>```

I've figured out that this implements some sort of "lazy" list, but I have absolutely no idea how it really works. I need to implement an Append and a Map Function based on the above type. Has anybody got an idea how to do that?

Any help would really be appreciated!

答: Yes, the lists can be infinite.  The code given in the other answers will append to the end of an infinite list, but there's no program you can write than can observe what is appended following an infinite list.</p>

OwnerDisplayName: Chriss

Body:
I'm currently trying to extend a friend's OCaml program. It's a huge collection of functions needed for some data analysis.. Since I'm not really an OCaml crack I'm currently stuck on a (for me) strange List implementation:

type 'a cell = Nil
    | Cons of ('a * 'a llist)
and 'a llist = (unit -> 'a cell);;

I've figured out that this implements some sort of "lazy" list, but I have absolutely no idea how it really works. I need to implement an Append and a Map Function based on the above type. Has anybody got an idea how to do that?

Any help would really be appreciated!

LastEditorDisplayName: starblue

OwnerDisplayName: Norman Ramsey


问:
PHP: game loop (threads or the sort)
I am writing PHP code to be a game client. It uses socket; socket_create followed by socket_connect and then socket_read. It works fine, but the issue is that the server can send a packet at any time which means socket_read needs to be happening constantly in a "game loop". So something like this:

```<code><?php
$reply = "";
do {
     $recv = "";
     $recv = socket_read($socket, '1400');
     if($recv != "") {
         $reply .= $recv;
     }
} while($recv != "");

echo($reply);
?>
</code>```

Doesn't work because it's stuck in the loop (server doesn't terminate connection until game is quit by client) and the PHP code needs to handle the packet stuff as it comes in.

So PHP doesn't really have threading. What's the best way of handling this?

答:
Basically any software platform is going to butt up against this problem. Most, as you've figured out, solve it with threading. While threading IS possible in PHP. It requires MAJORHAXXX. Such as launching a commandline php thread from within php.

It really doesn't end up being ideal.

However, there are other ways to get around this.

But you need to check ALL the marks on this list first:

[] - My game doesn't need to constantly keep checking the server, such as for player locations or complex movements. Anything beyond a chat-room level of data transfer and update rates should leave this box un-checked.

[] - My game doesn't need to be told BY THE SERVER anything. It is perfectly acceptable for the client to ask for anything it needs, perhaps once a second or better off once a minute.

[] - My game doesn't need to keep a constant simulation of a complex world running on the server for longer than it takes to complete a request. Tracking chat is one thing, doing physics and graphics modifications is another.

If you checked all of these boxes, then PHP is STILL IN THE GAME! Otherwise. Don't bother.

Basically, what I am saying here is that PHP is great for games that aren't really multiplayer, and that are turn-based or at least not very interactive. But once you have to keep things going without the player, PHP falls on its face.

VOODOO LEVEL

But if you simply MUST do this. There ARE ways to get around it.

A - Create a PHP Daemon that runs your world, pipe all other traffic to either a getter or setter request file that interacts with the database. So, you might request a getting of the game world state, or set a value that the player performed. All other game-world related things can be handled by the daemon and the game itself takes place in the database.

B - Use cron, not a Daemon. (dangerous, but we already established you as a risk taker, right?)

C - TRY only a Daemon and listening to sockets, then sending out threads (via exec()) to respond. Kind of like AndreKR's idea above, only you don't need to sleep. Problem here is you will almost always end up missing stuff or otherwise getting cut off. And the whole thing might explode if the Daemon get's run twice somehow..

Title: PHP: game loop (threads or the sort)

Body:
I am writing PHP code to be a game client. It uses socket; socket_create followed by socket_connect and then socket_read. It works fine, but the issue is that the server can send a packet at any time which means socket_read needs to be happening constantly in a "game loop". So something like this:

<?php
$reply = "";
do {
     $recv = "";
     $recv = socket_read($socket, '1400');
     if($recv != "") {
         $reply .= $recv;
     }
} while($recv != "");

echo($reply);
?>

Doesn't work because it's stuck in the loop (server doesn't terminate connection until game is quit by client) and the PHP code needs to handle the packet stuff as it comes in.

So PHP doesn't really have threading. What's the best way of handling this?


问:
How to set different color to some text of a textiew and make that text clickable?
In my app i want to use a text view that should have half of its text black and second half should be green, also i want the green part to be clickable.
I found some posts that show how to change color or how to make clickable but i am unable to find a combination of both. i have implemented this idea by myself, but the problem is that the string that should be clickable is not clickable. How to fix this?
Any help will be appreciated.
Here is my code</p>

```<code>String firststring="Hello i am a textiew";
lString secondstring="ClickMe";
SpannableStringBuilder builder = new SpannableStringBuilder();
SpannableString firstStringSpannable = new SpannableString(firststring);
firstStringSpannable .setSpan(new ForegroundColorSpan(Color.BLACK), 0, firststring.length(), 0);
builder.append(firstStringSpannable );

String space = " ";
SpannableString spaceSpannable = new SpannableString(space);
builder.append(spaceSpannable);

SpannableString secondSpannable = new SpannableString(secondstring);
secondSpannable .setSpan(new ForegroundColorSpan(Color.GREEN), 0,
builder.append(secondSpannable );

textview.setText(builder, TextView.BufferType.SPANNABLE);
String comepleteString = firststring + " " + secondstring;
SpannableString spannableString = new SpannableString(comepleteString);
int startIndex = comepleteString.indexOf(secondstring);
int endIndex = startIndex + secondstring.length();

Spannable Spannable = (Spannable) textview.getText();
ClickableSpan myClickableSpan = new ClickableSpan() {
    @Override
    public void onClick(View widget) {
//performing some function
    }
};
Spannable.setSpan(myClickableSpan, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
</code>```

答:
Hope this could help you :)</p>

```<code>protected void makeLinkClickable(SpannableStringBuilder strBuilder, final URLSpan span)
{
    int start = strBuilder.getSpanStart(span);
    int end = strBuilder.getSpanEnd(span);
    int flags = strBuilder.getSpanFlags(span);
    ClickableSpan clickable = new ClickableSpan() {
        public void onClick(View view) {
            // Do something with span.getURL() to handle the link click...
        }
    };
    strBuilder.setSpan(clickable, start, end, flags);
    strBuilder.removeSpan(span);
}

protected void setTextViewHTML(TextView text, String st1, String st2)
{
    CharSequence sequence = Html.fromHtml("<font color='green'>"+st1+"</font><font color='black'>"+st2+"</font");
    SpannableStringBuilder strBuilder = new SpannableStringBuilder(sequence);
    URLSpan[] urls = strBuilder.getSpans(0, sequence.length(), URLSpan.class);
    for(URLSpan span : urls) {
        makeLinkClickable(strBuilder, span);
    }
    text.setText(strBuilder);
    text.setMovementMethod(LinkMovementMethod.getInstance());
}
</code>```

Body:
In my app i want to use a text view that should have half of its text black and second half should be green, also i want the green part to be clickable.
I found some posts that show how to change color or how to make clickable but i am unable to find a combination of both. i have implemented this idea by myself, but the problem is that the string that should be clickable is not clickable. How to fix this?
Any help will be appreciated.
Here is my code

String firststring="Hello i am a textiew";
lString secondstring="ClickMe";
SpannableStringBuilder builder = new SpannableStringBuilder();
SpannableString firstStringSpannable = new SpannableString(firststring);
firstStringSpannable .setSpan(new ForegroundColorSpan(Color.BLACK), 0, firststring.length(), 0);
builder.append(firstStringSpannable );

String space = " ";
SpannableString spaceSpannable = new SpannableString(space);
builder.append(spaceSpannable);

SpannableString secondSpannable = new SpannableString(secondstring);
secondSpannable .setSpan(new ForegroundColorSpan(Color.GREEN), 0,
builder.append(secondSpannable );

textview.setText(builder, TextView.BufferType.SPANNABLE);
String comepleteString = firststring + " " + secondstring;
SpannableString spannableString = new SpannableString(comepleteString);
int startIndex = comepleteString.indexOf(secondstring);
int endIndex = startIndex + secondstring.length();

Spannable Spannable = (Spannable) textview.getText();
ClickableSpan myClickableSpan = new ClickableSpan() {
    @Override
    public void onClick(View widget) {
//performing some function
    }
};
Spannable.setSpan(myClickableSpan, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

Body:
Hope this could help you :)

protected void makeLinkClickable(SpannableStringBuilder strBuilder, final URLSpan span)
{
    int start = strBuilder.getSpanStart(span);
    int end = strBuilder.getSpanEnd(span);
    int flags = strBuilder.getSpanFlags(span);
    ClickableSpan clickable = new ClickableSpan() {
        public void onClick(View view) {
            // Do something with span.getURL() to handle the link click...
        }
    };
    strBuilder.setSpan(clickable, start, end, flags);
    strBuilder.removeSpan(span);
}

protected void setTextViewHTML(TextView text, String st1, String st2)
{
    CharSequence sequence = Html.fromHtml("<font color='green'>"+st1+"</font><font color='black'>"+st2+"</font");
    SpannableStringBuilder strBuilder = new SpannableStringBuilder(sequence);
    URLSpan[] urls = strBuilder.getSpans(0, sequence.length(), URLSpan.class);
    for(URLSpan span : urls) {
        makeLinkClickable(strBuilder, span);
    }
    text.setText(strBuilder);
    text.setMovementMethod(LinkMovementMethod.getInstance());
}


问:
How can I convert a BinaryExpression to Expression<Func<T, bool>>?
I have the following simple extension class

```<code>public static class ExpressionOrExtension
{
    public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> source, Expression<Func<T, bool>> expression)
    {
        if (source == null)
            return expression;
        return Expression.Or(source, expression);
    }
}
</code>```

But Expression.Or returns a BinaryExpression - How can I get it to return an Expression<Func<T, bool>> instead?

This is how I am trying to consume the method, using Entity Framework

```<code>    public IQueryable<BookVerse> FindByVerseReferences(string bookCode, params VerseReference[] verseReferences)
    {
        Expression<Func<BookVerse, bool>> conditions = null;
        foreach(VerseReference verseReference in verseReferences ?? new VerseReference[0])
        {
            conditions = conditions.Or<BookVerse>(x =>
                    x.BookCode == bookCode
                    && x.Chapter == verseReference.Chapter
                    && x.FirstVerse <= verseReference.LastVerse
                    && x.LastVerse >= verseReference.FirstVerse);
        }
        return MyDbContext.BookVerses.Where(conditions);
    }
</code>```

答:
You need to construct a lambda expression:

```<code>var p = Expression.Parameter(typeof(T));
return (Expression<Func<T,bool>>)Expression.Lambda(
    Expression.Or(
        Expression.Invoke(source, p)
    ,   Expression.Invoke(expression, p)
    )
,   p
);
</code>```

Demo:

```<code>Expression<Func<int,bool>> a = x=>x > 5;
Expression<Func<int,bool>> b = x=>x < -5;
var or = Or(a, b);
var f = (Func<int,bool>)or.Compile();
for (int i = -10 ; i <= 10 ; i++) {
    Console.WriteLine("{0} - {1}", i, f(i));
}
</code>```

Body:
I have the following simple extension class

public static class ExpressionOrExtension
{
    public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> source, Expression<Func<T, bool>> expression)
    {
        if (source == null)
            return expression;
        return Expression.Or(source, expression);
    }
}

But Expression.Or returns a BinaryExpression - How can I get it to return an Expression<Func<T, bool>> instead?

This is how I am trying to consume the method, using Entity Framework

    public IQueryable<BookVerse> FindByVerseReferences(string bookCode, params VerseReference[] verseReferences)
    {
        Expression<Func<BookVerse, bool>> conditions = null;
        foreach(VerseReference verseReference in verseReferences ?? new VerseReference[0])
        {
            conditions = conditions.Or<BookVerse>(x =>
                    x.BookCode == bookCode
                    && x.Chapter == verseReference.Chapter
                    && x.FirstVerse <= verseReference.LastVerse
                    && x.LastVerse >= verseReference.FirstVerse);
        }
        return MyDbContext.BookVerses.Where(conditions);
    }

Body:
You need to construct a lambda expression:

var p = Expression.Parameter(typeof(T));
return (Expression<Func<T,bool>>)Expression.Lambda(
    Expression.Or(
        Expression.Invoke(source, p)
    ,   Expression.Invoke(expression, p)
    )
,   p
);

Demo:

Expression<Func<int,bool>> a = x=>x > 5;
Expression<Func<int,bool>> b = x=>x < -5;
var or = Or(a, b);
var f = (Func<int,bool>)or.Compile();
for (int i = -10 ; i <= 10 ; i++) {
    Console.WriteLine("{0} - {1}", i, f(i));
}


问:
How to convert a point to polygon?
I have a big data in GeoJSON with Point type like this:

```<code>    {
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "Point",
        "coordinates": [
          2.8125,
          47.040182144806664
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "Point",
        "coordinates": [
          14.765625,
          48.69096039092549
        ]
      }
    }
  ]
}
</code>```

As far as I know, in order to create polygon on a map, my GeoJSON should have Polygon as a Type instead of Points. How can I do it? Does anybody have idea? Should I convert them into polygon? How? I really need your help guys... (I am using Mapbox-Gl-Js by the way)

Thanks!

答:
It's simple: I had a data regarding terrorism in csv with latitude, longitude. When i converted it to geojson I had a structure like this:
    {
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "Point",
        "coordinates": [
          2.8125,
          47.040182144806664
        ]
      }
    }

The question was: how I can create a map like this using this data: terrorism_map

I know that my geojson is useless in this case, but i need a way of creating map using this data. Sorry to confuse...

Title: How to convert a point to polygon?

Body:
I have a big data in GeoJSON with Point type like this:

    {
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "Point",
        "coordinates": [
          2.8125,
          47.040182144806664
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "Point",
        "coordinates": [
          14.765625,
          48.69096039092549
        ]
      }
    }
  ]
}

As far as I know, in order to create polygon on a map, my GeoJSON should have Polygon as a Type instead of Points. How can I do it? Does anybody have idea? Should I convert them into polygon? How? I really need your help guys... (I am using Mapbox-Gl-Js by the way)

Thanks!


问:
I am trying to create a table in sql, but im missing a keyword, cant find out how to fix it
I'm trying to create a table in SQL, but I'm missing a keyword, and I can't figure out how to fix it:</p>

```<code>CREATE TABLE Attendance_of_employee
(
  supervisior VARCHAR(30) DEFAULT 'NONE',
  arrival double NOT NULL,
  shift_end double NOT NULL,
  date_time DATE NOT NULL,
  worked_hours INT NOT NULL,
  ID_record VARCHAR(30) NOT NULL,
  employeeID INT NOT NULL,
  PRIMARY KEY (ID_record),
  FOREIGN KEY (employeeID) REFERENCES EmployeeTAB(employeeID)
);

Error report -
SQL Error: ORA-00905: chýbajúce kľúčové slovo
00905. 00000 -  "missing keyword"
*Cause:
*Action:
</code>```

答:
Use double precision instead of double.</p>

```<code>CREATE TABLE Attendance_of_employee( supervisior VARCHAR(30) DEFAULT 'NONE',
arrival double precision NOT NULL,
shift_end double precision NOT NULL, date_time DATE NOT NULL,
worked_hours INT NOT NULL,
ID_record VARCHAR(30) NOT NULL, employeeID INT NOT NULL, PRIMARY KEY (ID_record),
FOREIGN KEY (employeeID) REFERENCES EmployeeTAB(employeeID) );
</code>```

Body:
I'm trying to create a table in SQL, but I'm missing a keyword, and I can't figure out how to fix it:

CREATE TABLE Attendance_of_employee
(
  supervisior VARCHAR(30) DEFAULT 'NONE',
  arrival double NOT NULL,
  shift_end double NOT NULL,
  date_time DATE NOT NULL,
  worked_hours INT NOT NULL,
  ID_record VARCHAR(30) NOT NULL,
  employeeID INT NOT NULL,
  PRIMARY KEY (ID_record),
  FOREIGN KEY (employeeID) REFERENCES EmployeeTAB(employeeID)
);

Error report -
SQL Error: ORA-00905: chýbajúce kľúčové slovo
00905. 00000 -  "missing keyword"
*Cause:
*Action:

Body:
Use double precision instead of double.

CREATE TABLE Attendance_of_employee( supervisior VARCHAR(30) DEFAULT 'NONE',
arrival double precision NOT NULL,
shift_end double precision NOT NULL, date_time DATE NOT NULL,
worked_hours INT NOT NULL,
ID_record VARCHAR(30) NOT NULL, employeeID INT NOT NULL, PRIMARY KEY (ID_record),
FOREIGN KEY (employeeID) REFERENCES EmployeeTAB(employeeID) );


问:
How to show no result found from a AngularJS search?
I am fetching data from an api and I am using it to search something. When the json returns no result how to show NO RESULT FOUND.

Html code

```<code>        <div class="item item-input-inset">
    <label class="item-input-wrapper">
      <input type="text" placeholder="Search" ng-model="search">
    </label>
    <button class="button button-small" ng-click="load(search)">
      Submit
    </button>
  </div>
  <section class="list">
       <article ng-repeat="object in news">
        <div class="item">

         <div ng-repeat="item in object.news">
        <p class="noWhiteSpace"><b>Available Size</b> - {{item.size}}</p>

         </div>

         </div>
         <div ng-repeat="item in object.news" class="button-bar bar-dark" >
  <a  ng-click = openUrl(item.url); class="button">button</a>

        </div>
      </article>
        </section>
        </ion-content>
      </ion-view>
    </script>
</code>```

This is JS Code where I am fetching data from an api and also searching it.

```<code> $http({

    method: "GET",
    url: https://news.com/json?limit=50"
  })
  .then(function(newsData){
   $scope.news= newsData.data.data.articles;
   $scope.hide();
    console.log(data);

  })

      $scope.load = function(search) {
     $scope.show();
  $http({
    method: "GET",
    url: "https://news.com/json?query_term=" + encodeURIComponent(search)
  })
  .then(function(newsData){
   $scope.newsto= newsData.data.data.article;
   $scope.hide();
    console.log(data);

  });
}

})
</code>```

答:
Try this code :</p>

```<code><section class="list">
    <div ng-if="news">
    <article ng-repeat="object in news">
        <div class="item">

            <img ng-src="{{object.medium_cover_image}}">

            <h2 class="noWhiteSpace">{{object.title}}</h2>
            <p class="noWhiteSpace">{{object.genres}}</p>
            <p class="noWhiteSpace"><b>Release</b> - {{object.year}} </p>

            <div ng-repeat="item in object.news">
                <p class="noWhiteSpace"><b>Available Size</b> - {{item.size}}</p>

            </div>

        </div>
        <div ng-repeat="item in object.news" class="button-bar bar-dark">
            <a ng-click=o penUrl(item.url); class="button">button</a>

        </div>
    </article>
    </div>
    <div ng-if="news">
        No news to show
    </div>
</section>
</code>```

Body:
I am fetching data from an api and I am using it to search something. When the json returns no result how to show NO RESULT FOUND.

Html code

      <input type="text" placeholder="Search" ng-model="search">

    <button class="button button-small" ng-click="load(search)">
      Submit
    </button>

Available Size - {{item.size}}

  button

        </ion-content>
      </ion-view>
    </script>

This is JS Code where I am fetching data from an api and also searching it.

 $http({

    method: "GET",
    url: https://news.com/json?limit=50"
  })
  .then(function(newsData){
   $scope.news= newsData.data.data.articles;
   $scope.hide();
    console.log(data);

  })

      $scope.load = function(search) {
     $scope.show();
  $http({
    method: "GET",
    url: "https://news.com/json?query_term=" + encodeURIComponent(search)
  })
  .then(function(newsData){
   $scope.newsto= newsData.data.data.article;
   $scope.hide();
    console.log(data);

  });
}

})

Body:
Try this code :

<section class="list">
    <div ng-if="news">
    <article ng-repeat="object in news">
        <div class="item">

            <img ng-src="{{object.medium_cover_image}}">

            <h2 class="noWhiteSpace">{{object.title}}</h2>
            <p class="noWhiteSpace">{{object.genres}}</p>
            <p class="noWhiteSpace"><b>Release</b> - {{object.year}} </p>

            <div ng-repeat="item in object.news">
                <p class="noWhiteSpace"><b>Available Size</b> - {{item.size}}</p>

            </div>

        </div>
        <div ng-repeat="item in object.news" class="button-bar bar-dark">
            <a ng-click=o penUrl(item.url); class="button">button</a>

        </div>
    </article>
    </div>
    <div ng-if="news">
        No news to show
    </div>
</section>


问:
OWL API V5 read ontology from local file
in the current documentation example at the link:
https://github.com/owlcs/owlapi/blob/version5/contract/src/test/java/org/semanticweb/owlapi/examples/Examples.java
There is no example of how to load an ontology from a local file. There is only a way to load it from a string.

In the past when i used owl-api version 3
the following code worked perfectly:

```<code>    OWLOntologyManager manager =OWLManager.createOWLOntologyManager();
    File file = new File (path);
    OWLOntology ont = manager.loadOntologyFromOntologyDocument(IRI.create(file));
</code>```

however, in this version, the last line of the previous code:

```<code>manager.loadOntologyFromOntologyDocument(IRI.create(file));
</code>```

returns this error:

```<code>    Exception in thread "main" java.lang.NoSuchMethodError:
    org.semanticweb.owlapi.util.SAXParsers.initParserWithOWLAPIStandards(Lorg/xml/sax/ext/DeclHandler;)Ljavax/xml/parsers/SAXParser;
        at
org.semanticweb.owlapi.rdf.rdfxml.parser.RDFParser.parse(RDFParser.java:148)
    at org.semanticweb.owlapi.rdf.rdfxml.parser.RDFXMLParser.parse(RDFXMLParser.java:62)
    at uk.ac.manchester.cs.owl.owlapi.OWLOntologyFactoryImpl.loadOWLOntology(OWLOntologyFactoryImpl.java:173)
    at uk.ac.manchester.cs.owl.owlapi.OWLOntologyManagerImpl.load(OWLOntologyManagerImpl.java:954)
    at uk.ac.manchester.cs.owl.owlapi.OWLOntologyManagerImpl.loadOntology(OWLOntologyManagerImpl.java:918)
    at uk.ac.manchester.cs.owl.owlapi.OWLOntologyManagerImpl.loadOntologyFromOntologyDocument(OWLOntologyManagerImpl.java:859)
    at glass.main.ontology_Test_main2.readOntology(ontology_Test_main2.java:49)
    at glass.main.ontology_Test_main2.main(ontology_Test_main2.java:38)
</code>```

Kindly note the attachment, a small test java project, link:

dropbox.com/s/3787a3gsk2bwc26/test.tar.gz?dl=0

Kindly what am i doing wrong, i m sure that this code

Kindly would you please provide the correct way to do it, and add it to the tutorial example in the link https://github.com/owlcs/owlapi/blob/version5/contract/src/test/java/org/semanticweb/owlapi/examples/Examples.java

Thanks very much for your time.
Sincere regards

答:
You are very near to the solution:

```<code>final OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
final OWLOntology ontology = manager.loadOntologyFromOntologyDocument(new File("/home/galigator/myLocalDir/aura.owl"));
</code>```

Just use new File instead of IRI.create

Body:
in the current documentation example at the link:
https://github.com/owlcs/owlapi/blob/version5/contract/src/test/java/org/semanticweb/owlapi/examples/Examples.java
There is no example of how to load an ontology from a local file. There is only a way to load it from a string.

In the past when i used owl-api version 3
the following code worked perfectly:

    OWLOntologyManager manager =OWLManager.createOWLOntologyManager();
    File file = new File (path);
    OWLOntology ont = manager.loadOntologyFromOntologyDocument(IRI.create(file));

however, in this version, the last line of the previous code:

manager.loadOntologyFromOntologyDocument(IRI.create(file));

returns this error:

    Exception in thread "main" java.lang.NoSuchMethodError:
    org.semanticweb.owlapi.util.SAXParsers.initParserWithOWLAPIStandards(Lorg/xml/sax/ext/DeclHandler;)Ljavax/xml/parsers/SAXParser;
        at
org.semanticweb.owlapi.rdf.rdfxml.parser.RDFParser.parse(RDFParser.java:148)
    at org.semanticweb.owlapi.rdf.rdfxml.parser.RDFXMLParser.parse(RDFXMLParser.java:62)
    at uk.ac.manchester.cs.owl.owlapi.OWLOntologyFactoryImpl.loadOWLOntology(OWLOntologyFactoryImpl.java:173)
    at uk.ac.manchester.cs.owl.owlapi.OWLOntologyManagerImpl.load(OWLOntologyManagerImpl.java:954)
    at uk.ac.manchester.cs.owl.owlapi.OWLOntologyManagerImpl.loadOntology(OWLOntologyManagerImpl.java:918)
    at uk.ac.manchester.cs.owl.owlapi.OWLOntologyManagerImpl.loadOntologyFromOntologyDocument(OWLOntologyManagerImpl.java:859)
    at glass.main.ontology_Test_main2.readOntology(ontology_Test_main2.java:49)
    at glass.main.ontology_Test_main2.main(ontology_Test_main2.java:38)

Kindly note the attachment, a small test java project, link:

dropbox.com/s/3787a3gsk2bwc26/test.tar.gz?dl=0

Kindly what am i doing wrong, i m sure that this code

Kindly would you please provide the correct way to do it, and add it to the tutorial example in the link https://github.com/owlcs/owlapi/blob/version5/contract/src/test/java/org/semanticweb/owlapi/examples/Examples.java

Thanks very much for your time.
Sincere regards

Body:
You are very near to the solution:

final OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
final OWLOntology ontology = manager.loadOntologyFromOntologyDocument(new File("/home/galigator/myLocalDir/aura.owl"));

Just use new File instead of IRI.create

ContentLicense: CC BY-SA 4.0


问:
How do I track visits to facebook pages using Google Analytics or Yahoo Web Analytics?
I have recently looked into this and discovered that using FBML pages in a facebook fan page, I can add fb:google-analytics tags or image tags to track page visits. However I have found no method of tracking visits to other facebook tab pages, like "pictures" or "wall".

Is there a way do this?

Thanks

答:
Facebook does provide some limited analytics capabilities called Facebook Insights:

http://www.facebook.com/help/?faq=15221

Also outgoing links will be tagged with a tracking code so you can pick up which traffic is coming from your Facebook pages to your site.

However you cannot embed Google Analytics or Yahoo Analytics directly into the pages.


问:
UITextField Delegate "shouldChangeCharactersIn" not called for first entry in textfield
I am building a view which accepts 4 digit OTP. The code I have is as follows

"CodeText" is subclass of UITextField

```<code>    class RegisterController: ModelController, UITextFieldDelegate {

    @IBOutlet var firstDigit:CodeText?
    @IBOutlet var secondDigit:CodeText?
    @IBOutlet var thirdDigit:CodeText?
    @IBOutlet var fourthDigit:CodeText?

    override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationItem.hidesBackButton = true
        self.firstDigit!.delegate = self
        self.secondDigit!.delegate = self
        self.thirdDigit!.delegate = self
        self.fourthDigit!.delegate = self

        self.firstDigit!.becomeFirstResponder()
    }

    // UITextField Delegate Methods

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        if (textField == self.firstDigit) {

            if(textField.text!.characters.count >= 1 ) {

                self.secondDigit?.becomeFirstResponder()
            }
        }
        else if (textField == secondDigit) {

            if(textField.text!.characters.count >= 1 ) {

                self.thirdDigit?.becomeFirstResponder()
            }

        }
        else if (textField == thirdDigit) {

            if(textField.text!.characters.count >= 1 ) {

                self.fourthDigit?.becomeFirstResponder()
            }
        }
        else if (textField == fourthDigit) {

            print("Fourth Digit")

            if(textField.text!.characters.count >= 1 ) {

                self.fourthDigit?.resignFirstResponder()
            }
        }

        return true
    }
}
</code>```

Above code works fine for me except for one feature. I want the keyboard to be dismissed after fourth digit entry, but what's happening is the "shouldChange" delegate method is not called when the "fourthDigit" get it's focus and get it's first entry but the delegate is called when the textfield gets it's second entry and the keyboard is getting dismissed.

So in order to get the keyboard dismissed an unnecessary keystroke is needed.

Any suggestion would be helpful

答:
Please try string.length>0 instead of textField.text!.characters.count >= 1

EDIT

I've managed to get callback when user enters a character in textfield using a notification

```<code>// in your respective method where you init your text field
[_txtSearchLocation addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

- (void)textFieldDidChange :(UITextField *) textField{
}
</code>```

When this method gets call you can call textField.resignFirstResponder

Sorry for Obj-c, i copied this from my current open file thx

Body:
I am building a view which accepts 4 digit OTP. The code I have is as follows

"CodeText" is subclass of UITextField

    class RegisterController: ModelController, UITextFieldDelegate {

    @IBOutlet var firstDigit:CodeText?
    @IBOutlet var secondDigit:CodeText?
    @IBOutlet var thirdDigit:CodeText?
    @IBOutlet var fourthDigit:CodeText?

    override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationItem.hidesBackButton = true
        self.firstDigit!.delegate = self
        self.secondDigit!.delegate = self
        self.thirdDigit!.delegate = self
        self.fourthDigit!.delegate = self

        self.firstDigit!.becomeFirstResponder()
    }

    // UITextField Delegate Methods

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        if (textField == self.firstDigit) {

            if(textField.text!.characters.count >= 1 ) {

                self.secondDigit?.becomeFirstResponder()
            }
        }
        else if (textField == secondDigit) {

            if(textField.text!.characters.count >= 1 ) {

                self.thirdDigit?.becomeFirstResponder()
            }

        }
        else if (textField == thirdDigit) {

            if(textField.text!.characters.count >= 1 ) {

                self.fourthDigit?.becomeFirstResponder()
            }
        }
        else if (textField == fourthDigit) {

            print("Fourth Digit")

            if(textField.text!.characters.count >= 1 ) {

                self.fourthDigit?.resignFirstResponder()
            }
        }

        return true
    }
}

Above code works fine for me except for one feature. I want the keyboard to be dismissed after fourth digit entry, but what's happening is the "shouldChange" delegate method is not called when the "fourthDigit" get it's focus and get it's first entry but the delegate is called when the textfield gets it's second entry and the keyboard is getting dismissed.

So in order to get the keyboard dismissed an unnecessary keystroke is needed.

Any suggestion would be helpful

Body:
Please try string.length>0 instead of textField.text!.characters.count >= 1

EDIT

I've managed to get callback when user enters a character in textfield using a notification

// in your respective method where you init your text field
[_txtSearchLocation addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

- (void)textFieldDidChange :(UITextField *) textField{
}

When this method gets call you can call textField.resignFirstResponder

Sorry for Obj-c, i copied this from my current open file thx


答:
Try this out:-</p>

```<code>echo min(array_keys($arr));
</code>```

Title: Get the value of the lowest array key

Body:
I have an array which returns this:

    Array (
            [122] => value
            [43] => value1
            [654645] => value2
            [34634] => value3
            [3] => value4  // I want this
            [550] => value5
    )

How can I return value4 from the lowest key [3], I have read http://php.net/manual/en/array.sorting.php and attempted some of the sort by key examples with no luck.

Body:
Try this out:-

echo min(array_keys($arr));


答:
alternate choice for capture all event of your text field, with out coding

Cretae a IBAction (in your Current textfield VC)

Ctrl-Click (or right click) on the UITextField in Interface Builder

Connect the "Editing Changed" event to the File's Owner's IBAction added in the first step.

for e.g your UIControlEventEditingChanged method name is updateContentsOfTextField

and get output in

```<code>func updateContentsOfTextField(_ theTextField: UITextField) {
print("text changed: \(theTextField.text)")
}
</code>```

you can get the more information from here

Title: UITextField Delegate "shouldChangeCharactersIn" not called for first entry in textfield

Body:
alternate choice for capture all event of your text field, with out coding

Cretae a IBAction (in your Current textfield VC)

Ctrl-Click (or right click) on the UITextField in Interface Builder

Connect the "Editing Changed" event to the File's Owner's IBAction added in the first step.

for e.g your UIControlEventEditingChanged method name is updateContentsOfTextField

and get output in

func updateContentsOfTextField(_ theTextField: UITextField) {
print("text changed: \(theTextField.text)")
}

you can get the more information from here


问:
Overwrite the first and last column in csv file using python
I am new to data processing using CSV module. And i have input file And using this code`

```<code>import csv
path1 = "C:\\Users\\apple\\Downloads\\Challenge\\raw\\charity.a.data"
csv_file_path =          "C:\\Users\\apple\\Downloads\\Challenge\\raw\\output.csv.bak"

with open(path1, 'r') as in_file:
    in_file.__next__()
    stripped = (line.strip() for line in in_file)
    lines = (line.split(":$%:") for line in stripped if line)
    with open(csv_file_path, 'w') as out_file:
        writer = csv.writer(out_file)
        writer.writerow(('id', 'donor_id','last_name','first_name','year','city','state','postal_code','gift_amount'))
    writer.writerows(lines)
</code>```

`

Is it possible to remove (:) in the first and last column of csv file. And i want output be like

Please help me.

答:
If you just want to eliminate the ':' at the first and last column, this should work. Keep in mind that your dataset should be tab (or something other than comma) separated before you read it, because as I commented in your question, there are commas ',' in your dataset.

```<code>path1 = '/path/input.csv'
path2 = '/path/output.csv'

with open(path1, 'r') as input, open(path2, 'w') as output:
file = iter(input.readlines())
output.write(next(file))

for row in file:
    output.write(row[1:][:-2] + '\n')
</code>```

Update

So after giving your code, I added a small change to do the whole process starting from the initial file. The idea is the same. You should just exclude the first and the last char of each line. So instead of line.strip() you should have line.strip()[1:][:-2].

```<code>import csv
path1 = "C:\\Users\\apple\\Downloads\\Challenge\\raw\\charity.a.data"
csv_file_path = "C:\\Users\\apple\\Downloads\\Challenge\\raw\\output.csv.bak"

with open(path1, 'r') as in_file:
    in_file.__next__()
    stripped = (line.strip()[1:][:-2] for line in in_file)
    lines = (line.split(":$%:") for line in stripped if line)
    with open(csv_file_path, 'w') as out_file:
        writer = csv.writer(out_file)
        writer.writerow(('id', 'donor_id','last_name','first_name','year','city','state','postal_code','gift_amount'))
        writer.writerows(lines)
</code>```

Body:
I am new to data processing using CSV module. And i have input file And using this code`

import csv
path1 = "C:\\Users\\apple\\Downloads\\Challenge\\raw\\charity.a.data"
csv_file_path =          "C:\\Users\\apple\\Downloads\\Challenge\\raw\\output.csv.bak"

with open(path1, 'r') as in_file:
    in_file.__next__()
    stripped = (line.strip() for line in in_file)
    lines = (line.split(":$%:") for line in stripped if line)
    with open(csv_file_path, 'w') as out_file:
        writer = csv.writer(out_file)
        writer.writerow(('id', 'donor_id','last_name','first_name','year','city','state','postal_code','gift_amount'))
    writer.writerows(lines)

`

Is it possible to remove (:) in the first and last column of csv file. And i want output be like

Please help me.

Body:
If you just want to eliminate the ':' at the first and last column, this should work. Keep in mind that your dataset should be tab (or something other than comma) separated before you read it, because as I commented in your question, there are commas ',' in your dataset.

path1 = '/path/input.csv'
path2 = '/path/output.csv'

with open(path1, 'r') as input, open(path2, 'w') as output:
file = iter(input.readlines())
output.write(next(file))

for row in file:
    output.write(row[1:][:-2] + '\n')

Update

So after giving your code, I added a small change to do the whole process starting from the initial file. The idea is the same. You should just exclude the first and the last char of each line. So instead of line.strip() you should have line.strip()[1:][:-2].

import csv
path1 = "C:\\Users\\apple\\Downloads\\Challenge\\raw\\charity.a.data"
csv_file_path = "C:\\Users\\apple\\Downloads\\Challenge\\raw\\output.csv.bak"

with open(path1, 'r') as in_file:
    in_file.__next__()
    stripped = (line.strip()[1:][:-2] for line in in_file)
    lines = (line.split(":$%:") for line in stripped if line)
    with open(csv_file_path, 'w') as out_file:
        writer = csv.writer(out_file)
        writer.writerow(('id', 'donor_id','last_name','first_name','year','city','state','postal_code','gift_amount'))
        writer.writerows(lines)