text:
Q: STM32-RTC counts the time wrong With the following clock setup:

RTC counts the clock incorrectly.
The LSE frequency I use is 32.768kHz.
The clock goes 30 seconds a day.
Normally, the RTC shows 12:30:30 when it is normally 12:30:00.
Is this from the hardware or is it from the software?
The software section looks like this:
void vRTCInit(void)
{
  hrtc.Instance = RTC;
  hrtc.Init.HourFormat = RTC_HOURFORMAT_24/*RTC_HOURFORMAT_12*/;
  hrtc.Init.AsynchPrediv = 127;
  hrtc.Init.SynchPrediv = 255;
  hrtc.Init.OutPut = RTC_OUTPUT_DISABLE;
  hrtc.Init.OutPutRemap = RTC_OUTPUT_REMAP_NONE;
  hrtc.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
  hrtc.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN;
  if (HAL_RTC_Init(&hrtc) != HAL_OK)
  {
    Error_Handler();
  }

}

My system clock setups are as follows:
void SystemClock_Config(void)
{

  RCC_OscInitTypeDef RCC_OscInitStruct;
  RCC_ClkInitTypeDef RCC_ClkInitStruct;
  RCC_PeriphCLKInitTypeDef PeriphClkInit;

  /**Initializes the CPU, AHB and APB busses clocks
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_LSI
                                     | RCC_OSCILLATORTYPE_LSE | RCC_OSCILLATORTYPE_MSI;
  RCC_OscInitStruct.LSEState = RCC_LSE_ON;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = 16;
  RCC_OscInitStruct.LSIState = RCC_LSI_ON;
  RCC_OscInitStruct.MSIState = RCC_MSI_ON;
  RCC_OscInitStruct.MSICalibrationValue = 0;
  RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_6;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /**Initializes the CPU, AHB and APB busses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK
                                | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV16;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
  {
    Error_Handler();
  }

  PeriphClkInit.PeriphClockSelection =  RCC_PERIPHCLK_RTC | RCC_PERIPHCLK_LPTIM1
                                        | RCC_PERIPHCLK_ADC;
  PeriphClkInit.Lptim1ClockSelection = RCC_LPTIM1CLKSOURCE_LSE;
  PeriphClkInit.AdcClockSelection = RCC_ADCCLKSOURCE_SYSCLK;
  PeriphClkInit.RTCClockSelection = RCC_RTCCLKSOURCE_LSE;//LSE
  if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
  {
    Error_Handler();
  }

  /**Configure LSE Drive Capability
  */
  __HAL_RCC_LSEDRIVE_CONFIG(RCC_LSEDRIVE_LOW );

  /**Configure the main internal regulator output voltage
  */
  if (HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1) != HAL_OK)
  {
    Error_Handler();
  }

  /**Configure the Systick interrupt time
  */
  HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq() / 1000);

  /**Configure the Systick
  */
  HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);

  /**Enable MSI Auto calibration
  */
  HAL_RCCEx_EnableMSIPLLMode();

  /* SysTick_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(SysTick_IRQn, 15, 0);
}

If you notice, I set the RTC clock to LSE.


text:
Q: Algorithm for searching landscape of 2D "room" for obstacles I've done the usual google searching for an algorithm that describes this problem, but without much luck. The problem is as follows:
You're dropped off at a random point in a room, and expected to traverse the room and find all of the obstacles that lay within the room, marking them, and then moving on to find other obstacles. You can move in the 4 cardinal directions, but you can sense the environment around you in 8 directions (N, S, W, E, NW, SW, SE, NE). You also cannot remember locations you have visited previously.
Does anyone know the name of that problem or an algorithm to help solve it? Thanks!
An example of the room might look something like this:
UUUUUUUUUUUUUUUUUUUUU
U                   U
U                   U
U                   U
U       UUUUU       U
U       U   U       U
U       UUUUU       U
U                   U
U    UUUUUU         U
U    U    U         U
U    UUU  U         U
U      U  U         U
U    UUU  U         U
U    U    U         U
U    UUUUUU         U
U                   U
UUUUUUUUUUUUUUUUUUUUU

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unit test - test a method of a class I created a unit test file for testing the method part_firstname_lastname. I'm using PyCharm. When I run the test_person.py there's no error. The test is a success.
When I run the file in the command line by using  python test_person.py -v, the error is :

from School.person import Personne ModuleNotFoundError: No module
  named 'School'
  Blockquote

In the pycharm I don't have any errors, the import is good.
School is a package inside that I have the file person.py. The file test_person.py is in another package named Unit_Test
1- How can i solve it ?
2- Must i use Mock for that ?
class Person:

def __init__(self, first, last):
    self.__code = 0
    self.__firstname = first
    self.__lastname = last

def __str__(self):
    return self.firstname + ' ' + self.lastname

@property
def firstname(self):
    return self.__firstname

@firstname.setter
def firstname(self, value):
    self.__firstname = value

@property
def lastname(self):
    return self.__lastname

@lastname.setter
def lastname(self, value):
    self.__lastname = value

@staticmethod
def part_firstname_lastname(data):
    """
    This method take a part of the data
    @param : str : data
    :return: str : part of the data entered
    """
    if len(data) > 3:
        return data[0:3].upper()
    return data[0:1].upper()

test_person.py
    import unittest
from School.person import Person

class test_person(unittest.TestCase):
    def test_code_personne(self):

        p1 = Personne('Callier', 'John')
        p1.part_firstname_lastname(p1.firstname)
        self.assertEqual(p1.part_firstname_lastname(p1.firstname), 'CAD')

if __name__ == '__main__':
    unittest.main()

A: The correct way is to update the PYTHONPATH to contain the folder containing the School package.
It can be done at different level:

*

*inside a tool or framework that will actually launch the test (that is the way PyCharm works)

*change the PYTHONPATH environment variable from the command line before executing the test (syntax will depend of the OS and shell)

*change the sys.path system list directly from the test_person.py file before importing School - beware it is a rather intrusive way

*change the sys.path system list from a package containing the test_person.py. It can be a handy way if you always use a full test package


text:
Q: Bluetooth not working: Intel Wireless AC and Ubuntu 20.04 Bluetooth toggle does nothing:

sudo bluetoothctl:
Agent registered
[bluetooth]# connect f
No default controller available

rfkill:
ID TYPE      DEVICE      SOFT      HARD
 0 wlan      phy0   unblocked unblocked
 1 bluetooth hci0   unblocked unblocked

sudo systemctl status bluetooth:
● bluetooth.service - Bluetooth service
     Loaded: loaded (/lib/systemd/system/bluetooth.service; enabled; vendor preset: enabled)
     Active: active (running) since Sun 2020-09-20 19:24:38 IST; 35min ago
       Docs: man:bluetoothd(8)
   Main PID: 976 (bluetoothd)
     Status: "Running"
      Tasks: 1 (limit: 9351)
     Memory: 2.3M
     CGroup: /system.slice/bluetooth.service
             └─976 /usr/lib/bluetooth/bluetoothd

Sep 20 19:24:32 HP-Pavilion systemd[1]: Starting Bluetooth service...
Sep 20 19:24:32 HP-Pavilion bluetoothd[976]: Bluetooth daemon 5.53
Sep 20 19:24:38 HP-Pavilion systemd[1]: Started Bluetooth service.
Sep 20 19:24:39 HP-Pavilion bluetoothd[976]: Starting SDP server
Sep 20 19:24:39 HP-Pavilion bluetoothd[976]: Bluetooth management interface 1.14 initialized


text:
Q: What is the best way to build a model of automated system with neural network in Simulink (Matlab)? I'm tring to build a model contating neural network in Simulink.
My idea is to compose a model which includes a controlled object (electrical drive), PID controller and NN block for fine-tuning of the PID controller.
NN training is provided for to be the reinforcement learning. NN calculates the koefficients of the PID controller, then it receives the feedback from the output of the object and calcucales the koefficients for the next cycle to minimize the static error.
I've build the model without NN successfully.
Now I'm triyng to add the NN block, and it puts me getting in stuck.
1). What type of block should I use to create NN? Are there pre-set blocks in Simulink for NN (in which I have to only set number of layers and neurons and finctions of activation and loss?) Or the only way is to build NN from zero?
2). As I know variables in workspace are updated only after end of modeling. If I want to change parameters of a block in runtime I need to use S-function block and 'set_param' function in it. So is it the only way to transfer object output to NN block? Or may be there a possibility for automative transfer in runtime (like between PID controller and controlled object)?
Or may be someone has a better concept for making such a model in Simulink (or even in another Matlab toolbox)?
Any thoughts and links appiriciate. Thanks in advance.
P.S. Model of the drive I took from http://pnu.edu.ru/media/ejournal/articles-2017/TGU_8_217.pdf


text:
Q: Rubocop throwing issue on Date.strftime Iam trying to format a date with MONTH and YEAR format. But rubocop throws error as

Prefer annotated tokens (like %s) over unannotated tokens in below line.

Date.parse(event.available_date).strftime('%B %Y')

Any idea??

A: As per the discussion here https://github.com/rubocop-hq/rubocop/issues/5223 they have fixed the issue.
If the latest released version has the patch then you shouldn't be seeing the error after upgrading Rubocop.


text:
Q: LDAP Active Directory Login via MVC 4 I am having real troubles verifying the user.
There are two scenarios for who is logging in:

*

*User is registered on the domain.

*User is an external client.
And two scenarios for access:

*

*User is on the domain

*User is on an external PC.
So what I am hoping to do is:

*

*grab the users windows login, and attempt login via LDAP verification.

*If this fails, they are either not registered on domain, or not on a domain PC. So a form would come up to type in info.

*The form would then check against LDAP (registered user), else against the sites DB (external user).
Ive tried a few guides, and an intranet application. All that is doing is throwing my username onto screen. Regardless of anything. I have no idea how to verify it aagainst anything as I cant find ANY code relating to it.

A: It is impossible to configure your site to implement both Windows authentication and Forms authentication.
You should deploy your application twice.

*

*Once for AD authorization which will pass through if your user is logged on.

*The other for form authentication and provide a login box.

Be sure to set the corresponding authorization options in your IIS manager.
You can choose to only implement forms authentication.  And then choose to use a membership provider that verifies your credentials to AD. But a pass-trough option using the loggedon user from that pc would not be very secure


text:
Q: wso2 apeman3: Where do I put the APPID when configuring to call OpenWeather api? I'm wrapping OpenweatherAPI in a wso2 api : WeatherAPI
The openweatherapi has an appid= passed in every call. Where do I put it in WeatherAPI wso2-config ?
Note that I'm incorrectly showing resource and APPID in the endpoint section.
The production endpoint must only read:
https://api.openweathermap.org/data/2.5/
Please provide screenshot in your answer.

A: Backend Endpoint: https://api.openweathermap.org/data/2.5/
There should be a resource named /weather which accepts query parameter q. (i.e the API query)
APPID is the token that should be sent in every call, which is an access key for Weather API.
Since the APPID is a constant and should be sent with every request, you can add it in a mediation sequence and engage it in the as the In-Sequence of the API.
You can use a sequence similar to this example.
<sequence xmlns="http://ws.apache.org/ns/synapse" name="append_app_id">
    <property name="REST_URL_POSTFIX" expression="fn:concat(get-property('axis2','REST_URL_POSTFIX'), '&APPID=<value>')" scope="axis2" type="STRING"/>
</sequence>


text:
Q: Does macOS 10.13 on macbook pro 2017 support VP8/VP9/AV1 hardware acceleration? I know that macOS supports h.264 and h.265 hardware decode/encode (videotoolbox). Does it also support VP8/VP9/AV1 hardware decoding? Currently, playing a 4K video on YouTube is a bit slow.
I'm using macOS High Sierra on 13-inch 2017 MacBook Pro with 3.1 GHz Intel Core i5 and Intel Iris Plus Graphics 650 1536 MB.

A: For AV1, no. The only dedicated hardware decoding for AV1 is in NVIDIA's latest GPUs, the 3000 series, Intel's 11th gen chips, and AMD's RDNA2 GPUs.
According to this discussion, VP9 hardware decoding is available. On Chrome, check chrome://flags/ to see if "VideoToolbox VP9 Decoding" is enabled.


text:
Q: How to connect to Azure ServiceBus in Quarkus I want to connect to ServiceBus subscription from Quarkus. I found this article, which suggests to use ServiceBusJmsConnectionFactory and I am trying to make it work with smallrye
So far I tried:
import com.microsoft.azure.servicebus.jms.ServiceBusJmsConnectionFactory
import com.microsoft.azure.servicebus.primitives.ConnectionStringBuilder
import javax.enterprise.context.ApplicationScoped
import javax.enterprise.inject.Produces
import javax.jms.ConnectionFactory

@ApplicationScoped
class ConnectionFactoryBean {
    @Produces
    fun factory(): ConnectionFactory {
        var connectionStringBuilder = ConnectionStringBuilder("Endpoint=sb://mynamespace.servicebus.windows.net/;SharedAccessKeyName=NAME;SharedAccessKey=KEY");
        return ServiceBusJmsConnectionFactory(connectionStringBuilder, null)
    }
}

Then in my application.properties:
mp.messaging.incoming.my_topic_name.connector=smallrye-jms

And finally to receive messages:
@Incoming("my_topic_name")
protected suspend fun receiveMyEvent(myEvent: String) {
    //process
}

In terms of versions:
<dependency>
  <groupId>com.microsoft.azure</groupId>
  <artifactId>service-bus-jms-connection-factory</artifactId>
  <version>0.0.1</version>
</dependency>
<dependency>
  <groupId>io.smallrye.reactive</groupId>
  <artifactId>smallrye-reactive-messaging-jms</artifactId>
  <version>3.4.0</version>
</dependency>

It is failing with "An API incompatibility" error.
What is the correct way to receive messages using Kotlin/Quarkus from Azure ServiceBus?
UPDATE
I also tried to follow approach from Reactive messaging AMQP and Service Bus with Open Liberty
For that I dropped 2 listed dependencies, replaced them with
<dependency>
  <groupId>io.quarkus</groupId>
  <artifactId>quarkus-smallrye-reactive-messaging-amqp</artifactId>
</dependency>

And completely removed ConnectionFactoryBean.
For that I face

javax.net.ssl.SSLHandshakeException: Failed to create SSL connection

error. Adding quarkus.tls.trust-all=true or quarkus.ssl.native=true to properties did not work...
And it is still unclear, how to connect to the subscription? Will it be a change to the @Incoming attribute?

A: You can use Azure SDK libraries (maven artefact - com.azure.messaging.servicebus) to connect to Service Bus subscription.
For that you will need to create a ServiceBusProcessorClient connect to your namespace using usual connection string (available from the azure portal
under access policies), specify topicName and subscriptionName of it and then wait for messages. Here is an example code:
@ApplicationScoped
class ServiceBusClient() {
    private val scope = CoroutineScope(SupervisorJob())

    fun onStart(@Observes event: StartupEvent) {
        scope.startClient()
    }
    fun onStop(@Observes event: ShutdownEvent) {
        scope.cancel()
    }

    private fun CoroutineScope.startClient() = launch {
        val processorClient: ServiceBusProcessorClient = ServiceBusClientBuilder()
              .connectionString("CONNECTION_STRING")
              .processor()
              .topicName("TOPIC_NAME")
              .subscriptionName("SUBSCRIPTION_NAME")
              .processMessage { receivedMessageContext -> onMessage(receivedMessageContext) }
              .processError { errorContext -> onError(errorContext) }
              .buildProcessorClient()

        processorClient.start()
    }

    private fun onMessage(context: ServiceBusReceivedMessageContext) {
        //Process message
    }

    private fun onError(context: ServiceBusErrorContext) {
        //Handle errors
    }
}

You could get the content of the message using context.message.applicationProperties["PROPERTY_NAME"], context.message.body or context.message.subject as required.


text:
Q: Is using 'perhaps' in an essay appropriate? My teacher was criticizing me much for the informal words used in my essay today. It was blatant that she couldn't understand the half of them anyway, but she said 'perhaps' was also an informal word.
I can kind of understand her wording for this one, because apparently in essays you  need to speak without doubt or something around those lines...
So yeah, just wondering if it is appropriate for a formal essay.

Perhaps the greatest similarity shared in the novel extract and graphic novel, is how the woman followed her will to the very end.

This is what I said. This is a comparative essay BTW.

A: 'Perhaps' is not an informal word. It's got a 500 year history, it's used frequently in formal writing, no dictionary marks it as 'informal'. Using it in an essay is perfectly appropriate.


text:
Q: XSLT - How to use "value-of select=" when 2 xml tags share the same attribute name I am working on the following xml file:
<relational:BaseTable name="Table1">
    <columns name="Column1" Type="Number" </columns>
    <columns name="Column2" Type="Date" </columns>
 ....

I want create a CSV file like this
Table1, Column1, Number
Table1, Column1, Date
Table2, ...

I have figured out how to loop through the xml and format the output as csv. What the code below is missing is a way to repeat the name of the tables at the start of each line. I cannot figure out how to reference the "name" attribute of the parent (relational:BaseTable) tag.
<xsl:for-each select="relational:BaseTable">
   <xsl:for-each select="columns">
      <xsl:value-of select="@name"/>,<xsl:value-of select="@type"/>
      <xsl:text>
</xsl:text>
</xsl:for-each>
</xsl:for-each>

Thanks

A: To access the BaseTable's @name attribute, you just need to move up the hiearchy a bit:
<xsl:value-of select="../@name"/>,<xsl:value-of select="@name"/>,<xsl:value-of select="@type"/>

Note that you would need to do this even if the attribute names weren't the same, since the current reference context is a columns element.
I would also suggest simplifying the above line into a single value-of:
<xsl:value-of select="concat(../@name, ',', @name, ',', @type)"/>


text:
Q: PHP parse a csv with multi-character delimiters We are attempting to parse a csv file that contains multi-character delimiters. Here is the file:
foo;bar
bar;"foo
foo"
"foo;foo";bar

... and here is the logic we're trying to use to parse the file:
    while ($row = fgetcsv($file, 1000, ';'. '"')) {
        $data[] = $row;
    }

The problem is that when we run the logic, we get an exception stating that

fgetcsv(): delimiter must be a single character

Is there a flag value or ini value that can be set in order to allow multi-character delimiters?

A: I talked with my colleague about the code. It turns out that the concatenation dot should actually be a comma.


text:
Q: How do I reference a TEXT type in Informix 4gl? I have the following code in a 4gl module:
DEFINE f_drec RECORD LIKE verhistd.*
DEFINE f_input
   RECORD
      long_desc LIKE verhistd.long_desc
   END RECORD
Let f_input.long_desc = f_drec.long_desc

Where verhistd.long_desc is a TEXT data type.  But when I compile the code I get this error message:
|
|      The variable "f_input.long_desc" is too complex a type to be used in an
| assignment statement.
| See error number -4323.

The error message for -4323 just talks about arrays and screen records, not TEXT data types.

A: I've not used TEXT datatypes in any of the 4gl code I have to maintain, however a quick view of the documentation about TEXT fields in the IBM 4GL By Example documentation suggests that 4GL treats Text blobs as a special case and does not load them by default due to the potential memory use.
If you view the example code they have in Example 18 (sorry, they only have pdf versions of the documentation online now) it should give you a fairly straight forward example of how to deal with a TEXT blob.

Because a BLOB column can contain a very large amount of data, a 4GL
  program does not allocate space for a BLOB variable as it does other variable
  types. Instead of containing the actual value, a BLOB variable contains a
  pointer to the location where this data is stored. This location can be in
  memory, in a temporary file created by the program, or in a specified file
  named by the programmer. The LOCATE statement initializes the BLOB variable with the location of the BLOB value.


text:
Q: serialize/deserialize enum as element name (rather than element content/value) I need to deserialize/serialize XML which looks like this:
<color>
    <green/>
</color>

where <green/> may be <red/>, <blue/> etc. - very large (but limited) set.
I'd like to describe it as simple enum in my code:
enum ColorName
{
    [XmlEnum("red")]
    Red,
    [XmlEnum("green")]
    Green,
    [XmlEnum("blue")]
    Blue,

    ...
    etc.
}

But, if I write my object model like this:
class Color
{
    [XmlElement("name")]
    public ColorName ColorName;
}

class Something
{
    [XmlElement("color")]
    public Color Color;
}

enum gets into XML as a value, rather than element name:
<color>
    <name>green</name>
</color>

Is there any way to get enum value written into XML element name (see the first XML snippet - that's the goal), rather than XML element value, without having to re-type all the values (it's a very large set) as empty class names, or resorting to custom serialization (I would like to avoid it, because serialized class contains a lot of other members, which are perfectly serialized by default)?
(I can't change the schema, it's third-party).

A: No, this is not supported by simply decorading your classes with [Xml*] attributes. You will have to implement IXmlSerializable on Something and do it yourself. Note that in most cases you don't have to bother with the GetSchema method; implementing ReadXml and WriteXml is just fine.


text:
Q: not write JSON: Infinite recursion (StackOverflowError); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion I am developing Spring Boot + Data Jpa + Postgres + Swaggerfox example. In this example I am getting below error.
Error:
2019-08-06 20:29:02.449  WARN 24884 --- [nio-8080-exec-1] o.h.e.loading.internal.LoadContexts      : HHH000100: Fail-safe cleanup (collections) : org.hibernate.engine.loading.internal.CollectionLoadContext@4b0cc859<rs=HikariProxyResultSet@1568394184 wrapping org.postgresql.jdbc.PgResultSet@439cca7d>
2019-08-06 20:29:02.449  WARN 24884 --- [nio-8080-exec-1] o.h.e.loading.internal.LoadContexts      : HHH000100: Fail-safe cleanup (collections) : org.hibernate.engine.loading.internal.CollectionLoadContext@2b3b519c<rs=HikariProxyResultSet@1558688075 wrapping org.postgresql.jdbc.PgResultSet@749887a>
2019-08-06 20:29:02.449  WARN 24884 --- [nio-8080-exec-1] o.h.e.loading.internal.LoadContexts      : HHH000100: Fail-safe cleanup (collections) : org.hibernate.engine.loading.internal.CollectionLoadContext@2a2ad6ca<rs=HikariProxyResultSet@1350054348 wrapping org.postgresql.jdbc.PgResultSet@fc02ed0>
2019-08-06 20:29:02.449  WARN 24884 --- [nio-8080-exec-1] o.h.e.loading.internal.LoadContexts      : HHH000100: Fail-safe cleanup (collections) : org.hibernate.engine.loading.internal.CollectionLoadContext@7e063905<rs=HikariProxyResultSet@324722253 wrapping org.postgresql.jdbc.PgResultSet@35c774e7>
2019-08-06 20:29:02.449  WARN 24884 --- [nio-8080-exec-1] o.h.e.loading.internal.LoadContexts      : HHH000100: Fail-safe cleanup (collections) : org.hibernate.engine.loading.internal.CollectionLoadContext@49a76813<rs=HikariProxyResultSet@1730994902 wrapping org.postgresql.jdbc.PgResultSet@479f6959>
2019-08-06 20:29:02.449  WARN 24884 --- [nio-8080-exec-1] o.h.e.loading.internal.LoadContexts      : HHH000100: Fail-safe cleanup (collections) : org.hibernate.engine.loading.internal.CollectionLoadContext@89ebebe<rs=HikariProxyResultSet@2103425508 wrapping org.postgresql.jdbc.PgResultSet@6f08306>
2019-08-06 20:29:02.449  WARN 24884 --- [nio-8080-exec-1] o.h.e.loading.internal.LoadContexts      : HHH000100: Fail-safe cleanup (collections) : org.hibernate.engine.loading.internal.CollectionLoadContext@74e5843b<rs=HikariProxyResultSet@1775874661 wrapping org.postgresql.jdbc.PgResultSet@488cfe5f>
2019-08-06 20:29:02.449  WARN 24884 --- [nio-8080-exec-1] o.h.e.loading.internal.LoadContexts      : HHH000100: Fail-safe cleanup (collections) : org.hibernate.engine.loading.internal.CollectionLoadContext@359ac2be<rs=HikariProxyResultSet@60954866 wrapping org.postgresql.jdbc.PgResultSet@37708fb8>
2019-08-06 20:29:02.449  WARN 24884 --- [nio-8080-exec-1] o.h.e.loading.internal.LoadContexts      : HHH000100: Fail-safe cleanup (collections) : org.hibernate.engine.loading.internal.CollectionLoadContext@6fec0131<rs=HikariProxyResultSet@2098642686 wrapping org.postgresql.jdbc.PgResultSet@403d6495>

BaseEntity.java
@Data
@NoArgsConstructor
@AllArgsConstructor
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class BaseEntity {
    @CreatedDate
    @Column(name = "createdDate", nullable = false, updatable = false)
    private Instant createdDate;

    @LastModifiedDate
    @Column(name = "lastUpdateDate", nullable = false)
    private Instant lastUpdateDate;

    @Column(name = "createUser", nullable = false, length = 50)
    private String createUser;

    @Column(name = "lastUpdateUser", length = 50)
    private String lastUpdateUser;
}

Category.java
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
@Entity
@Table(name = "category")
public class Category extends BaseEntity implements java.io.Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "CATEGORY_ID", unique = true, nullable = false)
    private Integer categoryId;

    @Column(name = "NAME", nullable = false, length = 10)
    private String name;

    @Column(name = "[DESC]", nullable = false)
    private String desc;

    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "categories")
    private Set<Stock> stocks = new HashSet<>(0);

    @Builder(builderMethodName = "cBuilder")
    public Category(Integer categoryId, String name, String desc, Set<Stock> stocks,
            Instant createdDate,Instant lastUpdateDate, String createUser, String lastUpdateUser) {
        super(createdDate, lastUpdateDate, createUser, lastUpdateUser);
        this.categoryId = categoryId;
        this.name = name;
        this.desc = desc;
        this.stocks = stocks;
    }
}

Stock.java
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
@Entity
@Table(name = "stock", uniqueConstraints = { @UniqueConstraint(columnNames = "STOCK_NAME"),
        @UniqueConstraint(columnNames = "STOCK_CODE") })
public class Stock extends BaseEntity implements java.io.Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "STOCK_ID", unique = true, nullable = false)
    private Integer stockId;

    @Column(name = "STOCK_CODE", unique = true, nullable = false, length = 10)
    private String stockCode;

    @Column(name = "STOCK_NAME", unique = true, nullable = false, length = 20)
    private String stockName;

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinTable(name = "stock_category", catalog = "mkyongdb", joinColumns = {
            @JoinColumn(name = "STOCK_ID", nullable = false, updatable = false) }, inverseJoinColumns = {
                    @JoinColumn(name = "CATEGORY_ID", nullable = false, updatable = false) })
    private Set<Category> categories = new HashSet<>(0);

    @Builder(builderMethodName = "sBuilder")
    public Stock(Integer stockId, String stockCode, String stockName, Set<Category> categories, Instant createdDate,
            Instant lastUpdateDate, String createUser, String lastUpdateUser) {
        super(createdDate, lastUpdateDate, createUser, lastUpdateUser);
        this.stockId = stockId;
        this.stockCode = stockCode;
        this.stockName = stockName;
        this.categories = categories;
    }
}

When I launch: http://localhost:8080/swagger-ui.html#/Category_Management I get error mentioned above:
MainApplication
@SpringBootApplication
@EnableJpaAuditing
public class MyExampleApplication implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(MyExampleApplication.class, args);
    }

    @Autowired
    private StockRepository stockRepository;
    @Autowired
    private CategoryRepository categoryRepository;

    @Override
    public void run(String... args) throws Exception {
        Stock stock = Stock.sBuilder().stockCode("7052").stockName("PADINI").createUser("John Doe")
                .lastUpdateUser("John Doe").build();

        Category category1 = Category.cBuilder().name("CONSUMER").desc("CONSUMER COMPANY").createUser("John Doe")
                .lastUpdateUser("John Doe").build();

        Category category2 = Category.cBuilder().name("INVESTMENT").desc("INVESTMENT COMPANY").createUser("Neha Parate")
                .lastUpdateUser("Neha Parate").build();

        Set<Category> categories = new HashSet<>();
        categories.add(category1);
        categories.add(category2);

        stock.setCategories(categories);
        stockRepository.save(stock);
    }
}

Note: If I used @JsonIgnore suggested by many blocks then I loose objects associated entity data as well, but I am looking to show all data + associated entity data too.

A: The problem you are facing is circular reference.
@JsonManagedReference and @JsonBackReference are used to handle circular references.
@JsonManagedReference is used on a child reference of the target POJO.
@JsonBackReference is used in the corresponding child class. It is placed on the back-reference property.
Circular Reference


text:
Q: How to run a script from a module without change import? I want to run a script inside module that I created but I have a import problem.
I have a Main.py, a folder Data with Regression.py inside and another folder Image with Modifier.py inside.
Like this:
Main.py
Data/
   | __init__.py
   | Regression.py
   | Image/
      | __init__.py
      | Modifier.py

Main import Regression and Regression import Modifier.
Inside Regression.py I have import Image
but went I run Main.py I have the following error:
ModuleNotFoundError: No module named 'Image'
But if I use from Data import Image no error when I run main but I have a error when I run Regression.py:
ImportError: cannot import name 'Image' from 'Data'
The only solution I found is to do this:
if __name__ == "__main__":
    import Image
elif __name__ == "Data.Regression":
    from Data import Image

This solution works but it will be problematic if I create another module that uses Data.
Please, there is anoter solution ?
Main.py
import Data

if __name__ == "__main__":
    data = Data.Regression.LoadTest()
    print("End")

Data/__init__.py
__all__ = ["Classification", "Regression"]
from . import Classification
from . import Regression

Data/Regression.py
if __name__ == "__main__":
    import Image
elif __name__ == "Data.Regression":
    from Data import Image

import numpy as np

def LoadSet():
    #load img
    data = Image.Modifier.Modify(img)
    # other part of code
    return result

if __name__ == "__main__":
    test = Regression.LoadSet()
    # test code of Regression
    print("End")

Data/Image/__init__.py
__all__ = ["Modifier"]
from . import Modifier

Data/Image/Modifier.py
import numpy as np

def Modify(img):
# modify my image
    return img

A: Either use relative import:
from . import Image
or type full path to the module you're importing, relative to __main__:
import Data.Image
And please stick to the convention and name your modules in lowercase.


text:
Q: Finding $\int_{0}^{2\pi} \frac {(1+2\cos\theta)^n\cos(n\theta)}{3+2\cos\theta} \operatorname{d}\theta$ If $n$ is a positive integer find
$$
\int_{0}^{2\pi} \frac {(1+2\cos\theta)^n\cos(n\theta)}{3+2\cos\theta} \operatorname{d}\theta
$$
I know that I have to use contour integral with a circle of radius 1 centered at the origin, but I am having trouble converting the integral into the form $\int_{|z|}$
$$\int_{|z| = 1} \frac{(1+z+1/z)^n\cos(n\theta)}{3+(z+1/z)} \frac{1}{iz} \operatorname{d}z$$
I cant seem to find a way to expand $\cos(n\theta)$ into a function of $z$.
From the above equation, I can get that the poles of is at $z = -1.5 \pm \frac{\sqrt{5}}{2}$ and only the residual of $z = -1.5 + \frac{\sqrt{5}}{2}$ should be included.

A: Note that
$$\cos{n \theta} = \frac12 \left ( z^n + z^{-n}\right )$$
so upon your substitution, you get
$$-\frac{i}{2} \oint_{|z|=1} \frac{dz}{z} \frac{(1+z+z^{-1})^n (z^n+z^{-n})}{3+z+z^{-1}}$$
This can be rearranged to get
$$-\frac{i}{2} \oint_{|z|=1}  \frac{dz}{z^{2 n}} \frac{(1+z+z^2)^n (1+z^{2 n})}{1+3 z+z^2} $$
There are poles where $z^2+3 z+1=0$, or
$$z_{\pm} = \frac{-3\pm \sqrt{5}}{2}$$
i.e., $z_- = -\phi^2$, $z_+=-1/\phi^2$, where $\phi=(\sqrt{5}+1)/2$.  Thus only $z_+$ is within the unit circle and contributes to the integral.
For the pole at $z=0$, it may be easiest to find the coefficient of $z^{2 n-1}$ in the Maclurin expansion of
$$\frac{(1+z+z^2)^n (1+z^{2 n})}{1+3 z+z^2} $$
Not an easy task.  Good luck.

A: I don't know if it will be too late for the answer. What you need is to add $i\sin(n\theta)$ to the integral. Clearly
$$ \int_{0}^{2\pi} \frac {(1+2\cos\theta)^n\sin(n\theta)}{3+2\cos\theta} \operatorname{d}\theta=0. $$
Noting for $z=e^{i\theta}$, ones
$$ 1+2\cos\theta=|1+z|^2-1=(1+z)(1+\frac1z)-1=1+z+\frac1z, $$
and
$$3+2\cos\theta=1+(1+z)(1+\frac1z) $$
and hence
\begin{eqnarray}
&&\int_{0}^{2\pi} \frac {(1+2\cos\theta)^n\cos(n\theta)}{3+2\cos\theta} \operatorname{d}\theta\\
&=&\int_{0}^{2\pi} \frac {(1+2\cos\theta)^ne^{ni\theta }}{3+2\cos\theta} \operatorname{d}\theta\\
&=&-i\int_{|z|=1} \frac {(1+z+\frac1z)^{n}z^n}{1+(1+z)(1+\frac1z)}\frac{\operatorname{d}z}{iz}\\
&=&-i\int_{|z|=1} \frac {(z^2+z+1)^{n}}{z^2+3z+1}\operatorname{d}z\\
&=&-i\int_{|z|=1} \frac {(z^2+z+1)^{n}}{(z-z_1)(z-z_2)}\operatorname{d}z\\
&=&-i\cdot 2\pi i \cdot\text{Res}(\frac {(z^2+z+1)^{n}}{z-z_2},z=z_1)\\
&=&2\pi \frac {(z_1^2+z_1+1))^{n}}{z_1-z_2}\\
&=&\frac{2\pi(3-\sqrt5)^{n}}{\sqrt5}.
\end{eqnarray}
Here $z_1,z_2$ are two of $z^2+3z+1=0$,
$$ z_1=\frac{-3+\sqrt5}{2}, z_2=\frac{-3-\sqrt5}{2}. $$

A: Because I can't submit a comment, I submit an answer. Maple calculates it for concrete values of $n$. Hope, the following would be useful: the Maple command $$[seq(int((1+2*cos(theta))^n*cos(n*theta)/(3+2*cos(theta)), theta = 0 .. 2*Pi), n = [5, 10, 15, 30])]  $$ produces $$  [-1760\,\pi +{\frac {3936}{5}}\,\sqrt {5}\pi ,-6927360\,\pi +{\frac {
15490048}{5}}\,\sqrt {5}\pi ,-27264286720\,\pi +{\frac {60964798464}{5
}}\,\sqrt {5}\pi ,-1662161745149511598080\,\pi +{\frac {
3716706651753989275648}{5}}\,\sqrt {5}\pi ].
$$


text:
Q: Using explode arrays in foreach and only last array Inserted into table, how does arrays work? I get a text from html-form, didnt mention it here, but it looks like:

*

*John:John

*Mike:Mike

*Root:Admin

Here is my php code:
   $text = explode("\n", $_POST["info"]);
// - get data from html form and //explode it to pieces
    print_r($text);
// result is: Array ( [0] => John:John [1] => Mike:Mike [2] => Root:Admin )
    foreach ($text as $key => $value) {
      $val = explode (":", $value);
// want to explode it to pieces, result must be 0=>John 1=>John, 0=>Mike 1=>Mike, [0]=>Root [1]=>Admin
$sql = "INSERT INTO `redtable`(`NAME`,`NAME2`) VALUES('$val[0]','$val[1]');";
    }

When this code runs, it inserts into database only the last line, which are (Root:Admin), why it doesn't inserts John:John, Mike:Mike ...?
Where is the mistake?
Here is the result of echo $sql:
INSERT INTO `redtable`(`IGNAME`,`IGPASS`) VALUES('John','John ');INSERT INTO `redtable`(`IGNAME`,`IGPASS`) VALUES('Mike','Mike ');INSERT INTO `redtable`(`IGNAME`,`IGPASS`) VALUES('Root','Admin');

Here is the full code:
<?php

$servername = "localhost";
$username = "mysql";
$password = "mysql";
$dbname = "red";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$pieces = explode("\n", $_POST["info"]);
foreach ($pieces as $key => $value) {
  $val = explode (":", $value);
  $sql = "INSERT INTO `redtable`(`IGNAME`,`IGPASS`) VALUES('$val[0]','$val[1]');";
echo $sql;
}
if ($conn->query($sql) === TRUE) {
   echo "Days left updated";
} else {
  mysqli_error($conn);
    echo "Error: " . $sql . "
" . $conn->error;
}

$conn->close();
?>

Have trying using if-else statements, like this:
# code...
  $val = explode (":", $value);
  #  print_r($val);
  if (1 == 1) {
    $sql = "INSERT INTO `redtable`(`IGNAME`,`IGPASS`) VALUES('$val[0]','$val[1]');";

  }
  else {
  echo "esle";
  }

}

The same result, only the last line have been inserted to the DB.
GUYS, If SOMEONE NEED THE WORKING SOLUTION WATCH @Matt Rabe answer - working like a charm, you need just replace the brackets!

A: Mark Baker is right - you are executing your sql outside of your foreach loop. You are defining the $sql var inside your foreach, but the actual execution of it ($conn->query($sql)) occurs outside of the foreach.
Change this:
foreach ($pieces as $key => $value) {
  $val = explode (":", $value);
  $sql = "INSERT INTO `redtable`(`IGNAME`,`IGPASS`) VALUES('$val[0]','$val[1]');";
echo $sql;
}
if ($conn->query($sql) === TRUE) {
   echo "Days left updated";
} else {
  mysqli_error($conn);
    echo "Error: " . $sql . "
" . $conn->error;
}

To this:
foreach ($pieces as $key => $value) {
  $val = explode (":", $value);
  $sql = "INSERT INTO `redtable`(`IGNAME`,`IGPASS`) VALUES('$val[0]','$val[1]');";
echo $sql;

  if ($conn->query($sql) === TRUE) {
     echo "Days left updated";
  } else {
    mysqli_error($conn);
      echo "Error: " . $sql . "
" . $conn->error;
  }
}

Your code has numerous issues beyond this, but this should address your stated question.


text:
Q: Graphics on iPhone Application I have a graphic designer who is doing some graphics for my iPhone app. Most recently she made me a background pattern and posed me two questions that I'm unsure of how to answer:
1) What should the size of the background pattern be?
-For this I know that when I'm programming my app,the screen is in terms of 320 by 480 (when in portrait mode), however is this the appropriate unit that I should give her (I'm only worried about iPhone 4 and below for now)? Like for instance, I know there is a retina display and I've seen the phone resolution of my phone also be listed as 640 x 960. I'm just confused of what the best thing to tell her regarding this is, she does not have any iPhone experience and will be using the traditional graphic programs like illustrator, photo shop etc to do the graphic design.
2) What file type should it be?
-I've read the iPhone supports mostly all of the most popular graphic file types, but is there anyone particular that would work best on an iPhone app?

A: The standard for iPhone resource images is PNG. If you want to target iPhone 4+ with retina display, have the designer provide two versions of the PNG: A standard version and a double-sized version which should have @2x appended after the filename, but before the extension.
So
image.png

for regular resolution and
image@2x.png

for retina resolution. iOS will automatically pick the best one to use based on the screen available.


text:
Q: Java Generics - Choosing the correct generic service Lets say we have a product of different types, the different types have different internal variables and does not share anything beside the fact they are all products.
public interface Product {}
public class ProductA implements Product {
    private String productAVariable;
    // getters
}
public class ProductB implements Product {
    private String productBVariable;
    // getters
}

To get the quote/price of a product we must call an external service:
public interface QuoteService<T extends Product> {
    ProductPrice getQuote(T product);
}
public class ProductAQuoteService implements QuoteService<ProductA> {
    @Override
    public ProductPrice getQuote(ProductA product) {
        return new ProductPrice(someExternalService.getQuote(product.getProductAVariable()));
    }
}
public class ProductBQuoteService implements QuoteService<ProductB> {
    @Override
    public ProductPrice getQuote(ProductB product) {
        return new ProductPrice(someOtherExternalService.getQuote(product.getProductBVariable()));
    }
}

So far so good. The last step is to iterate through a List of Products in our shoppingcart. Fetching the price/quote for each one. But how can we do that in a generic way? Currently i have some if-else instance of statements, but I feel there must be something more generic?
List<Product> productsInCart = Lists.asList(new ProductA(), new ProductB());
for (Product product : productsInCart) {
    if (product instanceof ProductA) {
        productAQuoteService.getQuote((ProductA) product);
    } else if (product instanceof ProductB) {
        productBQuoteService.getQuote((ProductB) product);
    }
}


text:
Q: DNS-SD implementation I am trying to implement DNS-SD, and I understand how it works, but don't really understand the purpose, so I have a few questions about it.
Let us assume that we have two devices on local network, and we registered services both devices provide, how dns-sd really helps us, it just replaces ip:port/path/to/service with some symbolic name? What if we want to use that service in our program, for instance written in C, how we will handle it?

A: I think google will help you with why you would want to use it https://en.m.wikipedia.org/wiki/Zero-configuration_networking#DNS-SD
This is important if you can not define the path to the service ahea of time. For example if your C program is inside a printer and you want anybody on the network to be able to find the printer without knowing its IP address.
This has nothing to do with C itself but is a way to find things in a network regardless of the language used.


text:
Q: Updating a 3D graph every n minutes in Python I have the following code to plot a 3D graph in Python
data = # taken from an SQL query in (x, y, z) format #

x, y, z = zip(*data)
z = map(float, z)
grid_x, grid_y = np.mgrid[min(x):max(x):100j, min(y):max(y):100j]
grid_z = griddata((x, y), z, (grid_x, grid_y), method='cubic')

fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral)
plt.show()

I want the plot to be undated every 1 minute. I can get the data from the table using a thread every 1 minute but I am unable to update the plot.
Can you help me with a suggestion?
Thanks in advance!

A: Try this
while True:
    plt.pause(1)
    x1,x2,x3=random.uniform(-10,0),random.uniform(0,10),random.uniform(0,0.5)
    y1,y2,y3=random.uniform(-10,0),random.uniform(0,10),random.uniform(0,0.5)

    X,Y=np.arange(x1,x2,x3),np.arange(y1,y2,y3)
    X, Y = np.meshgrid(X, Y)
    R = np.sqrt(X**2 + Y**2)
    Z = np.sin(R)
    surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
                       linewidth=0, antialiased=False)

    plt.draw()

matplotlib.pyplot.pause
Pause for interval seconds.
If there is an active figure it will be updated and displayed, and the GUI event loop will run during the pause.
If there is no active figure, or if a non-interactive backend is in use, this executes time.sleep(interval).
This can be used for crude animation. For more complex animation, see matplotlib.animation.
This function is experimental; its behavior may be changed or extended in a future release.

A: After some research I found a way of doing this with matplotlib.animation.
The below Youtube link was of great help.
https://www.youtube.com/watch?v=7w8jk0r4lxA


text:
Q: Fatal error: Cannot instantiate abstract class DatabaseSchema in /home/myfoldername/public_html/demo/includes/database/database.inc on line 890 I moved Drupal site files from local to server then when i run the site it show the error

Fatal error: Cannot instantiate abstract class DatabaseSchema in /home/myfoldername/public_html/demo/includes/database/database.inc on line 890

Pls direct me on this

A: Clear the cache using drush cc.


text:
Q: relationships in hibernate when we want to start a project with hibernate and a Database (MySQL or Postgresql for example) in java it's better to perform the relationships between tables in database or in hibernate or both ?
i want to know what experts do about this ?
thanx

A: The whole point of hibernate, imho, is to remove yourself from the database and sql, and any dependcy to the database (and its vendor). It is literally just a store of data, and can be swapped out at a later date.
So you define your relationships (and all business logic) in the java code and let hibernate create the tables for you.
You should be aware of the relevant hibernate setting to enable table creations, and its pitfalls.

A: You can keep the relationships in your entities.
You can use the maven plugin (http://mojo.codehaus.org/maven-hibernate3/hibernate3-maven-plugin/hbm2ddl-mojo.html) to generate the relevant db schema.
This step also helps you validate the relationships that you define in the entities.


text:
Q: jQuery toggle to expand/contract all content independent of previous state file://localhost/C:/Users/kürşat/Desktop/yeni%20site/faq%20-%20Kopya/kopya.html
this is my photography tutorial page. I'm did manage to toggle on/off when someone clicks a question.
What I can't do : the top right button can expand all but it cannot contract all questions.
I should contract/expand all even if some of them were previously opened. At first my code was doing the opposite of previous state.
How can I do that?
Here is my code :
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

<link rel="stylesheet" type="text/css" href="styles.css"/>

Temel Fotoğrafçılık Bilgileri<button id="expand">Genişlet</button>

question 1?

answer 1.

question 2?

answer 2.

question 3?

answer 3.

Here is the working JSfiddle version:
http://jsfiddle.net/reJu9/

A: Change the expand click callback to
$("#expand").click(function(){
     var $this = $(this);
     if($this.text() == 'Genişlet')
        $('article').show();
     else
        $('article').hide();
     $this.text($this.text() == 'Genişlet' ? 'Küçült' : 'Genişlet');
});

Demo: http://jsfiddle.net/joycse06/reJu9/1/

A: Maintain a variable, which tells you if the button should expand or collapse questions.
Check this updated fiddle


text:
Q: While loop: Output something different on every second result I am running a plugin called Category Posts Widget for WordPress: http://wordpress.org/extend/plugins/category-posts/
It uses a while loop to display the names of all posts in a certain category. I want to get it so that there is a different class attached to the li tag on every second output.
Here is the block of code for the plugin:
// Post list
    echo "
\n";

    while ( $cat_posts->have_posts() )
    {
        $cat_posts->the_post();
    ?>

            <a class="post-title" href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent link to <?php the_title_attribute(); ?>"><?php the_title(); ?>

            <?php
                if (
                    function_exists('the_post_thumbnail') &&
                    current_theme_supports("post-thumbnails") &&
                    $instance["thumb"] &&
                    has_post_thumbnail()
                ) :
            ?>
                <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
                <?php the_post_thumbnail( 'cat_post_thumb_size'.$this->id ); ?>

            <?php endif; ?>

            <?php if ( $instance['date'] ) : ?>

<?php the_time("j M Y"); ?>

            <?php endif; ?>

            <?php if ( $instance['excerpt'] ) : ?>
            <?php the_excerpt(); ?>
            <?php endif; ?>

            <?php if ( $instance['comment_num'] ) : ?>

(<?php comments_number(); ?>)

            <?php endif; ?>

    <?php
    }

    echo "
\n";

I am just trying to get it so on each second one in the output list, the li has a different class, so cat-post-item-alt for example.
Thanks,
Wade

A: // ....
<? $type = ($type + 1) % 2; ?>
<li class="cat-post-item<?=$type ?>">

A: The following is untested, but it illustrates the basic principle. Just switch a boolean value on every instance of the loop. Even posts will additionally have the class cat-post-item-even, so that you won't have to modify your stylesheet more than necessary.
It's neat to discover that for loops can be used for things other than simple increments.
The two edited lines are marked as such.
// Post list
echo "
\n";

/* edited */    for($even=false;$cat_posts->have_posts();$even=!$even)
{
    $cat_posts->the_post();
?>
        <li class="cat-post-item<?php if($even) echo " cat-post-item-even"; ?>">
        <a class="post-title" href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent link to <?php the_title_attribute(); ?>"><?php the_title(); ?>

        <?php
            if (
                function_exists('the_post_thumbnail') &&
                current_theme_supports("post-thumbnails") &&
                $instance["thumb"] &&
                has_post_thumbnail()
            ) :
        ?>
            <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
            <?php the_post_thumbnail( 'cat_post_thumb_size'.$this->id ); ?>

        <?php endif; ?>

        <?php if ( $instance['date'] ) : ?>

<?php the_time("j M Y"); ?>

        <?php endif; ?>

        <?php if ( $instance['excerpt'] ) : ?>
        <?php the_excerpt(); ?>
        <?php endif; ?>

        <?php if ( $instance['comment_num'] ) : ?>

(<?php comments_number(); ?>)

        <?php endif; ?>

<?php
}

