问:
how to find the current div based on the scroll position without Jquery
Can someone help me out with this. I found a solution for this in Jquery but we need the solution in plain Javascript or Angular. I guess i'm missing something.fiddle.

When the content on the right panel is scrolled the corresponding left panel should get highlighted. How can we identify the current div element during the scroll to make it active? and that too without using JQuery.

var app = angular.module('app', []);
app.controller('TodoCtrl', ['$scope', '$window', '$element', function($scope, $window, $element) {
  var totalclasses = angular.element(document.querySelector(".section"));
  var offsets = document.getElementById('section3').getBoundingClientRect();

  angular.element($window).bind("scroll", function() {
    angular.forEach(totalclasses, function(value, key) {
    });
  });
}]);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#navigation {
  position: fixed;
  top: 0;
  left: 250px;
}

#sections {
  position: absolute;
  top: 0;
  left: 400px;
}

.section {
  height: 300px;
  margin: 10px;
  padding: 10px;
  border: 1px dashed black;
}

#section5 {
  height: 1000px;
}

.active {
  background: red;
}</code>```

Section 1

Section 2

Section 3

      I'm section 1

      I'm section 2

      I'm section 3

```

答:
i made a solution with plain Javascript ( hope it works for you )

check it below or in fiddle

it's pretty straight forward .

first condition in the IF -> if the document scrollTop value is bigger than the section offsetTop -> then it means the scroll position reached the top border of the section

second condition -> if the document scrollTop value is smaller than section offsetTop + section height it means that the scroll position is still on the section so keep the active class

if these 2 conditions are not met, then the scroll position is not on the section so remove the class active.

let me know if it helps

window.onscroll = function() {

  var section = document.getElementsByClassName("section");

  var bScroll = document.body.scrollTop;
  for (var i = 0; i
 offsets && bScroll < offsets + sHeight) {
      section[i].className = "section active";
    } else {
      section[i].className = "section";
    }

  }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#navigation {
  position: fixed;
  top: 0;
  left: 250px;
}

#sections {
  position: absolute;
  top: 0;
  left: 400px;
}

.section {
  height: 300px;
  margin: 10px;
  padding: 10px;
  border: 1px dashed black;
  transition: 0.3s;
}

#section5 {
  height: 1000px;
}

.active {
  background: red;
}</code>```

Section 1

Section 2

Section 3

    I'm section 1

    I'm section 2

    I'm section 3

```

Body:
Can someone help me out with this. I found a solution for this in Jquery but we need the solution in plain Javascript or Angular. I guess i'm missing something.fiddle.

When the content on the right panel is scrolled the corresponding left panel should get highlighted. How can we identify the current div element during the scroll to make it active? and that too without using JQuery.

var app = angular.module('app', []);
app.controller('TodoCtrl', ['$scope', '$window', '$element', function($scope, $window, $element) {
  var totalclasses = angular.element(document.querySelector(".section"));
  var offsets = document.getElementById('section3').getBoundingClientRect();

  angular.element($window).bind("scroll", function() {
    angular.forEach(totalclasses, function(value, key) {
    });
  });
}]);

#navigation {
  position: fixed;
  top: 0;
  left: 250px;
}

#sections {
  position: absolute;
  top: 0;
  left: 400px;
}

.section {
  height: 300px;
  margin: 10px;
  padding: 10px;
  border: 1px dashed black;
}

#section5 {
  height: 1000px;
}

.active {
  background: red;
}

Section 1

Section 2

Section 3

      I'm section 1

      I'm section 2

      I'm section 3

Body:
i made a solution with plain Javascript ( hope it works for you )

check it below or in fiddle

it's pretty straight forward .

first condition in the IF -> if the document scrollTop value is bigger than the section offsetTop -> then it means the scroll position reached the top border of the section

second condition -> if the document scrollTop value is smaller than section offsetTop + section height it means that the scroll position is still on the section so keep the active class

if these 2 conditions are not met, then the scroll position is not on the section so remove the class active.

let me know if it helps

window.onscroll = function() {

  var section = document.getElementsByClassName("section");

  var bScroll = document.body.scrollTop;
  for (var i = 0; i < section.length; i++) {

    var sHeight = section[i].offsetHeight;
    var offsets = section[i].offsetTop;

    if (bScroll > offsets && bScroll < offsets + sHeight) {
      section[i].className = "section active";
    } else {
      section[i].className = "section";
    }

  }

}

#navigation {
  position: fixed;
  top: 0;
  left: 250px;
}

#sections {
  position: absolute;
  top: 0;
  left: 400px;
}

.section {
  height: 300px;
  margin: 10px;
  padding: 10px;
  border: 1px dashed black;
  transition: 0.3s;
}

#section5 {
  height: 1000px;
}

.active {
  background: red;
}

<div id="navigation">
  <p id="msg">
  </p>
  <ul>
    <li class="section1">Section 1</li>
    <li class="section2">Section 2</li>
    <li id="section3">Section 3</li>
  </ul>
</div>
<div id="sections">
  <div data-id="section1" class="section">
    I'm section 1
  </div>
  <div data-id="section2" class="section">
    I'm section 2
  </div>
  <div data-id="section3" class="section">
    I'm section 3
  </div>

</div>


来源: stackexchange

问:
Debugging source files using chrome extension
I am trying to control the debugger using Chrome Extension.

I am using devtools-protocol and chrome extension documentation, but I have no idea how to implement them as I have not seen any samples of the methods in use. I used the sample extension from here which shows how to pause and resume the debugger only, but that's absolutely no use to me. I tried to implement some methods in the sample, but nothing happens.

```<code>function onDebuggerEnabled(debuggeeId) {
  chrome.debugger.sendCommand(debuggeeId, "Debugger.setBreakpointByUrl", {
        lineNumber: 45825,
        url: 'full https link to the js file from source tab'
  });
}
</code>```

The problem is that the js file I am trying to debug is loaded from the website inside the sources tab and it's huge, we talking 150k+ lines after its been formatted and it takes some time to load.

Now can anyone tell me how to simply add a break point inside the js file from the sources (USING CHROME EXTENSION) so it could be triggered on action which will then stops the debugger so I could change values etc?

答:
EDIT: Just saw your comment about this being for a custom extension you're writing. My answer won't help you (sorry!), but it might help people that come here looking for a way of setting normal breakpoints in Chrome.

Maybe you already did, but... Have you tried just clicking the line number of the line you want to set the breakpoint in?

Like this:

You can even enable or disable breakpoints in several different calls in the same line.

When the page is loaded, open Dev Tools with F12, then navigate to the JS file in the Sources panel, and add the breakpoints you want. Then, refresh the page to load it again -- Chrome will remember where you set the breakpoints and stop at them.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to control the debugger using Chrome Extension.

I am using devtools-protocol and chrome extension documentation, but I have no idea how to implement them as I have not seen any samples of the methods in use. I used the sample extension from here which shows how to pause and resume the debugger only, but that's absolutely no use to me. I tried to implement some methods in the sample, but nothing happens.

function onDebuggerEnabled(debuggeeId) {
  chrome.debugger.sendCommand(debuggeeId, "Debugger.setBreakpointByUrl", {
        lineNumber: 45825,
        url: 'full https link to the js file from source tab'
  });
}

The problem is that the js file I am trying to debug is loaded from the website inside the sources tab and it's huge, we talking 150k+ lines after its been formatted and it takes some time to load.

Now can anyone tell me how to simply add a break point inside the js file from the sources (USING CHROME EXTENSION) so it could be triggered on action which will then stops the debugger so I could change values etc?


问:
Firebase Analytics and Google Tag Manager : <FIRAnalytics/ERROR> Event name is reserved
I integrated Firebase and GTM over cocoapods:

```<code>pod 'Firebase/Core'
pod 'GoogleTagManager', '~> 5.0'
</code>```

Podfile.lock for the versions used :

Firebase/Core (3.12.0):

FirebaseAnalytics (= 3.6.0)

FirebaseCore (= 3.4.7)

FirebaseAnalytics (3.6.0):

FirebaseCore (~> 3.4)

FirebaseInstanceID (~> 1.0)

GoogleInterchangeUtilities (~> 1.2)

GoogleSymbolUtilities (~> 1.1)

GoogleToolboxForMac/NSData+zlib (~> 2.1)

FirebaseCore (3.4.7):

GoogleInterchangeUtilities (~> 1.2)

GoogleSymbolUtilities (~> 1.1)

GoogleToolboxForMac/NSData+zlib (~> 2.1)

FirebaseInstanceID (1.0.8)

GoogleAnalytics (3.17.0)

GoogleInterchangeUtilities (1.2.2):

GoogleSymbolUtilities (~> 1.1)

GoogleSymbolUtilities (1.1.2)

GoogleTagManager (5.0.8):

FirebaseAnalytics (~> 3.0)

GoogleAnalytics (~> 3.0)

GoogleUtilities (~> 1.3.0)

GoogleToolboxForMac/Defines (2.1.1)

GoogleToolboxForMac/NSData+zlib (2.1.1):

GoogleToolboxForMac/Defines (= 2.1.1)

GoogleUtilities (1.3.2):

GoogleSymbolUtilities (~> 1.1)

and followed the steps in documentation for the integration but i am having these warnings :

```<code><FIRAnalytics/ERROR> Event name is reserved. Ignoring event: user_engagement
<FIRAnalytics/ERROR> Event name is reserved. Ignoring event: first_open
</code>```

I know these are reserved events so i am not sending these. Can there an integration problem between GTM and firebase Analytics?

EDIT

I removed the ".json" extension from the config file. Logs said :

```<code>GoogleTagManager warning: No default container found. Container needs to be added to a container folder and added to the target.
Configuration was not found in database. The configuration will be fetched from the network when necessary
Firebase Analytics is ready to receive events
Firebase Analytics enabled
Fetching configuration from the server
Downloading data. Host: https://app-measurement.com/config/app/1:...
Successful fetched configuration from the server. Got network response. Code, size: 200, 106
Successfully parsed a configuration. Version: 1484056.........
Measurement data sent to network
Successful upload. Got network response. Code, size: 204, 0
</code>```

any ideas ???

but errors are gone ???

Any ideas

答: In my case the problem was because of including files in a wrong way. Just be sure to include container folder properly. A tip : folder icon color shall be blue in project navigator.</p>

Body:
I integrated Firebase and GTM over cocoapods:

pod 'Firebase/Core'
pod 'GoogleTagManager', '~> 5.0'

Podfile.lock for the versions used :

Firebase/Core (3.12.0):

FirebaseAnalytics (= 3.6.0)

FirebaseCore (= 3.4.7)

