text:
Q: Is it possible to cache HLS segments with AVPlayer? Root Problem
Our video buffers a lot when seeking in iOS. It buffers quite a bit more than our web player which saves copies of the already watched segments in temp storage.
Desired Solution
Caching the video segments locally on the device's disk. We're fine with caching a single quality and always replaying it.
Blocker
We can't find a way to perform caching within AVFoundation/AVPlayer.
What We've Tried
2 ways to intercept networking requests with AVPlayer.

*

*Conforming to AVAssetResourceLoaderDelegate and handling the loading of the media manually

Doesn't work with HLS. You can load the m3u8 files by implementing AVAssetResourceLoaderDelegate, which allows you to pass authentication or to decrypt the response, however the .ts files can't be loaded.
Here's the code we tried:
https://gist.github.com/nathanhillyer/84e46152d7c4c88183b6

*Implementing a NSURLProtocol to capture requests for .ts files.

AVURLAsset actually avoids being intercepted. Somehow the network requests just don't get captured. (No clue why)

A: Actually, we can get AVPlayer to play a video from network but if you want to to cache the downloaded data to play it locally, with AVPlayer that seems impossible now.
Fortunately, there are a great API is the resourceLoader object in AVURLAsset, which you can provide controlled access to a remote audio file to AVPlayer. This works like a local HTTP proxy but without all the hassles.
You can find more detail on https://gist.github.com/anonymous/83a93746d1ea52e9d23f

A: Let's start with really good news - iOS 10 and up - gives this out of the box.
No more need for hacks soon. More details can be found in the following WWDC16 session about whats new in HTTP Live Streaming:
https://developer.apple.com/videos/play/wwdc2016/504/
Now back to the current state of things - iOS 9 and lower:
With AVPlayer, no. But you can cache HLS segments via a local HTTP server and play the local stream with AVPlayer.
AVPlayer and AVAsset don't contain the necessary information when dealing with HLS playback (It behaves differently than a MP4 static file for example).
TL;DR - You need to use HTTP requests to get the segments and serve them using a local HTTP Server.
A few companies, including the one I'm working for, are using this strategy.
Use a connection to download the segments at the quality you want, rebuild the manifest and flatten it all into one directory and one quality and then use a local http server inside the app to serve it to AVPlayer (AVPlayer can only play HLS streams served over HTTP - not from file assets).
There are edge cases, such as, buffering if you want to play and download in one run, rebuilding the m3u8 manifest correctly, and different AVPlayer states with disk reading.
I've found this out from first hand knowledge, both having such a system in production for 5 years and other video products in the App Store that use the same solution - in total serving many users.
This is also the best solution we've found for android.

A: Starting with iOS 10, you can use AVFoundation to download and store HLS movies on users' devices while they have access to a fast, reliable network, and watch them later without a network connection.
AVAssetDownloadURLSession
This wwdc2016/504/ session talks about Offline HLS. It is about downloading and persisting assets using AVAssetDownloadURLSession, which is a subclass of URLSession, and here is used to manage AVAssetDownloadTasks. The APIs mentioned in this session are available after iOS10.
AVAggregateAssetDownloadTask
wwdc2017/504 session introduced AVAggregateAssetDownloadTask in iOS11.

An AVAssetDownloadTask used for downloading multiple AVMediaSelections for a single AVAsset, under the umbrella of a single download task.

Apple provides an example project for using AVFoundation to Play and Persist HTTP Live Streams. Demo doc. The demo project uses AVAggregateAssetDownloadTask
AVAssetDownloadStorageManager
/wwdc2017/504 also introduced a new API, AVAssetDownloadStorageManager, to manage the policy for automatic purging of downloaded AVAssets.

*

*Expiration date

*Priority (important, default)

// Get the singleton
let storageManager = AVAssetDownloadStorageManager.shared()
// Set the policy
let newPolicy = AVMutableAssetDownloadStorageManagementPolicy()
newPolicy.expirationDate = myExpiryDate
newPolicy.priority = .important
storageManager.setStorageManagementPolicy(newPolicy, forURL: myDownloadStorageURL)

*

*Working with HTTP Live Streaming

A: About NSURLProtocol:
As I understood, it make own requests, so your custom tags/fields/marks will be removed.
I've made it other way: redirect segments requests to some custom url scheme and just check the scheme in protocol's canInitWithRequest method.
This way it works just fine. (spent a week to figure whole hls-processing thing out...)


text:
Q: stateful and stateless streaming processing While starting to learn streaming processing, I hear the following two technical items: stateful streaming processing, and stateless streaming processing, what are the difference between them? I heard storm is stateless while storm trident is stateful, so in practice, where to use storm and where to use storm trident?

A: The difference between the two is, at a very high level, in the kind of operation you have to perform on them.
Some operations are stateless, that is, you process a record at a time.
Think of a bank teller, that processes a stream of customers, one at a time. Each customer is a new unit of work that does not depend on the previous.
A stateful operation is like hiring a new employee. You have a stream of people coming for interviews, but if you hire them or not, depends on your state, that is, what positions you have open.
For example,  let's say you're processing web logs. If  you want to know how many users are looking at a page per second, your processing is almost stateless: every second you calculate how many users came per page. Each new second, you don't care about the result of the previous second. That is a stateless operation.
Let's say that instead you want to calculate a forecast of how many users you'll have in the next second. You want to average the last 10 minutes, so you need to keep a queue with the last 10 * 60 seconds - that's the state you need to keep for your processing, and you need to update it every second, to keep the most recent 10 minutes of state.
That's of course a stateful operation.
A simpler stateful operation is just counting the total number of page view since the beginning of the site.
One critical difference between the two operations is that if the stream stops and you reset the system, you gotta take care of saving the state.
A stateless operation does not have any state to save so it's generally simpler.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Preventing "'System.DateTime' failed because the materialized value is null" I would like to prevent this from happening but in a different way rather than setting type of DateCreated to nullable DateTime.
The full exception reads like this:

The cast to value type 'System.DateTime' failed because the
  materialized value is null. Either the result type's generic parameter
  or the query must use a nullable type.

When I run following query on the database I can see that there are no null records in there so I believe that I should avoid setting the DateCreate property to nullable DateTime as it does not make much sense to me (even though I know it would solve the problem). Is there something I am understanding wrong?

Following line from the query is causing the issue:
DateCreated = subJoined.dateUploaded

This is the full LINQ query:
using (var db = new ABEntities())
            {
                var features = (from textObject in db.textObjects
                                join container in db.containers.DefaultIfEmpty() on textObject.textObjectPK equals
                                    container.textObjectPK into tObjsContainerJoined
                                from subContainerJoin in tObjsContainerJoined.DefaultIfEmpty()
                                join tObjsMedia in db.media on subContainerJoin.mediaID equals
                                    tObjsMedia.mediaID into tObjsMediaJoined
                                from subJoined in tObjsMediaJoined.DefaultIfEmpty()
                                from textContainer in tObjsContainerJoined
                                where
                                    textObject.version == Constants.Versions.LATEST &&
                                    textObject.textObjectTypeID == Constants.News.FEATURES &&
                                    textObject.deployDate <= DateTime.Now
                                select new TextObject
                                {
                                    Id = textObject.textObjectID,
                                    Title = textObject.title,
                                    ContainerId = textContainer.containerID,
                                    Description = textContainer.container1,
                                    DateCreated = textObject.deployDate,
                                    Media = new Media
                                           {
                                               Title = subJoined.title,
                                               MediaFormat = subJoined.extension,
                                               MediaTypeID = subJoined.mediaTypeID,
                                               MediaFile = subJoined.fileName,
                                               Credit = subJoined.credit,
                                               MembersOnly = subJoined.membersOnly,
                                               LastModified = subJoined.lastModified,
                                               DateCreated = subJoined.dateUploaded
                                           },
                                    TypeId = textObject.textObjectTypeID
                                }).OrderByDescending(t => t.DateCreated).ToList();

                return features;
            }

Here is media class definition:
[Serializable]
    public class Media
    {
        public int Id { get; set; }
        public string MediaFile { get; set; }
        public string Title { get; set; }
        public string Credit { get; set; }
        public int? MediaTypeID { get; set; }
        public string MediaFormat { get; set; }
        public bool? isYoutube { get; set; }
        public string YoutubeID { get; set; }
        public int Width { get; set; }
        public int Height { get; set; }
        public int Views { get; set; }
        public string Description { get; set; }
        public int SiloID { get; set; }
        public DateTime DateCreated { get; set; }
        public bool IsVideo { get; set; }
        public int SegmentId { get; set; }
        public string Extension { get; set; }
        public bool? ShowOnHomepage { get; set; }
        public bool? MembersOnly { get; set; }
        public DateTime? LastModified { get; set; }
}

Query that was being generated - caught by SQL Profiler:
SELECT
    [Project1].[textObjectPK] AS [textObjectPK],
    [Project1].[textObjectID] AS [textObjectID],
    [Project1].[title] AS [title],
    [Project1].[containerID] AS [containerID],
    [Project1].[container] AS [container],
    [Project1].[deployDate] AS [deployDate],
    [Project1].[title1] AS [title1],
    [Project1].[extension] AS [extension],
    [Project1].[mediaTypeID] AS [mediaTypeID],
    [Project1].[fileName] AS [fileName],
    [Project1].[credit] AS [credit],
    [Project1].[membersOnly] AS [membersOnly],
    [Project1].[C1] AS [C1],
    [Project1].[dateUploaded] AS [dateUploaded],
    [Project1].[textObjectTypeID] AS [textObjectTypeID]
    FROM ( SELECT
        [Extent1].[textObjectPK] AS [textObjectPK],
        [Extent1].[textObjectID] AS [textObjectID],
        [Extent1].[textObjectTypeID] AS [textObjectTypeID],
        [Extent1].[title] AS [title],
        [Extent1].[deployDate] AS [deployDate],
         CAST( [Extent3].[lastModified] AS datetime2) AS [C1],
        [Extent3].[mediaTypeID] AS [mediaTypeID],
        [Extent3].[fileName] AS [fileName],
        [Extent3].[title] AS [title1],
        [Extent3].[extension] AS [extension],
        [Extent3].[credit] AS [credit],
        [Extent3].[dateUploaded] AS [dateUploaded],
        [Extent3].[membersOnly] AS [membersOnly],
        [Join4].[containerID] AS [containerID],
        [Join4].[container] AS [container]
        FROM    [dbo].[textObjects] AS [Extent1]
        LEFT OUTER JOIN  (SELECT [Extent2].[textObjectPK] AS [textObjectPK], [Extent2].[mediaID] AS [mediaID]
            FROM   ( SELECT 1 AS X ) AS [SingleRowTable1]
            INNER JOIN [dbo].[containers] AS [Extent2] ON 1 = 1 ) AS [Join1] ON [Extent1].[textObjectPK] = [Join1].[textObjectPK]
        LEFT OUTER JOIN [dbo].[media] AS [Extent3] ON [Join1].[mediaID] = [Extent3].[mediaID]
        INNER JOIN  (SELECT [Extent4].[containerID] AS [containerID], [Extent4].[textObjectPK] AS [textObjectPK], [Extent4].[container] AS [container]
            FROM   ( SELECT 1 AS X ) AS [SingleRowTable2]
            INNER JOIN [dbo].[containers] AS [Extent4] ON 1 = 1 ) AS [Join4] ON [Extent1].[textObjectPK] = [Join4].[textObjectPK]
        WHERE (1 = [Extent1].[version]) AND (2 = [Extent1].[textObjectTypeID]) AND ([Extent1].[deployDate] <= (SysDateTime()))
    )  AS [Project1]
    ORDER BY [Project1].[deployDate] DESC