echo "
\n";

A: $counter=1;

for ($i=0; $i<=10; $i++) {

    if ($counter%3===0) {
        echo 'something else';
    } else {
        echo 'normal';
    }

    echo '
';

    $counter++;
}


text:
Q: Raspberry: Qt issue connecting device because SSH client-server capabilities don't match I'm trying to launch an application in C++ done with QtCreator:

This is the error:

I can see the error if I try to test the connection with created device or calling run on QtCreator.
I don't have any idea how to align capabilities.
Can someone tell me which file I have to modify to fix the issue?
I found some info about "sshd_config" file but I didn't find a way to solve.
I tried to modify the file as suggested, thanks by the way, but with the change the ssh doesn't start at all.

So, I'm sorry for the question but, there is a position defined where I can/should place the suggested line?
This is my file

I tried at the begin, at bottom, in the middle, nothing the connection was refused.

A: The client is offering a list of broken ciphers. You should consider updating the Qt Craetor or whatever is this software using to connect to the remote device.
The other possibility is to allow these ciphers on the server (device). Add
Ciphers +aes128-cbc

to your /etc/ssh/sshd_config and restart the sshd service. If it will not work, use for example this list:
Ciphers aes128-ctr,aes192-ctr,aes256-ctr,aes128-cbc

and restart the sshd service on the device.