FirebaseAnalytics (3.6.0):

FirebaseCore (~> 3.4)

FirebaseInstanceID (~> 1.0)

GoogleInterchangeUtilities (~> 1.2)

GoogleSymbolUtilities (~> 1.1)

GoogleToolboxForMac/NSData+zlib (~> 2.1)

FirebaseCore (3.4.7):

GoogleInterchangeUtilities (~> 1.2)

GoogleSymbolUtilities (~> 1.1)

GoogleToolboxForMac/NSData+zlib (~> 2.1)

FirebaseInstanceID (1.0.8)

GoogleAnalytics (3.17.0)

GoogleInterchangeUtilities (1.2.2):

GoogleSymbolUtilities (~> 1.1)

GoogleSymbolUtilities (1.1.2)

GoogleTagManager (5.0.8):

FirebaseAnalytics (~> 3.0)

GoogleAnalytics (~> 3.0)

GoogleUtilities (~> 1.3.0)

GoogleToolboxForMac/Defines (2.1.1)

GoogleToolboxForMac/NSData+zlib (2.1.1):

GoogleToolboxForMac/Defines (= 2.1.1)

GoogleUtilities (1.3.2):

GoogleSymbolUtilities (~> 1.1)

and followed the steps in documentation for the integration but i am having these warnings :

<FIRAnalytics/ERROR> Event name is reserved. Ignoring event: user_engagement
<FIRAnalytics/ERROR> Event name is reserved. Ignoring event: first_open

I know these are reserved events so i am not sending these. Can there an integration problem between GTM and firebase Analytics?

EDIT

I removed the ".json" extension from the config file. Logs said :

GoogleTagManager warning: No default container found. Container needs to be added to a container folder and added to the target.
Configuration was not found in database. The configuration will be fetched from the network when necessary
Firebase Analytics is ready to receive events
Firebase Analytics enabled
Fetching configuration from the server
Downloading data. Host: https://app-measurement.com/config/app/1:...
Successful fetched configuration from the server. Got network response. Code, size: 200, 106
Successfully parsed a configuration. Version: 1484056.........
Measurement data sent to network
Successful upload. Got network response. Code, size: 204, 0

any ideas ???

but errors are gone ???

Any ideas


问:
ASP.Net WebApi change this default request method mapping with action name
I am Creating a new Web API Controller named Customer.
and this Controller has one Action named "Create"

I couldn't make this Action able to be requested via "GET" HTTP Request
in this form

http://ip:port/api/Customer/Create?userId=x&password=y

except in this method :

```<code>public class CustomerController : ApiController
{
    [System.Web.Mvc.AcceptVerbs("GET", "POST")]
    [System.Web.Mvc.HttpGet]
    [ActionName("Create")]
    public MISApiResult<List<Branch>> GetCreate(string userID, string password)
    {
        return new MISApiResult<List<Branch>>() { Result = new List<Branch>() { new Branch() { ID = Guid.NewGuid(), Name = "Branch1" } }, ResultCode = 1, ResultMessage = "Sucess" };
    }
}
</code>```

Is there any other solution to preserve the action name as "Create" as next.

```<code>public class CustomerController : ApiController
{
    [System.Web.Mvc.AcceptVerbs("GET", "POST")]
    [System.Web.Mvc.HttpGet]
    public MISApiResult<List<Branch>> Create(string userID, string password)
    {
        return new MISApiResult<List<Branch>>() { Result = new List<Branch>() { new Branch() { ID = Guid.NewGuid(), Name = "Branch1" } }, ResultCode = 1, ResultMessage = "Sucess" };
    }
}
</code>```

Thanks.

Edit:

Sorry for not being clear at the first time.

According to this answer:

How does a method in MVC WebApi map to an http verb?

There is a default http method according to the action names, if it starts with Get it'll bemapped to GET HTTP Method be default otherwise it will be mapped to POST.

Is there a way to change this default mapping with a custom one so I could map an action named "Create" with "GET" Http Method for testing purpose since this way is faster for development

I tried to put HttpGet Attribute and AcceptVerbs("GET") and it still map the action with POST Http method.

I found a way like I said and it's to change the action method name into GetCreate and then put ActionName attribute with "Create" value.
but is there a way to change the default mapping?

Thanks again.

答:
You can use custom route fore this action:

```<code>[HttpGet]
[Route("customer/create")]
public MISApiResult<List<Branch>> Create(string userID, string password)
</code>```

Don't forget to enable attribute routing during application configuration (this should be added before default route definition):

```<code>config.MapHttpAttributeRoutes();
</code>```

Though I would recommend to follow the conventions and use appropriate HTTP verbs - if you are creating a customer, then by convention you should use POST request to endpoint api/customers. Otherwise your API can be confusing for other people.

Also I would recommend to use IHttpActionResult as the return type of your method:

```<code> public IHttpActionResult Post(string userID, string password)
 {
     if (_userRepository.Exists(userID))
         return BadRequest($"User with ID {userID} already exists");

     _userRepository.Create(userID, password);
     return StatusCode(HttpStatusCode.Created) // or CreatedAtRoute
 }
</code>```

Further reading: Attribute Routing in ASP.NET Web API 2

Body:
I am Creating a new Web API Controller named Customer.
and this Controller has one Action named "Create"

I couldn't make this Action able to be requested via "GET" HTTP Request
in this form

http://ip:port/api/Customer/Create?userId=x&password=y

except in this method :

public class CustomerController : ApiController
{
    [System.Web.Mvc.AcceptVerbs("GET", "POST")]
    [System.Web.Mvc.HttpGet]
    [ActionName("Create")]
    public MISApiResult<List<Branch>> GetCreate(string userID, string password)
    {
        return new MISApiResult<List<Branch>>() { Result = new List<Branch>() { new Branch() { ID = Guid.NewGuid(), Name = "Branch1" } }, ResultCode = 1, ResultMessage = "Sucess" };
    }
}

Is there any other solution to preserve the action name as "Create" as next.

public class CustomerController : ApiController
{
    [System.Web.Mvc.AcceptVerbs("GET", "POST")]
    [System.Web.Mvc.HttpGet]
    public MISApiResult<List<Branch>> Create(string userID, string password)
    {
        return new MISApiResult<List<Branch>>() { Result = new List<Branch>() { new Branch() { ID = Guid.NewGuid(), Name = "Branch1" } }, ResultCode = 1, ResultMessage = "Sucess" };
    }
}

Thanks.

Edit:

Sorry for not being clear at the first time.

According to this answer:

How does a method in MVC WebApi map to an http verb?

There is a default http method according to the action names, if it starts with Get it'll bemapped to GET HTTP Method be default otherwise it will be mapped to POST.

Is there a way to change this default mapping with a custom one so I could map an action named "Create" with "GET" Http Method for testing purpose since this way is faster for development

I tried to put HttpGet Attribute and AcceptVerbs("GET") and it still map the action with POST Http method.

I found a way like I said and it's to change the action method name into GetCreate and then put ActionName attribute with "Create" value.
but is there a way to change the default mapping?

Thanks again.

Body:
You can use custom route fore this action:

[HttpGet]
[Route("customer/create")]
public MISApiResult<List<Branch>> Create(string userID, string password)

Don't forget to enable attribute routing during application configuration (this should be added before default route definition):

config.MapHttpAttributeRoutes();

Though I would recommend to follow the conventions and use appropriate HTTP verbs - if you are creating a customer, then by convention you should use POST request to endpoint api/customers. Otherwise your API can be confusing for other people.

Also I would recommend to use IHttpActionResult as the return type of your method:

 public IHttpActionResult Post(string userID, string password)
 {
     if (_userRepository.Exists(userID))
         return BadRequest($"User with ID {userID} already exists");

     _userRepository.Create(userID, password);
     return StatusCode(HttpStatusCode.Created) // or CreatedAtRoute
 }

Further reading: Attribute Routing in ASP.NET Web API 2


问:
How to find a number that isn't there?
We have a custom number field on a training record, the number is recorded sequentially but there are gaps.  How do I find those gaps?  Consider this pseudocode

```<code>SELECT MIN(X)
FROM DUAL
WHERE X BETWEEN 1 AND 999999
  AND X NOT IN (SELECT AG_TRNID
                FROM PS_TRAINING
                WHERE AG_TRNID = X)
</code>```

This doesn't work, "X" is unknown.

Thanks!
Bruce

答:
I think there's no other way besides create a table's id to find the gaps</p>

```<code>declare @idMin bigint
declare @idMax bigint

set @idMin = (select min(AG_TRNID) from PS_TRAINING)
set @idMax = (select max(AG_TRNID) from PS_TRAINING)

create table numbers
(id bigint)

while (@idMax>@idMin)
begin
insert into numbers values(@idMin)

set @idMin=@idMin+1
end

select id from numbers
where id not in (SELECT AG_TRNID FROM PS_TRAINING)
</code>```

Title: How to find a number that isn't there?

Body:
We have a custom number field on a training record, the number is recorded sequentially but there are gaps.  How do I find those gaps?  Consider this pseudocode

SELECT MIN(X)
FROM DUAL
WHERE X BETWEEN 1 AND 999999
  AND X NOT IN (SELECT AG_TRNID
                FROM PS_TRAINING
                WHERE AG_TRNID = X)

This doesn't work, "X" is unknown.

Thanks!
Bruce

Body:
I think there's no other way besides create a table's id to find the gaps

declare @idMin bigint
declare @idMax bigint

set @idMin = (select min(AG_TRNID) from PS_TRAINING)
set @idMax = (select max(AG_TRNID) from PS_TRAINING)

create table numbers
(id bigint)

while (@idMax>@idMin)
begin
insert into numbers values(@idMin)

set @idMin=@idMin+1
end

select id from numbers
where id not in (SELECT AG_TRNID FROM PS_TRAINING)


问:
Unknown error inserting in table in Python 3
I'm trying to do a class to access a database in Sqlite3 in Python 3.
The database was created and when I check if its inserting on the database I get the following error on the second line of the init method:

```<code>File "~/implementacao 2/Dabase_Connection.py", line 16, in __init__
    self.insert_in_database('database_name.db','table_name', '(\'111\',\'qqqq\')')
  File "~/implementacao 2/Dabase_Connection.py", line 33, in insert_in_database
    c.execute('INSERT INTO '+ table_name + ' VALUES ( '+ data +' )')# Insert a row of data
sqlite3.OperationalError: near ",": syntax error
</code>```

The code is this one:

```<code>def __init__(self):
        # self.create_database('database_name.db', 'table_name', 'id TEXT, data TEXT')
        self.insert_in_database('database_name.db','table_name', '(\'111\',\'qqqq\')')
        # self.delete_from_database('database_name.db', 'table_name', 'data1')
        # self.update_in_database('database_name.db','table_name', 'data', 'data_nova', 'data1')
        # self.insert_all_in_database('database_name.db', 'table_name', [('data1','data1'),('data2','data2'),('data3','data3'),('data4','data4')])
        # self.Search_in_database('database_name.db', 'table_name', 'data')

def create_database(self,database_name,table_name,table_args):
    conn = sqlite3.connect(database_name)
    c = conn.cursor()
    c.execute('CREATE TABLE '+ table_name + '(' + table_args + ')')# Create table
    conn.commit() # Save (commit) the changes
    conn.close()# We can also close the connection if we are done with it.

# INSERT INTO prontuarios VALUES(id,prontuario);
def insert_in_database(self,database_name,table_name, data):
    conn = sqlite3.connect(database_name)
    c = conn.cursor()
    c.execute('INSERT INTO '+ table_name + ' VALUES ( '+ data +' )')# Insert a row of data
    conn.commit() # Save (commit) the changes
    conn.close()# We can also close the connection if we are done with it.

def delete_from_database(self,database_name,table_name, chave):
    conn = sqlite3.connect(database_name)
    c = conn.cursor()
    c.execute('DELETE FROM ' + table_name +' WHERE Id= '+ chave +' ; ')# Insert a row of data
    conn.commit() # Save (commit) the changes
    conn.close()# We can also close the connection if we are done with it.

def update_in_database(self,database_name,table_name, table_field, data, chave):
    conn = sqlite3.connect(database_name)
    c = conn.cursor()
    c.execute('UPDATE ' +table_name+ ' SET ' + table_field + ' = ' + data + ' WHERE id = ' + chave+' ;')# Insert a row of data
    conn.commit() # Save (commit) the changes
    conn.close()# We can also close the connection if we are done with it.

# persons = [("Hugo", "Boss"),("Calvin", "Klein")]
# Fill the table conn.executemany("'"insert into person(firstname, lastname) values (?, ?)", persons)

def insert_all_in_database(self,database_name,table_name, data):
    data_interrog = self.get_parameters(data)
    conn = sqlite3.connect(database_name)
    c = conn.cursor()
    c.executemany('insert into ' + table_sifnature + ' values ( '+ data_interrog +' ) ', data)
    conn.commit() # Save (commit) the changes
    conn.close()# We can also close the connection if we are done with it.

def Search_in_database(self,database_name,table_name, fields):
    conn = sqlite3.connect(database_name)
    c = conn.cursor()
    # Print the table contents
    for row in c.execute('select '+ fields + ' from ' +table_name):
        print(row)
</code>```

答:
The issue is your parameter for data, if you print the generated sql, it is not in correct format, it will be:

```<code>INSERT INTO table_name VALUES ( ('111','qqqq') )
</code>```

Change your second line to:

```<code>self.insert_in_database('database_name.db','table_name', '\'111\',\'qqqq\'')
</code>```

or:

```<code>self.insert_in_database('database_name.db','table_name', "\'111\',\'qqqq\'")
</code>```

Body:
I'm trying to do a class to access a database in Sqlite3 in Python 3.
The database was created and when I check if its inserting on the database I get the following error on the second line of the init method:

File "~/implementacao 2/Dabase_Connection.py", line 16, in __init__
    self.insert_in_database('database_name.db','table_name', '(\'111\',\'qqqq\')')
  File "~/implementacao 2/Dabase_Connection.py", line 33, in insert_in_database
    c.execute('INSERT INTO '+ table_name + ' VALUES ( '+ data +' )')# Insert a row of data
sqlite3.OperationalError: near ",": syntax error

The code is this one:

def __init__(self):
        # self.create_database('database_name.db', 'table_name', 'id TEXT, data TEXT')
        self.insert_in_database('database_name.db','table_name', '(\'111\',\'qqqq\')')
        # self.delete_from_database('database_name.db', 'table_name', 'data1')
        # self.update_in_database('database_name.db','table_name', 'data', 'data_nova', 'data1')
        # self.insert_all_in_database('database_name.db', 'table_name', [('data1','data1'),('data2','data2'),('data3','data3'),('data4','data4')])
        # self.Search_in_database('database_name.db', 'table_name', 'data')

def create_database(self,database_name,table_name,table_args):
    conn = sqlite3.connect(database_name)
    c = conn.cursor()
    c.execute('CREATE TABLE '+ table_name + '(' + table_args + ')')# Create table
    conn.commit() # Save (commit) the changes
    conn.close()# We can also close the connection if we are done with it.

# INSERT INTO prontuarios VALUES(id,prontuario);
def insert_in_database(self,database_name,table_name, data):
    conn = sqlite3.connect(database_name)
    c = conn.cursor()
    c.execute('INSERT INTO '+ table_name + ' VALUES ( '+ data +' )')# Insert a row of data
    conn.commit() # Save (commit) the changes
    conn.close()# We can also close the connection if we are done with it.

def delete_from_database(self,database_name,table_name, chave):
    conn = sqlite3.connect(database_name)
    c = conn.cursor()
    c.execute('DELETE FROM ' + table_name +' WHERE Id= '+ chave +' ; ')# Insert a row of data
    conn.commit() # Save (commit) the changes
    conn.close()# We can also close the connection if we are done with it.

def update_in_database(self,database_name,table_name, table_field, data, chave):
    conn = sqlite3.connect(database_name)
    c = conn.cursor()
    c.execute('UPDATE ' +table_name+ ' SET ' + table_field + ' = ' + data + ' WHERE id = ' + chave+' ;')# Insert a row of data
    conn.commit() # Save (commit) the changes
    conn.close()# We can also close the connection if we are done with it.

# persons = [("Hugo", "Boss"),("Calvin", "Klein")]
# Fill the table conn.executemany("'"insert into person(firstname, lastname) values (?, ?)", persons)

def insert_all_in_database(self,database_name,table_name, data):
    data_interrog = self.get_parameters(data)
    conn = sqlite3.connect(database_name)
    c = conn.cursor()
    c.executemany('insert into ' + table_sifnature + ' values ( '+ data_interrog +' ) ', data)
    conn.commit() # Save (commit) the changes
    conn.close()# We can also close the connection if we are done with it.

def Search_in_database(self,database_name,table_name, fields):
    conn = sqlite3.connect(database_name)
    c = conn.cursor()
    # Print the table contents
    for row in c.execute('select '+ fields + ' from ' +table_name):
        print(row)

Body:
The issue is your parameter for data, if you print the generated sql, it is not in correct format, it will be:

INSERT INTO table_name VALUES ( ('111','qqqq') )

Change your second line to:

self.insert_in_database('database_name.db','table_name', '\'111\',\'qqqq\'')

or:

self.insert_in_database('database_name.db','table_name', "\'111\',\'qqqq\'")


问:
Extracting HTML from XML with PHP/SimpleXML
I am trying to extract data from an XML file (the file format is not subject to alteration).  The XML data includes both content and appeareance info, in the form of HTML tags, which are causing me grief.  The relevant part of the XML looks like this:

```<code><item>
    <p>Some text</p>
    <p> Some more text</p>
    <p><i>This</i> is important text.</p>
</item>
</code>```

I need the contents of the  node, as a string (for later insertion into a DB).  The text is always wrapped in
 tags, so I try to iterate over those, using this code:

```<code>$namediscussion = '';

foreach($sectionxml->xpath('//p') as $p)
{
     $namediscussion = $namediscussion . $p . '</br>';

}

echo $namediscussion
</code>```

($sectionxml is the output of ximplexml_load_string() from a parent node).

The problem is that when I echo $namediscussion, what I get is:

```<code>Some text
Some more text
is important text.
</code>```

Note the missing word that was in italics.  How do I preserve this?  I'd prefer to use SimpleXML, but if I have to go to DOM, that's fine too.  Even direct string manipulation would work, but I can't seem to extract the entire string from the SimpleXML node.

Help greatly appreciated.

答:
You are casting simplexmlelement, and this will discard the content of the element children as explained here simplexmlelement::__toString

```<code>Does not return text content that is inside this element's children.
</code>```

To fix the missing word, you can use simplexmlelement::asXML instead of string cast as shown below

```<code>$namediscussion = $namediscussion . strip_tags($p->asXML()) . '</br>';
</code>```

Body:
I am trying to extract data from an XML file (the file format is not subject to alteration).  The XML data includes both content and appeareance info, in the form of HTML tags, which are causing me grief.  The relevant part of the XML looks like this:

<item>

Some text

 Some more text

This is important text.

</item>

I need the contents of the  node, as a string (for later insertion into a DB).  The text is always wrapped in
 tags, so I try to iterate over those, using this code:

$namediscussion = '';

foreach($sectionxml->xpath('//p') as $p)
{
     $namediscussion = $namediscussion . $p . '
';

}

echo $namediscussion

($sectionxml is the output of ximplexml_load_string() from a parent node).

The problem is that when I echo $namediscussion, what I get is:

Some text
Some more text
is important text.

Note the missing word that was in italics.  How do I preserve this?  I'd prefer to use SimpleXML, but if I have to go to DOM, that's fine too.  Even direct string manipulation would work, but I can't seem to extract the entire string from the SimpleXML node.

Help greatly appreciated.

Body:
You are casting simplexmlelement, and this will discard the content of the element children as explained here simplexmlelement::__toString

Does not return text content that is inside this element's children.

To fix the missing word, you can use simplexmlelement::asXML instead of string cast as shown below

$namediscussion = $namediscussion . strip_tags($p->asXML()) . '</br>';


问:
Does Java automatically save an 'evaluate' statement in a predefined Java variable?
Say I perform a simple add/concatenation statement:

```<code>variable + newInput
</code>```

Without setting the calculated value to a new variable, as in:

```<code>variable = variable + newInput
</code>```

or

```<code>variable += newInput
</code>```

Does Java have some sort of specifier to be able to use the computed sum or concatenated string?

Apparently in Python it is automatically saved in the implicit global variable _ -which is implementable like

```<code>Print(_)
</code>```

Is there anything like this in Java?

答:
The statement you show is evaluated and nothing is done with it.  Unless you bind a variable to the result, the evaluation occurs without effect.

This will not be flagged as an error by the compiler.

Body:
Say I perform a simple add/concatenation statement:

variable + newInput

Without setting the calculated value to a new variable, as in:

variable = variable + newInput

or

variable += newInput

Does Java have some sort of specifier to be able to use the computed sum or concatenated string?

Apparently in Python it is automatically saved in the implicit global variable _ -which is implementable like

Print(_)

Is there anything like this in Java?