A: Instead of setting the datatype to Nullable, you can convert your value in your query to a nullable type and check if this is null.
DateCreated = (DateTime?)subJoined.dateUploaded ?? DateTime.Now

Your query will look like this:
using (var db = new ABEntities())
{
    var features = (from textObject in db.textObjects
                    join container in db.containers.DefaultIfEmpty() on textObject.textObjectPK equals container.textObjectPK into tObjsContainerJoined
                    from subContainerJoin in tObjsContainerJoined.DefaultIfEmpty()
                    join tObjsMedia in db.media on subContainerJoin.mediaID equals tObjsMedia.mediaID into tObjsMediaJoined
                    from subJoined in tObjsMediaJoined.DefaultIfEmpty()
                    from textContainer in tObjsContainerJoined
                    where textObject.version == Constants.Versions.LATEST &&
                                    textObject.textObjectTypeID == Constants.News.FEATURES && textObject.deployDate <= DateTime.Now
                    select new TextObject
                    {
                          Id = textObject.textObjectID,
                          Title = textObject.title,
                          ContainerId = textContainer.containerID,
                          Description = textContainer.container1,
                          DateCreated = textObject.deployDate,
                          Media = new Media
                                 {
                                       Title = subJoined.title,
                                       MediaFormat = subJoined.extension,
                                       MediaTypeID = subJoined.mediaTypeID,
                                       MediaFile = subJoined.fileName,
                                       Credit = subJoined.credit,
                                       MembersOnly = subJoined.membersOnly,
                                       LastModified = subJoined.lastModified,
                                       DateCreated = (DateTime?)subJoined.dateUploaded ?? DateTime.Now
                                  },
                           TypeId = textObject.textObjectTypeID
                   }).OrderByDescending(t => t.DateCreated).ToList();

   return features;
}