A: I solved adding this string and as I was not sure where apply it, I would like to show exactly which line was added:


text:
Q: How do I create a GET with multiple possible parameters I'm using ASP.NET Web API (4 RTM) and would like to create a method(s) to handle a GET request. Think of this as GetCustomer() to handle my GET request.
Now, getting a customer by customer Id is quite simple; I pass the customer Id in the querystring and we're off and running. Suppose I want the option to pass one of two possible parameters; an integer representing the customer OR an abbreviation.
One option is to have a single method to handle the GET request for integers and strings. Then, inside the method I could test if the value is able to be parsed as an integer and handle it accordingly. But is this the correct way to handle this situation?
If I should have two separate methods, how do I do that?

A: Personally, I'd use just one entry point to that kind of code:
http://example.com/lookupUser?id=18475
http://example.com/lookupUser?userCode=jjs
http://example.com/lookupUser?FullName=Jeremy%20J%20%Starcher

Well, maybe not the last example since there could be multiple hits.

A: From your mention of using a (presumably unique) ID, you might want a separate action method for it. But from your description of a single intent, a single controller method is probably the way to go - and note you still wouldn't have to parse strings manually, the MVC model-binder can do that for you.
If you have separate methods, they have to have different URLs. They could be the same method name overloaded, but then they would still have to be decorated with ActionName attributes to assign them different identities. (Note you could use other selector attributes to distinquish, such as [HttpPost] or a custom attribute.)
Note you could also conditionally invoke different controller methods on a URL based on its parameters using a MapRoute (in Global.asax) that expects parameters.
The benefit of handling all the same type of activities in a single place is that the code becomes clearer, more maintainable, and less defect-prone. If you find that isn't the case, then break them up. This is the usual Don't Repeat Yourself/Single Point of Truth/Separation of Reponsibility stuff I'm talking about.
As a general rule I find in MVC that the URL path (without the querystring), the Controller Method, and the intent all break down along the same lines. For example, these two URLs follow that rule:
http://example.com/person/id/403
http://example.com/person/search?FirstName=Joe&LastName=Smith