问:
Converting Kinematics Equations to Matlab
Perhaps this isn't a programming question but a math question. But here goes.

Imagine that you are making a roller coaster powered by a motor on the vehicle. The vehicles have a fixed force value that they can achieve using this motor. In a section of your roller coaster you want to traverse a half loop like this one from one of my favorite video games: Rollercoaster Tycoon!

As you go around the half loop, you don't know what your speed will be or how long it will take you to go around it. However, you can figure out based on your engine acceleration, mass, and acceleration due to gravity what your maximum possible acceleration at any point along the half loop will be. Let's not muddle this discussion up with numbers, but instead assume that we've got the acceleration vs position curve available. It looks something like this:

I have successfully derived the formula for the velocity as a function of the acceleration vs position curve and the initial velocity. From the kinematic equation

```<code>v^2 = 2*a*p
</code>```

I can derive the velocity as a function of position.
v = sqrt(2 * [integral of a=f(p) wrt position])

which in MATLAB I can get by doing:

```<code>v = sqrt(2.*abs(trapz(pos, acc)));
</code>```

I actually am getting the velocity of every point along the track with the following code (acc and pos are arrays of acceleration vs position plotted above):

```<code>vel = 1;
newAcc = 0;
while ix <= length(acc)
    pa = acc(ix-1) + (acc(ix)-acc(ix-1))./2;
    newAP = (pos(ix)-pos(ix-1)).*pa; % This is more time efficient than trapz
    newAcc = newAcc + abs(2.*newAP);
    vel(ix) = sqrt(newAcc);
    ix = ix + 1;
end
</code>```

Now I reach my dilemma. I have acceleration, velocity, and position, and now I need time. I think my math is correct. Since I have a/v/p it should just be as simple as choosing any of the kinematic equations involving time and rearranging it to get time (I want to get the time at every position along the track so I can plot a/v/p as functions of time).

This should mean I can pick from any of these:

```<code>1.  p_f = p_i + v_i*t + 1/2*a*t^2
2.  v_f = v_i + a*t
3.  p = (v_i + v_f)*t/2
</code>```

Equation 1 is a quadratic. The other two look much simpler. Equation 2 looks promising. Let's try that.

```<code>t = (v_f - v_i)/a
</code>```

Converting this to Matlab, I think it should be this:

```<code>time = 0;
while ix <= length(acc)
    pa = acc(ix-1) + (acc(ix)-acc(ix-1))./2;
    newAP = (pos(ix)-pos(ix-1)).*pa; % This is more time efficient than trapz
    newAcc = newAcc + abs(2.*newAP);
    vel(ix) = sqrt(newAcc);

    dt = (vel(ix)-vel(ix-1))./acc(ix);
    time(ix) = time(ix-1) + dt;
    ix = ix + 1;
end
</code>```

But so far from my testing, this produces an incorrect result! I'm stumped on both the math and the algorithm. But I suppose this place is simply to answer the question about the algorithm. I can't see how my formula would be incorrect. Am I converting it in to Matlab incorrectly?

答:
The following code is the solution. I've been sitting on this for awhile, just forgot to answer the question.

while p < pf
    vel(i) = real(sqrt(vel(i-1).^2 + 2 .* ((acc(i)+acc(i-1))./2) .* (pos(i)-pos(i-1)) ));
    time(i) = time(i-1) + (pos(i)-pos(i-1)) ./ ( (vel(i)+vel(i-1))./2 );
    i = i + 1;
end
```

<p>The time function comes from a rearrangement of</p>

```d = (vi+vf)*t/2
```

modified for an array of position values.

Body:
Perhaps this isn't a programming question but a math question. But here goes.

Imagine that you are making a roller coaster powered by a motor on the vehicle. The vehicles have a fixed force value that they can achieve using this motor. In a section of your roller coaster you want to traverse a half loop like this one from one of my favorite video games: Rollercoaster Tycoon!

As you go around the half loop, you don't know what your speed will be or how long it will take you to go around it. However, you can figure out based on your engine acceleration, mass, and acceleration due to gravity what your maximum possible acceleration at any point along the half loop will be. Let's not muddle this discussion up with numbers, but instead assume that we've got the acceleration vs position curve available. It looks something like this:

I have successfully derived the formula for the velocity as a function of the acceleration vs position curve and the initial velocity. From the kinematic equation

v^2 = 2*a*p

I can derive the velocity as a function of position.
v = sqrt(2 * [integral of a=f(p) wrt position])

which in MATLAB I can get by doing:

v = sqrt(2.*abs(trapz(pos, acc)));

I actually am getting the velocity of every point along the track with the following code (acc and pos are arrays of acceleration vs position plotted above):

vel = 1;
newAcc = 0;
while ix <= length(acc)
    pa = acc(ix-1) + (acc(ix)-acc(ix-1))./2;
    newAP = (pos(ix)-pos(ix-1)).*pa; % This is more time efficient than trapz
    newAcc = newAcc + abs(2.*newAP);
    vel(ix) = sqrt(newAcc);
    ix = ix + 1;
end

Now I reach my dilemma. I have acceleration, velocity, and position, and now I need time. I think my math is correct. Since I have a/v/p it should just be as simple as choosing any of the kinematic equations involving time and rearranging it to get time (I want to get the time at every position along the track so I can plot a/v/p as functions of time).

This should mean I can pick from any of these:

1.  p_f = p_i + v_i*t + 1/2*a*t^2
2.  v_f = v_i + a*t
3.  p = (v_i + v_f)*t/2

Equation 1 is a quadratic. The other two look much simpler. Equation 2 looks promising. Let's try that.

t = (v_f - v_i)/a

Converting this to Matlab, I think it should be this:

time = 0;
while ix <= length(acc)
    pa = acc(ix-1) + (acc(ix)-acc(ix-1))./2;
    newAP = (pos(ix)-pos(ix-1)).*pa; % This is more time efficient than trapz
    newAcc = newAcc + abs(2.*newAP);
    vel(ix) = sqrt(newAcc);

    dt = (vel(ix)-vel(ix-1))./acc(ix);
    time(ix) = time(ix-1) + dt;
    ix = ix + 1;
end

But so far from my testing, this produces an incorrect result! I'm stumped on both the math and the algorithm. But I suppose this place is simply to answer the question about the algorithm. I can't see how my formula would be incorrect. Am I converting it in to Matlab incorrectly?

Body:
The following code is the solution. I've been sitting on this for awhile, just forgot to answer the question.

while p < pf
    vel(i) = real(sqrt(vel(i-1).^2 + 2 .* ((acc(i)+acc(i-1))./2) .* (pos(i)-pos(i-1)) ));
    time(i) = time(i-1) + (pos(i)-pos(i-1)) ./ ( (vel(i)+vel(i-1))./2 );
    i = i + 1;
end

The time function comes from a rearrangement of

d = (vi+vf)*t/2

modified for an array of position values.


问:
Typeerror: 'tuple' object is not callable in pygame
When I run this code:

```<code>SURFACER = SURFACEFONT.get_rect()
SURFACER.center(400, (ipnum*100))
</code>```

I get this error:

```<code>File "index.py", line 62, in <module>
    myFunction()
  File "index.py", line 55, in drawGamesToScreen
    SURFACER.center(400, ipnum*100)