Why does it gives an error on that specific line?
Disclaimer: this is just a guess (correct me if I'm wrong...)
Probably because you do a left join and EF expects that some values can be null and it throws an error as a precaution. It only throws an error at the DateTime datatype because it knows what to do when the other properties are null (strings and nullable types).


text:
Q: How to get the  tag value in this html with Selenium Webdriver using Java? How can the Webdriver xpath function be used to get the  tag value in the snippets below? The Java code is not working as expected.
Here is the HTML:

    QC_NUM:8300

Here is the Java code:
String valueOfbTag = driver.findElement(By.xpath("/p[1]/b[1]")).getText();

A: What you are using is an absolute xpath /p[1]/b[1] is expecting the root element in your xhtml to be p where I expect that you have html as your root element.
To solve this you can make it relative //p[1]/b[1] this will find all p elements in your tree and then find the first b element inside the first p element.
Te make this more specific you can select only the p elements with the correct class //p[@class='fontlarg'][1]/b[1].


text:
Q: Join controller names (Swagger) Is it possible to merge 2 different controls into one when we document in swagger?
from:
/api/v1/my_endpoint
/api/v1/my_controller_2/{id}
/api/v1/my_profile/{id}/all

to:
/api/v1/my_endpoint
/api/v1/my_endpoint/{id}
/api/v1/my_endpoint/{id}/all

Attached example
I'm using Swashbuckle (.Net Core)


text:
Q: Unable to use Ubuntu 19.04 on Asus Vivobook Pro (N580VD) I'm trying to install Ubuntu 19.04 on my Asus Vivobook Pro but I'm unable too.
I've made a bootable USB which works fine (and so does the installation process), But when the installation is finished I'm unable to reboot using the button in the installer (It will freeze). If I'm doing a hard reset, Ubuntu will boot but it will stutter and freeze from time to time.
What I've tried:

*

*Turned secure boot off

*Turned fast boot off

*Install without Nvidia drivers

*Install with Nvidia drivers

*Use a different bootable USB

*Use a different version (18.04)

*Use a different flavor (Ubuntu Budgie 18.04/19.04)

Does anyone have a clue how to fix this?

A: I just found an answer to my problem:

*

*Disable secure boot.

*Load Ubuntu from the USB, select "install Ubuntu" in GRUB and press "e".

*Change "Quiet splash" to "nomodeset" and press F10.

*Install Ubuntu with Nvidia drivers.


text:
Q: Hybris interceptor is not getting triggered I create ValidateInterceptor in below path and created bean in custombackoffice-backoffice-spring.xml

C:\hybris\bin\custom\custombackoffice\backoffice\src\com\custom\backoffice\interceptor\CustomAppeasementUserValidateInterceptor.java

bean is as below

<bean id="customAppeasementUserValidateInterceptor" class="de.hybris.platform.servicelayer.interceptor.impl.InterceptorMapping">
    <property name="interceptor" ref="customAppeasementUserValidateInterceptor" />
    <property name="typeCode" value="Appeasement" />
</bean>

when I modify particular model in backoffice and click on the save button, debugger never goes to interceptor it directly saves the model.
NOTE :- I can't write this interceptor in customcore because we can not import below services in custom core
import com.hybris.cockpitng.core.user.AuthorityGroupService;
import com.hybris.cockpitng.core.user.impl.AuthorityGroup;
Why the interceptor is not getting triggered?

A: The bean-id and the mapper bean-id are the same. Change either one. Ideally, it should be like-
<bean id="customAppeasementUserValidateInterceptorMapping" class="de.hybris.platform.servicelayer.interceptor.impl.InterceptorMapping">
    <property name="interceptor" ref="customAppeasementUserValidateInterceptor" />
    <property name="typeCode" value="Appeasement" />
</bean>

Notice the new id for the mapping bean i.e. customAppeasementUserValidateInterceptorMapping.


text:
Q: How to use postmessage() and content() methods on a cross domain environment? I have the below code that allows me to find the width of an input textbox inside an iframe on my webpage:
<iframe src="//www.example.com/" width="70%" height="500" id="frame"></iframe>
<script>
$( "#frame" ).contents().find( "input" ).css( "width" );
</script>

And I have this script that I used it in another website that allows me communicate from a child iframe to its parent mainpage
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

// Listening from iframe
eventer(messageEvent,function(e) {},false);

// into the sending child
parent.postMessage("SendWidthToParent","*");

I want to know how can I compact these two function in one (postmessage and contents), I couldn't manage to set the "contents script" into the "SendWidthToParent"
Appreciate any help.


text:
Q: Array of strings of multiple numbers. Math avg Please kindly help me with the following string/array mess.
The async function returns the following
[
'0 0 0.33 0.019 0 0 0.173 0.009',
'0 0.133 0 0 0 0 0 0.05',
'0.1 0.11 0.5 0 0 0 0 0.333',
'COMPLETE'
]
how do I find an average of the numbers of each string and how do I push the numbers of each string to its own html table?
I tried some combination of .toString().split() methods and the loops below but didnt get anywhere
const parametersOfCRWs = await getCRWs(idle, "worker:1");
let splits = parametersOfCRWs.toString().split(",");
let arr = "";
let sum = 0;
let count = 0;
for (let i = 0; i < splits.length-1; i++) {
arr = splits[i].split(" ");
for (let j = 0; j < arr.length; j++) {
sum = sum + Number(arr[j]);
console.log(arr[i]);
}
avg = sum / 8;   //always 8 numbers in every string
console.log(avg);

average number turned out to be wrong

A: You could split the strings, add all values and get the result for mapping.

const
    data = ['0 0 0.33 0.019 0 0 0.173 0.009', '0 0.133 0 0 0 0 0 0.05', '0.1 0.11 0.5 0 0 0 0 0.333', 'COMPLETE'],
    result = data.map(s => s === 'COMPLETE'
        ? s
        : s.split(' ').reduce((s, v) => s + +v, 0) / 8
    );

console.log(result);

A: This works even if you have unexpected tokens in your input strings. See snippet below.

const input = [
  "0 0 0.33 0.019 0 fssd 0 dfssd 0.173 0.009",
  "0 0.133 0 0 0 0 sdfsd 0 0.05",
  "0.1 0.11 0.5 dsfsd 0 0 dsfsd 0 0 0.333",
  "COMPLETE",
];

const output = input.map((str) => {
  const { sum, count } = str.split(" ").reduce(
    (avg, value) => {
      const possibleFloat = Number.parseFloat(value);
      if (isNaN(possibleFloat)) return avg;
      avg.sum += possibleFloat;
      avg.count++;
      return avg;
    },
    { sum: 0, count: 0 }
  );
  return sum / count;
});

console.log(output);

A: You can do something like:
(get your own data first, this data variable is just an example)

let data = [ "0 0 0.33 0.019 0 0 0.173 0.009", "0 0.133 0 0 0 0 0 0.05", "0.1 0.11 0.5 0 0 0 0 0.333", "COMPLETE" ]
data = data.map(e=> {
    if(e !== 'COMPLETE') {
        let average = 0
            e.split(' ').forEach(r => {average +=Number(r)})
        average = average/e.split(' ').length
        return average
    }
    return 'COMPLETE'
})
console.log(data)

output:
[ 0.066375, 0.022875, 0.130375, "COMPLETE" ]

A: The following code will give you a new array which contains the averages of all the numbers in each entry.

const validEntries = parametersOfCRWs.reduce((memo, entry) => {
  const numbers = entry.split(/\s+/);
  if (numbers.length !== 8) {
    // skip this entry (like "COMPLETE")
    return memo;
  }
  memo.push(numbers.map((n) => Number(n)));
  return memo
}, []);

const averages = validEntries.map((numbers) => numbers.reduce((a, b) => a + b));

console.log(validEntries, averages);

This basically assumes that the parametersOfCRWs is an actual javascript array.  So instead of toString().split(",") we just use it like an array.
For each entry we split the string by spaces.  If it doesn't have 8 entries (like "COMPLETE"), then we skip it.
If it does, we convert each element to a number so that we can compute the average.


text:
Q: send and receive files using sockets in c my problem is that when trying to send a .txt file from the server to the client, when the client receives the file only the first line of code in the txt is shown when in fact the entire file has to be shown, does anyone know how can i fix this problem?
Server
        FILE * Log = fopen("Log.txt", "r");
        while(!feof(Log)){
            char ms[T_MAX];
            fgets(ms, T_MAX, Log);
            if(send(client_socket, ms, T_MAX, 0) < 0){
                printf("\n[SERVER] ERROR -> %d\n",WSAGetLastError());
                            closesocket(servidor_socket);
                            closesocket(client_socket);
                            WSACleanup();
            return(1);
            }
        }
        fclose(Log);

this is what the server reads and would have to send to the client.
**
2022-10-24-17:18 :=============================
2022-10-24-17:19 :=======Example=======
2022-10-24-17:20 :=============================
**

Client

        if(recv(socket_aplication, ms, T_MAX, 0) <= 0){
                printf(" ERROR -> %d\n",WSAGetLastError());
                            closesocket(socket_aplication);
                            WSACleanup();
            return (1);
        }
            //here we show in the client console the result of what the server gave us
            printf(ms);

this is what the client console shows
**
2022-10-24-17:18 :=============================
**


text:
Q: Recognise Button Click from Instantiated Button - Hide Game Object in An Array Code is simply to generate buttons for a UI, and clicking the button hide the game object in the array, with only one visible at a time. At the moment I am struggling to get a button to work and change the game object that is visible, but have managed to get the object names in the array to replace the button text. Please Help!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ButtonListControl : MonoBehaviour
{

    [SerializeField]
    private GameObject ButtonTemplate;

    [SerializeField]
    private GameObject[] ApplianceList;
    GameObject ApplianceGUI;
    private int index;

    void Start()
    {
        ApplianceGUI = GameObject.Find("Canvas_GUI_ScrollList");
        ApplianceGUI.SetActive(false);

        // Finds GUI and turns off on run.

        foreach (GameObject Appliance in ApplianceList)
        {
            GameObject Button = Instantiate(ButtonTemplate) as GameObject;
            Button.GetComponent<ButtonListButton>().SetText(Appliance.name);
            Button.transform.SetParent(ButtonTemplate.transform.parent, false);

            Appliance.SetActive(false);

            if (ApplianceList[0])
                ApplianceList[0].SetActive(true);
            Button.SetActive(true);
        }
    }
  public void Option1Clicked()
    {
        foreach (GameObject Appliance in ApplianceList)
        {
            Appliance.SetActive(false);
            //Sets the current Game Object to false

            ApplianceList[1].SetActive(true);
            Debug.Log("New Appliance Chosen, Hiding Old model and displaying:", ApplianceList[1]);
        }
    }
       public void Option2Clicked()
    {
        foreach (GameObject Appliance in ApplianceList)
        {
            Appliance.SetActive(false);
            //Sets the current Game Object to false

            ApplianceList[2].SetActive(true);
            Debug.Log("New Appliance Chosen, Hiding Old model and displaying:", ApplianceList[2]);
        }
    }
       public void Option3Clicked()
    {
        foreach (GameObject Appliance in ApplianceList)
        {
            Appliance.SetActive(false);
            //Sets the current Game Object to false

            ApplianceList[3].SetActive(true);
            Debug.Log("New Appliance Chosen, Hiding Old model and displaying:", ApplianceList[3]);
        }
    }
       public void Option4Clicked()
    {
        foreach (GameObject Appliance in ApplianceList)
        {
            Appliance.SetActive(false);
            //Sets the current Game Object to false

            ApplianceList[4].SetActive(true);
            Debug.Log("New Appliance Chosen, Hiding Old model and displaying:", ApplianceList[4]);
        }
    }

A: When you instantiate a GameObject, you make a copy from the template.
When you call SetActive, you call it on the template objects so it's probably applied to the prefab.
You should call that on the instantiated object instead, so you need another list to store every clone.
Also, you can simplify the code quite a bit, giving every button an Index (when it's instantiated) representing it's position in the list and a reference to the list itself.
This way, you can set the OnClick callback in the Inspector to the ButtonListButton own method instead of having to create OptionNClicked for each one.
public sealed class ButtonListControl : MonoBehaviour
{
    private GameObject[] ApplianceList;

    // Hide every button except the one with the given index
    public void HideAllBut(int index)
    {
        for (int i = 0; i < ApplianceList.Length; i++)
        {
            ApplianceList[i].SetActive(i == index);
        }
    }

}
public sealed class ButtonListButton : MonoBehaviour
{
    [SerializeField]
    public int Index;
    [SerializeField]
    ButtonListControl List;

    // This asks the list to hide every button except for this one
    public void HideOthers()
    {
        List.HideAllBut(Index);
    }
}


text:
Q: Odd permissions on secondary harddrive in Win2008 R2 On my laptop I have a 250gb hd that's separated up in 2 drives:
C: which is 64gb
D: which is the rest.
I'm logging on my laptop as a domain user which is administrator on the laptop. However, when I want to save files through my browser on the D: drive i always receive an access denied. Same thing when I want to attach a vhd in hyper v that's on the D: drive. Also access denied. However no problems at all when using the C: drives.
So there is something weird going on, on that D: drive. Because I can move files to the D: drive using explorer just fine.
Any recommendations as what to do to make it use the exact same permissions as on the C: drive... This behavior was not present in Win7 or Vista and is something new to win2008 r2.
Thank you in advance.

A: I would guess that you don't have full control over the D: drive for your username. I don't know for sure, but 2008 may be more heavily locked down than Win7 or Vista.
It also could specifically be that the browser is running as more limited than administrator. Try to "run as" the browser as the Administrator account if you have access, or your account if you don't.

A: It's possible that by upgrading, the old owning user was not well converted to the new Windows version, therefore D: is owned by a phantom user.
The first step is to take ownership of D.
Start a Command Prompt box (cmd) using Run as Administrator, and enter:

takeown /r D:

(Use takeown /? for all options)
Then to give yourself full rights on the file:

cacls D: /t /e /G username:F

cacls can be used with wildcards and directory traversal. See:
Security from the command line with CACLS.
For a more evolved Visual Basic script see:
Xcacls.vbs to modify NTFS permissions.


text:
Q: How to run function after another function (UI form)? My problem is I need to push the button buttonGet to run function test (e) but only after three function executed (validateName (e), validateVk (e), validateEmail (e)) and appeared the new data in the form that will be checked by the function test (e).
All this should be done by clicking once buttonGet, is it possible?
Thank you for your time!
function doGet() {

            ...

              var handler = app.createServerHandler('_processSubmittedData').addCallbackElement(panel);
              var handler1 = app.createServerHandler('refresh').addCallbackElement(panel);
              var h1 = app.createServerHandler('validateEmail').addCallbackElement(panel);

              var h2 = app.createServerHandler('validateVk').validateMatches(vk, 'vk.com').addCallbackElement(panel);
              var h21 = app.createClientHandler().validateNotMatches(vk, 'vk.com')
              .forTargets(empty6)
              .setVisible(true);

              var h3 = app.createServerHandler('validateName').validateLength(fname, 2, 100).addCallbackElement(panel);
              var h31 = app.createClientHandler().validateNotLength(fname, 2, 100)
              .forTargets(empty1)
              .setVisible(true);

              button.addMouseUpHandler(handler);
          buttonGet.addClickHandler(h1)
        .addClickHandler(h2)
        .addClickHandler(h21)
        .addClickHandler(h3)
        .addClickHandler(h31)
        .addClickHandler(handler1);

        ...

              return app;
            }

function refresh(e) {
              ...

            }

function validateEmail(e){
              var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
              var app = UiApp.getActiveApplication();
              var email = e.parameter.email;
              Logger.log(email);
              if(emailPattern.test(email) == false) {
                app.getElementById('empty4');
                 }
              else {
                    app.getElementById('empty4').setText("Email принят!").setStyleAttribute('color', '#339900').setVisible(true)
                    app.getElementById('empty41').setText("ок");
                   }
              return app;
            }
function validateVk (e) {
              var app = UiApp.getActiveApplication();
              app.getElementById('empty6').setText('VK принят!').setStyleAttribute('color', '#339900').setVisible(true);
              app.getElementById('empty61').setText("ок");
              return app
            }
function validateName (e) {
              var app = UiApp.getActiveApplication();
              app.getElementById('empty1').setText('Здравствуйте, ' + e.parameter.fname + '!').setStyleAttribute('color', '#339900').setVisible(true);
              app.getElementById('empty11').setText("ок");
              return app
            }
function test(e) {
              var app = UiApp.getActiveApplication();
              var L1 = e.parameter.empty41
              var L2 = e.parameter.empty61
              var L3 = e.parameter.empty11
              if (L1 == 'ок' && L2 == 'ок' && L3 == 'ок') {
                app.getElementById('cb1').setVisible(true);
                app.getElementById('terms').setVisible(true);
              }
              return app
            }

A: I Think the best way to do it is to check directly each form element with a addChangeHandler. The addChangeHandler can check if all the fields are correctly filled in and only once it's done you can press the submit button.
Here a working example:
function doGet(){
 var app = UiApp.createApplication();
  var handler = app.createServerHandler("testData");
  var panel = app.createHorizontalPanel();
  var txt = app.createTextBox().setId("elementToTest").setName("elementToTest").addChangeHandler(handler);
  handler.addCallbackElement(txt);
  var but = app.createButton("submit").setId("submitButton").setEnabled(false);
  panel.add(txt).add(but);
  app.add(panel);
  return(app);
}

function testData(e){
  var app = UiApp.getActiveApplication();
  var val = e.parameter.elementToTest;
  if(val=="test"){
    app.getElementById("submitButton").setEnabled(true);
  }
  return(app);
}

I Hope I correctly answered your question.
Harold


text:
Q: Return default value if belongTo relation is returned null I have a belongTo relation, if join condition is matched then ok but when there is no data for this it returns null. In this case, I want it returns default value as I expected. This is what I try but it not success. Please help me?
class Task extends Model
{
    use SoftDeletes;

    protected $table = 'tasks';
    protected $fillable = [
        'name',
        'description',
        'project_id',
    ];
    protected $with = ['project', 'status'];

    // this is expected
    public function getProjectAttribute($value)
    {
        return $value ?? ['id' => '', 'name' => ''];
    }

    /**
     * @return App\Modules\Com\Models\Project
     */
    public function project()
    {
        return $this->belongsTo(Project::class, 'project_id', 'id')->select(['id', 'name']);
    }
}

With description attribute, I can override it but why I dont the same thing with project attribute? And how do I set where for project relation?
Like this Task::select(*)->project()->where('project.name', 'ABC');.

A: I've never used Laravel -- but... the documentation shows that you can set a default for belongsTo when using it for updating in order to avoid conditional checks. Perhaps it will work for selecting too.
You can try adding the default to the end of your call.
        return $this->belongsTo(Project::class, 'project_id', 'id')
               ->select(['id', 'name'])
               ->withDefault([
                     'project_id' => 'project.name',
                      'id' => 'ABC',
               ]);

Source: https://laravel.com/docs/6.x/eloquent-relationships#default-models
or
You could do a conditional check:
public function project()
{
    $return $this->belongsTo(Project::class, 'project_id', 'id')->select(['id', 'name']);

    if( $return === null )
      // return your default values
    else
      return $return;
}


text:
Q: Ejabberd install mod_multicast module through web interface I have installed ejabbered 15.09 on my mac. I am testing it with an iOS app and trying to send a multi cast message. For that my ejabberd server should have the "mod_multicast module".
I am trying to add it via web admin interface (Pic attached):
But no luck.. I have tried editing the ejabberd.yml file in the conf folder and added
mod_multicast:
access:
  multicast:
    all: allow
but still, when I send an IQ
I never see http://jabber.org/protocol/address this protocol in response, which signifies that my ejabbered server allows multicasting.

A: I think you should use empty option list with mod_multicast: []


text:
Q: Maximum likelihood estimator when $\sum_{j} \theta_j = 1$. How to impose this condition? I have a sample $x_1,\dots,x_n \stackrel{iid}{\sim}f(;\boldsymbol{\theta})$, where $\boldsymbol{\theta} = (\theta_1,\dots,\theta_d)$, and

*

*, $0<\theta_j<1$,

*$\sum_{j=1}^d\theta_j = 1$.

I can easily implement and evaluate the log likelihood function
$$\ell(\boldsymbol{\theta}) = \sum_{i=1}^n \log f(x_i;\boldsymbol{\theta}),$$
however I do not know how to impose the condition
$$\sum_{j=1}^d\theta_j = 1.$$
How is this kind of optimization done in maximum likelihood estimation?

A: You can write it as a sum over every $\theta_i$ except the last one, and replace that term with $1 - \sum_{j=1}^{d-1}\theta_i$.
If you also have boundaries (added, see comment), then you are in the realm of nonlinear contrained optimization, for which numerical and analytical approaches exist. Choices will depend on the actual $f$. There is  also the Lagrangian dual theorem which may be important in some cases. Perhaps you can look up a package in $R$ or $Python$ for maximum likelihood estimation and see how they do it.

A: Another practical solution that is pretty popular, is to define $\boldsymbol{\theta} \in \mathbb{R}^d$, and then use some function to transform it to desired range, e.g. in your case, you could use softmax function
$$
\ell(\boldsymbol{\theta}) = \sum_{i=1}^n \log f\Big(x_i;\;\operatorname{softmax}(\boldsymbol{\theta})\Big)
$$
If you need the parameter to be non-negative, you could use $\exp$ function, etc. The idea is to have unrestricted parameter values, that are transformed using a deterministic function to desired range.


text:
Q: interception coordinates of polygons Matplotlib I have two set of polygons gps coordinates (like on the picture). Is it possible in matplotlib (or maybe another library) to get coordinates of polygon which is intersection of two given polygons? Thanks in advance.

A: Although it may be overkill, but I recommend to use the Shapely package. An example is shown here which does exactly what you ask.
Matplotlib is only a plotting library so I don't think you can use it to solve this kind of problem.


text:
Q: Нумерация строк в ексель Подскажите кто знает, как пронумеровать строки в екселе?
Образец:

1

1

2

2

3

3

A: Вариант1. В А1 формулу и протянуть вниз:
=ЦЕЛОЕ(СТРОКА(A2)/2)

Вариант2.
В первых двух ячейках записать единицу, в третьей:
=A1+1

и протянуть формулу вниз


text:
Q: Uncaught (in promise): Server error I am getting this exception while using nativescript app.
EXCEPTION: Uncaught (in promise): Server error
JS: ORIGINAL STACKTRACE:
JS: Error: Uncaught (in promise): Server error
JS:     at resolvePromise (/data/data/com.yourdomain.appname/files/app/tns_modules/nativescript-angular/zone.js/dist/zone-nativescript.js:416:31)
JS:     at /data/data/com.yourdomain.appname/files/app/tns_modules/nativescript-angular/zone.js/dist/zone-nativescript.js:452:17
JS:     at ZoneDelegate.invokeTask (/data/data/com.yourdomain.appname/files/app/tns_modules/nativescript-angular/zone.js/dist/zone-nativescript.js:223:37)
JS:     at Object.onInvokeTask (/data/data/com.yourdomain.appname/files/app/tns_modules/@angular/core/bundles/core.umd.js:6197:41)
JS:     at ZoneDelegate.invokeTask (/data/data/com.yourdomain.appname/files/app/tns_modules/nativescript-angular/zone.js/dist/zone-nativescript.js:222:42)
JS:     at Zone.runTask (/data/data/com.yourdomain.appname/files/app/tns_modules/nativescript-angular/zone.js/dist/zone-nativescript.js:123:47)
JS:     at drainMicroTaskQueue (/data/data/com.yourdomain.appname/files/app/tns_modules/nativescript-angular/zone.js/dist/zone-nativescript.js:355:35)
JS: Unhandled Promise rejection: Server error ; Zone: angular ; Task: Promise.then ; Value: Server error

This is what i have :
login.component.tns.html
<StackLayout class="p-10">
<TextField [(ngModel)]="email" hint="email" autocorrect="false" autocapitalizationType="none"></TextField>
<TextField [(ngModel)]="password" hint="Password" secure="true"></TextField>
<Button text="signin" (tap)="login(user)"></Button>
<Button text="signup" (tap)="signup(user)"></Button>
</StackLayout>

login.component.ts
@BaseComponent({
moduleId: module.id,
selector: 'demo-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})

export class LoginComponent {
login() {
    this.user.password = this.password;
    this.user.username = this.email;
            this.loginService.signin(this.user)
        .subscribe(
        token => {
            this.loginCredentials.setUserId(token.userId);
            this.routerext.navigate(['/list'], {
                transition: {
                    duration: 1000,
                    name: 'slideTop',
                }
            });
        }
        )
};
}

login.service.ts
export class User {
constructor(
    public username: string,
    public password: string) { }
}

@Injectable()
export class LoginService {
signin(user: User) {
            return this.authModelApi.login({
        "email": user.username,
        "password": user.password
    })
        .map(token => token)
        .catch(this.handleError);
};
}

when clicking signin button i got this error "server Error". How should i resolve this issue? My web and desktop app working perfectly with this code. am using mongoDb as backend.am new to nativescript and angular2.Any help will really helpfull and highly appreciable.

A: I'm not sure which HTTP module you use to call this login service method
return this.authModelApi.login({
    "email": user.username,
    "password": user.password
})

From my experience, it seems for some reasons, you cannot use the native Angular HTTP module to perform HTTP requests. You have to use Nativescript HTTP module. So something like this,
import { getJSON, request } from "http";
...

return request({
  url: "....",
  method: "POST"
  headers: [your headers],
  content: [your content]
})

return getJSON("your url here")

Check out the official documentation here: https://docs.nativescript.org/angular/code-samples/http.html


text:
Q: Files list returned by os.walk is not in any discernible order Is there any way to sort the list of file names returned by os.walk such that it returns a list that is from youngest file to oldest file? Im trying to write a code that deletes files after a certain amount of time.
Here's what i have:
import os
import time
import shutil
from pathlib import pathlib
os.chdir("/home/pi/Videos")

while True:
    for root, files in os.walk(".", topdown = True)
        for name in files:
            f = os.path.join(root, name)
            print(f)

    st = os.stat(f)
    age = time.time()-st.st_mtime)
    print(age)
    if age > 200
       os.remove(f)
    time.sleep(1)

This works to delete any files in a folder, but if the file in question is not old enough to be deleted it will wait until the file can be deleted until it can move on to the next file. This is a problem. D:<
I've tried to use the shutil, pathlib, and os libraries to move the file from the folder it is in back into the folder it's in, but it doesn't change anything. ):< I'm out of knowledge of libraries.(im new)
I either need to organize the list returned by the os.walk() method so that the oldest are at the bottom (or top it doesnt matter) or have a way to skip the file if the file is underage.
Any help would be greatly appreciated. :D

A: I figured it out, thanks to @jpf, but i had to totally rework my code based on their suggestion. As stated in the question my ultimate goal is a code that deletes files that are older than x amount of time.
Here is the code that i came up with based on the suggestion.
import os
import time
os.chdir("/home/pi/Videos")
max_age = 50000 #this sets the maximum age of the files
while True:
    list_of_files = os.listdir() #returns list of all files in a folder
    sorted_list = sorted(list_of_files,key = os.path.getmtime)#sorts list based on age
    file = sorted_list[0] #defines oldest file in list
    st = os.stat(file)
    age = (time.time() - st.st_mtime) #returns age of file in seconds by subtracting time since epoch from time of file metadata change
    print(file,"is",age,"seconds old")
    if age > max_age: #checks if file is older than max_age
         print(file,"is older than ",max_age," seconds old") #if older prints this statement and deletes the file
         os.remove(file)
    else   #if younger then the loop breaks
         break

This code uses os.listdir to return the file names in a list.
Then I used sorted to sort that list from oldest to youngest
Then I started the deletion process from oldest to youngest, breaking when the file age was too young to delete.


text:
Q: useEffect hook is running in loop and hanging the application What I am building here is a simple todo application using hooks
with two input fields and one submit button. On submit I am saving the content of the inputs in an array and storing it in async storage. Using retrieve function I am fetching the values and displaying it below in a view component in list form.
useEffect(() => {
  // AsyncStorage.clear();
  retrieveData();
}, [data]);

const retrieveData = async () => {
  try {
    const valueString = await AsyncStorage.getItem("user");
    const value = JSON.parse(valueString);
    setData(value);
  } catch (error) {
    console.log(error);
  }
};

Removing the data element from the useEffect, doesn't update the component and the current value updated in the array is not displayed. It does get displayed only after another text is added in the array and the same goes on for the future addition to the data. But the app doesn't hang for sure.
Thanks for any help

A: Your useEffect hook will run any time data is changed. (As it is in the dependency list).
However, inside your useEffect you call retrieveData which calls setData(value);.
This will update data. Which in turn, will trigger useEffect again.
If you are wanting to just call retrieveData once on startup, you can empty the dependency list and it will act like componentDidMount.

A: You are passing [data] as second argument to useEffect which is dependency list.

That is the reason it is looping infinite. change it to [], it will run only once.
useEffect(() => {
    // AsyncStorage.clear();
    retrieveData();
  }, [data]);


text:
Q: Unknown property when using html-data-id attribute in apex:dataTable I am getting a unknown property error, when using the var from data table in a html-data-id attribute, it is working in apex attributes perfect. I can't figure out how to make it work for html-data-id attribute.
                <apex:dataTable value="{!flatProductlineItems}" var="lineItem">
                    <apex:column headerValue="{!$ObjectType.Opportunity_Line_Item__c.fields.Category__c.Label}" styleClass="{!if(lineItem.showError=true,'ErrorInRed','')}">
                        <apex:outputText value="{!lineItem.product.Category__c}" rendered="{!IF(lineItem.lastRecord, false, true)}" />
                    </apex:column>
                    <apex:column headerValue="{!$ObjectType.Opportunity_Line_Item__c.fields.District__c.Label}" styleClass="{!if(lineItem.showError=true,'ErrorInRed','')}">
                        <apex:outputText value="{!lineItem.product.District__c}" rendered="{!IF(lineItem.lastRecord, false, true)}" />
                    </apex:column>
                    <apex:column headerValue="{!$ObjectType.Opportunity_Line_Item__c.fields.Start_Date__c.Label}" styleClass="{!if(lineItem.showError=true,'ErrorInRed','')}">
                        <apex:inputField value="{!lineItem.product.Start_Date__c}" rendered="{!IF(lineItem.lastRecord == false, true, false)}"/>
                    </apex:column>
                    <apex:column headerValue="{!$ObjectType.Opportunity_Line_Item__c.fields.Total_Amount__c.label}" styleClass="{!if(lineItem.showError=true,'ErrorInRed','')}">
                        <apex:inputText html-data-id="{!lineItem.position}" style="text-align:right;" value="{!lineItem.product.Total_Amount__c}" rendered="{!IF(lineItem.lastRecord == false, true, false)}" />
                        <apex:inputText value="{!lineItem.subTotalAmount}" style="text-align:right;" rendered="{!lineItem.lastRecord}" html-readonly="true" />
                    </apex:column>
                    <apex:column styleClass="{!if(lineItem.showError=true,'ErrorInRed','')}">.
                        <apex:commandButton value="-" action="{!removeFlatProduct}" status="LoadingSpinner" rendered="{!IF(lineItem.lastRecord == false, true, false)}" reRender="flatPanelContainer,errorPanel" style="text-align:center;width:20px;">
                            <apex:param name="flatProductToRemove" value="{!lineItem.position}" assignTo="{!flatProductToRemove}" />
                        </apex:commandButton>
                    </apex:column>
                </apex:dataTable>

I am getting an error that the property lineItem is not found in the controller  , however it should use the property from var attribute.
Here is the flatProductLineItems variable in the controller:
   public List<LineItemWrapper> flatProductLineItems { get {
        if(flatProductLineItems == null) {
            flatProductLineItems = new List<LineItemWrapper>();
        }
        return flatProductLineItems;
    } set; }

If i remove the attribute html-data-id from the apex:inputText everything is compiling and working ok.

A: This is what I tried and it's working for me. Make sure you put the datatable tags inside the apex:form tag.
    <apex:page controller="CONTROLLER">
     <apex:form>
      <apex:dataTable value="{!LIST}" var="VAR">
        <apex:column headerValue="Name">
            <apex:inputText html-data-id="{!VAR.NameString}" value="
                                                            {!VAR.NameString}"/>
        </apex:column>
     </apex:dataTable>
  </apex:form>
</apex:page>


text:
Q: How can I tell if a set of parens in Perl code will act as grouping parens or form a list? In perl, parentheses are used for overriding precedence (as in most programming languages) as well as for creating lists. How can I tell if a particular pair of parens will be treated as a grouping construct or a one-element list?
For example, I'm pretty sure this is a scalar and not a one-element list: (1 + 1)
But what about more complex expressions? Is there an easy way to tell?

A: *

*Context.

*Parentheses don't have the role you think they have in creating a list.

Examples:
$x = 1 + 1;   # $x is 2.
$x = (1 + 1); # $x is 2.
@x = 1 + 1;   # @x is (2).
@x = (1 + 1); # @x is (2).

$x = (1 + 1, 1 + 2); # $x is 3.
@x = (1 + 1, 1 + 2); # @x is (2, 3).

Roughly speaking, in list context the comma operator separates items of a list; in scalar context the comma operator is the C "serial comma", which evaluates its left and right sides, and returns the value of the right side. In scalar context, parentheses group expressions to override the order of operations, and in list context, parentheses do... the exact same thing, really. The reason they're relevant in assigning to arrays is this:
# Comma has precedence below assignment.
# @a is assigned (1), 2 and 3 are discarded.
@a = 1, 2, 3;

# @a is (1, 2, 3).
@a = (1, 2, 3);

As for your question "is it a scalar or a one-element list", it's just not a meaningful question to ask of an expression in isolation, because of context. In list context, everything is a list; in scalar context, nothing is.
Recommended reading: perlop, perldata, Programming Perl.

A: Three key principles are useful here:
Context is king. The evaluation of your example (1 + 1) depends on the context.
$x = (1 + 1); # Scalar context. $x will equal 2. Parentheses do nothing here.
@y = (1 + 1); # List context. @y will contain one element: (2).
              # Parens do nothing (see below), aside from following
              # syntax conventions.

In a scalar context, there is no such thing as a list. To see this, try to assign what appears to be a list to a scalar variable. The way to think about this is to focus on the behavior of the comma operator: in scalar context it evaluates its left argument, throws that value away, then evaluates its right argument, and returns that value. In list context, the comma operator inserts both arguments into the list.
@arr  = (12, 34, 56); # Right side returns a list.

$x    = (12, 34, 56); # Right side returns 56. Also, we get warnings
                      # about 12 and 34 being used in void context.

$x = (@arr, 7);       # Right side returns 7. And we get a warning
                      # about using an array in a void context.

Parentheses do not create lists. The comma operator creates the list (provided that we are in list context). When typing lists in Perl code, the parentheses are needed for precedence reasons -- not for list-creation reasons. A few examples:

*

*The parentheses have no effect: we are evaluating an array in scalar
context, so the right side returns the array size.
$x = (@arr);

*Parentheses are not needed to create a list with one element.
@arr = 33;         # Works fine, with @arr equal to (33).

*But parentheses are needed with multiple items -- for precedence reasons.
@arr = 12, 34, 56; # @arr equals (12). And we get warnings about using
                   # 34 and 56 in void context.


text:
Q: Run-Time error '1004' Application-defined or object-defined error on extracting webpage data Hi I am trying to extract data from a website using excel VBA
but I am getting error on line With Sheets("WTD Inputs PPR").Range("A1").QueryTable
Sub WTDPPR()
    Set Rng = ActiveCell
    Application.ScreenUpdating = False

    Sheets("WTD Inputs PPR").Visible = True
    Sheets("WTD Inputs PPR").Select
    Columns("A:AA").Select
    Selection.ClearContents
    With Sheets("WTD Inputs PPR").Range("A1").QueryTable
     .Connection = "URL;" + Range("LinkWTDPPR").Value
     .Refresh BackgroundQuery:=False
     Sheets("WTD Inputs PPR").Select
     Columns("A:A").Select
     Selection.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
     Semicolon:=False, Comma:=True, Space:=False, other:=False, FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), _
     Array(7, 1), Array(8, 1), Array(9, 1), Array(10, 1), Array(11, 1), Array(12, 1), Array(13, 1), Array(14, 1), Array(15, 1), Array(16, 1), Array(17, 1)), TrailingMinusNumbers:=True

     Application.ScreenUpdating = False
     Sheets("WTD Inputs PPR").Visible = False

    End With
    Application.ScreenUpdating = False

End Sub

Since I'm a novice at VBA, could you help me identify where the problem is occuring and any way i can resolve it?


text:
Q: record the values in ascending in dataframe is a table of the following form
numbers
0   2,4,9,1,3
1   10,5,8,2
2   4,8
3   5,2,9,6
4   3,8,5,1

how to record the values in ascending?
need to get a table of the following form
 numbers
0   1,2,3,4,9
1   2,5,8,10
2   4,8
3   2,5,6,9
4   1,3,5,8

A: You can split the strings, sort the integers and then join them back as strings:
df.numbers.apply(lambda x: ','.join(map(str, sorted(map(int, x.split(","))))))

#0    1,2,3,4,9
#1     2,5,8,10
#2          4,8
#3      2,5,6,9
#4      1,3,5,8
#Name: numbers, dtype: object

You can assign this back to column numbers if you want to change the column to the new sorted version:
df['numbers'] = df.numbers.apply(lambda x: ','.join(map(str, sorted(map(int, x.split(","))))))


text:
Q: Question regarding differentiability of a function on a closed interval versus at a point. I'm currently new to Calculus and i'm really confused about the differentiability of a function. Especially when it comes to differentiability on a closed interval versus at a point.
So suppose I have a function $f(x)=3x+1$ at $x$ in [-3,2]. Outside of its domain, the function is not defined.
What i could inferred from the textbook is that, $f(x)$ is continuous on the closed interval [-3,2], because it is differentiable on (-3,2) and is respectively right-sided and left-sided differentiable on -3 and 2.
But then, what could I say about its differentiability on the point -3 and 2? As the textbook defined, for the function to be differentiable on a point c, $f'(c+)$ must be equal to $f'(c-)$. From that, I could say that the function is not differentiable at points -3 and 2 because the $f'(3-)$ and $f'(2+)$ does not exist.
So now am I able to conclude that $f(x)$ is differentiable on [-3,2] but not at the two points -3 and 2 themselves? Is this contradicting each others?
I really appreciate any help, thank you.


text:
Q: Local Google Cloud Appengine not starting I am trying to run the getting-started samples from Google for Google Cloud Appengine (https://github.com/GoogleCloudPlatform/getting-started-java/tree/master/appengine-standard-java8/helloworld). Although the deployment works and it is running in Google Cloud, I fail to start it for the local Java appengine emulator.
Google SDK is newest (231), Maven 3.5, Java 8.
I try to start that with "mvn appengine:run"
an 26, 2019 11:18:18 PM com.google.cloud.tools.appengine.cloudsdk.CloudSdk logCommand
INFO: submitting command: /usr/lib/jvm/java-ibm-x86_64-80/jre/bin/java -Duse_jetty9_runtime=true -D--enable_all_permissions=true -Dappengine.sdk.root=/home/user/workspace/google-cloud-sdk/platform/google_appengine/google/appengine/tools/java -cp /home/user/workspace/google-cloud-sdk/platform/google_appengine/google/appengine/tools/java/lib/appengine-tools-api.jar com.google.appengine.tools.development.DevAppServerMain --allow_remote_shutdown --disable_update_check --no_java_agent /home/user/workspace/umapi/v1.0.2/server/target/helloAppengine-1.0.0
[INFO] GCLOUD: java.lang.RuntimeException: Unable to create a DevAppServer
[INFO] GCLOUD:  at com.google.appengine.tools.development.DevAppServerFactory.doCreateDevAppServer(DevAppServerFactory.java:401)
[INFO] GCLOUD:  at com.google.appengine.tools.development.DevAppServerFactory.access$000(DevAppServerFactory.java:31)
[INFO] GCLOUD:  at com.google.appengine.tools.development.DevAppServerFactory$1.run(DevAppServerFactory.java:318)
[INFO] GCLOUD:  at com.google.appengine.tools.development.DevAppServerFactory$1.run(DevAppServerFactory.java:315)
[INFO] GCLOUD:  at java.security.AccessController.doPrivileged(AccessController.java:640)
[INFO] GCLOUD:  at com.google.appengine.tools.development.DevAppServerFactory.createDevAppServer(DevAppServerFactory.java:314)
[INFO] GCLOUD:  at com.google.appengine.tools.development.DevAppServerMain$StartAction.apply(DevAppServerMain.java:384)
[INFO] GCLOUD:  at com.google.appengine.tools.util.Parser$ParseResult.applyArgs(Parser.java:45)
[INFO] GCLOUD:  at com.google.appengine.tools.development.DevAppServerMain.run(DevAppServerMain.java:257)
[INFO] GCLOUD:  at com.google.appengine.tools.development.DevAppServerMain.main(DevAppServerMain.java:248)
[INFO] GCLOUD: Caused by: java.lang.RuntimeException: java.lang.NoSuchMethodException: sun.net.www.protocol.https.Handler.openConnection(java.net.URL)
[INFO] GCLOUD:  at com.google.appengine.tools.development.StreamHandlerFactory.getDeclaredMethod(StreamHandlerFactory.java:162)
[INFO] GCLOUD:  at com.google.appengine.tools.development.LocalURLFetchServiceStreamHandler.<init>(LocalURLFetchServiceStreamHandler.java:52)
[INFO] GCLOUD:  at com.google.appengine.tools.development.StreamHandlerFactory.<init>(StreamHandlerFactory.java:106)
[INFO] GCLOUD:  at com.google.appengine.tools.development.StreamHandlerFactory.install(StreamHandlerFactory.java:65)
[INFO] GCLOUD:  at com.google.appengine.tools.development.DevAppServerImpl.<init>(DevAppServerImpl.java:125)
[INFO] GCLOUD:  at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
[INFO] GCLOUD:  at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:83)
[INFO] GCLOUD:  at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:57)
[INFO] GCLOUD:  at java.lang.reflect.Constructor.newInstance(Constructor.java:437)
[INFO] GCLOUD:  at com.google.appengine.tools.development.DevAppServerFactory.doCreateDevAppServer(DevAppServerFactory.java:386)
[INFO] GCLOUD:  ... 9 more
[INFO] GCLOUD: Caused by: java.lang.NoSuchMethodException: sun.net.www.protocol.https.Handler.openConnection(java.net.URL)
[INFO] GCLOUD:  at java.lang.Class.newNoSuchMethodException(Class.java:562)
[INFO] GCLOUD:  at java.lang.Class.throwExceptionOrReturnNull(Class.java:1195)
[INFO] GCLOUD:  at java.lang.Class.getMethodHelper(Class.java:1259)
[INFO] GCLOUD:  at java.lang.Class.getDeclaredMethod(Class.java:931)
[INFO] GCLOUD:  at com.google.appengine.tools.development.StreamHandlerFactory.getDeclaredMethod(StreamHandlerFactory.java:158)
[INFO] GCLOUD:  ... 18 more
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 10.816 s
[INFO] Finished at: 2019-01-26T23:18:18+01:00
[INFO] Final Memory: 45M/153M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal com.google.cloud.tools:appengine-maven-plugin:1.3.1:run (default-cli) on project helloAppengine: Execution default-cli of goal com.google.cloud.tools:appengine-maven-plugin:1.3.1:run failed: Non zero exit: 1 -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginExecutionException

A: I found now the error myself.
It is simply not working with "java-ibm-x86_64-80" in JAVA_HOME.
I am using now instead "java-8-openjdk-amd64" as JAVA_HOME and no problem anymore.


text:
Q: Variables no declaradas en word 2007 Voy a hablar de versiones algo antiguas, pero es lo que hay.
Trabajo a menudo con Word 2003. He mantenido esta versión porque en Word 2007 la estructura de barras de la interfaz de usuario es mucho menos personalizable y no quiero renunciar a mis barras y botones asociados a macros programadas por mi.
Ahora estoy haciendo pruebas a ver cómo va el pasarme por fin a 2007. Para ello he creado una normal.dotm a partir de mi antigua normal.dot. No me preocupa ahora el mencionado tema de las barras (estoy dispuesto a renunciar a parte de la personalización) pero me encuentro con el siguiente problema: aunque asumo que no es la practica más aconsejable, tengo muchas macros en las que utilizo variables que no he declarado. Al ejecutarlas ahora en word 2007, mis macros se detienen, aparece el mensaje <"Error de compilación. No se puede encontrar el proyecto o la biblioteca"> y el intérprete aparece detenido en la línea donde aparece la variable no declarada.
Entonces voy a Editor de VBA - Herramientas - Opciones y deshabilito la opción <"Requerir declaración de variables">. Pero el problema sigue igual. Adelanto que no es una cuestión relativa a que falten Librerías, porque se reproduce con un programa como
    Sub prueba ()
    'Dim aaaaadd As String
    aaaaadd = "dfdfd"
    End Sub

y además porque si descomento la línea con la declaración el programa corre normalmente sin interrupmirse.
¿Alguna sugerencia?


text:
Q: impulses in domain region and something in frequency region I am studying about the fourier series and fourier transform.
and I am suffering to deal with the picture that I will show you

I am sure that the signal upper in the picture has periodicity and
I know that some periodic continous signals can be represented by impulses
(because of fourire series)
but I don't know why those signals with same magnitude.
So my question is that
why the signals in lower picture is same value at P, 2P, 3P ?
and How can I get those signals( impulses which have same value ) from the
upper circle?
Thank you for answers in advanced.


text:
Q: Как изменить функцию лайка в конструкторе класса Вместо того, чтобы брать элемент лайка из события, можно определить свойство, в котором будет храниться кнопка. Причем определить нужно в методе, который вызывается единожды в течение жизни экземпляра класса(от его создания до уничтожения), чтобы поиск не производится при каждой обработке события:
Подскажите, пожалуйста, как это реализовать на моем проекте, я новичок и запуталась.
Пример.
someMethod1() {
   this._element = document.querySelector(...);
}

someMethod2() {
   // использование элемента из this._element
}

   class Card {
     constructor(data, templateSelector, openImagePopup) { // Передаю данные в виде объекта, а в самом классе присвоить полям нужные свойства:
       this._name = data.name;
       this._link = data.link;
       this._openImagePopup = openImagePopup;
       this._templateSelector = templateSelector,'#card__template';
     }

     /** Получить нужную разметку */
     _getTemplateCard() {
       const cardElement = document
         .querySelector(this._templateSelector)
         .content
         .querySelector('.element')
         .cloneNode(true); // Клонирую элемент

       return cardElement; // Возвращаю разметку карточки
     }

   /// Не получается сделать, все окрашивается в черный цвет///
     // _likeButton(like) {
     //   this._element = document.querySelector(like, '.element__like');
     // }
     // _handleLikeButton(like) {
     //   like.this._element.classList.toggle('element__like_active');
     //   }
     /////////////

     /** Навешиваю слушатель события */
     _setEventListeners() {
       const deleteCard = this._element.querySelector('.element__delete');
       deleteCard.addEventListener('click', () => this._handleDeleteButton())

       const likeCard = this._element.querySelector('.element__like');
       likeCard.addEventListener('click', (evt) => this._handleLikeButton(evt))
     }

    generateCard() {
       // Запишем разметку в приватное поле _element.
       // Так у других элементов появится доступ к ней.
       this._element = this._getTemplateCard();
       this._setData();
       this._setEventListeners();

       return this._element;
     }
   }


text:
Q: Domain name changes - how to redirect with ASP MVC 4 we have change our domain name from old.com to new.com and put a new ASP MVC 4 web site on old.com
Because search engine still point to old.com we would like to redirect some urls to the new one.
What is the possible ways to tap into ASP MVC pipeline to respond with redirect answer?
Thank you,
Ido.

A: If the only thing that has changed is the domain name, why not just use IIS to set up a permanent site redirect from old to new instead of using MVC?

A:
The HTTP response status code 301 Moved Permanently is used for
  permanent redirection.
Google recommends using a 301 redirect to change the URL of a page as
  it is shown in search engine results.

According to this question here you have 2 options:

*

*Installing the HTTP Redirect feature in IIS7.

*Do redirection at application level (using Application_BeginRequest at Global.asax).


text:
Q: jquery get values of multiple button clicked in twig i put a button in loop of ring and loop or jewel each, so i can get the value of the selected ring and jewel each. However, i can only select one among ring and jewel. when i click ring and then jewel, the ring button that i selected is no longer focused.
How can i separate them so that i can only select one in ring and one in jewel?
this is the styles

this is the javascript
$(".button").click(function(){
        var value = $(this).val();
        //alert(value);
    })
    $(".button2").click(function(){
        var value = $(this).val();
        //alert(value);
    })

this is the twig

    {% set idx = 0 %}
    {% for ring in rings %}

            {% set path = 'customRing/ring/' ~ring.ring_shape~ '/' %}
            <button class="button" value = "{{ring.id}}">

            </button>
            {% set idx = idx + 1 %}

Ring Name: {{ ring.ring_name }}

Ring Type: {{ ring.ring_type }}

Ring Shape: {{ ring.ring_shape }}

Ring Size: {{ ring.size }}

Price: {{ ring.price }}

    {% endfor %}

    {% for jewel in jewels %}

Ring Name: {{ jewel.jewel_name }}

Ring Type: {{ jewel.jewel_rotation }}

Price: {{ jewel.price }}

            <button class="button2" value = "{{jewel.id}}">
                {% set path = 'customRing/jewel/' ~jewel.image_name~%}

            </button>

    {% endfor %}

A: i changed css and jquery to this and it's working
$(document).ready(function () {
        var ring_button = $(".button").on("click", function () {
            $(".button").removeClass("active");
            $(this).addClass("active");
        });
        var jewel_button = $(".button2").on("click", function () {
            $(".button2").removeClass("active");
            $(this).addClass("active");
        });
    });

.button{
            border: none;
            background-color: #fff;
        }
        .button:focus{
            border: 3;
            background-color: #000;
        }
        .button2{
            border: none;
            background-color: #fff;
        }
        .button2:focus{
            border: 3;
            background-color: #000;
        }
        .active {
            border: 4px solid #FFCC00;
            outline:0;
        }


text:
Q: Check whether given series is convergent or divergent.
Let $a_1$=$1$ and $a_{n+1}$=$\left(\frac{2+\cos(n)}{n^{1/2}}\right)a_n$.
  Determine whether $\sum_n a_n$ converges or diverges.

I have one try as follows.
$2+\cos(n)\geq 1$ and since $a_n$ is positive I can write $a_{n-1}\left(\frac{2+\cos(n)}{n^{1/2}}\right)\geq \frac{a_{n-1}}{\sqrt{n}}$... and so by comparison test I am claiming series is divergent..Am I right?

A: You have that
$$a_{n+1} = \left(\frac{\prod_{k=1}^n(2+\cos(k))}{\sqrt{n!}} \right)$$
Then, the following inequalities hold true
$$\frac{1}{\sqrt{n!}} \le a_{n+1} \le \frac{3^n}{\sqrt{n!}} $$
Compare, and you will find if it diverges or converges.

A: No, your attempt is not conclusive. You show that $a_n \geq \frac{a_{n-1}}{\sqrt{n-1}}$ (you have a small mismatch in the index, but that's not a big deal), but by itself this does not lead to the conclusin you claim. Note that $a_n \geq \frac{a_{n-1}}{\sqrt{n-1}}$ and $a_n \geq \frac{1}{\sqrt{n-1}}$ are two entirely different things.
Actually, the series is convergent. Here is one could go to prove it, in two ways.
Outline 1 (simple)
Use the ratio test. Indeed,
$$
\left\lvert \frac{a_{n+1}}{a_n}\right\rvert = \frac{2+\cos n}{\sqrt{n}} \leq \frac{3}{\sqrt{n}} \xrightarrow[n\to\infty]{} 0
$$
and so...
Outline 2 (complicated):

*

*for all $n\geq 1$, $$0\leq a_n \leq b_n$$
where $(b_n)_n$ is the sequence defined by $b_1=1$, and $b_{n+1} \stackrel{\rm def}{=}\frac{3}{\sqrt{n}}b_n$.

*We have a closed-form for $b_n$, as $b_{n+1} = \prod_{k=1}^n \frac{3}{\sqrt{k}} = \frac{3^n}{\sqrt{n!}}$.

*By e.g. using Stirling's approximation and comparison, this closed-form allows you to conclude that $\sum_n b_n$ converges.

*By comparison (using the first point), this then implies that $\sum_n a_n$ converges.


text:
Q: xspec: failure when expected and result are the same I use xspec for testing of stylesheets. Most of the time it works fine, but once in a while tests fail without a valid reason: the expected and the actual result are the same.   Seemingly: everything is green in the comparison screen.
In that case, I mostly get it working again after trying all kinds of things, but without knowing what  change 'did it'.
It would be most helpful if xspec would report the reason of the failure, but if you can help me (instead of the xspec output) to shine some light on this, I'd be very happy.
This is a reduced test case:
xsl:
<xsl:stylesheet version="2.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:uc="http://www.infinity-loop.de/namespace/upcast/4.0/"
  xmlns:xlink="http://www.w3.org/1999/xlink"
  xmlns:html="http://www.w3.org/HTML/1998/html4"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  exclude-result-prefixes="uc xlink html xs xsl">

  <xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/>

  <xsl:template match="bezwaar">
    <xsl:variable name="content">
      <xsl:element name="{name()}">
        <xsl:apply-templates select="@*|node()"/>
      </xsl:element>
    </xsl:variable>
    <xsl:copy-of select="$content"/>
  </xsl:template>

  <xsl:template match="@*" >
    <xsl:attribute name="{name()}" namespace="{namespace-uri()}">
      <xsl:value-of select="." />
    </xsl:attribute>
  </xsl:template>

  <xsl:template match="*">
    <xsl:element name="{name()}" namespace="{namespace-uri()}">
      <xsl:apply-templates select="@*|node()" />
    </xsl:element>
  </xsl:template>
</xsl:stylesheet>

xspec:
<?xml version="1.0" encoding="UTF-8"?>
<x:description
    xmlns:x = "http://www.jenitennison.com/xslt/xspec"
    stylesheet="file:/home/rdgon/project/kraak/kraak-xslt/publicatiebladen/staatscourant/stcrt_step2.xsl">
  <x:param name='ns' select="false()"/>

  <x:scenario label='test'>
    <x:scenario label='werkt dit'>
      <x:context><bezwaar>
          <al>Noem in het bezwaarschrift:</al>
          <al nadruk="cur">Vergeet niet te ondertekenen.</al>
        </bezwaar>
      </x:context>
      <x:expect>
        <bezwaar>
          <al>Noem in het bezwaarschrift:</al>
        <al nadruk="cur">Vergeet niet te ondertekenen.</al>
      </bezwaar>
    </x:expect>
    </x:scenario>
  </x:scenario>
</x:description>

Test report showing failure:

Can you explain what I am failing to see?
Ruud

A: Because xsl:variable doesn't have @as, your result is a document node. But your x:expect expects an element.
If you want to let your x:expect expect a document node, you need to add select="/" to x:expect. Look for an explanation "If you specify no @select" in  XSpec Wiki.

A: If you have run your XSL then bezwaar Element come 2 times and come extra namespace because you have x:context and x:expect in the same element. if you want to x:expect same as x:context then you can try this code.
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:x = "http://www.jenitennison.com/xslt/xspec"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs x">

<xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="x:scenario">
    <xsl:apply-templates select="x:scenario/x:context/bezwaar"/>
</xsl:template>
<xsl:template match="bezwaar">
    <xsl:element name="{local-name()}">
        <xsl:apply-templates select="@*|node()"/>
    </xsl:element>
</xsl:template>
<xsl:template match="al">
    <xsl:element name="{local-name()}">
        <xsl:apply-templates select="@*|node()"/>
    </xsl:element>
</xsl:template>
<xsl:template match="@*">
    <xsl:attribute name="{local-name(.)}">
        <xsl:value-of select="."/>
    </xsl:attribute>
</xsl:template>

or if you want bezwaar multiple times then you can comment 1st template match.


text:
Q: Shortcode API: How to get name that matched shortcode RegEx? I am looking for a way to reproduce what is described in the documentation: An overloaded shortcode callback.
According to the docs, the $atts array will contain the string that matched the shortcode RegEx. The position inside $atts depends on if the callback name matches the shortcode or not. The following example is taken from the docs:
add_shortcode('foo','foo'); // two shortcodes referencing the same callback
add_shortcode('bar','foo');
  produces this behavior:
[foo a='b'] ==> callback to: foo(array('a'=>'b'),NULL,"foo");
[bar a='c'] ==> callback to: foo(array(0 => 'bar', 'a'=>'c'),NULL,"");

So I registered my shortcodes like this:
add_shortcode('foo', 'foo');
add_shortcode('bar', 'foo');
function foo($attributes, $content = null) {
    echo '
';
    var_dump($attributes);
    echo '
';
}

Unfortunately, $attributes is always empty, it does not contain the name of the shortcode (WP 4.0).
Is this an error in the documentation or am I going wrong somewhere?

A: I think you just forgot to run the shortcodes [foo a='b'] and [bar a='c'] through the do_shortcode filter:
do_shortcode( '[foo a='b'] [bar a='c']' )

The output of the_content() is filtered through the do_shortcode, so you can just add it into your editor instead.
Running your code I get the following output for the $arguments dump:
array (size=1)
  'a' => string 'b' (length=1)

and
array (size=1)
  'a' => string 'c' (length=1)

so there's no '0' => 'bar' part here.
But you can get the current shortcode tag from the third parameter of the shortcode callback ( I first heard about it in this answer by @toscho )
I just checked the source and if we check out the do_shortcode_tag function we  will find:
// self-closing tag
return $m[1] . call_user_func( $shortcode_tags[$tag], $attr, null,  $tag ) . $m[6];

where $tag is the third parameter containing the shortcode tag.
So in your case you can change your callback to:
function foo( $attributes = array(), $content = null, $tag = '' ) {

    echo $tag; // current shortcode tag

    echo '
';
    var_dump($attributes);
    echo '
';
}

to get information about the current shortcode tag.

A: Shortcode callbacks get a third argument with the shortcode name. there's a note about this in the docs:

Appears to always appear as third argument as of 2.9.2.

add_shortcode('foo', 'wpse173855_shortcode');
add_shortcode('bar', 'wpse173855_shortcode');

function wpse173855_shortcode($atts, $content, $name)
{
    echo '
';
    var_dump($name);
    echo '
';
}

A look at the source reveals that the shortcode that was matched is always passed in.


text:
Q: utility of #define in c++ I just found out this code from a tutorial for matrix addition in c++ by reading the values from a file-
I wanted to ask what does #define does here? What is so special in it? And how is it different from separately declaring M and N as int or char in main?
code
#include <iostream>
#include <fstream>
using namespace std;

#define M 4
#define N 5

void matrixSum (int P[M][N], int Q[M][N], int R[M][N]);
void matrixSum (int P[M][N], int Q[M][N], int R[M][N]) {
 for (int i=0; i<M; i++)    // compute C[][]
  for (int j=0; j<N; j++)
    R[i][j] = P[i][j] + Q[i][j];
}

int main () {

 ifstream f;
 int A[M][N];
 int B[M][N];
 int C[M][N];

    f.open("values");   // open file

    for (int i=0; i<M; i++)     // read A[][]
      for (int j=0; j<N; j++)
        f >> A[i][j];

    for (int i=0; i<M; i++)     // read B[][]
      for (int j=0; j<N; j++)
        f >> B[i][j];

    matrixSum (A,B,C);      // call to function

    for (int i=0; i<M; i++) {   // print C[][]
      for (int j=0; j<N; j++)
        cout << C[i][j] << " ";
      cout << endl;
    }
    f.close();
}

A: The thought of const int M = 4; and const int N = 5; made the author shake in his boots because of the whopping 8 bytes of memory, so he used #define instead.

A: #define and other commands beginning with # are commands run by the C preprocessor before compilation begins.
Specifically, #define tells the preprocessor that everywhere the token M occurs, the text "4" should be used in its place. You are correct in that using a normal variable definition is the preferred way of accomplishing the same functionality. The reason being the variable definition is processed by the compiler with the rest of the code and #defines involve a step before compilation. More complex #defines can lead to very difficult and confusing compiler errors. If something is wrong in the #define, the line that uses the #define lists the error (since the code was copy pasted there before compilation) not the line with the #define.  Nevertheless, you'll see a lot of old C style code that defines constants with #defines.

A: As a side note, a more general solution would be this, using function template:
template<size_t M, size_t N>
void matrixSum (int (&P)[M][N], int (&Q)[M][N], int (&R)[M][N]);

template<size_t M, size_t N>
void matrixSum (int (&P)[M][N], int (&Q)[M][N], int (&R)[M][N])
{
  for (int i=0; i<M; i++)
    for (int j=0; j<N; j++)
       R[i][j] = P[i][j] + Q[i][j];
}
int main ()
{

 const int M = 4; //now in main!
 const int N = 5;

 ifstream f;
 int A[M][N];
 int B[M][N];
 int C[M][N];

 //same as before
}

I think this is better than using #define, because using const or enum helps in debugging. A more detailed explanation is here:
C++ - enum vs. const vs. #define

A: It is a preprocessor directive of the form
#define identifier token-sequence

The preprocessor runs before the compiler transforms your code for use in the compiler. The order is as follows:

*

*Trigraph replacement

*Line splicing

*Macro definition and expansion

So with the #define you can have character manipulation (macro substitution).
Whenever M is seen 4 will be substituted.
The compiler will then see
 void matrixSum (int P[4][5], int Q[4][5], int R[4][5]);  // ..etc

The other way would be to use the const qualifier on a global variable.
In C, it would be
// Some fileA.c
const int M; // initialize

// Some fileB.c
const int M = 4; // defined

So I would say try to avoid when possible because macros are a form of text substitution, they do not obey scope and type rules.


text:
Q: Importing text file in DXL script? I am looking for a solution which helps to import a text file in the code, I am doing this to remove the hard coded values. Instead, I would want to call a text file and read values, which does the mapping. Making the code independent of projects. Any Idea how to do it ?
OleAutoObj createWrapperObj(Object obj) {
OleAutoArgs args = create
OleAutoObj wrapper = null
print oleMethod(d2e, "CreateObjectWrapper", args, wrapper)

olePut(wrapper, "ModuleName", name(m))
olePut(wrapper, "aObjectType", unicodeString(obj."aObjectType"))
olePut(wrapper, "TestDescription", unicodeString(obj."Object Short Text"))
olePut(wrapper, "TestPictureName", unicodeString(obj."ID"))
olePut(wrapper, "TestFocus", unicodeString(obj."Test_Focus"))

return wrapper }

Thank you

A: Create a file with each parameter you want to read on its own line.
Here is an example of how to read the file.
string filename="C:/parameters.txt" // can also use relative paths
Stream input = read filename
string param
input >> param //this reads the first line into the string param

//... continue to input into each variable
//... and then when all done

close input

I think this is what you are asking for.


text:
Q: Determining if there exists numbers n1, n2 in a, b and n3 in c such that n1 + n2 = n3 [ftt, polynomial multiplication] Hello I am working on a problem that seems to be out of my league so any tips, pointers to reading materials etc. are really appreciated. That being said here is the problem:
given 3 subsets of numbers a, b, c ⊆ {0, ..., n}. In nlog(n) check if there exists numbers n1, n2 in a, b and n3 in c where n1 + n2 = n3.
I am given the hint to convert a and b to polynomial coefficients and to use polynomial multiplication using ftt to multiply the coefficients of a and b.
Now where I am stuck is after getting the result of the polynomial multiplication, what do I do next?
Thank you in advanced.
from numpy.fft import fft, ifft
from numpy import real, imag

def polynomial_multiply(a_coeff_list, b_coeff_list):
    # Return the coefficient list of the multiplication
    # of the two polynomials
    # Returned list must be a list of floating point numbers.
    # list from complex to reals by using the
    # real function in numpy
    len_a = len(a_coeff_list)
    len_b = len(b_coeff_list)
    for i in range(len_a-1):
        b_coeff_list.append(0)
    for i in range(len_b-1):
        a_coeff_list.append(0)
    a_fft = fft(a_coeff_list)
    b_fft = fft(b_coeff_list)
    c = []
    for i in range(len(a_fft)):
        c.append(a_fft[i] * b_fft[i])
    inverse_c = ifft(c)
    return real(inverse_c)

# inputs sets a, b, c
# return True if there exist n1 in a, n2 in B such that n1+n2 in C
# return False otherwise
# number n which signifies the maximum number in a, b, c
def check_sum_exists(a, b, c, n):
    a_coeffs = [0]*n
    b_coeffs = [0]*n
    # convert sets a, b into polynomials as provided in the hint
    # a_coeffs and b_coeffs should contain the result
    i = 0
    for item in a:
        a_coeffs[i] = item
        i += 1
    i = 0
    for item in b:
        b_coeffs[i] = item
        i += 1
    # multiply them together
    c_coeffs = polynomial_multiply(a_coeffs, b_coeffs)
    # now this is where i am lost
    # how to determine with c_coeffs?
    return False
    # return True/False

A: Thanks to all who helped. I figured it out and hopefully this can help anyone who runs into a similar problem. The issue I had was I incorrectly assigned the coefficients for a_coeffs and b_coeffs.
Here is the solution which passed the tests for those interested.
from numpy.fft import fft, ifft
from numpy import real, imag

def check_sum_exists(a, b, c, n):
    a_coeffs = [0] * n
    b_coeffs = [0] * n
    # convert sets a, b into polynomials as provided in the hint
    # a_coeffs and b_coeffs should contain the result
    for coeff in a:
        a_coeffs[coeff] = 1
    for coeff in b:
        b_coeffs[coeff] = 1
    # multiply them together
    c_coeffs = polynomial_multiply(a_coeffs, b_coeffs)
    # use the result to solve the problem at hand
    for coeff in c:
        if c_coeffs[coeff] >= .5:
            return True
    return False
    # return True/False

def polynomial_multiply(a_coeff_list, b_coeff_list):
    # Return the coefficient list of the multiplication
    # of the two polynomials
    # Returned list must be a list of floating point numbers.
    # Please convert list from complex to reals by using the
    # real function in numpy.
    for i in range(len(a_coeff_list) - 1):
        b_coeff_list.append(0)
    for i in range(len(b_coeff_list) - 1):
        a_coeff_list.append(0)
    a_fft = fft(a_coeff_list)
    b_fft = fft(b_coeff_list)
    c = []
    for i in range(len(a_fft)):
        c.append(a_fft[i] * b_fft[i])
    return real(ifft(c))


text:
Q: Ternary Operation on Files (nio/Java 7) I need to create a tempFile. But before I create it, I need to check it if Path exists using Files. I am able to achieve it using below:
    Path docName;
    try {
        if (Files.exists(docName)) {
            Files.delete(docName);
        }
    } catch (Exception ex) {
    }

    try {
        docName = Files.createFile(docName);
    } catch (FileAlreadyExistsException ignoreit) {
    }

Wondering if there is a way to minimize above using Java 7+ APIs. An elegant way of doing it, I mean to say.
Say for example, using Ternary operator if I try for below:
????  result = Files.exists(docName) ? Files.delete(docName) : Files.createFile(docName);

Question: What (data-type) should I put in place of ???? ?

A: Nothing, a ternary expression would work only if both branches return the same (or compatible) types, and it's not the same as your other code.  delete() returns void while create() returns a Path.
try {
    if (Files.exists(docPath))
        Files.delete(docPath);
    docPath = Files.create(docPath)
}
catch...


text:
Q: Find an orthonormal basis of $\mathbb R^3$, with its usual scalar product, whose first two vectors belong to the equation plane The equation plane is $x_1 + x_2 + x_3 = 0$.
$(-1,0,1)$ and $(0,1,-1)$ are on the equation plan.
I don't know if I am suppose to use Gram-Schmidt process to find the third right?
Or I am suppose to find a third vector eg: $(1,1,1)$
and use Gram-Schmidt process on the three vectors

A: Apply Gram-Schmidt to $\{(-1,0,1),(0,1,-1)\}$, normalize the vectors that you get, and you shall get an orthonormal basis of that plane, which will be
$$
\left\{\frac1{\sqrt2}(-1,0,1),\frac1{\sqrt6}(-1,2,-1)\right\}.
$$
Then,
\begin{multline}
\left\{\frac1{\sqrt2}(-1,0,1),\frac1{\sqrt6}(-1,2,-1),\frac1{\sqrt2}(-1,0,1)\times\frac1{\sqrt6}(-1,2,-1)\right\}=\\
=\left\{\frac1{\sqrt2}(-1,0,1),\frac1{\sqrt6}(-1,2,-1),\frac1{\sqrt3}(-1,-1,-1)\right\}
\end{multline}
shall be an orthonormal basis of $\mathbb{R}^3$.


text:
Q: In Outlook 2010, is there any way to disable the "Quick Click" for categorization? I really like categorization in Outlook 2010. However, my instinct is to always left-click on the categories column, which always triggers a "Quick Click" action and sets the category to whatever the default "Quick Click" category is.
Is there a way to disable that feature? I would like to be forced to choose the category and never have a "default".
Edit: I've tried setting the "Quick Click" category to "No Category" and this seems to work for a while but then later get reset back to a different category. Possibly a bug?
Edit: Nevermind, after setting the "Quick Click" to "No Category" from the ribbon and not by right clicking on individual emails, I don't seem to have this problem anymore. So, the solution, as paradroid pointed out, was to modify this setting from the ribbon.

A: When you click on Categories on the ribbon toolbar, select Set Quick Link. Then select None.
It looks like there's a Group Policy administrative template, which allows defining Categories, so it may be happening through that.  That would explain why you can change it or a while, but goes back to what the policy tells it to.
Does it always go back to the same setting?
You'd have to ask your systems administrator to change this, if this is the case, unless it was deliberately set for a reason.


text:
Q: Error:(48, 13) error: illegal start of expression
I get this error occcure when I build sign apk don't know but when I build simple apk these error does not occur,plz help me resolve this.

    PTAdChartboostBridge.s_activity.get)
    {

    PTAdChartboostBridge(new Runnable);

        {

            public void run();
            {
                if (PTAdChartboostBridge.appId() == null || PTAdChartboostBridge.appSignature() == null) {

                    Chartboost.startWithAppId(PTAdChartboostBridge.activity, PTAdChartboostBridge.appId(), PTAdChartboostBridge.appSignature());
                    Chartboost.setLoggingLevel(Level.ALL);
                    Chartboost.setDelegate(delegate);
                    Chartboost.onCreate(PTAdChartboostBridge.activity);

                    initComplete = true;

                    Chartboost.onStart(PTAdChartboostBridge.activity);
                    return;
                }

            }

        }

error is in this code plzz help???

A: You are not doing whatever you are trying to. Your format is totally wrong.
I would suggest you go through basics again.
However correct format will be as below
new Runnable() {
    @Override
    public void run() {
         if (PTAdChartboostBridge.appId() == null || PTAdChartboostBridge.appSignature() == null) {

            Chartboost.startWithAppId(PTAdChartboostBridge.activity, PTAdChartboostBridge.appId(), PTAdChartboostBridge.appSignature());
            Chartboost.setLoggingLevel(Level.ALL);
            Chartboost.setDelegate(delegate);
            Chartboost.onCreate(PTAdChartboostBridge.activity);

            initComplete = true;

            Chartboost.onStart(PTAdChartboostBridge.activity);
            return;
        }
    }
}


text:
Q: How to make multicheck for post/page meta box Please help me understand how to make Multicheck type for metabox. Search for all internet and nothing. Thanks.

      UPDATE
@Jan I have a headache from this function. I dont know whats wrong.I'm trying your method but nothing, then I'm trying get_posts but with this method I have too many troubles. With your method I get this error before content:
Warning: urldecode() expects parameter 1 to be string, array given in Z:\home\mysite.net\www\wp-includes\query.php on line 1878

Here is my code:
<?php
        $catids = get_post_meta($post->ID,'_mtb_multicheck',false);
        $limit = 10;
        query_posts( array('posts_per_page' => $limit, 'cat' => $catids, 'paged' => get_query_var('paged') ) );
    ?>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>

        <!-- Content-->

<?php endwhile; ?>
            <?php pagination(); ?>
<?php else : ?>
            <!--Error message here-->

<?php endif; ?>

I want to know what my vatiables return. Make this:
query_posts( array('posts_per_page' => $limit, 'cat' => print_r($catids), 'paged' => get_query_var('paged') ) );

and get this on my page:
Array ( [0] => 5 [1] => 5 [2] => 3 )

I think it's my query_posts printed, not $catids. It's a big, big trouble. I feel myself like a nerd. Please help me.

A: The post metadata can store multiple values either as distinct entries in the postmeta table, or as one entry with the value as a serialized PHP array. The serialization may require less code, but the distinct entries allow faster querying later ("give me all posts that have at least option A of the multicheck checked").
I took the code you linked to and made the following changes to allow a "multicheck":
// in show():
// Line 254: replace it by:
$meta = get_post_meta($post->ID, $field['id'], 'multicheck' != $field['type'] /* If multicheck this can be multiple values */);
// Add the following to the switch:
case 'multicheck':
    foreach ( $field['options'] as $value => $name ) {
        // Append `[]` to the name to get multiple values
        // Use in_array() to check whether the current option should be checked
        echo '<input type="checkbox" name="', $field['id'], '[]" id="', $field['id'], '" value="', $value, '"', in_array( $value, $meta ) ? ' checked="checked"' : '', ' /> ', $name, '<br/>';
    }
    break;

// In save():
// Line 358: replace it by:
$old = get_post_meta($post_id, $name, 'multicheck' != $field['type'] /* If multicheck this can be multiple values */);
// Lines 409-413: Wrap them in an else-clause, and prepend them by:
if ( 'multicheck' == $field['type'] ) {
    // Do the saving in two steps: first get everything we don't have yet
    // Then get everything we should not have anymore
    if ( empty( $new ) ) {
        $new = array();
    }
    $aNewToAdd = array_diff( $new, $old );
    $aOldToDelete = array_diff( $old, $new );
    foreach ( $aNewToAdd as $newToAdd ) {
        add_post_meta( $post_id, $name, $newToAdd, false );
    }
    foreach ( $aOldToDelete as $oldToDelete ) {
        delete_post_meta( $post_id, $name, $oldToDelete );
    }
} else {
    // The original lines 409-413
}

Two extra changes to prevent PHP warnings when WP_DEBUG is enabled:
// Line 337:
if ( ! isset( $_POST['wp_meta_box_nonce'] ) || !wp_verify_nonce($_POST['wp_meta_box_nonce'], basename(__FILE__))) {
// Line 359:
$new = isset( $_POST[$field['id']] ) ? $_POST[$field['id']] : null;

With these changes, you can use a "multicheck" by defining it like this:
array(
    'name' => 'Multicheck',
    'id' => $prefix . 'multicheck',
    'type' => 'multicheck',
    'options' => array(
        'a' => 'Apple',
        'b' => 'Banana',
        'c' => 'Cherry',
    ),
)


text:
Q: How to join my table with information_schema.columns i need to join my table with information_schema.columns to get data type for all column.
my sql is following.
select stock_code,automatic,semiautomatic,manual from VehicleInfoForParts

i want to join my VehicleInfoForParts with information_schema.columns to get a output like
Column_Name       Value               datatype
-------------     -------            --------------
stock_code           A112                varchar
automatic            1                   bit
semiautomatic        0                   bit
manual               1                   bit

please advise. thanks .

A: You can't achieve that with a simple join (you basically want to "join" columns with rows...). As I said in your earlier question, solve your problem with the bit columns in the application, not in the database. That has multiple advantages, including

*

*It works for every table holding bit columns if you keep your data model consistent

*You don't store language specific texts in your SQL code, with makes translating your application easier