We express our intent in the URL to get either a single person or possible multiple matches.
You said you might pass an abbreviation (which doesn't sound like it would be unique), as one of two parameters. If each of the optional parameters were independently unique, then it probably doesn't make sense to form a question for more than one at a time. It would get complex to figure out which method to pass the request to before actually entering the workhorse of your custom controller logic, if you might have a, or b, or a AND b.
Also, technologies like LINQ make it quite easy to dynamically compose your query procedurally to have either or both constraint on the results.
[HttpGet]
public ViewResult Search(string FirstName, string LastName) {
     var people = AllPeopleInDatabase();
     if (!string.IsNullOrEmpty(FirstName)) people=people.Where(p => p.FirstName==FirstName);
     if (!string.IsNullOrEmpty(LastName)) people=people.Where(p => p.LastName==LastName);
     return View(people);
}

Putting a unique ID into that mix doesn't make sense to me only because I can't think of a programmatic scenario offhand (except for the fairly unique case of password validation) where you only want to get the specified record if another criteria matches. So, if someone asks for an id and it doesn't exist, it is probably an error case, where if someone searches by criteria that don't yield results, it probably is not an error case. But still, you could:
public ViewResult Search(string FirstName, string LastName, int? id) {

edit: Also note that the model-binder will handle properties on classes, and that's the typical way to bind multiple parameters:
public ViewResult Search(MyCriteriaViewModel criteria) {

edit2: also note that RESTful services (which WebAPI is ideally suited to) have standard practices for CRUD URLs. The following is from http://www.asp.net/web-api/overview/creating-web-apis/creating-a-web-api-that-supports-crud-operations :
Action                      HTTP method  Relative URI
Get a list of all products  GET          /api/products
Get a product by ID         GET          /api/products/id
Get a product by category   GET          /api/products?category=category
Create a new product        POST         /api/products
Update a product            PUT          /api/products/id
Delete a product            DELETE       /api/products/id

Good luck!


text:
Q: .png make pygame laggy I saw that when you wanna blit a .png image to your pygame display, the FPS drop from 60 to 20, is there a way to get around this, or maybe I did something wrong in my code ?
EDIT : I just tried .convert_alpha(), and it's going around 40 FPS now
menu = pygame.image.load("Ecran titre\\principal\\menu.png")
clock = pygame.time.Clock()

gameExit = False

while not gameExit :

    for event in pygame.event.get():
        if (event.type == pygame.QUIT):
            gameExit = True

    #gameDisplay.fill(0)

    gameDisplay.blit(background,(0,0)) # background is a jpeg image with .convert()

    gameDisplay.blit(menu,(0,0))
    pygame.display.update()
    clock.tick(60)
    pygame.display.set_caption("fps: " + str(clock.get_fps()))

A: convert_alpha() is a good first step in managing images within pygame. It is also important to know that blitting an image to the surface is much slower than blitting a surface to a surface. I would pre-draw all images you plan on using onto their own surfaces. Then I would blit those surfaces to the screen. for example, the below code happens outside the game loop:
img_rect = get_image("my_image.png").get_rect()
img_surface = pygame.Surface((img_rect.width, img_rect.height), pygame.SRCALPHA)
img_surface.fill((0, 0, 0, 0))
img_surface.blit(get_image("my_image.png"), img_rect)

Then in the game loop:
gameDisplay.blit(img_surface, (x, y))

In general, you want to take as much as you possibly can out of the game loop. In this case, you are pre-processing the image and doing a faster surface-to-surface blit.
In the future, consider using cProfile for python. It will really help you nail down what exactly is making you code sluggish. Here is some good info on it:
Python getting meaningful results from cProfile

A: First of all, you should use .convert_alpha(), like "The4thIceman" stated in a previous answer.  That can really speed up your code, and it should be used on all loaded images.
Second of all, you should use multithreading.  Multithreading is the art of making your programs run multiple things at the same time.  Python has a built in "thread" library (though I think it is "_thread" in Python 3) that allows you to do this easily.
Refer to https://docs.python.org/3/library/_thread.html


text:
Q: Fetching feeds by date I want to be fetching feeds from a site on a daily basis. I only want to fetch the present day's feeds alone. Is there a way i can specify the date i intend to fetch as a parameter or i will just need to check the date of each fetched feed and stop fetching when the date is not the present day's date?
Thanks in advance.

A: That can only happen if the people who created the feed allow you to specify a date to fetch as a parameter. There isn't really a standardized API for these types of things, and every RSS feed provider is different. I'd suggest emailing the site owners to see if they have something like that.
If you don't want to email them, or they don't have the requested API, you are going to have to pull the whole RSS feed, parse is, and then figure out what to do from there.


text:
Q: Extract object after watershed segmentation I have segmented my image using the Watershed algorithm, the result is pretty satisfying.
Now, I would like to extract and store what has been segmented but I don't really know how to do it.
Do you guys have an idea please ?
Thank you.

A: Could you not do a connected component analysis(8 connectedness) on the output image based on the color / index information. I think that would give you the easiest starting point.
All the pixels in the neighborhood which are in the same segment and you can store that information and further use it.
However I don't think you can do background/foreground segmentation based on watershed as that requires a little more information than just segments for each frame. You will have to somehow keep a track of previous frame information too. There are a lot of papers. Go through them. Grimmson's paper was seminal. I've seen a lot more these days. Pixel Based Adaptive Segmenter was the best but very slow, in my opinion.


text: Q: How to use Conscrypt library for ssl socketchannel in android? On the conscrypt git page , there are no sample usage available to use the conscrypt for ssl socketChannel with sslEngine. Could anyone please provide sample usage example or guide me how to use conscrypt to make NIO socketchannel tcp socket with server(tcp based ssl server).


text:
Q: Creating a simple webserver using sockets I have the following code for server in C. The web browser will serve as the client. So far, what I know is I need to run the executable file from the terminal and open a web browser and type: localhost:54321 . 54321 is port number where we need to run the web server. The next thing we need to do is parse the http request received from the web browser and obtain the name of the object requested.
I know how to parse but I don't know how to receive the object. Should I use form inputs to get the name of the object?
Thanks in Advance! Just a newbie in socket programming and I am only able to create sockets.
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char **argv)
{
  int listenfd,connfd;
  struct sockaddr_in servaddr,cliaddr;
  socklen_t len = sizeof(cliaddr);
  char cli_ip[32];
  char mesg[1024];

  listenfd = socket(PF_INET,SOCK_STREAM,0);
  bzero(&servaddr, sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
  servaddr.sin_port = htons(54321);
  if ( bind( listenfd, (struct sockaddr*) &servaddr, sizeof(servaddr) ) < 0 ){
      perror(NULL);
      exit(-1);
  }

  //not present in udp server
  listen(listenfd,2);

  while(1){
      //not present in udp server
    connfd = accept(listenfd,(struct sockaddr *)&cliaddr,&len);
    inet_ntop(AF_INET,(struct in_addr *) &cliaddr.sin_addr, cli_ip, sizeof(cli_ip) );
    printf("Client %s connected. \n",cli_ip);
    while(1){
      memset(mesg,0,sizeof(mesg));
      if( recvfrom(connfd,mesg,sizeof(mesg),0,(const struct sockaddr *)&cliaddr,&len) > 0 ){
            printf("From %s port %d: %s",cli_ip,ntohs(cliaddr.sin_port),mesg);
      }
      else {
        printf("Client %s disconnected. \n",cli_ip);
        break;
      }
    }
    close(connfd);
  }
  close(listenfd);
  return 0;
}

EDITED: This is the exact specifications given:
Parse the HTTP request (using strtok) received from the web browser and obtain the name of the object requested. For example, index.html will be sent in the response:
GET /index.html HTML/1.1
Host: localhost:54321
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:15.0) Gecko/20100101 Firefox/15.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

A: I assume this is a training exercise?
You need to keep reading from the socket and parsing as you go, until you determine you have read the entire header.  Then you need to parse it (if you haven't already done so), and send a response.
So, you can't have just one recvfrom(), you need to loop.
It also won't (efficiently) handle multiple browsers until you explicitly support it, via poll/select and/or threads and/or forked processes.


text:
Q: Tensorflow: ValueError: Expected non-integer, got  I'm just starting with Tensorflow and when I call m.fit(input_fn=lambda: self.input_fn(train_data), steps=train_steps), then I receive the following error.
File "/Library/Python/2.7/site-packages/tensorflow/contrib/layers/python/layers/feature_column_ops.py", line 161, in _input_from_feature_columns
    transformed_tensor = transformer.transform(column)
File "/Library/Python/2.7/site-packages/tensorflow/contrib/layers/python/layers/feature_column_ops.py", line 882, in transform
    feature_column.insert_transformed_feature(self._columns_to_tensors)
File "/Library/Python/2.7/site-packages/tensorflow/contrib/layers/python/layers/feature_column.py", line 991, in insert_transformed_feature
    self.sparse_id_column.insert_transformed_feature(columns_to_tensors)
File "/Library/Python/2.7/site-packages/tensorflow/contrib/layers/python/layers/feature_column.py", line 572, in insert_transformed_feature
    name="lookup")
File "/Library/Python/2.7/site-packages/tensorflow/contrib/lookup/lookup_ops.py", line 1018, in index_table_from_tensor
    "integer" if dtype.is_integer else "non-integer", keys.dtype))