TypeError: 'tuple' object is not callable
</code>```

答:
center on a Rect instance returns a tuple, so you can't use .center(x,y) here. Just asign a new tuple, like this:

```<code>SURFACER.center = (400, (ipnum*100))
</code>```

Body:
When I run this code:

SURFACER = SURFACEFONT.get_rect()
SURFACER.center(400, (ipnum*100))

I get this error:

File "index.py", line 62, in <module>
    myFunction()
  File "index.py", line 55, in drawGamesToScreen
    SURFACER.center(400, ipnum*100)
TypeError: 'tuple' object is not callable

Body:
center on a Rect instance returns a tuple, so you can't use .center(x,y) here. Just asign a new tuple, like this:

SURFACER.center = (400, (ipnum*100))


问:
How can I deal with @objc inference deprecation with #selector() in Swift 4?
I'm trying to convert my project's source code from Swift 3 to Swift 4. One warning Xcode is giving me is about my selectors.

For instance, I add a target to a button using a regular selector like this:

```<code>button.addTarget(self, action: #selector(self.myAction), for: .touchUpInside)
</code>```

This is the warning it shows:

Argument of '#selector' refers to instance method 'myAction()' in 'ViewController' that depends on '@objc' attribute inference deprecated in Swift 4

Add '@objc' to expose this instance method to Objective-C

Now, hitting Fix on the error message does this to my function:

```<code>// before
func myAction() { /* ... */ }

// after
@objc func myAction() { /* ... */ }
</code>```

I don't really want to rename all of my functions to include the @objc mark and I'm assuming that's not necessary.

How do I rewrite the selector to deal with the deprecation?

Related question:

The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

答:
The fix-it is correct – there's nothing about the selector you can change in order to make the method it refers to exposed to Objective-C.

The whole reason for this warning in the first place is the result of SE-0160. Prior to Swift 4, internal or higher Objective-C compatible members of NSObject inheriting classes were inferred to be @objc and therefore exposed to Objective-C, therefore allowing them to be called using selectors (as the Obj-C runtime is required in order to lookup the method implementation for a given selector).

However in Swift 4, this is no longer the case. Only very specific declarations are now inferred to be @objc, for example, overrides of @objc methods, implementations of @objc protocol requirements and declarations with attributes that imply @objc, such as @IBOutlet.

The motivation behind this, as detailed in the above linked proposal, is firstly to prevent method overloads in NSObject inheriting classes from colliding with each other due to having identical selectors. Secondly, it helps reduce the binary size by not having to generate thunks for members that don't need to be exposed to Obj-C, and thirdly improves the speed of dynamic linking.

If you want to expose a member to Obj-C, you need to mark it as @objc, for example:

```<code>class ViewController: UIViewController {

    @IBOutlet weak var button: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        button.addTarget(self, action: #selector(foo), for: .touchUpInside)
    }

    <b>@objc</b> func foo() {
       // ...
    }
}</code>```

(the migrator should do this automatically for you with selectors when running with the "minimise inference" option selected)

To expose a group of members to Obj-C, you can use an @objc extension:

```<code>@objc extension ViewController {

    // both exposed to Obj-C
    func foo() {}
    func bar() {}
}
</code>```

This will expose all the members defined in it to Obj-C, and give an error on any members that cannot be exposed to Obj-C (unless explicitly marked as @nonobjc).

If you have a class where you need all Obj-C compatible members to be exposed to Obj-C, you can mark the class as @objcMembers:

```<code>@objcMembers
class ViewController: UIViewController {
   // ...
}
</code>```

Now, all members that can be inferred to be @objc will be. However, I wouldn't advise doing this unless you really need all members exposed to Obj-C, given the above mentioned downsides of having members unnecessarily exposed.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to convert my project's source code from Swift 3 to Swift 4. One warning Xcode is giving me is about my selectors.

For instance, I add a target to a button using a regular selector like this:

button.addTarget(self, action: #selector(self.myAction), for: .touchUpInside)

This is the warning it shows:

Argument of '#selector' refers to instance method 'myAction()' in 'ViewController' that depends on '@objc' attribute inference deprecated in Swift 4

Add '@objc' to expose this instance method to Objective-C

Now, hitting Fix on the error message does this to my function:

// before
func myAction() { /* ... */ }

// after
@objc func myAction() { /* ... */ }

I don't really want to rename all of my functions to include the @objc mark and I'm assuming that's not necessary.

How do I rewrite the selector to deal with the deprecation?

Related question:

The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

Body:
The fix-it is correct – there's nothing about the selector you can change in order to make the method it refers to exposed to Objective-C.

The whole reason for this warning in the first place is the result of SE-0160. Prior to Swift 4, internal or higher Objective-C compatible members of NSObject inheriting classes were inferred to be @objc and therefore exposed to Objective-C, therefore allowing them to be called using selectors (as the Obj-C runtime is required in order to lookup the method implementation for a given selector).

However in Swift 4, this is no longer the case. Only very specific declarations are now inferred to be @objc, for example, overrides of @objc methods, implementations of @objc protocol requirements and declarations with attributes that imply @objc, such as @IBOutlet.

The motivation behind this, as detailed in the above linked proposal, is firstly to prevent method overloads in NSObject inheriting classes from colliding with each other due to having identical selectors. Secondly, it helps reduce the binary size by not having to generate thunks for members that don't need to be exposed to Obj-C, and thirdly improves the speed of dynamic linking.

If you want to expose a member to Obj-C, you need to mark it as @objc, for example:

class ViewController: UIViewController {

    @IBOutlet weak var button: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        button.addTarget(self, action: #selector(foo), for: .touchUpInside)
    }

    @objc func foo() {
       // ...
    }
}

(the migrator should do this automatically for you with selectors when running with the "minimise inference" option selected)

To expose a group of members to Obj-C, you can use an @objc extension:

@objc extension ViewController {

    // both exposed to Obj-C
    func foo() {}
    func bar() {}
}

This will expose all the members defined in it to Obj-C, and give an error on any members that cannot be exposed to Obj-C (unless explicitly marked as @nonobjc).

If you have a class where you need all Obj-C compatible members to be exposed to Obj-C, you can mark the class as @objcMembers:

@objcMembers
class ViewController: UIViewController {
   // ...
}

Now, all members that can be inferred to be @objc will be. However, I wouldn't advise doing this unless you really need all members exposed to Obj-C, given the above mentioned downsides of having members unnecessarily exposed.


问:
How do I Listen events from the toolbar in fragments?
Im Making an App that consist in One activity with a tablayout and a Viewpager, I have 3 tabs where each tab has a fragment. The main activity has a Toolbar with a Swich on it.

The point is that I need listen events changes from this switch in the main activity and the fragments. Actually I called onCreateOptionsMenu and onOptionItemSelected in MainActivity and works but Is possible use this methods in fragments again? o How can I listen events from UI controls in the toolbar from a fragment?

Mi Code is:

MainActivity.java

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
    setSupportActionBar(myToolbar);

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);

    if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
        wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
    }else{
        if(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,Manifest.permission.ACCESS_FINE_LOCATION)){
            Toast.makeText(MainActivity.this,"Debes autorizar los permisos de ubicacion",Toast.LENGTH_SHORT).show();
        }else{
            ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},LOCATION_REQUEST_CODE);
        }
    }

}

private void setupViewPager(ViewPager viewPager){
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new OneFragment(), getString(R.string.tabRedes));
    adapter.addFragment(new TwoFragment(),getString(R.string.tabRedesGuardadas));
    adapter.addFragment(new ThreeFragment(),getString(R.string.tabMapas));
    viewPager.setAdapter(adapter);

}

@Override
public boolean onCreateOptionsMenu(Menu menu){
    getMenuInflater().inflate(R.menu.menuactionbar,menu);
    final SwitchCompat switch1= (SwitchCompat) menu.findItem(R.id.switch_wifi).getActionView().findViewById(R.id.switchForActionBar);

    if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){

        switch1.setChecked(wifiManager.isWifiEnabled());

        if(wifiManager.isWifiEnabled()){
            switch1.setText(R.string.switchOnWifiEs);
        }else {
            switch1.setText(R.string.swtichOffWifiEs);
            //wifiManager.setWifiEnabled(true);
        }

        switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    switch1.setText(R.string.switchOnWifiEs);
                    wifiManager.setWifiEnabled(true);
                    Toast.makeText(MainActivity.this,R.string.switchingOnWifiEs,Toast.LENGTH_SHORT).show();
                }
                else{
                    switch1.setText(R.string.swtichOffWifiEs);
                    wifiManager.setWifiEnabled(false);
                    Toast.makeText(MainActivity.this,R.string.switchingOffWifiEs,Toast.LENGTH_SHORT).show();
                }
            }
        });

    }else{
        if(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,Manifest.permission.ACCESS_FINE_LOCATION)){
            Toast.makeText(MainActivity.this,"Debes autorizar los permisos de ubicacion",Toast.LENGTH_SHORT).show();
        }else{
            ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},LOCATION_REQUEST_CODE);
        }
    }

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item){

    switch (item.getItemId()){
        case R.id.menu_settings:
            Intent nav = new Intent(MainActivity.this,configuracion_Activity.class);
            startActivity(nav);
            return true;
        case R.id.menu_acercade:
            Intent nav2 = new Intent(MainActivity.this,acercade_Activity.class);
            startActivity(nav2);
            return true;
        default:
            Toast.makeText(MainActivity.this,"Estas entrando en e Default",Toast.LENGTH_SHORT).show();
            return super.onOptionsItemSelected(item);
    }
}
</code>```

答:
you should check this out
How to get Toolbar from fragment?

this helped me a long time ago. d:

Body:
Im Making an App that consist in One activity with a tablayout and a Viewpager, I have 3 tabs where each tab has a fragment. The main activity has a Toolbar with a Swich on it.

The point is that I need listen events changes from this switch in the main activity and the fragments. Actually I called onCreateOptionsMenu and onOptionItemSelected in MainActivity and works but Is possible use this methods in fragments again? o How can I listen events from UI controls in the toolbar from a fragment?

Mi Code is:

MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
    setSupportActionBar(myToolbar);

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);

    if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
        wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
    }else{
        if(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,Manifest.permission.ACCESS_FINE_LOCATION)){
            Toast.makeText(MainActivity.this,"Debes autorizar los permisos de ubicacion",Toast.LENGTH_SHORT).show();
        }else{
            ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},LOCATION_REQUEST_CODE);
        }
    }

}

private void setupViewPager(ViewPager viewPager){
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new OneFragment(), getString(R.string.tabRedes));
    adapter.addFragment(new TwoFragment(),getString(R.string.tabRedesGuardadas));
    adapter.addFragment(new ThreeFragment(),getString(R.string.tabMapas));
    viewPager.setAdapter(adapter);

}

@Override
public boolean onCreateOptionsMenu(Menu menu){
    getMenuInflater().inflate(R.menu.menuactionbar,menu);
    final SwitchCompat switch1= (SwitchCompat) menu.findItem(R.id.switch_wifi).getActionView().findViewById(R.id.switchForActionBar);

    if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){

        switch1.setChecked(wifiManager.isWifiEnabled());

        if(wifiManager.isWifiEnabled()){
            switch1.setText(R.string.switchOnWifiEs);
        }else {
            switch1.setText(R.string.swtichOffWifiEs);
            //wifiManager.setWifiEnabled(true);
        }

        switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    switch1.setText(R.string.switchOnWifiEs);
                    wifiManager.setWifiEnabled(true);
                    Toast.makeText(MainActivity.this,R.string.switchingOnWifiEs,Toast.LENGTH_SHORT).show();
                }
                else{
                    switch1.setText(R.string.swtichOffWifiEs);
                    wifiManager.setWifiEnabled(false);
                    Toast.makeText(MainActivity.this,R.string.switchingOffWifiEs,Toast.LENGTH_SHORT).show();
                }
            }
        });

    }else{
        if(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,Manifest.permission.ACCESS_FINE_LOCATION)){
            Toast.makeText(MainActivity.this,"Debes autorizar los permisos de ubicacion",Toast.LENGTH_SHORT).show();
        }else{
            ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},LOCATION_REQUEST_CODE);
        }
    }

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item){

    switch (item.getItemId()){
        case R.id.menu_settings:
            Intent nav = new Intent(MainActivity.this,configuracion_Activity.class);
            startActivity(nav);
            return true;
        case R.id.menu_acercade:
            Intent nav2 = new Intent(MainActivity.this,acercade_Activity.class);
            startActivity(nav2);
            return true;
        default:
            Toast.makeText(MainActivity.this,"Estas entrando en e Default",Toast.LENGTH_SHORT).show();
            return super.onOptionsItemSelected(item);
    }
}


问:
android.content.ActivityNotFoundException: Unable to find explicit activity class when call StartActivity()
From my Package A class, I try to Start Activity in Package B.

It works ok, when I try this way:

```<code>new Intent(getApplicationContext(), ClassB.class);
</code>```

However, when try to create Intent via this way:

```<code>ComponentName componentName = ComponentName.unflattenFromString("com.example.package/.ClassB");
</code>```

It gives error: **android.content.ActivityNotFoundException:** Unable to find explicit activity class {}; have you declared this activity in your AndroidManifest.xml? My problem is need to call it 2nd way only via ComponentName.

Though I have referred to all relevant loops for this question, didn't found solution. Also I have declared ok in my manifest like below (otherwise I suppose it would not have been called via 1st method):

```<code><activity android:name="com.example.package.ClassB"
    android:exported="true"
    android:excludeFromRecents="true" />
</code>```

Please check if possible to help ? Also both package are part of same App.

答:
If everything you wrote in your question is correct, then the application ID of your app is not com.example.package. So, change:

```<code>ComponentName componentName = ComponentName.unflattenFromString("com.example.package/.ClassB");
</code>```

to:

```<code>ComponentName componentName = ComponentName.unflattenFromString("xxx/com.example.package.ClassB");
</code>```

