问:
How to I read the number of LIVE users from Google Analytics in my .NET MVC application?
I have a ASP.NET MVC web application. I want to show the number of LIVE users from a website.

How can I read this from Google Analytics?

I have already followed this guide:
http://www.markwemekamp.com/blog/c/how-to-read-from-google-analytics-using-c/
But I can't get the code to work. It keeps on running and gives a System.NullReferenceException.

So I hope there are people with better idea's or guides here. And please, only complete guides with every detail in it. Not those half guide where you don't know what to do.

Thanks in Advance.

Update:

This is the code from the guide that I am using. I only added the date's. I am using the code in de Global.asax.cs file.

The Null exception occures on this piece of code:

```<code>foreach (var x in response.Reports.First().Data.Rows)
    {
        Debug.WriteLine("The next line doesn't appear: seee.....");
        Debug.WriteLine(string.Join(", ", x.Dimensions) + "   " + string.Join(", ", x.Metrics.First().Values));
    }
</code>```

Code:

```<code>protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        UnityConfig.RegisterComponents();
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        Database.SetInitializer<EFDbContext>(null);
        MethodSomethingGoogle();
    }

    public void MethodSomethingGoogle()
    {
        string todaysDate = DateTime.Now.ToString("yyyy-MM-dd");
        string tomorrowsDate = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");

        try
        {
            var filepath = @"C:\Users\ckersten\Downloads\Dashboard-Match-Online-b2f3f0b438a1.json";
            var filepath2 = @"~\App_Data\Dashboard-Match-Online-b2f3f0b438a1.json";

            // path to the json file for the Service account
            var viewid = "109154097";    // id of the view you want to read from
            Googl

            eCredential credentials;
                using (var stream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
                {
                    string[] scopes = { AnalyticsReportingService.Scope.AnalyticsReadonly };
                    var googleCredential = GoogleCredential.FromStream(stream);
                    credentials = googleCredential.CreateScoped(scopes);
                }

                var reportingService = new AnalyticsReportingService(
                    new BaseClientService.Initializer
                    {
                        HttpClientInitializer = credentials
                    });
                var dateRange = new DateRange
                {
                    StartDate = todaysDate,
                    EndDate = tomorrowsDate
                };
                var sessions = new Metric
                {
                    Expression = "ga:pageviews",
                    Alias = "Sessions"
                };
                var date = new Dimension { Name = "ga:date" };

                var reportRequest = new ReportRequest
                {
                    DateRanges = new List<DateRange> { dateRange },
                    Dimensions = new List<Dimension> { date },
                    Metrics = new List<Metric> { sessions },
                    ViewId = viewid
                };
                var getReportsRequest = new GetReportsRequest
                {
                    ReportRequests = new List<ReportRequest> { reportRequest }
                };
                var batchRequest = reportingService.Reports.BatchGet(getReportsRequest);
                var response = batchRequest.Execute();
                foreach (var x in response.Reports.First().Data.Rows)
                {
                    Debug.WriteLine("The next line doesn't appear: seee.....");
                    Debug.WriteLine(string.Join(", ", x.Dimensions) + "   " + string.Join(", ", x.Metrics.First().Values));
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("Google Exception: " + e.ToString());
            }
            Debug.WriteLine(Console.ReadLine());
        }
</code>```

答:
Your code uses the reporting api which isnt going to give you real time data.   Data in the reporting api wont be done processing for 24 -48 hours .

You should be using the realtime api if you want to see whats going on now.   Just remember that you can only make 10000 requests against the api a day per view.

```<code>DataResource.RealtimeResource.GetRequest request =
service.Data.Realtime.Get(String.Format("ga:{0}", profileId), "rt:activeUsers");
RealtimeData feed = request.Execute();

foreach (List  row in realTimeData.Rows)
{
 foreach (string col in row)
    {
     Console.Write(col + " ");  // writes the value of the column
     }
Console.Write("\r\n");
}
</code>```

My tutorial on the realtime api here  GitHub sample project can be found here you also might want to consider using a service account

Note:

The Real Time Reporting API, in limited beta, is available for developer preview only. Sign up to access the API.

Body:
I have a ASP.NET MVC web application. I want to show the number of LIVE users from a website.

How can I read this from Google Analytics?

I have already followed this guide:
http://www.markwemekamp.com/blog/c/how-to-read-from-google-analytics-using-c/
But I can't get the code to work. It keeps on running and gives a System.NullReferenceException.

So I hope there are people with better idea's or guides here. And please, only complete guides with every detail in it. Not those half guide where you don't know what to do.

Thanks in Advance.

Update:

This is the code from the guide that I am using. I only added the date's. I am using the code in de Global.asax.cs file.

The Null exception occures on this piece of code:

foreach (var x in response.Reports.First().Data.Rows)
    {
        Debug.WriteLine("The next line doesn't appear: seee.....");
        Debug.WriteLine(string.Join(", ", x.Dimensions) + "   " + string.Join(", ", x.Metrics.First().Values));
    }

Code:

protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        UnityConfig.RegisterComponents();
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        Database.SetInitializer<EFDbContext>(null);
        MethodSomethingGoogle();
    }

    public void MethodSomethingGoogle()
    {
        string todaysDate = DateTime.Now.ToString("yyyy-MM-dd");
        string tomorrowsDate = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");

        try
        {
            var filepath = @"C:\Users\ckersten\Downloads\Dashboard-Match-Online-b2f3f0b438a1.json";
            var filepath2 = @"~\App_Data\Dashboard-Match-Online-b2f3f0b438a1.json";

            // path to the json file for the Service account
            var viewid = "109154097";    // id of the view you want to read from
            Googl

            eCredential credentials;
                using (var stream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
                {
                    string[] scopes = { AnalyticsReportingService.Scope.AnalyticsReadonly };
                    var googleCredential = GoogleCredential.FromStream(stream);
                    credentials = googleCredential.CreateScoped(scopes);
                }

                var reportingService = new AnalyticsReportingService(
                    new BaseClientService.Initializer
                    {
                        HttpClientInitializer = credentials
                    });
                var dateRange = new DateRange
                {
                    StartDate = todaysDate,
                    EndDate = tomorrowsDate
                };
                var sessions = new Metric
                {
                    Expression = "ga:pageviews",
                    Alias = "Sessions"
                };
                var date = new Dimension { Name = "ga:date" };

                var reportRequest = new ReportRequest
                {
                    DateRanges = new List<DateRange> { dateRange },
                    Dimensions = new List<Dimension> { date },
                    Metrics = new List<Metric> { sessions },
                    ViewId = viewid
                };
                var getReportsRequest = new GetReportsRequest
                {
                    ReportRequests = new List<ReportRequest> { reportRequest }
                };
                var batchRequest = reportingService.Reports.BatchGet(getReportsRequest);
                var response = batchRequest.Execute();
                foreach (var x in response.Reports.First().Data.Rows)
                {
                    Debug.WriteLine("The next line doesn't appear: seee.....");
                    Debug.WriteLine(string.Join(", ", x.Dimensions) + "   " + string.Join(", ", x.Metrics.First().Values));
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("Google Exception: " + e.ToString());
            }
            Debug.WriteLine(Console.ReadLine());
        }

Body:
Your code uses the reporting api which isnt going to give you real time data.   Data in the reporting api wont be done processing for 24 -48 hours .

You should be using the realtime api if you want to see whats going on now.   Just remember that you can only make 10000 requests against the api a day per view.

DataResource.RealtimeResource.GetRequest request =
service.Data.Realtime.Get(String.Format("ga:{0}", profileId), "rt:activeUsers");
RealtimeData feed = request.Execute();

foreach (List  row in realTimeData.Rows)
{
 foreach (string col in row)
    {
     Console.Write(col + " ");  // writes the value of the column
     }
Console.Write("\r\n");
}

My tutorial on the realtime api here  GitHub sample project can be found here you also might want to consider using a service account

Note:

The Real Time Reporting API, in limited beta, is available for developer preview only. Sign up to access the API.


来源: stackexchange

问:
Write python dictionary into textfile
I want to write my python dictionary in a text file where each line contain one key and its value, with comma as separation. I am using the following code:

```<code>with open(compounds, 'w') as f:
    for key, value in dict_NTID_IDs_in_EisDatabase.items():
        f.write('%s:%s\n' % (key, value))
</code>```

But it returns me the following error TypeError: expected str, bytes or os.PathLike object, not list

答:
I hope it will help you!</p>

```<code>dic = {'Python' : '.py', 'C++' : '.cpp', 'Java' : '.java'}
f = open("dic.txt","w")
f.write( str(dic) )
f.close()
</code>```

ContentLicense: CC BY-SA 3.0

Title: Write python dictionary into textfile

Body:
I want to write my python dictionary in a text file where each line contain one key and its value, with comma as separation. I am using the following code:

with open(compounds, 'w') as f:
    for key, value in dict_NTID_IDs_in_EisDatabase.items():
        f.write('%s:%s\n' % (key, value))

But it returns me the following error TypeError: expected str, bytes or os.PathLike object, not list

Body:
I hope it will help you!

dic = {'Python' : '.py', 'C++' : '.cpp', 'Java' : '.java'}
f = open("dic.txt","w")
f.write( str(dic) )
f.close()


问:
ES6 Map key to be either string or number
I have a ES6 Map , where keys are number. Some time the key is number and some time the key is string which represents a number. The map will never have duplicate key at runtime for me. Example I will never have key "1" and 1 .

While retrieving from map I need a simple one liner code which will negate whether if the key is a string or a number.

```<code>var map = new Map();
undefined
map.set('1', 'string one');
map.set(2, 'number tow')
Map(2) {"1" => "string one", 2 => "number tow"}
map.get(1)
undefined
map.get('1')
"string one"
</code>```

答:
I've created a function that gets the value from the given map. It works both ways, from string to int and from int to string.

var map = new Map();
map.set('1', 'string one');
map.set(2, 'number two');

function getFromMap(map, key){
  return map.get(key) || map.get(key.toString()) || map.get(parseInt(key));
}

console.log(getFromMap(map, 1));
console.log(getFromMap(map, '2'));```

Body:
I have a ES6 Map , where keys are number. Some time the key is number and some time the key is string which represents a number. The map will never have duplicate key at runtime for me. Example I will never have key "1" and 1 .

While retrieving from map I need a simple one liner code which will negate whether if the key is a string or a number.

var map = new Map();
undefined
map.set('1', 'string one');
map.set(2, 'number tow')
Map(2) {"1" => "string one", 2 => "number tow"}
map.get(1)
undefined
map.get('1')
"string one"


问:
GROUP BY with JOIN not giving correct result
How can I find the number of persons from each country

Person table

country_id, fName, lName

Countries table

country_id, country_name

I can find the number of persons from each country with their country IDs, using the below SQL statement

```<code>select
 p.country_id, COUNT(p.country_id) as [Count]
from
 persons p
GROUP BY
 p.country_id
</code>```

But what if I want to fetch country_name instead of country_id?
I tried this so far but it does not work as expected so I am missing something here.

```<code>select
    c.country_name, COUNT(p.country_id) as [Count]
from
    persons p INNER JOIN countries c ON p.country_id = c.country_id
GROUP BY
    p.country_id
</code>```

SQL Server 2000

答:
You could use group by c.country_name .. the column you have in select and you use for refer the group by</p>

```<code>select    c.country_name, COUNT(p.country_id) as [Count]
from  persons p INNER JOIN countries c ON p.country_id = c.country_id
GROUP BY  c.country_name
</code>```

Body:
How can I find the number of persons from each country

Person table

country_id, fName, lName

Countries table

country_id, country_name

I can find the number of persons from each country with their country IDs, using the below SQL statement

select
 p.country_id, COUNT(p.country_id) as [Count]
from
 persons p
GROUP BY
 p.country_id

But what if I want to fetch country_name instead of country_id?
I tried this so far but it does not work as expected so I am missing something here.

select
    c.country_name, COUNT(p.country_id) as [Count]
from
    persons p INNER JOIN countries c ON p.country_id = c.country_id
GROUP BY
    p.country_id

SQL Server 2000

Body:
You could use group by c.country_name .. the column you have in select and you use for refer the group by

select    c.country_name, COUNT(p.country_id) as [Count]
from  persons p INNER JOIN countries c ON p.country_id = c.country_id
GROUP BY  c.country_name


问:
Dynamic table rows and columns
I'd like to be able to add/remove rows/columns in my table but I don't how to achieve this given my knowledge in js/jquery is basic. I've search and seen related topics but none fits to what I wanted to happen.

As you can see in my code below I have 11 columns with the  tag and a default row and they must not be affected by remove. Also, when adding new column the PO increments like PO 10.

```<code><table class="main-table" id="po-table" border="1">
    <tbody>
        <tr class="table-header">
            <td>#</td>
            <td>Course Code</td>
            <td>Course Name</td>
            <td>PO 1</td>
            <td>PO 2</td>
            <td>PO 3</td>
            <td>PO 4</td>
            <td>PO 5</td>
            <td>PO 6</td>
            <td>PO 7</td>
            <td>PO 8</td>
            <td>PO 9</td>
        </tr>
        <tr class="default-row">
            <td>1</td>
            <td><input type="text" name="course_code[]"></td>
            <td><input type="text" name="course_name[]"></td>
            <td><input type="checkbox" name="po1[]" value="Po1"></td>
            <td><input type="checkbox" name="po2[]" value="Po2"></td>
            <td><input type="checkbox" name="po3[]" value="Po3"></td>
            <td><input type="checkbox" name="po4[]" value="Po4"></td>
            <td><input type="checkbox" name="po5[]" value="Po5"></td>
            <td><input type="checkbox" name="po6[]" value="Po6"></td>
            <td><input type="checkbox" name="po7[]" value="Po7"></td>
            <td><input type="checkbox" name="po8[]" value="Po8"></td>
            <td><input type="checkbox" name="po9[]" value="Po9"></td>
        </tr>
    </tbody>
</table>
</code>```

Picture of the output:

答:
For Dynamic creation of tables with respect to entered row and column, you can use this code

```<code><!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Dynamic Table</title>
<script>
function createTable()
{
rn = window.prompt("Input number of rows", 1);
cn = window.prompt("Input number of columns",1);

 for(var r=0;r<parseInt(rn,10);r++)
  {
   var x=document.getElementById('myTable').insertRow(r);
   for(var c=0;c<parseInt(cn,10);c++)
    {
     var y=  x.insertCell(c);
     y.innerHTML="Row-"+r+" Column-"+c;
    }
   }
}

</script>
<style type="text/css">
body {margin: 30px;}
</style>
</head><body>
<table id="myTable" border="1">
</table><form>
<input type="button" onclick="createTable()" value="Create the table">
</form></body></html>
</code>```

Title: Dynamic table rows and columns

Body:
I'd like to be able to add/remove rows/columns in my table but I don't how to achieve this given my knowledge in js/jquery is basic. I've search and seen related topics but none fits to what I wanted to happen.

As you can see in my code below I have 11 columns with the  tag and a default row and they must not be affected by remove. Also, when adding new column the PO increments like PO 10.

            #
            Course Code
            Course Name
            PO 1
            PO 2
            PO 3
            PO 4
            PO 5
            PO 6
            PO 7
            PO 8
            PO 9

            1
            <input type="text" name="course_code[]">
            <input type="text" name="course_name[]">
            <input type="checkbox" name="po1[]" value="Po1">
            <input type="checkbox" name="po2[]" value="Po2">
            <input type="checkbox" name="po3[]" value="Po3">
            <input type="checkbox" name="po4[]" value="Po4">
            <input type="checkbox" name="po5[]" value="Po5">
            <input type="checkbox" name="po6[]" value="Po6">
            <input type="checkbox" name="po7[]" value="Po7">
            <input type="checkbox" name="po8[]" value="Po8">
            <input type="checkbox" name="po9[]" value="Po9">

Picture of the output:

Body:
For Dynamic creation of tables with respect to entered row and column, you can use this code

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Dynamic Table</title>
<script>
function createTable()
{
rn = window.prompt("Input number of rows", 1);
cn = window.prompt("Input number of columns",1);

 for(var r=0;r<parseInt(rn,10);r++)
  {
   var x=document.getElementById('myTable').insertRow(r);
   for(var c=0;c<parseInt(cn,10);c++)
    {
     var y=  x.insertCell(c);
     y.innerHTML="Row-"+r+" Column-"+c;
    }
   }
}

</script>
<style type="text/css">
body {margin: 30px;}
</style>
</head><body>
<table id="myTable" border="1">
</table><form>
<input type="button" onclick="createTable()" value="Create the table">
</form></body></html>


问:
ASP.NET code behind file not nested under the related aspx file in Visual Studio
In my C# ASP.NET Web Site using .NET Framework 4.0, I have a couple of pages where the related .cs file is not under its related aspx file.  I recently moved the files to a subdirectory.  I have 10 pages and for 8 of them the move worked just fine and the .cs file is under the aspx.  However for two pages, the .cs file now no longer shows below the aspx file.  How can I fix this so that the cs is shown correctly underneath the aspx file?  When I compare the top of the markup pages, the two problem pages look just like the other 8 pages.  I don't see any issues there.</p>

答:
In general for VS projects the nesting is driven by the <DependentUpon/> element. You can fix it by editing the project file directly.
Change:

```<code>    <Compile Include="blah.child" />
</code>```

To:

```<code>    <Compile Include="blah.child">
      <DependentUpon>blah.parent</DependentUpon>
    </Compile>
</code>```

This works for any nested files, like .sass -> .css -> .min.css

```<code>    <Compile Include="blah.css">
      <DependentUpon>blah.scss</DependentUpon>
    </Compile>
    <Compile Include="blah.min.css">
      <DependentUpon>blah.css</DependentUpon>
    </Compile>
</code>```

Body:
In general for VS projects the nesting is driven by the <DependentUpon/> element. You can fix it by editing the project file directly.
Change:

    <Compile Include="blah.child" />

To:

    <Compile Include="blah.child">
      <DependentUpon>blah.parent</DependentUpon>
    </Compile>

This works for any nested files, like .sass -> .css -> .min.css

    <Compile Include="blah.css">
      <DependentUpon>blah.scss</DependentUpon>
    </Compile>
    <Compile Include="blah.min.css">
      <DependentUpon>blah.css</DependentUpon>
    </Compile>

ContentLicense: CC BY-SA 4.0


问:
Objective-C, member variables and class variables
i need some help on understanding how to use class/member variable from a instance method in Objective-C.

Any snipplet / example is highly appreciated.

Thanks.

答:
Objective-C doesn't have class variables, and what you call a member variable is called an instance variable. Instance variables can be referenced by name from within an instance method. And if you need the behavior of a class variable, you can use a file-level static instead.

Here's a very quick sample:

Foo.h

```<code>@interface Foo : NSObject {
    NSString *foo;
}
@end
</code>```

Foo.m

```<code>static NSString *bar;

@implementation Foo
- (void)foobar {
    foo = @"test"; // assigns the ivar
    bar = @"test2"; // assigns the static
}
@end
</code>```

Body:
Objective-C doesn't have class variables, and what you call a member variable is called an instance variable. Instance variables can be referenced by name from within an instance method. And if you need the behavior of a class variable, you can use a file-level static instead.

Here's a very quick sample:

Foo.h

@interface Foo : NSObject {
    NSString *foo;
}
@end

Foo.m

static NSString *bar;

@implementation Foo
- (void)foobar {
    foo = @"test"; // assigns the ivar
    bar = @"test2"; // assigns the static
}
@end

ContentLicense: CC BY-SA 2.5


问:
Jenkins user is gone after macOS update
I'm running Jenkins as a CI server on a Mac. It was running fine on macOS 10.12 with the typical setup with user jenkins.

Today I upgraded macOS to 10.13 (High Sierra). Jenkins could not start after the upgrade process completed. Furthermore, there was no user jenkins on the system. All Jenkins files are there, but there is no jenkins user in Settings -> Users & Groups. If I try to use jenkins user in Terminal, for instance if I try to change file ownership to jenkins with chown, I get:

```<code>chown: jenkins: illegal user name
</code>```

How do I fix this?

答:
I've managed to re-create jenkins user by extracting the script commands that create it from Jenkins installation. I ran this script in particular:</p>

```<code>JENKINS_HOMEDIR="/Users/Shared/Jenkins"
DEFAULTS_PLIST="/Library/Preferences/org.jenkins-ci.plist"

if dscl . -list /Users/jenkins; then
    echo 'jenkins user already exists, attempting to change the shell to /bin/bash'
    # Will fail if UserShell is not /usr/bin/false, but that's ok.
    # Then we will assume an admin has changed it.
    dscl . -change /Users/jenkins UserShell /usr/bin/false /bin/bash
else
    echo 'No jenkins user found, creating jenkins user and group'

# Find free uid under 500
    uid=$(dscl . -list /Users uid | sort -nrk 2 | awk '$2 < 500 {print $2 + 1; exit 0}')
    if [ $uid -eq 500 ]; then
        echo 'ERROR: All system uids are in use!'
        exit 1
    fi
    echo "Using uid $uid for jenkins"

    gid=$uid
    while dscl -search /Groups gid $gid | grep -q $gid; do
        echo "gid $gid is not free, trying next"
        gid=$(($gid + 1))
    done
    echo "Using gid $gid for jenkins"

    dscl . -create /Groups/jenkins PrimaryGroupID $gid

    dscl . -create /Users/jenkins UserShell /bin/bash
    dscl . -create /Users/jenkins Password '*'
    dscl . -create /Users/jenkins UniqueID $uid
    dscl . -create /Users/jenkins PrimaryGroupID $gid
    dscl . -create /Users/jenkins NFSHomeDirectory "$JENKINS_HOMEDIR"

    dscl . -append /Groups/jenkins GroupMembership jenkins
fi

# identify the real default group name for user jenkins
groupid=`dscl . read /Users/jenkins PrimaryGroupID | awk '{print $2}'`
gname=`id -n -g $groupid`

echo "Using jenkins:${gname} as file owner and group for jenkins daemon files"

find "$JENKINS_HOMEDIR" \( -not -user jenkins -or -not -group ${gname} \) -print0 | xargs -0 chown jenkins:${gname}

# Add defaults for heap sizing
arch=$(uname -m)
if [ $arch = 'x86_64' ]; then
    defaults write $DEFAULTS_PLIST heapSize 512m
    defaults write $DEFAULTS_PLIST permGen 512m
    defaults write $DEFAULTS_PLIST minHeapSize 256m
    defaults write $DEFAULTS_PLIST minPermGen 256m
else
    # i386
    defaults write $DEFAULTS_PLIST heapSize 128m
    defaults write $DEFAULTS_PLIST permGen 128m
    defaults write $DEFAULTS_PLIST minHeapSize 64m
    defaults write $DEFAULTS_PLIST minPermGen 64m
fi

defaults write $DEFAULTS_PLIST httpPort 8080

# Set tmpdir
JENKINS_TMPDIR="$JENKINS_HOMEDIR/tmp"
defaults write $DEFAULTS_PLIST tmpdir $JENKINS_TMPDIR
mkdir -p $JENKINS_TMPDIR
chown jenkins:${gname} $JENKINS_TMPDIR

# Create log directory, which can be written by Jenkins daemon
mkdir -p /var/log/jenkins
chown jenkins:${gname} /var/log/jenkins
</code>```

Title: Jenkins user is gone after macOS update

Body:
I'm running Jenkins as a CI server on a Mac. It was running fine on macOS 10.12 with the typical setup with user jenkins.

Today I upgraded macOS to 10.13 (High Sierra). Jenkins could not start after the upgrade process completed. Furthermore, there was no user jenkins on the system. All Jenkins files are there, but there is no jenkins user in Settings -> Users & Groups. If I try to use jenkins user in Terminal, for instance if I try to change file ownership to jenkins with chown, I get:

chown: jenkins: illegal user name

How do I fix this?

Body:
I've managed to re-create jenkins user by extracting the script commands that create it from Jenkins installation. I ran this script in particular:

JENKINS_HOMEDIR="/Users/Shared/Jenkins"
DEFAULTS_PLIST="/Library/Preferences/org.jenkins-ci.plist"

if dscl . -list /Users/jenkins; then
    echo 'jenkins user already exists, attempting to change the shell to /bin/bash'
    # Will fail if UserShell is not /usr/bin/false, but that's ok.
    # Then we will assume an admin has changed it.
    dscl . -change /Users/jenkins UserShell /usr/bin/false /bin/bash
else
    echo 'No jenkins user found, creating jenkins user and group'

# Find free uid under 500
    uid=$(dscl . -list /Users uid | sort -nrk 2 | awk '$2 < 500 {print $2 + 1; exit 0}')
    if [ $uid -eq 500 ]; then
        echo 'ERROR: All system uids are in use!'
        exit 1
    fi
    echo "Using uid $uid for jenkins"

    gid=$uid
    while dscl -search /Groups gid $gid | grep -q $gid; do
        echo "gid $gid is not free, trying next"
        gid=$(($gid + 1))
    done
    echo "Using gid $gid for jenkins"

    dscl . -create /Groups/jenkins PrimaryGroupID $gid

    dscl . -create /Users/jenkins UserShell /bin/bash
    dscl . -create /Users/jenkins Password '*'
    dscl . -create /Users/jenkins UniqueID $uid
    dscl . -create /Users/jenkins PrimaryGroupID $gid
    dscl . -create /Users/jenkins NFSHomeDirectory "$JENKINS_HOMEDIR"

    dscl . -append /Groups/jenkins GroupMembership jenkins
fi

# identify the real default group name for user jenkins
groupid=`dscl . read /Users/jenkins PrimaryGroupID | awk '{print $2}'`
gname=`id -n -g $groupid`

echo "Using jenkins:${gname} as file owner and group for jenkins daemon files"

find "$JENKINS_HOMEDIR" \( -not -user jenkins -or -not -group ${gname} \) -print0 | xargs -0 chown jenkins:${gname}

# Add defaults for heap sizing
arch=$(uname -m)
if [ $arch = 'x86_64' ]; then
    defaults write $DEFAULTS_PLIST heapSize 512m
    defaults write $DEFAULTS_PLIST permGen 512m
    defaults write $DEFAULTS_PLIST minHeapSize 256m
    defaults write $DEFAULTS_PLIST minPermGen 256m
else
    # i386
    defaults write $DEFAULTS_PLIST heapSize 128m
    defaults write $DEFAULTS_PLIST permGen 128m
    defaults write $DEFAULTS_PLIST minHeapSize 64m
    defaults write $DEFAULTS_PLIST minPermGen 64m
fi

defaults write $DEFAULTS_PLIST httpPort 8080

# Set tmpdir
JENKINS_TMPDIR="$JENKINS_HOMEDIR/tmp"
defaults write $DEFAULTS_PLIST tmpdir $JENKINS_TMPDIR
mkdir -p $JENKINS_TMPDIR
chown jenkins:${gname} $JENKINS_TMPDIR

# Create log directory, which can be written by Jenkins daemon
mkdir -p /var/log/jenkins
chown jenkins:${gname} /var/log/jenkins


问:
Trying to style a Sidebar Widget Navigation with JQuery
For the navigational items which have a submenu, for example, 'Primary Fees', I have included an arrow. Now when I hover over the Main Menu Item, I have included an animation which rotates the arrow and highlights the Main Menu item with red. In order to rotate the arrow, I added a .rotateOnHover class to all the Main Menu Items which have the arrow. then I use CSS to perform the rotation animation.

Now to the problem. When I hover over the submenu Items, I want to keep that particular Main Menu item highlighted and keep the arrow rotated. For example, when I hover over 'Grade 1-3 Boarding', I want to keep 'Primary Fees' highlighted and I want to keep the arrow rotated.  I did some searching on the interwebs, and in particular StackOverflow, and I was encouraged to use Jquery to achieve this task. Since this is in essence, hovering over a child element and changing the style of its parent element.

The problem is when I hover over the submenu items e.g. 'Grade 1-3 Boarding', it applies the rotating arrow animation to ALL the main menu items which have the same arrow and arrow class, .rotateOnHover.

How can I hover over a submenu item and apply my desired hover effects to its parent Menu Item Only and not all the menu items?

Any help will be appreciated.

Also, any styling tips for the sidebar and the website, in general, will be appreciated. This is my very first website and I'm learning on the job.

This is the code for the sidebar

HTML

```<code><div class="sidebar-widget">
    <div class="sidebarExplore">
        <h4>
            <span style="color: grey; text-align: center; margin:auto; display:block; font-size: 25px;">
            <i class="fa fa-globe" aria-hidden="true"></i> Explore This Section</span>
        </h4>
    </div>
    <ul class="sidebarExploreList">
        <li class="dropdownsidebaritem">
            <a href="#"> Primary Fees&nbsp<i class="fa fa-chevron-circle-down rotateOnHover"></i></a>
            <div class="sidebarExploreSubmenu" style="font-size: 12px;">
                <a href="" style="font-size: 15px; font-weight:bold; padding: 5px;">Grade 1 - 3 - Boarding</a>
                <a href="" style="font-size: 15px; font-weight:bold; padding: 5px;">Grade 4 - 7 - Boarding</a>
                <a href="" style="font-size: 15px; font-weight:bold; padding: 5px;">Other Costs -  Boarding</a>
                <a href="" style="font-size: 15px; font-weight:bold; padding: 5px;">Reception - Day School</a>
                <a href="" style="font-size: 15px; font-weight:bold; padding: 5px;">Grade 1 - 3 - Day School</a>
                <a href="" style="font-size: 15px; font-weight:bold; padding: 5px;">Grade 4 - 7 - Day School</a>
                <a href="" style="font-size: 15px; font-weight:bold; padding: 5px;">Other Costs - Day School</a>
            </div>
        </li>
        <li class="dropdownsidebaritem"><a href="#">Secondary Fees&nbsp<i class="fa fa-chevron-circle-down rotateOnHover"></i></a></li>
        <li><a href="#">Admission Forms</a></li>
        <li><a href="#">School Fee Policy</a></li>
    </ul>
</div>
</code>```

CSS

```<code> .sidebar-widget {
    border:1px solid #afb1b3;
    margin-top: 13.8%;
    margin-right: 5%;
    overflow: hidden;
    background-color: #f3f3f3;
    float: right;
    width: 20%;
    height: auto;

}

.sidebar-widget ul {
    list-style-type: none;
    padding: 0;
    margin: 0;

}

.sidebar-widget ul li {
    list-style-type: none;
    width: 100%;
     border-top: 1px solid black;

}

.sidebar-widget ul li:last-child{
    list-style-type: none;
    width: 100%;
    border-bottom: 1px solid black;
}
.sidebar-widget ul li a{
    display: block;
    position: relative;
    text-decoration: none;
    text-align: center;
    padding: 20px;
    font-size: 18px;
    font-weight: 100;
    text-rendering: optimizeLegibility;

}

.sidebarExploreSubmenu{
    display: none;
    position: relative;
    color: black;
    background-color:white;
    font-size: 11px;
    border-bottom: 0.5px solid bisque;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

.sidebarExploreSubmenu a{
    padding: 10px;
    text-decoration: none;
    display: block;
    text-align: center;
    font-size: 10px;

}
.rotateOnHover {
    font-size:18px;
     -webkit-transition: -webkit-transform .8s ease-in-out;
          transition: transform .8s ease-in-out;
}

.sidebar-widget a:hover {
    background-color: #990000;
    color: white;
}
.dropdownsidebaritem a:hover  .rotateOnHover {
     -webkit-transform: rotate(180deg);
          transform: rotate(180deg);
}

.sidebarExploreSubmenu a:hover{
    font-size: 10px;
}
</code>```

JS

```<code><script type="text/javascript">

$(document).ready(function() {

    $( '.dropdownsidebaritem' ).hover(
        function(){
            $(this).children('.sidebarExploreSubmenu')
                .delay(100)
                    .slideDown(500);
        },
        function(){
            $(this).children('.sidebarExploreSubmenu')
                .clearQueue()
                .slideUp(500);
        }
    );
});

$(function() {
  $('.sidebarExploreSubmenu a').hover(function() {
    $('.rotateOnHover').css('transform', 'rotate(180deg)');
  }, function() {
    // on mouseout, reset the transform
    $('.rotateOnHover').css('transform', '');
  });
});

</script>
</code>```

答:
First of all don't style inline elements, example:

```<code>    <a href="" style="font-size: 15px; font-weight:bold; padding: 5px;">Grade 4 - 7 - Day School</a>
</code>```

instead make it like that:

```<code><a href="" class="sidebarExploreSubmenu-anchor">Grade 4 - 7 - Day School</a>
</code>```

and then in style.css add:

```<code>.sidebarExploreSubmenu-anchor {
font-size: 15px; font-weight:bold; padding: 5px; }
</code>```

It can make your website messy. Try to do everything in style.css, remember that there're levels in which browser are reading styles, example:
!important > inline styles > #style .style .style > .style .style > .style

Body:
For the navigational items which have a submenu, for example, 'Primary Fees', I have included an arrow. Now when I hover over the Main Menu Item, I have included an animation which rotates the arrow and highlights the Main Menu item with red. In order to rotate the arrow, I added a .rotateOnHover class to all the Main Menu Items which have the arrow. then I use CSS to perform the rotation animation.

Now to the problem. When I hover over the submenu Items, I want to keep that particular Main Menu item highlighted and keep the arrow rotated. For example, when I hover over 'Grade 1-3 Boarding', I want to keep 'Primary Fees' highlighted and I want to keep the arrow rotated.  I did some searching on the interwebs, and in particular StackOverflow, and I was encouraged to use Jquery to achieve this task. Since this is in essence, hovering over a child element and changing the style of its parent element.

The problem is when I hover over the submenu items e.g. 'Grade 1-3 Boarding', it applies the rotating arrow animation to ALL the main menu items which have the same arrow and arrow class, .rotateOnHover.

How can I hover over a submenu item and apply my desired hover effects to its parent Menu Item Only and not all the menu items?

Any help will be appreciated.

Also, any styling tips for the sidebar and the website, in general, will be appreciated. This is my very first website and I'm learning on the job.

This is the code for the sidebar

HTML

             Explore This Section

             Primary Fees&nbsp

                Grade 1 - 3 - Boarding
                Grade 4 - 7 - Boarding
                Other Costs -  Boarding
                Reception - Day School
                Grade 1 - 3 - Day School
                Grade 4 - 7 - Day School
                Other Costs - Day School

Secondary Fees&nbsp

Admission Forms

School Fee Policy

CSS

 .sidebar-widget {
    border:1px solid #afb1b3;
    margin-top: 13.8%;
    margin-right: 5%;
    overflow: hidden;
    background-color: #f3f3f3;
    float: right;
    width: 20%;
    height: auto;

}

.sidebar-widget ul {
    list-style-type: none;
    padding: 0;
    margin: 0;

}

.sidebar-widget ul li {
    list-style-type: none;
    width: 100%;
     border-top: 1px solid black;

}

.sidebar-widget ul li:last-child{
    list-style-type: none;
    width: 100%;
    border-bottom: 1px solid black;
}
.sidebar-widget ul li a{
    display: block;
    position: relative;
    text-decoration: none;
    text-align: center;
    padding: 20px;
    font-size: 18px;
    font-weight: 100;
    text-rendering: optimizeLegibility;

}

.sidebarExploreSubmenu{
    display: none;
    position: relative;
    color: black;
    background-color:white;
    font-size: 11px;
    border-bottom: 0.5px solid bisque;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

.sidebarExploreSubmenu a{
    padding: 10px;
    text-decoration: none;
    display: block;
    text-align: center;
    font-size: 10px;

}
.rotateOnHover {
    font-size:18px;
     -webkit-transition: -webkit-transform .8s ease-in-out;
          transition: transform .8s ease-in-out;
}

.sidebar-widget a:hover {
    background-color: #990000;
    color: white;
}
.dropdownsidebaritem a:hover  .rotateOnHover {
     -webkit-transform: rotate(180deg);
          transform: rotate(180deg);
}

.sidebarExploreSubmenu a:hover{
    font-size: 10px;
}

JS

Body:
First of all don't style inline elements, example:

    <a href="" style="font-size: 15px; font-weight:bold; padding: 5px;">Grade 4 - 7 - Day School</a>

instead make it like that:

<a href="" class="sidebarExploreSubmenu-anchor">Grade 4 - 7 - Day School</a>

and then in style.css add:

.sidebarExploreSubmenu-anchor {
font-size: 15px; font-weight:bold; padding: 5px; }

It can make your website messy. Try to do everything in style.css, remember that there're levels in which browser are reading styles, example:
!important > inline styles > #style .style .style > .style .style > .style


问:
How to set validation on Phone number in PHP
This is my code:

I never set validation for phone number field, I try "/^([0-9]{3})-[0-9]{3}-[0-9]{4}$/" this type of code for validation,
I enter text in the phone number field, they accept in backend

what can I do? for set validation for phone number field.

```<code><!DOCTYPE HTML>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>

<?php
$nameErr = $phoneErr = "";
$name =  $phone = "";

$error = 0;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // collect value of input field

     $name = htmlspecialchars($_REQUEST['name']);
     $phone = htmlspecialchars($_REQUEST['phone']);

    if (empty($name)) {
        $nameErr = "* Name is required";
      $error = 1;
        // echo "Name is empty";
    }

    if (empty($phone)) {
        // echo "phone is empty";
        $phoneErr = "* Phone is required";
        $error = 1;
    }

}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
    <h1>Login Form</h1>
  Name: <input type="text" name="name" onkeydown="return alphaOnly(event);" value="<?php echo $name ?>">
   <span class="error"> <?php echo $nameErr?></span>
  <br></br>

  Phone: <input type="text" name="phone" value="<?php echo $phone ?>">
    <span class="error"> <?php echo $phoneErr?></span>
   <br><br>

  <input type="submit">

  <br><br>

</form>

</body>
</html>
</code>```

I need to validate phone number in PHP, but the example do not work.
How can I set validation for mobile number

答:
According to comments and example phone number that you given, this code will validating number of digits and first two numbers of your country, i just replaced + with 0, for sure they won't enter plus.

```<code>$tel = '091-9869123456';

if(preg_match("/^[0-9]{3}-[0-9]{10}$/", $tel)) {
    echo "valid";
} else {
    echo "invalid";
}
</code>```

Now for more validating need to check country code:

```<code>if(substr($tel, 0, 3) == '091'){
    echo "valid";
} else {
    echo "invalid, it should start with 091";
}
</code>```

Or you do this with same preg_match like this:

```<code>if(preg_match("/^[091]{3}-[0-9]{10}$/", $tel)) {
    echo "valid";
} else {
    echo "invalid";
}
</code>```

Demo

Body:
This is my code:

I never set validation for phone number field, I try "/^([0-9]{3})-[0-9]{3}-[0-9]{4}$/" this type of code for validation,
I enter text in the phone number field, they accept in backend

what can I do? for set validation for phone number field.

<!DOCTYPE HTML>

<?php
$nameErr = $phoneErr = "";
$name =  $phone = "";

$error = 0;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // collect value of input field

     $name = htmlspecialchars($_REQUEST['name']);
     $phone = htmlspecialchars($_REQUEST['phone']);

    if (empty($name)) {
        $nameErr = "* Name is required";
      $error = 1;
        // echo "Name is empty";
    }

    if (empty($phone)) {
        // echo "phone is empty";
        $phoneErr = "* Phone is required";
        $error = 1;
    }

}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">

Login Form

  Name: <input type="text" name="name" onkeydown="return alphaOnly(event);" value="<?php echo $name ?>">
    <?php echo $nameErr?>

  Phone: <input type="text" name="phone" value="<?php echo $phone ?>">
     <?php echo $phoneErr?>

  <input type="submit">

</form>

I need to validate phone number in PHP, but the example do not work.
How can I set validation for mobile number

Body:
According to comments and example phone number that you given, this code will validating number of digits and first two numbers of your country, i just replaced + with 0, for sure they won't enter plus.

$tel = '091-9869123456';

if(preg_match("/^[0-9]{3}-[0-9]{10}$/", $tel)) {
    echo "valid";
} else {
    echo "invalid";
}

Now for more validating need to check country code:

if(substr($tel, 0, 3) == '091'){
    echo "valid";
} else {
    echo "invalid, it should start with 091";
}

Or you do this with same preg_match like this:

if(preg_match("/^[091]{3}-[0-9]{10}$/", $tel)) {
    echo "valid";
} else {
    echo "invalid";
}

Demo


问:
Not able to call the function from C DLL
```<code>//DLL Code

#include <stdio.h>

extern "C"

{

__declspec(dllexport) void DisplayHelloFromDLL()

    {
        printf("Hello from DLL !\n");
    }
}

//Program Accessing DLL

#include<windows.h>
#include<iostream>
#include<conio.h>

typedef void (*DisplayHelloFromDLLFuncPtr)();
using namespace std;

int main()

{

    HINSTANCE hGetProcIDDLL = LoadLibrary("L:\\C_Learning\\Library\\MyLib\\Debug\\MyLib.dll");
    if (!hGetProcIDDLL)
    {

        cout << "\nCould Not The Library";
        return EXIT_FAILURE;

    }

    else

    {
        cout << "\nDLL is Loaded";

    }

    DisplayHelloFromDLLFuncPtr LibMainEntryPoint=(DisplayHelloFromDLLFuncPtr)GetProcAddress(hGetProcIDDLL, "DisplayHelloFromDLL");

    if (!DisplayHelloFromDLL)
    {

        cout << "\nCould not locate the function";
        return EXIT_FAILURE;
    }

    cout << DisplayHelloFromDLL();

    return EXIT_SUCCESS;

    _getch();
    return 0;

}
</code>```

Code executes till cout statement in else condition.

Receive Error while compiling for Function in DLL.

Error received 'DisplayHelloFromDLL': undeclared identifier

Ran Depends.exe which confirms about the function availability in DLL address space.

DLL and Sample Program is compiled with 32-bit environment.

6.Program sole purpose is to call function C DLL and print Hello From DLL message.

Any Suggestions ?

答:
You named the variable holding the "DisplayHelloFromDLL" function pointer as "LibMainEntryPoint":

```<code>DisplayHelloFromDLLFuncPtr LibMainEntryPoint=(DisplayHelloFromDLLFuncPtr)GetProcAddress(hGetProcIDDLL, "DisplayHelloFromDLL");
</code>```

but then you try to use it with different name (DisplayHelloFromDLL):

```<code>if (!DisplayHelloFromDLL) ...
</code>```

Be consistent with the variable names, and the code should work.
change it to:

DisplayHelloFromDLLFuncPtr DisplayHelloFromDLL=(DisplayHelloFromDLLFuncPtr)GetProcAddress(hGetProcIDDLL, "DisplayHelloFromDLL");

Body:
//DLL Code

#include <stdio.h>

extern "C"

{

__declspec(dllexport) void DisplayHelloFromDLL()

    {
        printf("Hello from DLL !\n");
    }
}

//Program Accessing DLL

#include<windows.h>
#include<iostream>
#include<conio.h>

typedef void (*DisplayHelloFromDLLFuncPtr)();
using namespace std;

int main()

{

    HINSTANCE hGetProcIDDLL = LoadLibrary("L:\\C_Learning\\Library\\MyLib\\Debug\\MyLib.dll");
    if (!hGetProcIDDLL)
    {

        cout << "\nCould Not The Library";
        return EXIT_FAILURE;

    }

    else

    {
        cout << "\nDLL is Loaded";

    }

    DisplayHelloFromDLLFuncPtr LibMainEntryPoint=(DisplayHelloFromDLLFuncPtr)GetProcAddress(hGetProcIDDLL, "DisplayHelloFromDLL");

    if (!DisplayHelloFromDLL)
    {

        cout << "\nCould not locate the function";
        return EXIT_FAILURE;
    }

    cout << DisplayHelloFromDLL();

    return EXIT_SUCCESS;

    _getch();
    return 0;

}

Code executes till cout statement in else condition.

Receive Error while compiling for Function in DLL.

Error received 'DisplayHelloFromDLL': undeclared identifier

Ran Depends.exe which confirms about the function availability in DLL address space.

DLL and Sample Program is compiled with 32-bit environment.

6.Program sole purpose is to call function C DLL and print Hello From DLL message.

Any Suggestions ?

Body:
You named the variable holding the "DisplayHelloFromDLL" function pointer as "LibMainEntryPoint":

DisplayHelloFromDLLFuncPtr LibMainEntryPoint=(DisplayHelloFromDLLFuncPtr)GetProcAddress(hGetProcIDDLL, "DisplayHelloFromDLL");

but then you try to use it with different name (DisplayHelloFromDLL):

if (!DisplayHelloFromDLL) ...

Be consistent with the variable names, and the code should work.
change it to:

DisplayHelloFromDLLFuncPtr DisplayHelloFromDLL=(DisplayHelloFromDLLFuncPtr)GetProcAddress(hGetProcIDDLL, "DisplayHelloFromDLL");


问:
can some one help me calculating time difference between two Date Stamps?
My date formats are like this:
(u'Task', u'2017-01-06T02:23:44.000-0500') .. stage 1
(u'Task', u'2017-01-06T05:27:10.000-0500') .. stage 2
(u'Task', u'2017-01-10T14:42:44.000-0500') ...stage 2

I have to calulcate the time difference between every stage
I am using this (which I know is incorrect :-()

```<code>    import datetime as dt
    date_format = "yyyy-mm-ddThh-mm-ss"
    x1= d1.split('T')[0]+' '+(d1.split('T'))[1][:8]
    x2= d2.split('T')[0]+' '+(d2.split('T'))[1][:8]

    d1=('2017-01-06T02:23:44.000-0500')
    d2=('2017-01-19T17:30:21.000-0500')

#some string slicing to get rid of T and the timezone indicator
    start_dt = dt.datetime.strptime(x1, 'yyyy-mm-ddhh:mm:ss')
    end_dt = dt.datetime.strptime(x2, 'yyyy-mm-ddhh:mm:ss')

    x = start_dt - end_dt
</code>```

It returns me a format mismatch error

can someone help me find the time spent between stage 1 and stage 2 I have to calculate this recursively

答:
You can do it like this:

```<code>import datetime as dt

# parses the string in Format 'yyyyMMddHHMMSS'
def parse(s):
    return dt.datetime.strptime(s,"%Y%m%d%H%M%S")

# removes all T-: from string, leaves to . for split, returns only left part of split
def reformat(s):
    return ''.join([x for x in s if x not in "T-:"]).split('.')[0]

d1=('2017-01-06T02:23:44.000-0500')
d2=('2017-01-19T17:30:21.000-0500')

f1 = reformat(d1)
f2 = reformat(d2)

start = parse(f1)
end   = parse(f2)
delta = end - start

print(d1 + "=>" + f1)
print(d2 + "=>" + f2)
print(delta)
</code>```

Prints:

```<code>2017-01-06T02:23:44.000-0500=>20170106022344
2017-01-19T17:30:21.000-0500=>20170119173021
13 days, 15:06:37
</code>```

Body:
My date formats are like this:
(u'Task', u'2017-01-06T02:23:44.000-0500') .. stage 1
(u'Task', u'2017-01-06T05:27:10.000-0500') .. stage 2
(u'Task', u'2017-01-10T14:42:44.000-0500') ...stage 2

I have to calulcate the time difference between every stage
I am using this (which I know is incorrect :-()

    import datetime as dt
    date_format = "yyyy-mm-ddThh-mm-ss"
    x1= d1.split('T')[0]+' '+(d1.split('T'))[1][:8]
    x2= d2.split('T')[0]+' '+(d2.split('T'))[1][:8]

    d1=('2017-01-06T02:23:44.000-0500')
    d2=('2017-01-19T17:30:21.000-0500')

#some string slicing to get rid of T and the timezone indicator
    start_dt = dt.datetime.strptime(x1, 'yyyy-mm-ddhh:mm:ss')
    end_dt = dt.datetime.strptime(x2, 'yyyy-mm-ddhh:mm:ss')

    x = start_dt - end_dt

It returns me a format mismatch error

can someone help me find the time spent between stage 1 and stage 2 I have to calculate this recursively

Body:
You can do it like this:

import datetime as dt

# parses the string in Format 'yyyyMMddHHMMSS'
def parse(s):
    return dt.datetime.strptime(s,"%Y%m%d%H%M%S")

# removes all T-: from string, leaves to . for split, returns only left part of split
def reformat(s):
    return ''.join([x for x in s if x not in "T-:"]).split('.')[0]

d1=('2017-01-06T02:23:44.000-0500')
d2=('2017-01-19T17:30:21.000-0500')

f1 = reformat(d1)
f2 = reformat(d2)

start = parse(f1)
end   = parse(f2)
delta = end - start

print(d1 + "=>" + f1)
print(d2 + "=>" + f2)
print(delta)

Prints:

2017-01-06T02:23:44.000-0500=>20170106022344
2017-01-19T17:30:21.000-0500=>20170119173021
13 days, 15:06:37


问:
PHP Select multiple desc limit's?
In my sql table i had more then 300000 entries.

```<code> $marketname = more then 200 !
</code>```

with this select i can see the last 15 entries.

```<code>$sql = "SELECT price FROM markets where market = '" . $marketname . "' order by time desc LIMIT 15,1";
$sql = "SELECT price FROM markets where market = '" . $marketname . "' order by time desc LIMIT 15,1";
</code>```

and so on for the last 30, 60, 120.

```<code>$sql = "SELECT price FROM markets where market = '" . $marketname . "' order by time desc LIMIT 30,1";
$sql = "SELECT price FROM markets where market = '" . $marketname . "' order by time desc LIMIT 60,1";
</code>```

But is there a combination of all, because when i show it on one page its very very slow with 200 markets!!

like..

```<code>$sql = "SELECT price FROM markets where market = '" . $marketname . "' order by time desc LIMIT 15,1 AND LIMIT 30,1 AND LIMIT 60,1 AND LIMIT 120,1";
</code>```

答:
First of all, try to not do SQL injection style SQL. Use PDO or MySQLi with prepared statements. With that in mind, do not limit your query's last part.

```<code>SELECT price FROM markets WHERE market = :marketName ORDER BY time DESC limit 100
</code>```

Would query the price of the market by marketname (prep statement), order it and limit it to 100 records.

Title: PHP Select multiple desc limit's?

Body:
In my sql table i had more then 300000 entries.

 $marketname = more then 200 !

with this select i can see the last 15 entries.

$sql = "SELECT price FROM markets where market = '" . $marketname . "' order by time desc LIMIT 15,1";
$sql = "SELECT price FROM markets where market = '" . $marketname . "' order by time desc LIMIT 15,1";

and so on for the last 30, 60, 120.

$sql = "SELECT price FROM markets where market = '" . $marketname . "' order by time desc LIMIT 30,1";
$sql = "SELECT price FROM markets where market = '" . $marketname . "' order by time desc LIMIT 60,1";

But is there a combination of all, because when i show it on one page its very very slow with 200 markets!!

like..

$sql = "SELECT price FROM markets where market = '" . $marketname . "' order by time desc LIMIT 15,1 AND LIMIT 30,1 AND LIMIT 60,1 AND LIMIT 120,1";

Body:
First of all, try to not do SQL injection style SQL. Use PDO or MySQLi with prepared statements. With that in mind, do not limit your query's last part.

SELECT price FROM markets WHERE market = :marketName ORDER BY time DESC limit 100

Would query the price of the market by marketname (prep statement), order it and limit it to 100 records.


问:
CRM 2011 Report in IFRAME not accessible through javascript
Is it possible to access report data and it's param using java script when report gets displayed inside IFRAME on the CRM form.

Althought Iframe is accessible and if it contains html then html will be accessible but does it allow to access report in Iframe ?

Thanks

答:
yes you can access report inside iframe below is how we have done it. We have CRM 2013 on-premise setup.

We use custom JavaScript code to hide report ribbon on report inside CRM Dashboard inside iframe.

On CRM Dashboard or form where you have the report which you want to access through JavaScript, add an html Web Resource which will have the following code.

```<code>function onBodyLoad(){
var contentIFrame0= window.top.document.getElementById('contentIFrame0')
if(contentIFrame0)
 {
     var dashboardFrame=contentIFrame0.contentDocument.frames["dashboardFrame"];
     if (dashboardFrame!= undefined) {
         var elem = mainFrame.document.frames["yourReportIframe"];
         if (elem != undefined && elem.document.getElementById("compatibilityNotification")!=undefined) {
            elem.document.getElementById("compatibilityNotification").style.display = "none";;
            elem.document.getElementById("crmMenuBar").style.display = "none";
          }
     else {
         setTimeout(onBodyLoad, 3000);
     }
 }
}
</code>```

Please note that the above code snippet is specifically for CRM Dashboards, you should change it to your specific needs for CRM forms.

Body:
yes you can access report inside iframe below is how we have done it. We have CRM 2013 on-premise setup.

We use custom JavaScript code to hide report ribbon on report inside CRM Dashboard inside iframe.

On CRM Dashboard or form where you have the report which you want to access through JavaScript, add an html Web Resource which will have the following code.

function onBodyLoad(){
var contentIFrame0= window.top.document.getElementById('contentIFrame0')
if(contentIFrame0)
 {
     var dashboardFrame=contentIFrame0.contentDocument.frames["dashboardFrame"];
     if (dashboardFrame!= undefined) {
         var elem = mainFrame.document.frames["yourReportIframe"];
         if (elem != undefined && elem.document.getElementById("compatibilityNotification")!=undefined) {
            elem.document.getElementById("compatibilityNotification").style.display = "none";;
            elem.document.getElementById("crmMenuBar").style.display = "none";
          }
     else {
         setTimeout(onBodyLoad, 3000);
     }
 }
}

Please note that the above code snippet is specifically for CRM Dashboards, you should change it to your specific needs for CRM forms.


问:
Saving and restoring Keras BLSTM CTC model
I have been working on speech emotion recognition deep neural network. I have used keras Bidirectional LSTM with CTC loss. i trained the model and saved it

model_json = model.to_json()
with open("ctc_model.json", "w") as json_file:
  json_file.write(model_json)
model.save_weights("ctc_weights.h5")

The problem is i can not use this model to test on on unseen data because the model accepts 4 argument as input and calculates the ctc loss..just build the model and train. so how can i save a model in such away that in require only one input. not the labels, and length. Basically how can i save a model as this function test_func = K.function([net_input], [output])

```<code>def ctc_lambda_func(args):
    y_pred, labels, input_length, label_length = args

   shift = 2
   y_pred = y_pred[:, shift:, :]
   input_length -= shift
   return K.ctc_batch_cost(labels, y_pred, input_length, label_length)
def build_model(nb_feat, nb_class, optimizer='Adadelta'):
    net_input = Input(name="the_input", shape=(200, nb_feat))
    forward_lstm1  = LSTM(output_dim=64,
                      return_sequences=True,
                      activation="tanh"
                     )(net_input)
    backward_lstm1 = LSTM(output_dim=64,
                      return_sequences=True,
                      activation="tanh",
                      go_backwards=True
                     )(net_input)
    blstm_output1  = Merge(mode='concat')([forward_lstm1, backward_lstm1])

    forward_lstm2  = LSTM(output_dim=64,
                      return_sequences=True,
                      activation="tanh"
                     )(blstm_output1)
    backward_lstm2 = LSTM(output_dim=64,
                      return_sequences=True,
                      activation="tanh",
                      go_backwards=True
                     )(blstm_output1)
    blstm_output2  = Merge(mode='concat')([forward_lstm2, backward_lstm2])

    hidden = TimeDistributed(Dense(512, activation='tanh'))(blstm_output2)
    output = TimeDistributed(Dense(nb_class + 1, activation='softmax')) (hidden)

    labels = Input(name='the_labels', shape=[1], dtype='float32')
    input_length = Input(name='input_length', shape=[1], dtype='int64')
    label_length = Input(name='label_length', shape=[1], dtype='int64')
    loss_out = Lambda(ctc_lambda_func, output_shape=(1,), name="ctc")([output, labels, input_length, label_length])
    model = Model(input=[net_input, labels, input_length, label_length], output=[loss_out])
    model.compile(loss={'ctc': lambda y_true, y_pred: y_pred}, optimizer=optimizer, metrics=[])

    test_func = K.function([net_input], [output])

    return model, test_func
model, test_func = build_model(nb_feat=nb_feat, nb_class=nb_class, optimizer=optimizer)
 for epoch in range(number_epoches):
     inputs_train = {'the_input': X_train[i:i+batch_size],
                    'the_labels': y_train[i:i+batch_size],
                    'input_length': np.sum(X_train_mask[i:i+batch_size], axis=1, dtype=np.int32),
                    'label_length': np.squeeze(y_train_mask[i:i+batch_size]),
                   }
     outputs_train = {'ctc': np.zeros([inputs_train["the_labels"].shape[0]])}

    ctcloss = model.train_on_batch(x=inputs_train, y=outputs_train)

    total_ctcloss += ctcloss * inputs_train["the_input"].shape[0] * 1.
loss_train[epoch] = total_ctcloss / X_train.shape[0]
</code>```

```<code>Here is the my model summary
</code>```

答:
Try the following solution:

```<code>import keras.backend as K

def get_prediction_function(model):
    input_tensor = model.layers[0].input
    output_tensor = model.layers[-5].output
    net_function = K.function([input_tensor, K.learning_phase()], [output_tensor])
    def _result_function(x):
        return net_function([x, 0])[0]
    return _result_function
</code>```

Now your network function might be obtained by:

```<code>test_function = get_prediction_function(model)
</code>```

Body:
I have been working on speech emotion recognition deep neural network. I have used keras Bidirectional LSTM with CTC loss. i trained the model and saved it

model_json = model.to_json()
with open("ctc_model.json", "w") as json_file:
  json_file.write(model_json)
model.save_weights("ctc_weights.h5")

The problem is i can not use this model to test on on unseen data because the model accepts 4 argument as input and calculates the ctc loss..just build the model and train. so how can i save a model in such away that in require only one input. not the labels, and length. Basically how can i save a model as this function test_func = K.function([net_input], [output])

def ctc_lambda_func(args):
    y_pred, labels, input_length, label_length = args

   shift = 2
   y_pred = y_pred[:, shift:, :]
   input_length -= shift
   return K.ctc_batch_cost(labels, y_pred, input_length, label_length)
def build_model(nb_feat, nb_class, optimizer='Adadelta'):
    net_input = Input(name="the_input", shape=(200, nb_feat))
    forward_lstm1  = LSTM(output_dim=64,
                      return_sequences=True,
                      activation="tanh"
                     )(net_input)
    backward_lstm1 = LSTM(output_dim=64,
                      return_sequences=True,
                      activation="tanh",
                      go_backwards=True
                     )(net_input)
    blstm_output1  = Merge(mode='concat')([forward_lstm1, backward_lstm1])

    forward_lstm2  = LSTM(output_dim=64,
                      return_sequences=True,
                      activation="tanh"
                     )(blstm_output1)
    backward_lstm2 = LSTM(output_dim=64,
                      return_sequences=True,
                      activation="tanh",
                      go_backwards=True
                     )(blstm_output1)
    blstm_output2  = Merge(mode='concat')([forward_lstm2, backward_lstm2])

    hidden = TimeDistributed(Dense(512, activation='tanh'))(blstm_output2)
    output = TimeDistributed(Dense(nb_class + 1, activation='softmax')) (hidden)

    labels = Input(name='the_labels', shape=[1], dtype='float32')
    input_length = Input(name='input_length', shape=[1], dtype='int64')
    label_length = Input(name='label_length', shape=[1], dtype='int64')
    loss_out = Lambda(ctc_lambda_func, output_shape=(1,), name="ctc")([output, labels, input_length, label_length])
    model = Model(input=[net_input, labels, input_length, label_length], output=[loss_out])
    model.compile(loss={'ctc': lambda y_true, y_pred: y_pred}, optimizer=optimizer, metrics=[])

    test_func = K.function([net_input], [output])

    return model, test_func
model, test_func = build_model(nb_feat=nb_feat, nb_class=nb_class, optimizer=optimizer)
 for epoch in range(number_epoches):
     inputs_train = {'the_input': X_train[i:i+batch_size],
                    'the_labels': y_train[i:i+batch_size],
                    'input_length': np.sum(X_train_mask[i:i+batch_size], axis=1, dtype=np.int32),
                    'label_length': np.squeeze(y_train_mask[i:i+batch_size]),
                   }
     outputs_train = {'ctc': np.zeros([inputs_train["the_labels"].shape[0]])}

    ctcloss = model.train_on_batch(x=inputs_train, y=outputs_train)

    total_ctcloss += ctcloss * inputs_train["the_input"].shape[0] * 1.
loss_train[epoch] = total_ctcloss / X_train.shape[0]

Here is the my model summary

Body:
Try the following solution:

import keras.backend as K

def get_prediction_function(model):
    input_tensor = model.layers[0].input
    output_tensor = model.layers[-5].output
    net_function = K.function([input_tensor, K.learning_phase()], [output_tensor])
    def _result_function(x):
        return net_function([x, 0])[0]
    return _result_function

Now your network function might be obtained by:

test_function = get_prediction_function(model)


问:
systemd yocto recipe for an existing executable
I'm looking for a template recipe for enabling a systemd recipe in yocto. The executable is already installed by a recipe provided by yocto. The goal of this recipe is to provide make /usr/bin/btattach be run at startup.

As a start I created the following structure in my layer in the appropriate recipe directory:

```<code>btattach-systemd/
|-- files
|   `-- btattach.service
`-- btattach-systemd.bb
</code>```

The content of the recipe

```<code>SUMMARY = "Writes patterns to the fb device"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"

inherit systemd

REQUIRED_DISTRO_FEATURES= "systemd"

SRC_URI = "file://btattach.service"
S = "${WORKDIR}"

do_install () {
    install -m 0644 ${WORKDIR}/btattach.service.service ${D}${sysconfdir}/systemd/system
 }

SYSTEMD_SERVICE_${PN} = "btattach.service"
</code>```

Besides that, the IMAGE_INSTALL in the image recipe has been correctly extended with btattach-systemd.

bitbake btattach-systemd runns ok but when trying to build the complete image the at do_rootfs step for the whole image.   with the error:

```<code> * opkg_solver_install: Cannot install package btattach-systemd.
</code>```

Ideas on where the bug is?

答:
I am sorry for not commenting your question as I have no reputation for that. Also, LetoThe2nd answer is more complete than mine, but here follows a possible quick fix:

It seems to me you are installing 'btattach.service.service' instead of 'btattach.service'.

Body:
I'm looking for a template recipe for enabling a systemd recipe in yocto. The executable is already installed by a recipe provided by yocto. The goal of this recipe is to provide make /usr/bin/btattach be run at startup.

As a start I created the following structure in my layer in the appropriate recipe directory:

btattach-systemd/
|-- files
|   `-- btattach.service
`-- btattach-systemd.bb

The content of the recipe

SUMMARY = "Writes patterns to the fb device"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"

inherit systemd

REQUIRED_DISTRO_FEATURES= "systemd"

SRC_URI = "file://btattach.service"
S = "${WORKDIR}"

do_install () {
    install -m 0644 ${WORKDIR}/btattach.service.service ${D}${sysconfdir}/systemd/system
 }

SYSTEMD_SERVICE_${PN} = "btattach.service"

Besides that, the IMAGE_INSTALL in the image recipe has been correctly extended with btattach-systemd.

bitbake btattach-systemd runns ok but when trying to build the complete image the at do_rootfs step for the whole image.   with the error:

 * opkg_solver_install: Cannot install package btattach-systemd.

Ideas on where the bug is?


问:
datatable th value should come in dropdown as per attached image
Here is my fiddle, I need my th value/text to show in my drop down just like a placeholder.

Here is the image which I want to achieve through my Jquery code.

jsfiddle.net/gkm0L680/1

答:
I have update your fiddle you can check.

you just get title text and added into default option

```<code>var title = $($("#filters").find("th")[column.index()]).text();
var select = $('<select><option value="">'+title+'</option></select>')
</code>```

Body:
I have update your fiddle you can check.

you just get title text and added into default option

var title = $($("#filters").find("th")[column.index()]).text();
var select = $('<select><option value="">'+title+'</option></select>')


问:
How to select an element that depends on another by XPath
I need to build an xpath that returns my element only if dependency is present on the screen.

I'm currently filtering my element using the following snippet:

```<code>//div[contains(text(), 'my element')]
</code>```

...

          dependency

my element

```

答:
```<code>//div[contains(text(), 'my element')][//a[contains(text(), 'dependency')]]
</code>```

Body:
I need to build an xpath that returns my element only if dependency is present on the screen.

I'm currently filtering my element using the following snippet:

//div[contains(text(), 'my element')]

...

          dependency

my element


问:
PHP Foreach inside foreach display data in table row
How can I display data in a tablerow inside a foreach function? The agenda variable works fine, the rows variable is the one making problems, I need it inside a  tag

```<code><?php
$agenda = $days = json_decode(get_field( "field_uc_content_json" ));
unset($agenda[0]); ?>

<table class="table">
    <thead>
        <tr>
          <th> Day </th>
          <th>Description</th>
          <th>Hours</th>
        </tr>
    </thead>
<tbody>
   <?php foreach($agenda as $column) { ?>
   <tr>
    <td><?php echo $column[0]; ?></td>
    <td><?php
    $rows = explode( "\n", $column[1]);
    foreach ($rows as $row) { ?>
    <tr> <?php echo $row; ?> </tr>
    <?php    } ?>
   </td>
</tbody>
</table>
</code>```

The second foreach

vardump agenda

vardump rows

答:
This will do it:

```<code><tbody>
<?php foreach($agenda as $column):
    $rows = explode("\n", $column[1]);?>
    <tr>
        <td rowspan="<?php count($rows) + 1?>"><?php $column[0];?></td>
    </tr>

    <?php foreach($rows as $row): ?>
        <tr>
            <td><?php echo $row ;?></td>
            <td><?php echo $row ;?></td>
        </tr>
    <?php endforeach;

endforeach; ?>
</tbody>
</code>```

As we (and icecub) discussed in the chatroom.

Good luck friend.

Body:
How can I display data in a tablerow inside a foreach function? The agenda variable works fine, the rows variable is the one making problems, I need it inside a  tag

<?php
$agenda = $days = json_decode(get_field( "field_uc_content_json" ));
unset($agenda[0]); ?>

           Day
          Description
          Hours

   <?php foreach($agenda as $column) { ?>

    <?php echo $column[0]; ?>
    <?php
    $rows = explode( "\n", $column[1]);
    foreach ($rows as $row) { ?>

 <?php echo $row; ?>

    <?php    } ?>

The second foreach

vardump agenda

vardump rows

Body:
This will do it:

<tbody>
<?php foreach($agenda as $column):
    $rows = explode("\n", $column[1]);?>
    <tr>
        <td rowspan="<?php count($rows) + 1?>"><?php $column[0];?></td>
    </tr>

    <?php foreach($rows as $row): ?>
        <tr>
            <td><?php echo $row ;?></td>
            <td><?php echo $row ;?></td>
        </tr>
    <?php endforeach;

endforeach; ?>
</tbody>

As we (and icecub) discussed in the chatroom.

Good luck friend.


问:
Is it possible to add image behind doughnut chart with transparency color in ng2chart?
I have the requirement to add image behind ng2 doughnut chart with transparency color, the image will be in doughnut chart  behind the color and not beyond that and not center of doughnut chart. is it possible to do it programtically. it is  single image .
AnyOne help appreciated.

```<code>Here is  plunker demo: https://plnkr.co/edit/lxwEBXQXseUrE6BsHI9h?p=preview
</code>```

chart with transparency:

output be like this:

答:
Background in Highcharts is an SVG element, so if you want to add image background to it you should apply defs pattern:

```<code>events: {
  render: function() {
    var chart = this,
      renderer = chart.renderer,
      bg = chart.plotBackground;

    var pattern = renderer.createElement('pattern').add(renderer.defs).attr({
      width: 1,
      height: 1,
      id: 'bg-pattern',
      patternContentUnits: 'objectBoundingBox'
    });

    renderer.image('https://avatars3.githubusercontent.com/u/15981345?s=400&v=4', 0, 0, 1, 1).attr({}).add(pattern);

    bg.css({
      color: 'url(#bg-pattern)'
    });
  }
}
</code>```

Points opacity can be set via CSS:

```<code>.highcharts-point {
  opacity: 0.5;
}
</code>```

Live demo: http://jsfiddle.net/kkulig/694gs6qv/

Docs reference:
https://www.highcharts.com/docs/chart-design-and-style/gradients-shadows-and-patterns

API reference:

https://api.highcharts.com/highcharts/chart.events.render

https://api.highcharts.com/class-reference/Highcharts.SVGRenderer

Body:
I have the requirement to add image behind ng2 doughnut chart with transparency color, the image will be in doughnut chart  behind the color and not beyond that and not center of doughnut chart. is it possible to do it programtically. it is  single image .
AnyOne help appreciated.

Here is  plunker demo: https://plnkr.co/edit/lxwEBXQXseUrE6BsHI9h?p=preview

chart with transparency:

output be like this:

Body:
Background in Highcharts is an SVG element, so if you want to add image background to it you should apply defs pattern:

events: {
  render: function() {
    var chart = this,
      renderer = chart.renderer,
      bg = chart.plotBackground;

    var pattern = renderer.createElement('pattern').add(renderer.defs).attr({
      width: 1,
      height: 1,
      id: 'bg-pattern',
      patternContentUnits: 'objectBoundingBox'
    });

    renderer.image('https://avatars3.githubusercontent.com/u/15981345?s=400&v=4', 0, 0, 1, 1).attr({}).add(pattern);

    bg.css({
      color: 'url(#bg-pattern)'
    });
  }
}

Points opacity can be set via CSS:

.highcharts-point {
  opacity: 0.5;
}

Live demo: http://jsfiddle.net/kkulig/694gs6qv/

Docs reference:
https://www.highcharts.com/docs/chart-design-and-style/gradients-shadows-and-patterns

API reference:

https://api.highcharts.com/highcharts/chart.events.render

https://api.highcharts.com/class-reference/Highcharts.SVGRenderer


问:
Check variable equality against a list of values
I'm checking a variable, say foo, for equality to a number of values. For example,

```<code>if( foo == 1 || foo == 3 || foo == 12 ) {
    // ...
}
</code>```

The point is that it is rather much code for such a trivial task. I came up with the following:

```<code>if( foo in {1: 1, 3: 1, 12: 1} ) {
    // ...
}
</code>```

but also this does not completely appeal to me, because I have to give redundant values to the items in the object.

Does anyone know a decent way of doing an equality check against multiple values?

答:
You can write if(foo in L(10,20,30)) if you define L to be

```<code>var L = function()
{
    var obj = {};
    for(var i=0; i<arguments.length; i++)
        obj[arguments[i]] = null;

    return obj;
};
</code>```

Body:
I'm checking a variable, say foo, for equality to a number of values. For example,

if( foo == 1 || foo == 3 || foo == 12 ) {
    // ...
}

The point is that it is rather much code for such a trivial task. I came up with the following:

if( foo in {1: 1, 3: 1, 12: 1} ) {
    // ...
}

but also this does not completely appeal to me, because I have to give redundant values to the items in the object.

Does anyone know a decent way of doing an equality check against multiple values?

Body:
You can write if(foo in L(10,20,30)) if you define L to be

var L = function()
{
    var obj = {};
    for(var i=0; i<arguments.length; i++)
        obj[arguments[i]] = null;

    return obj;
};


问:
Thread not working as intended
I am pretty confuse why my program is not working as intended.

I have three similar function:

```<code>static void *L1(void *ptr )
{
    char *text = (char *)ptr;
    int ret;
    int fd = open("/dev/L1", O_RDWR);

    ret = write(fd, text, strlen(Send)); // Send string to LKM
}

static void *L2(void *ptr )
{
    char *text = (char *)ptr;
    int ret;
    int fd = open("/dev/L2", O_RDWR);

    ret = write(fd, text, strlen(Send)); // Send string to LKM
}

static void *L3(void *ptr )
{
    char *text = (char *)ptr;
    int ret;
    int fd = open("/dev/L3", O_RDWR);

    ret = write(fd, text, strlen(Send)); // Send string to LKM
}
</code>```

Next I have a function for creating thread:

```<code>static void createKThread(void* (*a)(void *), void* (*b)(void *), void* (*c)(void *))

{
  pthread_t t1, t2, t3;
  int T1, T2, T3;

  T1 =  pthread_create(&t1, NULL, a, NULL);
  T2 =  pthread_create(&t2, NULL, b, NULL);
  T3 =  pthread_create(&td3, NULL, c, NULL);

  pthread_join(t1, NULL);
  pthread_join(t2, NULL);
  pthread_join(t3, NULL);

}
</code>```

In my main I am doing :

```<code>     int main(){

     Send2[0] = 'a';
     createKThread(L1(&Send[0]), L2(&Send[0]), L3(&Send[0])); //First

     Send2[0] = 'b';
     createKThread(L1(&Send[0]), L2(&Send[0]), L3(&Send[0])); //Second
     return 0;
     }
</code>```

My main program terminates after completion of the first function call `createKThread´. I can't figure out why, I would like the second function call to work and I would like to add more code to my main program. Please advice me on what I am doing wrongly.

答:
You mess up your thread functions.
I assume your functions L1 etc. are supposed to run as thread functions.

```<code>static void *L1(void *ptr )
{
    char *text = (char *)ptr;
    int ret;
    int fd = open("/dev/L1", O_RDWR);

    ret = write(fd, text, strlen(Send)); // Send string to LKM
}
</code>```

Doesn't your compiler shout about missing return value?

When you call your create function, you pass the return values from these functions:

```<code>createKThread(L1(&Send[0]), L2(&Send[0]), L3(&Send[0])); //First
</code>```

Instead of passing the address of the functions, you call them!
As they return random value you create threads with random function addresses.

Title: Thread not working as intended

Body:
I am pretty confuse why my program is not working as intended.

I have three similar function:

static void *L1(void *ptr )
{
    char *text = (char *)ptr;
    int ret;
    int fd = open("/dev/L1", O_RDWR);

    ret = write(fd, text, strlen(Send)); // Send string to LKM
}

static void *L2(void *ptr )
{
    char *text = (char *)ptr;
    int ret;
    int fd = open("/dev/L2", O_RDWR);

    ret = write(fd, text, strlen(Send)); // Send string to LKM
}

static void *L3(void *ptr )
{
    char *text = (char *)ptr;
    int ret;
    int fd = open("/dev/L3", O_RDWR);

    ret = write(fd, text, strlen(Send)); // Send string to LKM
}

Next I have a function for creating thread:

static void createKThread(void* (*a)(void *), void* (*b)(void *), void* (*c)(void *))

{
  pthread_t t1, t2, t3;
  int T1, T2, T3;

  T1 =  pthread_create(&t1, NULL, a, NULL);
  T2 =  pthread_create(&t2, NULL, b, NULL);
  T3 =  pthread_create(&td3, NULL, c, NULL);

  pthread_join(t1, NULL);
  pthread_join(t2, NULL);
  pthread_join(t3, NULL);

}

In my main I am doing :

     int main(){

     Send2[0] = 'a';
     createKThread(L1(&Send[0]), L2(&Send[0]), L3(&Send[0])); //First

     Send2[0] = 'b';
     createKThread(L1(&Send[0]), L2(&Send[0]), L3(&Send[0])); //Second
     return 0;
     }

My main program terminates after completion of the first function call `createKThread´. I can't figure out why, I would like the second function call to work and I would like to add more code to my main program. Please advice me on what I am doing wrongly.

Body:
You mess up your thread functions.
I assume your functions L1 etc. are supposed to run as thread functions.

static void *L1(void *ptr )
{
    char *text = (char *)ptr;
    int ret;
    int fd = open("/dev/L1", O_RDWR);

    ret = write(fd, text, strlen(Send)); // Send string to LKM
}

Doesn't your compiler shout about missing return value?

When you call your create function, you pass the return values from these functions:

createKThread(L1(&Send[0]), L2(&Send[0]), L3(&Send[0])); //First

Instead of passing the address of the functions, you call them!
As they return random value you create threads with random function addresses.


问:
I want use the values in my dict., too calculate - but it doesn't work
I have the following code:

```<code>mydict = {"test1": (2,3), "test2": (1)}

for key,value in mydict.items():
    mydict[key] = 1/(1+value)
print(mydict)
</code>```

But I get this error:

```<code>"TypeError: unsupported operand type(s) for +: 'int' and 'tuple'"
</code>```

The thing that I want is this:

For test1 that contains of two values, I want the following:

```<code>1/(a+1) + 1/(b+1) = 0.5833
</code>```

a and b being the values in the tuple for the corresponding key

```<code>test1 = 0.5833
</code>```

similarly, for test2

```<code>1/(a+1) = 1/2 = 0.5

test2 = 0.5
</code>```

答:
To achieve this you need to iterate through the the tuple. I have amended your code below and added comments of points of interest. Please let me know if this works as expected? </p>

```<code>mydict = {"test1": (2,3 ), "test2": ( 1)}

for key,value  in mydict.items():
    # state the value as 0 to allow iterations to be added to together
    mydict[key] = 0

    # we check if it is a integer
    if not isinstance(value, int):
        #if not an integer we interate through the values
        for x in value:
            # add the value to the total
            mydict[key] += 1/(1+x)

    else:
        mydict[key] = 1/(1+value)
print(mydict)
</code>```

Body:
I have the following code:

mydict = {"test1": (2,3), "test2": (1)}

for key,value in mydict.items():
    mydict[key] = 1/(1+value)
print(mydict)

But I get this error:

"TypeError: unsupported operand type(s) for +: 'int' and 'tuple'"

The thing that I want is this:

For test1 that contains of two values, I want the following:

1/(a+1) + 1/(b+1) = 0.5833

a and b being the values in the tuple for the corresponding key

test1 = 0.5833

similarly, for test2

1/(a+1) = 1/2 = 0.5

test2 = 0.5

Body:
To achieve this you need to iterate through the the tuple. I have amended your code below and added comments of points of interest. Please let me know if this works as expected?

mydict = {"test1": (2,3 ), "test2": ( 1)}

for key,value  in mydict.items():
    # state the value as 0 to allow iterations to be added to together
    mydict[key] = 0

    # we check if it is a integer
    if not isinstance(value, int):
        #if not an integer we interate through the values
        for x in value:
            # add the value to the total
            mydict[key] += 1/(1+x)

    else:
        mydict[key] = 1/(1+value)
print(mydict)


问:
Angular 4 | how can i set a timer and will update my API data?
How can i set timer that will update my API data when the countdown is done, and will back to original countdown when the API data is updated.

Example i want to count to 10 and after that my API data will be updated and so on.

Below is my code with timer.

```<code>import { Component, ViewEncapsulation, Pipe, PipeTransform, VERSION  } from '@angular/core';
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import { SlicePipe, DatePipe } from '@angular/common';
import {Observable} from 'rxjs/Observable'
import 'rxjs/add/observable/timer'
import 'rxjs/add/operator/map'
import 'rxjs/add/operator/take'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  encapsulation: ViewEncapsulation.None,
})

export class AppComponent{

public data: any;
countDown;
counter = 10;

constructor( private http: Http ) {
    this.countDown = Observable.timer(0,1000)
  .take(this.counter)
  .map(() => --this.counter);
}

ngOnInit() {
    this.getVoicepicData();
    this.getData();
    console.log('hi');
}

getData(){
    let headers = new Headers({
        'token': "MY TOKEN GOES HERE",
        'Content-Type': 'application/json'
    });

    let options: RequestOptions = new RequestOptions({ headers: headers });

    return this.http.get('http://my.apidatahere.com/api/', options)
        .map((res: Response) => res.json())
}

getVoicepicData() {
    this.getData().subscribe(data => {
        this.data = data
    })
}
}
</code>```

答:
You can do it like :

```<code>alive = true;

constructor(private appTest : AppTestService) {

    // start calling your api every 10 secs
    Observable.timer(0,10000)
    .takeWhile(() => this.alive) // only fires when component is alive
    .subscribe(() => {
        this.appTest.getData().subscribe(data=> {
           console.log(data);
        })
    });

}

ngOnDestroy(){
    this.alive = false; // switches your Observable off
}
</code>```

Here is the working demo of that, please have a look :

https://stackblitz.com/edit/angular-interval-observable

Body:
How can i set timer that will update my API data when the countdown is done, and will back to original countdown when the API data is updated.

Example i want to count to 10 and after that my API data will be updated and so on.

Below is my code with timer.

import { Component, ViewEncapsulation, Pipe, PipeTransform, VERSION  } from '@angular/core';
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import { SlicePipe, DatePipe } from '@angular/common';
import {Observable} from 'rxjs/Observable'
import 'rxjs/add/observable/timer'
import 'rxjs/add/operator/map'
import 'rxjs/add/operator/take'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  encapsulation: ViewEncapsulation.None,
})

export class AppComponent{

public data: any;
countDown;
counter = 10;

constructor( private http: Http ) {
    this.countDown = Observable.timer(0,1000)
  .take(this.counter)
  .map(() => --this.counter);
}

ngOnInit() {
    this.getVoicepicData();
    this.getData();
    console.log('hi');
}

getData(){
    let headers = new Headers({
        'token': "MY TOKEN GOES HERE",
        'Content-Type': 'application/json'
    });

    let options: RequestOptions = new RequestOptions({ headers: headers });

    return this.http.get('http://my.apidatahere.com/api/', options)
        .map((res: Response) => res.json())
}

getVoicepicData() {
    this.getData().subscribe(data => {
        this.data = data
    })
}
}

Body:
You can do it like :

alive = true;

constructor(private appTest : AppTestService) {

    // start calling your api every 10 secs
    Observable.timer(0,10000)
    .takeWhile(() => this.alive) // only fires when component is alive
    .subscribe(() => {
        this.appTest.getData().subscribe(data=> {
           console.log(data);
        })
    });

}

ngOnDestroy(){
    this.alive = false; // switches your Observable off
}

Here is the working demo of that, please have a look :

https://stackblitz.com/edit/angular-interval-observable


问:
visual studio 2015 IIS Express cannot debug asp.net 4 project
I was working on 2 projects using VS 2013. Recently I had to switch to VS 2015 and opened these projects in the same. One of the 2 project, which is a .net 4.5 framework version project works fine, and I am able to debug in IIS Express.
However, the second project - .net 4.0 project - I cannot debug using IIS express.
When I try to debug I get a 500 error

The configuration section 'system.web.extensions' cannot be read because it is missing a section declaration

I managed to resolve that particular error with help from this stackoverflow link The configuration section 'system.web.extensions' cannot be read because it is missing a section declaration

But still I could not debug as I got another error

Unrecognized attribute 'targetFramework'
  at this line :
  in web.config

I am not able find a solution to this problem. there are some articles which suggest solutions for IIS, but not for IIS Express. I am not able to understand why this happens, as the other project (.net 4.5) works fine, so this is not a problem with IIS express framework config, but project related. I did not make any changes to code whiles moving from vs 2013 to vs 2015. What can I do to debug the code using IIS express in vs2015. preferably by not making changes to web.config as this is working fine on the production server.

答:
First, you remove the targetFramework from the trouble line in the web.config`

IIS Express configuration is stored in an XML file for each solution.
In that file, you can find <applicationPools> section and set their managedRuntimeVersion attribute.

This file is located in your "$(SolutionFolder)\.vs\applicationhost.config". Note that the ".vs" folder is hidden by default.
The file structure is similar to this:

```<code><configuration>
.
.
.

<system.applicationHost>

    <applicationPools>
        <add name="Clr4IntegratedAppPool" managedRuntimeVersion="v4.0" managedPipelineMode="Integrated" CLRConfigFile="%IIS_USER_HOME%\config\aspnet.config" autoStart="true" />
        <add name="Clr4ClassicAppPool" managedRuntimeVersion="v4.0" managedPipelineMode="Classic" CLRConfigFile="%IIS_USER_HOME%\config\aspnet.config" autoStart="true" />
        <add name="Clr2IntegratedAppPool" managedRuntimeVersion="v2.0" managedPipelineMode="Integrated" CLRConfigFile="%IIS_USER_HOME%\config\aspnet.config" autoStart="true" />
        <add name="Clr2ClassicAppPool" managedRuntimeVersion="v2.0" managedPipelineMode="Classic" CLRConfigFile="%IIS_USER_HOME%\config\aspnet.config" autoStart="true" />
        <add name="UnmanagedClassicAppPool" managedRuntimeVersion="" managedPipelineMode="Classic" autoStart="true" />
        <applicationPoolDefaults managedRuntimeLoader="v4.0">
            <processModel />
        </applicationPoolDefaults>
    </applicationPools>

   <sites>
        <site name="WebSite1" id="1" serverAutoStart="true">
            <application path="/" applicationPool="Clr4IntegratedAppPool">
                <virtualDirectory path="/" physicalPath="%IIS_SITES_HOME%\WebSite1" />
            </application>
            <bindings>
                <binding protocol="http" bindingInformation=":8080:localhost" />
            </bindings>
        </site>

.
.
.
</configuration>
</code>```

Body:
First, you remove the targetFramework from the trouble line in the web.config`

IIS Express configuration is stored in an XML file for each solution.
In that file, you can find <applicationPools> section and set their managedRuntimeVersion attribute.

This file is located in your "$(SolutionFolder)\.vs\applicationhost.config". Note that the ".vs" folder is hidden by default.
The file structure is similar to this:

<configuration>
.
.
.

<system.applicationHost>

    <applicationPools>
        <add name="Clr4IntegratedAppPool" managedRuntimeVersion="v4.0" managedPipelineMode="Integrated" CLRConfigFile="%IIS_USER_HOME%\config\aspnet.config" autoStart="true" />
        <add name="Clr4ClassicAppPool" managedRuntimeVersion="v4.0" managedPipelineMode="Classic" CLRConfigFile="%IIS_USER_HOME%\config\aspnet.config" autoStart="true" />
        <add name="Clr2IntegratedAppPool" managedRuntimeVersion="v2.0" managedPipelineMode="Integrated" CLRConfigFile="%IIS_USER_HOME%\config\aspnet.config" autoStart="true" />
        <add name="Clr2ClassicAppPool" managedRuntimeVersion="v2.0" managedPipelineMode="Classic" CLRConfigFile="%IIS_USER_HOME%\config\aspnet.config" autoStart="true" />
        <add name="UnmanagedClassicAppPool" managedRuntimeVersion="" managedPipelineMode="Classic" autoStart="true" />
        <applicationPoolDefaults managedRuntimeLoader="v4.0">
            <processModel />
        </applicationPoolDefaults>
    </applicationPools>

   <sites>
        <site name="WebSite1" id="1" serverAutoStart="true">
            <application path="/" applicationPool="Clr4IntegratedAppPool">
                <virtualDirectory path="/" physicalPath="%IIS_SITES_HOME%\WebSite1" />
            </application>
            <bindings>
                <binding protocol="http" bindingInformation=":8080:localhost" />
            </bindings>
        </site>

.
.
.
</configuration>


问:
(Xamarin.Android) Turn camera picture if the device orientation was landscape
I want to make a Xamarin.Android app where I can capture pictures like the camera...

When I take the picture i have to turn the picture in the correct orientation. So when the orientation was landscape or upside down I want to turn it to portrait...
But I don't know how I can do this.

Here is my code

```<code> private async void TakePhotoButtonTapped(object sender, EventArgs e)
    {
        _camera.StopPreview();

        AlertDialog.Builder builder = new AlertDialog.Builder(activity);

        builder.SetMessage("Search for faces...");
        builder.SetTitle("Warten");

        AlertDialog dialog = builder.Create();

        dialog.Show();

        byte[] imageBytes;

        var image = _textureView.Bitmap;

        using (var imageStream = new MemoryStream())
        {
            await image.CompressAsync(Bitmap.CompressFormat.Jpeg, 50, imageStream);
            image.Recycle();
            imageBytes = imageStream.ToArray();
        }

        var base64image = Convert.ToBase64String(imageBytes);

        FaceRecognition faceRecognition = new FaceRecognition();
        var result = faceRecognition.SendPhoto(base64image);

        dialog.Hide();

        _camera.StartPreview();
    }
</code>```

答:
You could use Android.Content.Res.Orientation to get your device orientation, when the orientation was Landscape, use RequestedOrientation  to  request orientation of the activity.

For example  :

```<code>if (Resources.Configuration.Orientation == Android.Content.Res.Orientation.Landscape)
{
    RequestedOrientation = ScreenOrientation.Portrait;
}
</code>```

Body:
I want to make a Xamarin.Android app where I can capture pictures like the camera...

When I take the picture i have to turn the picture in the correct orientation. So when the orientation was landscape or upside down I want to turn it to portrait...
But I don't know how I can do this.

Here is my code

 private async void TakePhotoButtonTapped(object sender, EventArgs e)
    {
        _camera.StopPreview();

        AlertDialog.Builder builder = new AlertDialog.Builder(activity);

        builder.SetMessage("Search for faces...");
        builder.SetTitle("Warten");

        AlertDialog dialog = builder.Create();

        dialog.Show();

        byte[] imageBytes;

        var image = _textureView.Bitmap;

        using (var imageStream = new MemoryStream())
        {
            await image.CompressAsync(Bitmap.CompressFormat.Jpeg, 50, imageStream);
            image.Recycle();
            imageBytes = imageStream.ToArray();
        }

        var base64image = Convert.ToBase64String(imageBytes);

        FaceRecognition faceRecognition = new FaceRecognition();
        var result = faceRecognition.SendPhoto(base64image);

        dialog.Hide();

        _camera.StartPreview();
    }

Body:
You could use Android.Content.Res.Orientation to get your device orientation, when the orientation was Landscape, use RequestedOrientation  to  request orientation of the activity.

For example  :

if (Resources.Configuration.Orientation == Android.Content.Res.Orientation.Landscape)
{
    RequestedOrientation = ScreenOrientation.Portrait;
}


问:
Swift 3 test if SKSpriteNode subclass of SKNode contains touches
```<code>class MainNode:SKNode {
    class Box: SKSpriteNode {
        override init(texture: SKTexture?, color: UIColor, size: CGSize) {
            super.init(texture: SKTexture(imageNamed: "testIMG1"), color: UIColor.clear, size: CGSize(width: 50, height: 50))
        }
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
    var subclassNode: SKSpriteNode!
    var box = Box()

    convenience init(size: CGSize) {
        self.init()

        box = Box()
        box.position.x = 0

        subclassNode = SKSpriteNode(color: UIColor.red, size: CGSize(width: 40, height: 40))
        subclassNode.position.x =  0
        subclassNode.zPosition = 6

        self.addChild(subclassNode)
    }
}
</code>```

In my class MainNode im trying to test if the SKSpriteNode subclass Box contains the touches in my GameScene

adding

```<code>for touch in touches {
    let location = touch.location(in: self)
    if MainNode.SubclassNode.contains(location) {
        print("Subclass contains touch")
    }
}
</code>```

to either my GameScene class or my MainNode class does not seem to work at all even when SubclassNode.isUserInteractionEnabled = true

how can I determine the if the touch is in my subclass?

答:
I figured it out with some more research and help from KnightOfDragon

I set self.isUserInteractionEnabled = true and then gave my subclassNode a name subclassNode.name = "SubclassNode" then I added this code into my MainNode class

```<code>override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
        let location = touch.location(in: self)
        let touchedNode = self.atPoint(location)
        if let name = touchedNode.name
        {
            if name == "SubclassNode" {
                print("touched Subclass Node")
            }
        }
    }
}
</code>```

Body:
class MainNode:SKNode {
    class Box: SKSpriteNode {
        override init(texture: SKTexture?, color: UIColor, size: CGSize) {
            super.init(texture: SKTexture(imageNamed: "testIMG1"), color: UIColor.clear, size: CGSize(width: 50, height: 50))
        }
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
    var subclassNode: SKSpriteNode!
    var box = Box()

    convenience init(size: CGSize) {
        self.init()

        box = Box()
        box.position.x = 0

        subclassNode = SKSpriteNode(color: UIColor.red, size: CGSize(width: 40, height: 40))
        subclassNode.position.x =  0
        subclassNode.zPosition = 6

        self.addChild(subclassNode)
    }
}

In my class MainNode im trying to test if the SKSpriteNode subclass Box contains the touches in my GameScene

adding

for touch in touches {
    let location = touch.location(in: self)
    if MainNode.SubclassNode.contains(location) {
        print("Subclass contains touch")
    }
}

to either my GameScene class or my MainNode class does not seem to work at all even when SubclassNode.isUserInteractionEnabled = true

how can I determine the if the touch is in my subclass?

Body:
I figured it out with some more research and help from KnightOfDragon

I set self.isUserInteractionEnabled = true and then gave my subclassNode a name subclassNode.name = "SubclassNode" then I added this code into my MainNode class

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
        let location = touch.location(in: self)
        let touchedNode = self.atPoint(location)
        if let name = touchedNode.name
        {
            if name == "SubclassNode" {
                print("touched Subclass Node")
            }
        }
    }
}