ValueError: Expected non-integer, got <dtype: 'int32'>.

In the feature columns that I pass to fit(), there are only int32and int64, but that should not be the problem, should it?

A: I think it could happen that you use categorical features with tf.SparseTensor but your feature columns contain int32.
In this case just convert your integer columns into string, for example like this:
# using Pandas
for f in categorical_features:
    df_train[f] = df_train[f].astype(str)
    df_test[f] = df_test[f].astype(str)


text:
Q: Why is this openmp+mpi code hanging My code hangs whenever I try running it with many threads. Here's it,
double CMpifun::sendData2()
{
    double *tStatistics=new double[8], tmp_time; // wall clock time
    double SY, Sto, header[SZ_HEADER];
    int a_tasks=0, file_p=0;
    vector<myDataType *> d = getData();

    int idx=0;
    opt_k.k=1; opt_k.proc_files=0; opt_k.p=this->node_sz; SY=0; Sto=0;
    std::fill(header,header+SZ_HEADER,-1);

    omp_set_num_threads(4);// for now
    // parallel region
    #pragma omp parallel default(none) shared(idx,SY,Sto,d,a_tasks,stdout) firstprivate(header) //firstprivate(dat_dim,dat)
    {
        int tid = omp_get_thread_num(), cur_idx, cur_k; int N=d.size();
        while (idx<N) { // Assign tasks and fetch results where available
            printf("-------------------------\n%d - 1\n", tid); fflush(stdout);
            #pragma omp critical(update__a_task)
            {
                printf("%d - critique 1\n", tid); fflush(stdout);
                if (idx<N) {
                    printf("%d - critique 2\n", tid); fflush(stdout);
                    if (a_tasks<node_sz-1){ // available nodes to assign
                        printf("%d - 2.1\n", tid); fflush(stdout);
                        MPI_Recv(header,SZ_HEADER,MPI_DOUBLE,MPI_ANY_SOURCE,TAG_HEADER,MY_COMM_GRP,this->Stat);
                        cur_idx=idx; cur_k=opt_k.k; idx+=cur_k;
                        a_tasks+=cur_k;
                    } else {// all nodes assigned. only fetch result
                        printf("%d - 2.2\n", tid); fflush(stdout);
                        MPI_Recv(header,SZ_HEADER,MPI_DOUBLE,MPI_ANY_SOURCE,TAG_RESULT,MY_COMM_GRP,this->Stat);
                    }
             }else ;//printf("%d - done task assignment\n", tid); fflush(stdout);

         }

            printf("%d - 3\n", tid); fflush(stdout);
            if (cur_idx<N) {
             printf("%d: cur_idx:%d, opt_k.k:%d, idx:%d, N:%d \n", tid, cur_idx,opt_k.k,idx,N); fflush(stdout);
             if(this->Stat->MPI_TAG == TAG_HEADER){ // serve tasks
                 printf("%d - task %d being assigned to %d\n", tid,cur_idx,(int)header[4]); fflush(stdout);
                 while (cur_k && cur_idx<N) {
                     printf("%d - T1\n", tid); fflush(stdout);
                         header[1]=d[cur_idx]->nRows; header[2]=d[cur_idx]->nCols;  header[3]=cur_idx;
                         header[9]=--cur_k;
                         MPI_Send(header,SZ_HEADER,MPI_DOUBLE,(int)header[4],TAG_HEADER,MY_COMM_GRP);
                         printf("%d - T2 %d\n", tid,(int)header[4]); fflush(stdout);
                         MPI_Send(d[cur_idx]->data,d[cur_idx]->nRows*d[cur_idx]->nCols,MPI_DOUBLE,(int)header[4],TAG_DATA,MY_COMM_GRP);
                         printf("%d - T3 %d\n", tid,(int)header[4]); fflush(stdout);
                         delete[] d[cur_idx]->data;  ++cur_idx;
                 }
             } else if(this->Stat->MPI_TAG == TAG_RESULT){ // collect results
                 printf("%d - result from %d\n", tid,(int)header[4]); fflush(stdout);
                 while(true){
                     printf("%d - R1\n", tid); fflush(stdout);
                     #pragma omp atomic
                        --a_tasks;
                     double *results = new double[(int)(header[1]*header[2])];
                 MPI_Recv(results,(int)(header[1]*header[2]),MPI_DOUBLE,(int)header[4],TAG_DATA,MY_COMM_GRP,this->Stat);
                     printf("%d - R2 received result from %d\n", tid,(int)header[4]); fflush(stdout);
                 delete[] results;
                     if ((int)header[9]>0) {
                         MPI_Recv(header,SZ_HEADER,MPI_DOUBLE,(int)header[4],TAG_RESULT,MY_COMM_GRP,this->Stat);
                     } else break;
                 } //end while
             } // end collect results
         } //end if(loopmain)
         printf("%d - NExt idx: %d\n", tid,idx); fflush(stdout);
     } // end while(loopmain)
    } // end parallel section]

    printf("<<<<<<<<<<<<< MASTER - COLLECTING RESULTS >>>>>>>>>>>> "); fflush(stdout);
    printf("MASTER - pending tasks:%d\n",a_tasks); fflush(stdout);
    while (a_tasks>0) {
        printf("MASTER - wait for slave result request... pending tasks:%d\n",a_tasks); fflush(stdout);
        MPI_Recv(header,SZ_HEADER,MPI_DOUBLE,MPI_ANY_SOURCE,TAG_RESULT,MY_COMM_GRP,this->Stat);
        while (true) {
            double *results = new double[(int)(header[1]*header[2])];
            printf("MASTER - wait for result from %d... pending tasks\n",(int)header[4]); fflush(stdout);
            MPI_Recv(results,(int)(header[1]*header[2]),MPI_DOUBLE,(int)header[4],TAG_DATA,MY_COMM_GRP,this->Stat);
            delete[] results;
            --a_tasks;
            if ((int)header[9]>0) {
                printf("MASTER - result from slave .. some more\n"); fflush(stdout);
                MPI_Recv(header,SZ_HEADER,MPI_DOUBLE,(int)header[4],TAG_RESULT,MY_COMM_GRP,this->Stat);
            } else break;
        }
    }

    message("<<<<<<<<<<<<<<<<<< MASTER - terminate slaves >>>>>>>>>>>>>>>>>");
    for(int i=1;i<node_sz;++i){ // terminate
      MPI_Recv(header,SZ_HEADER,MPI_DOUBLE,MPI_ANY_SOURCE,TAG_HEADER,MY_COMM_GRP,this->Stat);
        printf("MASTER - terminate to signal %d\n",(int)header[4]); fflush(stdout);
      MPI_Send(header,SZ_HEADER,MPI_DOUBLE,(int)header[4],TAG_TERMINATE,MY_COMM_GRP);
        printf("MASTER - done terminated %d\n",(int)header[4]); fflush(stdout);
    }
    printf("MASTER - bye\n"); fflush(stdout);
    return 0;

The Slave function is as follows,
void CMpifun::slave2()
{
    double *Data; vector<myDataType> dataQ; vector<hist_type> resQ;
    char out_opt='b'; // irrelevant
    myDataType *out_im = new myDataType;    hist_type *out_hist;    CLdp ldp;
    int file_cnt=0; double tmp_t; //local variables
    double time_arr[3]={}; //1: task wait latency, 2: task set total send time, 3: taskset total process time

    while (true) { // main while loop
        printf("Slave: %d - ........... ready for task......\n",myRank); fflush(stdout);
        header[4]=myRank;   MPI_Send(header,SZ_HEADER,MPI_DOUBLE,MASTER,TAG_HEADER,MY_COMM_GRP);
        time_arr[0] = MPI_Wtime();
        printf("Slave: %d - got master. waiting for task\n",myRank); fflush(stdout);
        MPI_Recv(header,SZ_HEADER,MPI_DOUBLE,MASTER,MPI_ANY_TAG,MY_COMM_GRP,this->Stat);
        time_arr[0] = MPI_Wtime() - time_arr[0]; // wait for task latency
        if(this->Stat->MPI_TAG == TAG_TERMINATE) {
            printf("Slave: %d - terminate signal received\n",myRank); fflush(stdout);
            break;
        }
        printf("Slave: %d - got header. waiting for data\n",myRank); fflush(stdout);
        //receive data
        tmp_t = MPI_Wtime();
        while(true) {
            Data=new double[(int)(header[1]*header[2])];
            MPI_Recv(Data,(int)(header[1]*header[2]),MPI_DOUBLE,MASTER,TAG_DATA,MY_COMM_GRP,this->Stat);
            myDataType d; d.data=Data; d.nRows=(int)header[1]; d.nCols=(int)header[2];
            dataQ.push_back(d);
            file_cnt++;
            if ((int)header[9]) {
                MPI_Recv(header,SZ_HEADER,MPI_DOUBLE,MASTER,TAG_HEADER,MY_COMM_GRP,this->Stat);
            } else break;
        }
        time_arr[1] = (MPI_Wtime()-tmp_t); // Total bandwidth time for entire taskset

        file_cnt = dataQ.size();
        tmp_t = MPI_Wtime();
        printf("Slave: %d - got data. processing\n",myRank); fflush(stdout);
        while (dataQ.size()) { // process data
            out_hist = new hist_type();
            myDataType d = dataQ.back(); dataQ.pop_back(); // critical section
            ldp.process(d.data, d.nRows,d.nCols,out_opt,out_im, out_hist);
            resQ.push_back(*out_hist); out_hist=0;
            delete[] d.data; delete[] out_im->data;
        }
        time_arr[2] = (MPI_Wtime()-tmp_t); // Total processing time for entire taskset

        // tuma results
        //time_arr[1] /= file_cnt; time_arr[2] /= file_cnt;
        printf("Slave: %d - sending results\n",myRank); fflush(stdout);
        header[4]=myRank; header[6]=time_arr[0]; header[7]=time_arr[1]; header[8]=time_arr[2];
        for (size_t i = 0; i < resQ.size(); i++) {
            header[1]=resQ[i].h_nHists; header[2]=resQ[i].h_binSz; header[9]=resQ.size()-i-1;
            MPI_Send(header,SZ_HEADER,MPI_DOUBLE,MASTER,TAG_RESULT,MY_COMM_GRP);
            MPI_Send(resQ[i].hist_data,resQ[i].h_nHists*resQ[i].h_binSz,MPI_DOUBLE,MASTER,TAG_DATA,MY_COMM_GRP);
        }
        resQ.clear();

    } // end main while loop
    message("terminating");
}

It hangs after a random number of iterations of the if (idx<N) loop. I've been at this for the 2 whole days. Can someone please scrutinize the code and let me in the know on what's causing the problem? All help appreciated in advance

A: I decided to create unique header tags for every MPI communication pair - it did solve the problem. Is there a way I can delete this question?


text:
Q: Accessing UWP Child Element Programmatically from Other Class I have an UWP XAML named MyPage.xaml like below
<Page
    x:Class="AffiliaTool.Lib.View.BrowserWindowView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:core="using:Microsoft.Xaml.Interactions.Core"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:i="using:Microsoft.Xaml.Interactivity"
    xmlns:local="using:AffiliaTool.Lib.View"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:tk="using:Microsoft.Toolkit.Uwp.UI.Controls"
    xmlns:vm="using:AffiliaTool.Lib.ViewModel"
    mc:Ignorable="d">
    <tk:TabView x:Name="TabViewBar" />
</Page>

And from other class, I want to instantiate that class and manipulate TabView programmatically like below
var mypage = new MyPage();
mypage.TabViewBar.Visibility = Windows.UI.Xaml.Visibility.Collapsed;

I used to be able to access Child element programmatically from other class when coding WPF, but why can't I do that in UWP but from codebehind? Anyway to go around this?
Thanks

A: You can. Just add a FieldModifier like this:
<tk:TabView x:Name="TabViewBar" x:FieldModifier="public"/>

then you can access TabViewBar from another class.
Hope that helps.


text:
Q: How to convert a dictionary object to Node in py2neo? I have a dictionary object like the following
node_info = {'id':'2344','name':'xyz'}

I want to convert it to py2neo Node so that it can be created using graph.create(). Node.cast() is no longer supported. Any other way

A: According to the definition for py2neo v4.0's Node class:
class py2neo.data.Node(*labels, **properties)
which means you can pass any number of labels:
Node("Person", "Professor")
and any number of labelled/named properties:
Node(id=10, name="Long John Silver")

Answering your question
You can achieve the above with either a list (for labels) and dict (for named properties):
labels = ["Person", "Professor"]
props  = {"id": 10, "name": "Long John Silver"}
print(Node(*labels, **props))

will yield:
(:Person:Professor {id: 10, name: 'Long John Silver'})
This is because of Python's *args and **kwargs in python Geeks4Geeks ref


text:
Q: Get current logged in user in provider hosted app I have to get current logged in user in provider hosted app event receiver.
I used the below code to get the current user name, but I got current user name as Sharepoint App instead of Current logged in user.
currentUser = clientContext.Web.CurrentUser;
clientContext.Load(currentUser, x => x.LoginName, y => y.Id);
clientContext.Load(currentUser, Z => Z.Title);
clientContext.ExecuteQuery();

How to get the current logged in user?

A: If you are using app only context in your provider hosted app then you need to do a li'l extra work and use TokenHelper to get appOnlyAccessToken. On App's page load, just run the below script:
var contextTokenString = TokenHelper.GetContextTokenFromRequest(Page.Request);
Uri sharepointUrl = new Uri(Request.QueryString["SPHostUrl"]);
SharePointContextToken contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, Request.Url.Authority);
string appOnlyAccessToken = TokenHelper.GetAppOnlyAccessToken(contextToken.TargetPrincipalName, sharepointUrl.Authority, contextToken.Realm).AccessToken;
using (var clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl.ToString(), appOnlyAccessToken))
            {
                var currentUser = clientContext.Web.CurrentUser;
                clientContext.Load(currentUser);
                clientContext.ExecuteQuery();

                // TODO: display logged in user however you want
            }