where xxx is the application ID of your app. In particular, the right-hand side of the component name should be the android:name value for the <activity> in the manifest, and the left-hand side should be the application ID of the app. You can always call getComponentName() on an activity to find out its ComponentName (e.g., to log to LogCat to see what it looks like).

Then, reconsider doing any of this. While you write that you "need to call it 2nd way only via ComponentName", I cannot think of any scenario where ComponentName would be a requirement.

For example, suppose that you are saving the string representation of the ComponentName in a file. That is risky, as it means that you can never refactor your app, as otherwise your saved ComponentName values will become invalid. Instead, save something in the file that represents a logical activity, and have application code that maps that value to the proper Java class to use in an explicit Intent.

Body:
From my Package A class, I try to Start Activity in Package B.

It works ok, when I try this way:

new Intent(getApplicationContext(), ClassB.class);

However, when try to create Intent via this way:

ComponentName componentName = ComponentName.unflattenFromString("com.example.package/.ClassB");

It gives error: **android.content.ActivityNotFoundException:** Unable to find explicit activity class {}; have you declared this activity in your AndroidManifest.xml? My problem is need to call it 2nd way only via ComponentName.

Though I have referred to all relevant loops for this question, didn't found solution. Also I have declared ok in my manifest like below (otherwise I suppose it would not have been called via 1st method):

<activity android:name="com.example.package.ClassB"
    android:exported="true"
    android:excludeFromRecents="true" />

Please check if possible to help ? Also both package are part of same App.

Body:
If everything you wrote in your question is correct, then the application ID of your app is not com.example.package. So, change:

ComponentName componentName = ComponentName.unflattenFromString("com.example.package/.ClassB");

to:

ComponentName componentName = ComponentName.unflattenFromString("xxx/com.example.package.ClassB");

where xxx is the application ID of your app. In particular, the right-hand side of the component name should be the android:name value for the <activity> in the manifest, and the left-hand side should be the application ID of the app. You can always call getComponentName() on an activity to find out its ComponentName (e.g., to log to LogCat to see what it looks like).

Then, reconsider doing any of this. While you write that you "need to call it 2nd way only via ComponentName", I cannot think of any scenario where ComponentName would be a requirement.

For example, suppose that you are saving the string representation of the ComponentName in a file. That is risky, as it means that you can never refactor your app, as otherwise your saved ComponentName values will become invalid. Instead, save something in the file that represents a logical activity, and have application code that maps that value to the proper Java class to use in an explicit Intent.