Well, I am your savior today. You can thank me later! :)


text:
Q: How to avoid codeigniter cache we developed a site in codeingiter framework. we are facing a issue in codeigniter cache problem. The problem like this
When user is logged in, our header bar info should be Welcome Mr.xxxxx.
If user is logged out, our header info should be Welcome Guest.
Here user after logged out, the header is showing logged out user name.
While am pressing Ctrl+F5. It will appear correctly.
We tried a lot.
also set database query cache false $db['default']['cache_on'] = FALSE;
Inside a cache folder(application\cache) there is no cache file except index.html and .htaccess
The output cache also be $this->output->cache(0);.
And Also tried this one.
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate"/>
<meta http-equiv="Pragma" content="no-cache"/>
<meta http-equiv="Expires" content="0"/>

Any help or pointing in the right direction will be fine. Thx!

A: Have you tried using CI's output class?
http://www.codeigniter.com/userguide3/libraries/output.html#CI_Output::set_header
$this->output->set_header('HTTP/1.0 200 OK');
$this->output->set_header('HTTP/1.1 200 OK');
$this->output->set_header('Last-Modified: '.gmdate('D, d M Y H:i:s', $last_update).' GMT');
$this->output->set_header('Cache-Control: no-store, no-cache, must-revalidate');
$this->output->set_header('Cache-Control: post-check=0, pre-check=0');
$this->output->set_header('Pragma: no-cache');


text:
Q: Установка Drupal 7: failed to connect to your database server При установке Drupal 7 столкнулся с проблемой.

Failed to connect to your database server. The server reports the following message: SQLSTATE[28000] [1045] Access denied for user 'admin'@'localhost' (using password: YES).

Вот линк на скрин

ПС. Устанавливаю на виртуальный сервер.

A: Да в общем-то все просто... Drupal говорит вам, что не смог подключиться к указанной вами базе по указанному вами адресу с указанными вами учетными данными по причине того, что пользователю admin хоста localhoct запрещен доступ.Хотелось бы предварительно уточнить... К базе подключиться пробовали? Это в принципе возможно? Ну, типа, из shell или через phpMyAdmin? Пользователь admin в MySQL заведен, или только пост-установочный root? А root-ом подключиться пробовали?Одним словом - присоединяюсь к @Ilya Makarov. Подробности виртуалки в общем и базы в частности - в студию!
A: Похоже, что да, в MySQL есть у вас юзер admin с неизвестным паролем. А что, при установке об этом не спрашивали? Я бы в таком случае переименовал бы все конфиги, относящиеся к этому делу (переименовал бы - чтобы в случае чего можно было вернуть обратно), и запустил заново!


text:
Q: Pandas to calculate pct_change on specified freq option I would like to calculate 1 year, 2, years, 3 years growth rate of weekly/daily DataFrame :
start = '20100101'
end = '20201117'

df_ts = pd.DataFrame(index=pd.bdate_range(start=start, end=end, freq='D'))
df_ts['valeur1'] = range(1, df_ts.shape[0]+1)