问:
Monitoring ICY Stream Metadata Title (Python)
I would like to continually read the stream and update the title information. (Something like this is posted here: Receive ice cast meta data with python, however it makes multiple requests, and I was looking to just make one stream request. The protocol is described here: http://www.smackfu.com/stuff/programming/shoutcast.html. It seems to only work once then stop working. Here is what I have so far:

```<code>import urllib2
import struct
import re

request = urllib2.Request('http://icy1.abacast.com:80/wbeb-wbebhd2aac-64')
request.add_header('Icy-MetaData','1')
opener = urllib2.build_opener()
data=opener.open(request)

while True:
    audio = data.read(2048) # 2048 is the metadata interval for this stream
    metadata_size = struct.unpack('B', data.read(1))[0]*16
    metadata = data.read(metadata_size).rstrip(b'\0')
    m = re.search(br"StreamTitle='([^']*)';", metadata)
    title = m.group(1).decode('latin1', errors='replace')
    print title
</code>```

I believe the reason why that one doesn't work is that the url is not opened as a stream, is that possible to do with urllib2?

I also have one that doesnt work made with requests.get:

```<code>def monitor():
     url = 'http://icy1.abacast.com:80/wbeb-wbebhd2aac-64'
     r = requests.get(url, headers={'Icy-MetaData': 1}, stream=True)
     metadata = StringIO.StringIO()
     byte_counter = 0
     meta_counter = 0
     metadata_interval = r.headers['icy-metaint']
     metadata_size = 0
     length = None
     data_bool = True
     for data in r.iter_content(1):
        byte_counter+=1
        print "byte %s" % byte_counter
        if (byte_counter <= 2048):
            pass # audio data
        if (byte_counter > 2048):
            if (meta_counter == 0):
                metadata_size = struct.unpack('B', data)[0]*16
                print "METADATA SIZE: %s" % metadata_size
                meta_counter+=1
            elif (meta_counter <= int(metadata_size+1)):
                metadata.write(data)
                meta_counter+=1
            else: data_bool = False
        if (data_bool is False):
            byte_counter = 0
            meta_counter = 0
            meta_interval = 0
            metadata_size = 0
            meta = metadata.read().rstrip(b'\0')
            m = re.search(br"StreamTitle='([^']*)';", meta)
            if m is not None:
                title = m.group(1).decode('latin1', errors='replace')
                print "Title is: %s" % title
            metadata = StringIO.StringIO()
            data_bool = True
</code>```

答:
Not sure if you did already find a way in the meantime. But as I came across the same question - here is my (working but barely tested) version.

Widely based on your suggestion, with some adaptions and python3 support:

```<code>from __future__ import unicode_literals

import re
import requests
import sys

try:
    from StringIO import StringIO as BytesIO
except ImportError:
    from io import BytesIO

def icy_monitor(stream_url, callback=None):

    r = requests.get(stream_url, headers={'Icy-MetaData': '1'}, stream=True)
    if r.encoding is None:
        r.encoding = 'utf-8'

    byte_counter = 0
    meta_counter = 0
    metadata_buffer = BytesIO()

    metadata_size = int(r.headers['icy-metaint']) + 255

    data_is_meta = False

    for byte in r.iter_content(1):

        byte_counter += 1

        if (byte_counter <= 2048):
            pass

        if (byte_counter > 2048):
            if (meta_counter == 0):
                meta_counter += 1

            elif (meta_counter <= int(metadata_size + 1)):

                metadata_buffer.write(byte)
                meta_counter += 1
            else:
                data_is_meta = True

        if (byte_counter > 2048 + metadata_size):
            byte_counter = 0

        if data_is_meta:

            metadata_buffer.seek(0)

            meta = metadata_buffer.read().rstrip(b'\0')

            m = re.search(br"StreamTitle='([^']*)';", bytes(meta))
            if m:
                title = m.group(1).decode(r.encoding, errors='replace')
                print('New title: {}'.format(title))

                if callback:
                    callback(title)

            byte_counter = 0
            meta_counter = 0
            metadata_buffer = BytesIO()

            data_is_meta = False

def print_title(title):
    print('Title: {}'.format(title))

if __name__ == '__main__':

    stream_url = sys.argv[1]
    icy_monitor(stream_url, callback=print_title)
</code>```

Body:
I would like to continually read the stream and update the title information. (Something like this is posted here: Receive ice cast meta data with python, however it makes multiple requests, and I was looking to just make one stream request. The protocol is described here: http://www.smackfu.com/stuff/programming/shoutcast.html. It seems to only work once then stop working. Here is what I have so far:

import urllib2
import struct
import re

request = urllib2.Request('http://icy1.abacast.com:80/wbeb-wbebhd2aac-64')
request.add_header('Icy-MetaData','1')
opener = urllib2.build_opener()
data=opener.open(request)

while True:
    audio = data.read(2048) # 2048 is the metadata interval for this stream
    metadata_size = struct.unpack('B', data.read(1))[0]*16
    metadata = data.read(metadata_size).rstrip(b'\0')
    m = re.search(br"StreamTitle='([^']*)';", metadata)
    title = m.group(1).decode('latin1', errors='replace')
    print title

I believe the reason why that one doesn't work is that the url is not opened as a stream, is that possible to do with urllib2?

I also have one that doesnt work made with requests.get:

def monitor():
     url = 'http://icy1.abacast.com:80/wbeb-wbebhd2aac-64'
     r = requests.get(url, headers={'Icy-MetaData': 1}, stream=True)
     metadata = StringIO.StringIO()
     byte_counter = 0
     meta_counter = 0
     metadata_interval = r.headers['icy-metaint']
     metadata_size = 0
     length = None
     data_bool = True
     for data in r.iter_content(1):
        byte_counter+=1
        print "byte %s" % byte_counter
        if (byte_counter <= 2048):
            pass # audio data
        if (byte_counter > 2048):
            if (meta_counter == 0):
                metadata_size = struct.unpack('B', data)[0]*16
                print "METADATA SIZE: %s" % metadata_size
                meta_counter+=1
            elif (meta_counter <= int(metadata_size+1)):
                metadata.write(data)
                meta_counter+=1
            else: data_bool = False
        if (data_bool is False):
            byte_counter = 0
            meta_counter = 0
            meta_interval = 0
            metadata_size = 0
            meta = metadata.read().rstrip(b'\0')
            m = re.search(br"StreamTitle='([^']*)';", meta)
            if m is not None:
                title = m.group(1).decode('latin1', errors='replace')
                print "Title is: %s" % title
            metadata = StringIO.StringIO()
            data_bool = True

Body:
Not sure if you did already find a way in the meantime. But as I came across the same question - here is my (working but barely tested) version.

Widely based on your suggestion, with some adaptions and python3 support:

from __future__ import unicode_literals

import re
import requests
import sys

try:
    from StringIO import StringIO as BytesIO
except ImportError:
    from io import BytesIO

def icy_monitor(stream_url, callback=None):

    r = requests.get(stream_url, headers={'Icy-MetaData': '1'}, stream=True)
    if r.encoding is None:
        r.encoding = 'utf-8'

    byte_counter = 0
    meta_counter = 0
    metadata_buffer = BytesIO()

    metadata_size = int(r.headers['icy-metaint']) + 255

    data_is_meta = False

    for byte in r.iter_content(1):

        byte_counter += 1

        if (byte_counter <= 2048):
            pass

        if (byte_counter > 2048):
            if (meta_counter == 0):
                meta_counter += 1

            elif (meta_counter <= int(metadata_size + 1)):

                metadata_buffer.write(byte)
                meta_counter += 1
            else:
                data_is_meta = True

        if (byte_counter > 2048 + metadata_size):
            byte_counter = 0

        if data_is_meta:

            metadata_buffer.seek(0)

            meta = metadata_buffer.read().rstrip(b'\0')

            m = re.search(br"StreamTitle='([^']*)';", bytes(meta))
            if m:
                title = m.group(1).decode(r.encoding, errors='replace')
                print('New title: {}'.format(title))

                if callback:
                    callback(title)

            byte_counter = 0
            meta_counter = 0
            metadata_buffer = BytesIO()

            data_is_meta = False

def print_title(title):
    print('Title: {}'.format(title))

if __name__ == '__main__':

    stream_url = sys.argv[1]
    icy_monitor(stream_url, callback=print_title)


问:
How to open "save to android pay" url from android app?
Now I'm in the following situation: our server sends ready-for-use JWT hash for current user card, but there are seems to no way to open "save to android pay" url from android app button: there are only web applications integration tutorial: https://developers.google.com/save-to-android-pay/reference/s2w-reference
So, I have to some way render this html: <g:savetoandroidpay jwt="JWT" onsuccess="successHandler" onfailure="failureHandler" /> into button and handle javascript callbacks from Java.
Or, maybe, there are some another way?

答:
```<code>Uri androidPayUri = Uri.parse("https://www.android.com/payapp/savetoandroidpay/" + jwt);
Intent intent = new Intent(Intent.ACTION_VIEW, androidPayUri);
</code>```

...

Here you can find an example JWT to test:

https://developers.google.com/save-to-android-pay/reference/s2w-reference

Body:
Uri androidPayUri = Uri.parse("https://www.android.com/payapp/savetoandroidpay/" + jwt);
Intent intent = new Intent(Intent.ACTION_VIEW, androidPayUri);

...

Here you can find an example JWT to test:

https://developers.google.com/save-to-android-pay/reference/s2w-reference


答:
why dont you specify route. You actual issue is using System.Web.Mvc
use System.Web.Http instead

```<code> using System.Web.Http;
 [RoutePrefix("api/Customer")]
    public class CustomerController : ApiController
    {
        [HttpGet]
        [Route("Create")]
        public MISApiResult<List<Branch>> Create(string userID, string password)
        {
            return new MISApiResult<List<Branch>>() { Result = new List<Branch>() { new Branch() { ID = Guid.NewGuid(), Name = "Branch1" } }, ResultCode = 1, ResultMessage = "Sucess" };
        }
    }
</code>```

Title: ASP.Net WebApi change this default request method mapping with action name

Body:
I am Creating a new Web API Controller named Customer.
and this Controller has one Action named "Create"

I couldn't make this Action able to be requested via "GET" HTTP Request
in this form

http://ip:port/api/Customer/Create?userId=x&password=y

except in this method :

public class CustomerController : ApiController
{
    [System.Web.Mvc.AcceptVerbs("GET", "POST")]
    [System.Web.Mvc.HttpGet]
    [ActionName("Create")]
    public MISApiResult<List<Branch>> GetCreate(string userID, string password)
    {
        return new MISApiResult<List<Branch>>() { Result = new List<Branch>() { new Branch() { ID = Guid.NewGuid(), Name = "Branch1" } }, ResultCode = 1, ResultMessage = "Sucess" };
    }
}

Is there any other solution to preserve the action name as "Create" as next.

public class CustomerController : ApiController
{
    [System.Web.Mvc.AcceptVerbs("GET", "POST")]
    [System.Web.Mvc.HttpGet]
    public MISApiResult<List<Branch>> Create(string userID, string password)
    {
        return new MISApiResult<List<Branch>>() { Result = new List<Branch>() { new Branch() { ID = Guid.NewGuid(), Name = "Branch1" } }, ResultCode = 1, ResultMessage = "Sucess" };
    }
}

Thanks.

Edit:

Sorry for not being clear at the first time.

According to this answer:

How does a method in MVC WebApi map to an http verb?

There is a default http method according to the action names, if it starts with Get it'll bemapped to GET HTTP Method be default otherwise it will be mapped to POST.

Is there a way to change this default mapping with a custom one so I could map an action named "Create" with "GET" Http Method for testing purpose since this way is faster for development

I tried to put HttpGet Attribute and AcceptVerbs("GET") and it still map the action with POST Http method.

I found a way like I said and it's to change the action method name into GetCreate and then put ActionName attribute with "Create" value.
but is there a way to change the default mapping?

Thanks again.

Body:
why dont you specify route. You actual issue is using System.Web.Mvc
use System.Web.Http instead

 using System.Web.Http;
 [RoutePrefix("api/Customer")]
    public class CustomerController : ApiController
    {
        [HttpGet]
        [Route("Create")]
        public MISApiResult<List<Branch>> Create(string userID, string password)
        {
            return new MISApiResult<List<Branch>>() { Result = new List<Branch>() { new Branch() { ID = Guid.NewGuid(), Name = "Branch1" } }, ResultCode = 1, ResultMessage = "Sucess" };
        }
    }


问:
Design sidebar with border
I have a design in PSD file like that: original design psd

and now, I'm trying convert this design on psd file to html file. This is my result and it isn't look like design: convert to html

答: Make the li and a elements 100% width, display block. give the  a padding of 30px left or so, and then give it a left border of 3px solid transparent. On hover, change the border color to yellow. </p>

Title: Design sidebar with border


问:
Synchronization of C++ Error Log File across thread
Can any one provide a sample code to achieve sync when a particular log file is accessed by multiple threads. I have heard of using a critical section object but not clear on how to use the same.</p>

答:
The details of the implementation will vary depending on which platform (Win32, Posix, ...) you are, and on which library you use (QT, boost, ...). However, the general idea will be the same, as the primitive that you can use have equivalents.

This series of articles should give you a good understanding of the available option on the different platform, and what are the equivalences.

With this you should be able to write a CriticalSection class:

```<code>class CriticalSection
{
    // System specific object

public:
    CriticalSection();
    ~CriticalSection();

    void Lock();
    void Unlock();
};
</code>```

Then, to send data to your log file, you'll acquire the lock, send the data and then release the lock.

```<code>static CriticalSection gLogFileCS;
static std::ofstream*  gLogFilePtr;

void SendLogMessage(const char* message)
{
    gLogFileCS.Lock();
    gLogFilePtr->write(message);
    gLogFileCS.Unlock();
}
</code>```

You should probably use RAII to ensure that you always unlock the CriticalSection when you're done with it. You'll write a CriticalSectionScopeLock class,

```<code>class CriticalSectionScopeLock
{
    CriticalSection& CriticalSection_;

public:
    CriticalSectionScopeLock(CriticalSection& cs)
    : CriticalSection_(cs)
    {
        cs.Lock();
    }

    ~CriticalSectionScopeLock()
    {
        cs.Unlock();
    }
};
</code>```

and then the SendLogMessage function can be rewritten like that:

```<code>void SendLogMessage(const char* message)
{
    CriticalSectionScopeLock lock(gLogFileCS);
    gLogFilePtr->write(message);
}
</code>```

This can be improved by posting message in a queue (you take the lock when pushing in the queue), and then having another thread writing data to the file. This will reduce contention on the lock, as writing to the disk can block the current thread, and it is generally a bad idea to have a thread block while holding a synchronization resource.

```<code>enum MessageType
{
    MessageQuit,
    MessageLog,
};

struct LogThreadMessage
{
    MessageType type;
    char*       data;
};

static CriticalSection gLogThreadQueueCS;
static std::list< LogThreadMessage > gLogThreadQueue;

void StartupLogThread(const char* filename)
{
    // System specific stuff to create a thread, and have
    // it run the LogThreadLoop function.
}

static void LogThreadLoop(std::ostream& logFile)
{
    for (;;)
    {
        std::list< LogThreadMessage > queue;
        {
            CriticalSectionScopeLock lock(gLogThreadQueueCS);
            queue.swap(gLogThreadQueue);
        }

        while (!queue.empty())
        {
            LogThreadMessage msg = queue.front();
            queue.pop_front();

            switch (msg.type)
            {
                case MessageQuit:
                    return;

                case MessageLog:
                    logFile.write(msg.data);
                    break;
            }
        }

        sleep(10);
    }
}

void PostLogThreadMessage(const LogThreadMessage& msg)
{
    CriticalSectionScopeLock lock(gLogThreadQueueCS);
    gLogThreadQueue.insert(gLogThreadQueue.end(), msg);
}

void SendLogMessage(char* message)
{
    LogThreadMessage msg;
    msg.type = MessageLog;
    msg.data = message;

    PostLogThreadMessage(msg);
}

void StopLogThread()
{
    LogThreadMessage msg;
    msg.type = MessageLog;
    msg.data = message;

    PostLogThreadMessage(msg);
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
The details of the implementation will vary depending on which platform (Win32, Posix, ...) you are, and on which library you use (QT, boost, ...). However, the general idea will be the same, as the primitive that you can use have equivalents.

This series of articles should give you a good understanding of the available option on the different platform, and what are the equivalences.

With this you should be able to write a CriticalSection class:

class CriticalSection
{
    // System specific object

public:
    CriticalSection();
    ~CriticalSection();

    void Lock();
    void Unlock();
};

Then, to send data to your log file, you'll acquire the lock, send the data and then release the lock.

static CriticalSection gLogFileCS;
static std::ofstream*  gLogFilePtr;

void SendLogMessage(const char* message)
{
    gLogFileCS.Lock();
    gLogFilePtr->write(message);
    gLogFileCS.Unlock();
}

You should probably use RAII to ensure that you always unlock the CriticalSection when you're done with it. You'll write a CriticalSectionScopeLock class,

class CriticalSectionScopeLock
{
    CriticalSection& CriticalSection_;

public:
    CriticalSectionScopeLock(CriticalSection& cs)
    : CriticalSection_(cs)
    {
        cs.Lock();
    }

    ~CriticalSectionScopeLock()
    {
        cs.Unlock();
    }
};

and then the SendLogMessage function can be rewritten like that:

void SendLogMessage(const char* message)
{
    CriticalSectionScopeLock lock(gLogFileCS);
    gLogFilePtr->write(message);
}

This can be improved by posting message in a queue (you take the lock when pushing in the queue), and then having another thread writing data to the file. This will reduce contention on the lock, as writing to the disk can block the current thread, and it is generally a bad idea to have a thread block while holding a synchronization resource.

enum MessageType
{
    MessageQuit,
    MessageLog,
};

struct LogThreadMessage
{
    MessageType type;
    char*       data;
};

static CriticalSection gLogThreadQueueCS;
static std::list< LogThreadMessage > gLogThreadQueue;

void StartupLogThread(const char* filename)
{
    // System specific stuff to create a thread, and have
    // it run the LogThreadLoop function.
}

static void LogThreadLoop(std::ostream& logFile)
{
    for (;;)
    {
        std::list< LogThreadMessage > queue;
        {
            CriticalSectionScopeLock lock(gLogThreadQueueCS);
            queue.swap(gLogThreadQueue);
        }

        while (!queue.empty())
        {
            LogThreadMessage msg = queue.front();
            queue.pop_front();

            switch (msg.type)
            {
                case MessageQuit:
                    return;

                case MessageLog:
                    logFile.write(msg.data);
                    break;
            }
        }

        sleep(10);
    }
}

void PostLogThreadMessage(const LogThreadMessage& msg)
{
    CriticalSectionScopeLock lock(gLogThreadQueueCS);
    gLogThreadQueue.insert(gLogThreadQueue.end(), msg);
}

void SendLogMessage(char* message)
{
    LogThreadMessage msg;
    msg.type = MessageLog;
    msg.data = message;

    PostLogThreadMessage(msg);
}

void StopLogThread()
{
    LogThreadMessage msg;
    msg.type = MessageLog;
    msg.data = message;

    PostLogThreadMessage(msg);
}


问:
Python `ctypes` - How to copy buffer returned by C function into a bytearray
A pointer to buffer of type POINTER(c_ubyte) is returned by the C function (the image_data variable in the following code). I want this data to be managed by Python, so I want to copy it into a bytearray. Here's the function call

```<code>image_data = stb_image.stbi_load(filename_cstr, byref(width),
                                 byref(height), byref(num_channels),
                                 c_int(expected_num_channels))
</code>```

We get to know the width and height of the image only after that call, so can't pre-allocate a bytearray.

I would have used

```<code> array_type = c.c_ubyte * (num_channels.value * width.value * height.value)

 image_data_bytearray = bytearray(cast(image_data, array_type))
</code>```

But the type to cast to must be a pointer, not array, so I get an error.

```<code>TypeError: cast() argument 2 must be a pointer type, not c_ubyte_Array_262144
</code>```

What should I do?

答:
Your variable array_type shouldn't even be called thus as it is in fact not an initialized C array nor any kind of type, but a Python object prepared for doing the array initialization.
Well, initialized array also shouldn't be called thus as well. :D

You should be doing there an equivalent of:

```<code>unsigned char array[channels*width*height];
</code>```

in C. Then array is a pointer to N*types unsigned char pointing to first byte of the array. (index 0)
A cast() should get a pointer to see the data's type,. So doing:

```<code>array = (c.c_ubyte*(channels*width*height))()
</code>```

should do the trick. But you don't need extra allocated memory. So you can create a pointer as suggested in a comment.

But I suggest you use:

```<code>image_data = bytearray(c.string_at(image_data))
</code>```

It should work, assuming, of course, that returned image is null terminated. Well, this also implies using signed chars but it doesn't have to be.
If you wrote the C portion, just allocate one byte extra to the memory that will contain an image which is declared/cast to contain unsigned chars and put the last item to 0.
Then leave the algorithm to work as before. If you do not null terminate it, you will still get the whole image with string_at(), but there will be a memory leak of 3 bytes or so more. Very undesirable.

I used this trick in my C module for colorspace conversion. It works extremely fast as there are no loops, No anything extra. string_at() just pulls in the buffer and creates Python string wrapper around it.
Then you can use numpy.fromstring(...) or array.array("B", image_data) or use bytearray() as above  etc.

Otherwise, well, I saw your answer just now. You can do it as you wrote as well, but I think that my dirty trick is better (if you can change the C code, of course).

P.S. Whoops! I just saw in a doc string that string_at() can have an optional argument size. Perhaps using it will completely ignore the termination and there wouldn't be any leakage. I am asking myself now why didn't I use it in my project but messed with null termination.
Perhaps out of lazyness. Using size shouldn't require any modifications to C code. So it would be:

```<code>image_data = bytearray(c.string_at(image_data, channels*width*height))
</code>```

Body:
A pointer to buffer of type POINTER(c_ubyte) is returned by the C function (the image_data variable in the following code). I want this data to be managed by Python, so I want to copy it into a bytearray. Here's the function call

image_data = stb_image.stbi_load(filename_cstr, byref(width),
                                 byref(height), byref(num_channels),
                                 c_int(expected_num_channels))

We get to know the width and height of the image only after that call, so can't pre-allocate a bytearray.

I would have used

 array_type = c.c_ubyte * (num_channels.value * width.value * height.value)

 image_data_bytearray = bytearray(cast(image_data, array_type))

But the type to cast to must be a pointer, not array, so I get an error.

TypeError: cast() argument 2 must be a pointer type, not c_ubyte_Array_262144

What should I do?

Body:
Your variable array_type shouldn't even be called thus as it is in fact not an initialized C array nor any kind of type, but a Python object prepared for doing the array initialization.
Well, initialized array also shouldn't be called thus as well. :D

You should be doing there an equivalent of:

unsigned char array[channels*width*height];

in C. Then array is a pointer to N*types unsigned char pointing to first byte of the array. (index 0)
A cast() should get a pointer to see the data's type,. So doing:

array = (c.c_ubyte*(channels*width*height))()

should do the trick. But you don't need extra allocated memory. So you can create a pointer as suggested in a comment.

But I suggest you use:

image_data = bytearray(c.string_at(image_data))

It should work, assuming, of course, that returned image is null terminated. Well, this also implies using signed chars but it doesn't have to be.
If you wrote the C portion, just allocate one byte extra to the memory that will contain an image which is declared/cast to contain unsigned chars and put the last item to 0.
Then leave the algorithm to work as before. If you do not null terminate it, you will still get the whole image with string_at(), but there will be a memory leak of 3 bytes or so more. Very undesirable.

I used this trick in my C module for colorspace conversion. It works extremely fast as there are no loops, No anything extra. string_at() just pulls in the buffer and creates Python string wrapper around it.
Then you can use numpy.fromstring(...) or array.array("B", image_data) or use bytearray() as above  etc.

Otherwise, well, I saw your answer just now. You can do it as you wrote as well, but I think that my dirty trick is better (if you can change the C code, of course).

P.S. Whoops! I just saw in a doc string that string_at() can have an optional argument size. Perhaps using it will completely ignore the termination and there wouldn't be any leakage. I am asking myself now why didn't I use it in my project but messed with null termination.
Perhaps out of lazyness. Using size shouldn't require any modifications to C code. So it would be:

image_data = bytearray(c.string_at(image_data, channels*width*height))


问:
URL Rewrite with parameter and php query
Directories:
 eventfinder is project folder

Localhost

-- project1

-- project2

-- eventfinder

--- .htaccess

User comes to the page http://localhost/eventfinder/ and types 'randomevent123' after /eventfinder/

then php query happens with ?event=randomevent123

```<code>$event = $_GET['event'];

$stmt = $conn->prepare("SELECT * FROM events WHERE name = :name");
$stmt->bindParam(":name", $event);
$stmt->execute();
</code>```

and returns data from database

I am trying to rewrite my url but I don't understand what is the problem...

```<code>http://localhost/eventfinder/index.php?event=randomevent123
</code>```

to

```<code>http://localhost/eventfinder/randomevent123
</code>```

With .htaccess

```<code>RewriteEngine On
RewriteRule ^([^/]*)$ /index.php?event=$1 [L]
</code>```

But query won't work.

答:
```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ /eventfinder/index.php?event=$1 [L]
</code>```

You can us !-f and !-d checks on the requested filename to ensure that the URL that's being typed is not a file and not a directory before doing the rewrite itself - it prevents a recursive loop on index.php

Body:
Directories:
 eventfinder is project folder

Localhost

-- project1

-- project2

-- eventfinder

--- .htaccess

User comes to the page http://localhost/eventfinder/ and types 'randomevent123' after /eventfinder/

then php query happens with ?event=randomevent123

$event = $_GET['event'];

$stmt = $conn->prepare("SELECT * FROM events WHERE name = :name");
$stmt->bindParam(":name", $event);
$stmt->execute();

and returns data from database

I am trying to rewrite my url but I don't understand what is the problem...

http://localhost/eventfinder/index.php?event=randomevent123

to

http://localhost/eventfinder/randomevent123

With .htaccess

RewriteEngine On
RewriteRule ^([^/]*)$ /index.php?event=$1 [L]

But query won't work.

Body:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ /eventfinder/index.php?event=$1 [L]

You can us !-f and !-d checks on the requested filename to ensure that the URL that's being typed is not a file and not a directory before doing the rewrite itself - it prevents a recursive loop on index.php


问:
minDate and maxDate options are not working in datepicker
I'm using the "datepicker" plugin on my project, it's set to decade view, and I want to disable the future dates, for this I have used the maxDate option but it's not working, my code:

$('#data_1 .input-group.date').datepicker({
    todayBtn: "linked",
    maxDate: "0",
    keyboardNavigation: false,
    forceParse: false,
    calendarWeeks: true,
    autoclose: true
});
```

tried with 0 and new Date

答:
Try below code:

```<code>var today = new Date();
$('#data_1 .input-group.date').datepicker({
            todayBtn: "linked",
            endDate: "today",
            maxDate: today
            keyboardNavigation: false,
            forceParse: false,
            calendarWeeks: true,
            autoclose: true
        });
</code>```

Also you can try with:

```<code> maxDate: 0
</code>```

Body:
I'm using the "datepicker" plugin on my project, it's set to decade view, and I want to disable the future dates, for this I have used the maxDate option but it's not working, my code:

$('#data_1 .input-group.date').datepicker({
    todayBtn: "linked",
    maxDate: "0",
    keyboardNavigation: false,
    forceParse: false,
    calendarWeeks: true,
    autoclose: true
});

tried with 0 and new Date

Body:
Try below code:

var today = new Date();
$('#data_1 .input-group.date').datepicker({
            todayBtn: "linked",
            endDate: "today",
            maxDate: today
            keyboardNavigation: false,
            forceParse: false,
            calendarWeeks: true,
            autoclose: true
        });

Also you can try with:

 maxDate: 0


问:
Coupon not getting applied?
I have created promotion through backoffice but coupon is not getting applied on percentage discount for products. Its showing something like coupon code entered is no longer valid. I have attached image also. Any suggestion?

答:
I advise you to check that you performed all steps in the hybris instruction: Creating Single-Code Coupon

In short, coupon creation is not enough. You need to:

Setup promotion rule to use that coupon

Publish promotion rule

Verify that coupon status is active

Title: Coupon not getting applied?


问:
ForEach() : Why can't use break/continue inside
Since ForEach() method loop through all list members, Why can't I use a break/continue clause while I can use them inside a normal foreach loop

```<code>lstTemp.ForEach(i=>
 {
   if (i == 3)
   break;
   //do sth
 }
);
</code>```

Error:

"No enclosing loop out of which to
break or continue"

答: Because you delegate an action for each item in the list.</p>

Body:
Since ForEach() method loop through all list members, Why can't I use a break/continue clause while I can use them inside a normal foreach loop

lstTemp.ForEach(i=>
 {
   if (i == 3)
   break;
   //do sth
 }
);

Error:

"No enclosing loop out of which to
break or continue"