df_ts['gr'] = 100*df_ts.pct_change(periods=1, freq='Y)
df_ts

I thought pct_change(periods=n, freq='Y') was the good way to do it but I get an error result with this simple date.
I need to emphasise that in my data I have weekly/daily data and I operate others operation so I need to put this inside apply(lambda x: x.pct_change(periods=n, freq='Y').
Any suggestions to do it simply ?

A: You are assigning a new dataframe to a column because you did .pct_change on the dataframe not the column. Try this:
df_ts['gr'] = df_ts['valeur1'].pct_change(periods=1, freq='Y')


text:
Q: Get data from SPList with a key value I´m starting with Sharepoint 2010 development with Visual Studio and I´ve been the entire evening looking for a solution to retrieve data from a list according with the value of one of its fields.
I´m looking for something like
SPListItem item = list.GetItemWithValue("Field_Name");

What I´m trying to achieve is convert a SPList into a html list with a TreeView format.
Thanks a lot for your help!

A: You can do this by using CAML query.
SPQuery oQuery = new SPQuery();
oQuery.Query= " <Where><Eq><FieldRef Name='Field_Name' /><Value Type='Text'>Field_Value</Value></Eq></Where>";
SPListItemCollection items = mylist.GetItems(oQuery);


text:
Q: how to check restart reason of stateful set in kubernetes cluster I am deploy a elasticsearch cluster in kubernetes,now the cluster pod restart for many times.For elasticsearch cluster stable,I want to find out why the cluster restart.Now I check the restart pods log it only shows the restarted log output,but the restarted log is no errors,I try to set the cluster not start automatic and I could see the error output on fail,It shows:
StatefulSet.apps "es-cluster" is invalid: spec.template.spec.restartPolicy: Unsupported value: "Never": supported values: "Always"

so which is the best way to find out why the pods restart?

A: To get a detailed view of the log snipper or immediate reasons for startup failures of a pod, run
kubectl describe pod <pod> -n <namespace>

Ideally you should run it as soon as a pod restarts (or you can force it by deleting the pod). This can/should be done in addition to the above comment that suggests tailing the logs, up to the moment when the pods fail to start. Be mindful that if there are multiple containers in a pod you may also need to
kubectl logs -f <pod> -n <namespace> -c <container name> --previous

Cheers

A: To get the log of restarted pod run
kubectl logs -f <pod> -n <namespace> --previous


text:
Q: Latex Error: File `siam10.clo' not found when I compile with Texify and PDFTexify recently I had installed Miktex 2.9.3972 because I have an old PIII running Windows XP service pack 3, but when I try to compile the Proof.tex file, PC gives this result:
Command Line:   texify.exe --src --tex-option=--interaction=errorstopmode --tex-option=--synctex=-1 "C:\Documents and Settings\Administrador\Mis documentos\BackUp\SS\Proof.tex"
Startup Folder: C:\Documents and Settings\Administrador\Mis documentos\BackUp\SS

This is pdfTeX, Version 3.1415926-1.40.11 (MiKTeX 2.9)
entering extended mode

("C:/Documents and Settings/Administrador/Mis documentos/BackUp/SS/Proof.tex"
LaTeX2e <2009/09/24>
Babel <v3.8l> and hyphenation patterns for english, afrikaans, ancientgreek, ar
abic, armenian, assamese, basque, bengali, bokmal, bulgarian, catalan, coptic,
croatian, czech, danish, dutch, esperanto, estonian, farsi, finnish, french, ga
lician, german, german-x-2009-06-19, greek, gujarati, hindi, hungarian, iceland
ic, indonesian, interlingua, irish, italian, kannada, kurmanji, lao, latin, lat
vian, lithuanian, malayalam, marathi, mongolian, mongolianlmc, monogreek, ngerm
an, ngerman-x-2009-06-19, nynorsk, oriya, panjabi, pinyin, polish, portuguese,
romanian, russian, sanskrit, serbian, slovak, slovenian, spanish, swedish, swis
sgerman, tamil, telugu, turkish, turkmen, ukenglish, ukrainian, uppersorbian, u
senglishmax, welsh, loaded.

("C:\Documents and Settings\Administrador\Mis documentos\BackUp\SS\spani
shsiamltex.cls"
Document Class: spanishsiamltex 1996/10/11 v1.2 LaTeX document class
("C:\Archivos de programa\MiKTeX 2.9\tex\latex\base\leqno.clo")
("C:\Archivos de programa\MiKTeX 2.9\tex\latex\base\leqno.clo")

! LaTeX Error: File `siam10.clo' not found.

Type X to quit or <RETURN> to proceed,
or enter new name. (Default extension: clo)

Enter file name:

Process has been terminated ...

I downloaded siamltex1213.zip which includes siam10.clo from:
https://www.siam.org/journals/auth-info.php

and I copied it to:
C:\Archivos de programa\MiKTeX 2.9

folder, but it doesn't work.
Does anyone know what can I do??
Thanks, Before Hand!!

A: I guess that C:\Archivos de programa\MiKTeX 2.9 is the standard path like c:\Progamme\MiKTeX 2.9 in a german installation or c:\Program Files\MiKTeX 2.9 in an english installation.  Then please do not manually install files there.
Looking into the named zip file I think the best way is for you to create a new directory MyLaTeX for your user "MyUser", for example C:\Users\MyUser\Documents\MyLaTeX.  Then copy/extract the files from the zip file into your directory MyLaTeX.  Now copy your file Proof.tex (and other files you needed for it like images) into the directory MyLaTeX.
To test the zip file you can compile file ex_article.tex and check the resulting log file for error messages.  That should compile without problems.
Now you can compile your file Proof.tex.
At last a tip: First test are easier done, if you use the terminal/console to start the compiling with pdflatex Proof.tex for LaTeX etc.
TeXify or PDFTeXify are separate programs and can result in error you will not get with compiling from terminal or start usual compiling (step by step) with your editor.
If you know what an local texmf is (I suggest you to learn the advantages of a localtexmf; there is a question about localtexmf on this web page, please use the search to find it) you can install the content of the zip into your local TeXMF tree.
Because we have not file Proof.tex I can not test it and show you the result on my computer ...


text:
Q: CSS float logic( inner text not moved) I would like to know float logic.
Please see below code.

a

b

result
http://jsfiddle.net/5ccLv2tb/
I can understand logic that blue box moves to left 0 top 0.
But Why is inner text (b) not moved ?

A: Essentially what's happening is that your second inner div, the one with the blue background and letter "b" as its content, isn't wide enough for the content to remain within the boundaries of the block you created, so it's pushed below the floated div, almost as if the clear property was set to left or both.
The W3 states:

Since a float is not in the flow, non-positioned block boxes created
  before and after the float box flow vertically as if the float did not
  exist. However, the current and subsequent line boxes created next to
  the float are shortened as necessary to make room for the margin box
  of the float.

Further...

If a shortened line box is too small to contain any content, then the
  line box is shifted downward (and its width recomputed) until either
  some content fits or there are no more floats present. Any content in
  the current line before a floated box is reflowed in the same line on
  the other side of the float. In other words, if inline-level boxes are
  placed on the line before a left float is encountered that fits in the
  remaining line box space, the left float is placed on that line,
  aligned with the top of the line box, and then the inline-level boxes
  already on the line are moved accordingly to the right of the float
  (the right being the other side of the left float) and vice versa for
  rtl and right floats.
The border box of a table, a block-level replaced element, or an
  element in the normal flow that establishes a new block formatting
  context (such as an element with 'overflow' other than 'visible') must
  not overlap the margin box of any floats in the same block formatting
  context as the element itself. If necessary, implementations should
  clear the said element by placing it below any preceding floats, but
  may place it adjacent to such floats if there is sufficient space.
  They may even make the border box of said element narrower than
  defined by section 10.3.3. CSS2 does not define when a UA may put said
  element next to the float or by how much said element may become
  narrower.

You can see that if the second inner div with the blue background is wider, say about 60px, then the content site to the right of the floated div, which is what is normally expected.
Example. In the following document fragment, the containing block is too narrow to contain the content next to the float, so the content gets moved to below the floats where it is aligned in the line box according to the text-align property.
p { width: 10em; border: solid aqua; }
span { float: left; width: 5em; height: 5em; border: solid blue; }

  Supercalifragilisticexpialidocious

This fragment might look like this:

A: The blue box is a block level box and its position is explained by the following:

Since a float is not in the flow, non-positioned block boxes created before and after the float box flow vertically as if the float did not exist.

(http://www.w3.org/TR/CSS21/visuren.html#floats)
The text "b" is a line box or a line of text, this means it will flow around the float under normal circumstances:

A line box is next to a float when there exists a vertical position that satisfies all of these four conditions: (a) at or below the top of the line box, (b) at or above the bottom of the line box, (c) below the top margin edge of the float, and (d) above the bottom margin edge of the float.

(http://www.w3.org/TR/CSS21/visuren.html#floats)
This can be seen if we remove the width restriction in your example:

a

b

However, as you have provided a width for the blue box the following is apparent:

If a shortened line box is too small to contain any content, then the line box is shifted downward (and its width recomputed) until either some content fits or there are no more floats present.

(http://www.w3.org/TR/CSS21/visuren.html#floats)
As there is no room for the text to flow alongside the floated element it gets pushed down below it. It appears disconnected from the blue box as its dimensions have been restricted and overflow is set to visible by default.
Removing the height restriction from your example will show how the blue box would normally expand to fit the text:

a

b


text:
Q: IIS7: rewriteMap equivalent of exact match rule

I have a site at mydomain.com/mysite and I want to configure a set of redirections in IIS7.
To redirect from mydomain.com/mysite/old.aspx to mydomain.com/mysite/new.aspx I can write:
<system.webServer>
  <rewrite>
    <rules>
      <rule name="test" patternSyntax="ExactMatch" stopProcessing="true">
        <match url="old.aspx" />
        <action type="Redirect" url="new.aspx" />
      </rule>
    </rules>

But to get the same with a rewrite map, instead, I also have to specify the /mysite/ part:
<rewriteMaps>
  <rewriteMap name="TestRewriteMap">
    <add key="/mysite/old.aspx" value="/mysite/new.aspx" />
  </rewriteMap>
</rewriteMaps>
<rules>
  <rule name="Redirect rule1 for TestRewriteMap">
    <match url=".*" />
    <conditions>
      <add input="{TestRewriteMap:{REQUEST_URI}}" pattern="(.+)" />
    </conditions>
    <action type="Redirect" url="{C:1}" appendQueryString="false" />
  </rule>
</rules>

Is there a way I can avoid specifying the site name in the rewrite map URLs?

A: I assume your put the web.config with this rewrite rule in the folder /mysite?
You should be able to replace {TestRewriteMap:{REQUEST_URI}} with {TestRewriteMap:{REQUEST_FILENAME}}. Then you you can remove /mysite/ from both the key and value in the <rewriteMap></rewriteMap>. Remember that this will also match any old.aspx deeper in the directory structure (under /mysite/).


text:
Q: Can't write to ostream in gnu linux c++ error: invalid operands of types ofstream and 'const char [2]' to binary 'operator Can't compile this small code on Linux:
#include <fstream>
#include <string>
#include <iostream>
#include <stdio.h>
using namespace std;
int main(){
    char fileName[512];
    sprintf(fileName, "test");
    ofstream iriFile(string(fileName));
    iriFile<<",";
    return 0;
}

I am compiling like this: g++ test.cpp and am getting this:

test.cpp:12:11: error: invalid operands of types
  'std::ofstream(std::__cxx11::string) {aka
  std::basic_ofstream(std::__cxx11::basic_string)}' and
  'const char [2]' to binary 'operator<<'   iriFile<<",";

What might be the reason?

A: Ok, the solution is to remove implicit string() creation:
string sFileName(fileName)
ofstream iriFile(sFileName);

A: First of all you do not need to explicitly convert const char * to std::string there is std::ifstream constructor for it:
 std::ofstream iriFile(fileName);

but if you want to be extra safe and verbose use proper C++ then:
std::ofstream iriFile( static_cast<std::string>(fileName) );

not C style cast.

A: As you pointed out, removing the explicit string creation fixes it.
It could be worth to add that this can also be fixed for types with explicit constructors by using list initialization, like so:
ofstream iriFile(string{sFileName});


text:
Q: Mapping a function with levelspec vs. Mapping over a flattened list I have borrowed the following cyclic permutations list making function from here.
CyclicPermutations[list_] := Map[RotateRight[list, #] &, Range[Length[list]] - 1]

Using this function I make a list of cyclic permutations of the digits of some prime numbers as follows:
Table[CyclicPermutations[IntegerDigits[Prime[n]]], {n, 100, 101}]

{{{5, 4, 1}, {1, 5, 4}, {4, 1, 5}}, {{5, 4, 7}, {7, 5, 4}, {4, 7, 5}}}

Reconstructing the list of numbers using Map[f,list,levelspec] and FromDigits gives:
Map[FromDigits,Table[CyclicPermutations[IntegerDigits[Prime[n]]], {n, 100, 101}], 1]

{{514, 451, 145}, {574, 457, 745}}

The integers have been permuted again in the reconstruction. However, the following code does not permute them again at the cost of losing needed structure:
FromDigits/@Flatten[Table[CyclicPermutations[IntegerDigits[Prime[n]]], {n, 100, 101}], 1]

{541, 154, 415, 547, 754, 475}

I could partition this list properly but it would be very nice to keep the original nested structure.
edit:
I changed my function slightly to:
CyclicPermutations[list_]:=Table[RotateRight[list, n],{n, 1, Length[list]}]

An implementation of Project Euler # 35
count = 0;
Table[If[AllTrue[FromDigits/@CyclicPermutations[IntegerDigits[Prime[n]]],PrimeQ],count+=1],{n, 1, 78498}];
count

55

A: You can use Map directly in your table. In your second line use:
Table[FromDigits /@ CyclicPermutations[IntegerDigits[Prime[n]]], {n, 100, 101}]

{{541, 154, 415}, {547, 754, 475}}

The issue with your Map[FromDigits, ...] solution is that you call FromDigits for a list of lists, instead of simple list of digits.  FromDigits seems to have some undocumented threading syntax:
FromDigits[{{1, 2, 3}, {1, 2, 3}, {1, 2, 3}, {1, 2, 3}}]

{1111, 2222, 3333}

A: You might be looking for MapAt:
MapAt[FromDigits, Table[CyclicPermutations[IntegerDigits[Prime[n]]], {n, 100, 101}], {All, All}]

{{541, 154, 415}, {547, 754, 475}}

{All, All} here means that FromDigits is applied to all elements in the second dimension. {All, 1} would apply it to the first element of all elements in in the second dimension. {1, All} would apply it to all of the elements of the first dimension.

A: You can Map FromDigits[Transpose @ #] & at level 1:
Map[FromDigits[Transpose@#] &,
 Table[CyclicPermutations[IntegerDigits[Prime[n]]], {n, 100, 101}], 1]

{{541, 154, 415}, {547, 754, 475}}

Alternatively, you can Map FromDigits  at level {2}
Map[FromDigits, Table[CyclicPermutations[IntegerDigits[Prime[n]]], {n, 100,
   101}], {2}]

{{541, 154, 415}, {547, 754, 475}}

You can also use:
Map[FromDigits, Transpose /@
  Table[CyclicPermutations[IntegerDigits[Prime[n]]], {n, 100, 101}], 1]

{{541, 154, 415}, {547, 754, 475}}

FromDigits[Transpose[#]] & /@
 Table[CyclicPermutations[IntegerDigits[Prime[n]]], {n, 100, 101}]

{{541, 154, 415}, {547, 754, 475}}