text:
Q: How can I output every line an XUnit test touches upon execution? I have an application that I can step through debugging when executing an Xunit test case. I want to log every line it touches so I can read the whole flow in one long page (like a log file of source code).
How can I output the execution to a log file?
For the curious, this is so I can see the flow of some legacy code to figure out the logic required for a rewrite. Of course, the requirements, use cases, etc was not maintained so this is my strategy to pull it from the only source of truth: current production code.
method1(var a)
{
    print(" test " + a);
    method2(a * 2);
}

method2(var b)
{
    if (b > 10)
    {
        print("b too big");
    }
    else
    {
        print("b is " + b);
    }
}

Test case executes method1(2); so output would be something like:
class1.method1(2).print(" test " + a);
class1.method1(2).method2(a * 2);
class1.method2(4).if (b > 10)
class1.method2(4).else
class1.method2(4).print("b is " + b);

Is this possible to get this log? If so, does anyone know how to do it?
Thanks in advance!

A: Not an easy task, you would need to attach a custom debugger through code to your running process or start a new process with a your debugger attached.
Step through each line (so that it breaks after each statement, read your your current stack location, and output the line where it's currently at. Potentially needing to map and use the .pdb file and source code.
Generally, a very hard task to do!

A: Generally, you can use my Runtime Flow tool to log all executed methods with parameters. I haven't tried it with an XUnit test, but it is probably possible to configure customized run settings for monitoring.


text:
Q: Get android device orientation even when autoRotation is turned off I have an android app in which the screen orientation is set to portrait in manifest file.
It uses a custom camera in b/w , to take a photo and I need to save the photo.
Before I save the image I have to rotate the image depending on how the user is holding the camera, so that the image gets saved in the right orientation.
So, is there any way by which I can get the device orientation even when my app is running in portrait mode and android "auto-rotation" feature is ON.
How can I achieve this?

A: You should do the rotation depending on the orientation information within the image, not depending on the device orientation.
Here is some more information on how to determine the rotation.
Since this does not help, have you tried hackpod's answer here:
getResources().getConfiguration().orientation

A: To get current device orientation try this:
getWindowManager().getDefaultDisplay().getRotation();

A: Simply check, the height and width of the image. If the height is less than your width, it means the user was holding the phone horizontally, so you have to rotate it.

A: I am currently using android orientation sensor to solve this problem and its working perfectly. Till someone gives a better working method , am accepting this as answer for other who have the same question.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Exporting forecasting model and accuracy information from the "forecast" package in R I have searched through the forum and has not been able to find any specific information that has been able to solve the below.
The main question is how to export (1) the model information (chosen model and parameters) from the forecast function, and (2) the accuracy information (MAPE, MSE etc.) from the generated forecast?
I am able to find the information just by calling the object forecast(retail)$model but not able to actually output the information column by column in the file. This has presumably something to do with the predefined matrix.
The only post I have been able to find is the folloing, but not been able to apply it onto my example.
Export accuracy of multiple timeseries forecasts in r into csv-document
I am working of the example from the post: https://robjhyndman.com/hyndsight/batch-forecasting/
The following code loops through in a for loop columns by columns and generates a statistical point forecast (mean object) based on the forecast() function and outputs to a column by column csv file.
library(forecast)

retail <- read.csv("https://robjhyndman.com/data/ausretail.csv",header=FALSE)
retail <- ts(retail[,-1],f=12,s=1982+3/12)

ns <- ncol(retail)
h <- 24
fcast <- matrix(NA,nrow=h,ncol=ns)
for(i in 1:ns)
  fcast[,i] <- forecast(retail[,i],h=h)$mean

write(t(fcast),file="retailfcasts.csv",sep=",",ncol=ncol(fcast))

Hope someone is able to help out with refactoring the above code.
Highly appreciate all the help / guidance you can provide.

A: You can use the following code to successfully export a csv file.
After you have created your matrix, do this:
fcast <- as.data.frame(fcast)
write.table(fcast, file="retailfcasts.csv", quote=F, sep=";", dec=",", na="", row.names=T, col.names=T)

Is the solution you were looking for?


text:
Q: What returns CustInvoiceJour.salesTable I'm learning to develop dynamics ax 2012 and I need to find the data in salesTable corresponding to a CustInvoiceJour record.
Does the method CustInvoiceJour.salesTable return the whole table or the associated record?

A: It returns a sales table buffer that has records associated with customer invoice journal.

A: The return type of the function is tablebuffer as a tablebuffer type salesTable is return from the function as a foreign key relationship is exist between custinvoicejour and salesTable on salesId field.

SalesTable       salesTable = SalesTable::find(this.SalesId, _update);

salestable buffer is find from custinvoicejour current buffer field value this.salesId which is pass into salestable function find which returns salestable buffer contains field values.
SalesTable  salesTable(boolean _update = false)
{
    SalesTable       salesTable = SalesTable::find(this.SalesId, _update);
    SalesTableDelete salesTableDelete;
    SalesTable_RU salesTableRU;

    if (!salesTable && this.SalesId && this.SalesType != SalesType::Journal)
    {
        salesTableDelete = SalesTableDelete::find(this.SalesId);
        if (salesTableDelete.SalesTable)
        {
            [salesTable] = salesTableDelete.SalesTable;
            salesTableRU = SalesTable_RU::findBySalesTable(salesTable.RecId);
            salesTable.packSalesTable_RU(salesTableRU);
        }
    }

    return salesTable;
}


text:
Q: PowerShell script problem, cause of lacking knowledge I have kinda 0 expirience of coding but wanted to get myself a script which would take some work of me.'
Started this yesterday and just googled myself everything together.
What I want to do is open a vnc viewer(remote desktop app for our raspberrys), copy paste a link there, log into the website, fullscreen it and leave the session of vnc viwer, go into the next pi (we have 6 different where we need to do this every 3 hours) and do exactly the same.
I get everything together just with simple phrases like:
$wshell.SendKeys("{TAB}")
$wshell.SendKeys("{Enter}")

etc. but the only problem I have no is to close the session of vncviewer without killing the overview console(both have different tasks in task manager but named the same, only different is the ProcessID but this is changing for every start.
I figured out myself 3 different solutions but couldn't find a working answer on this in different forums or tech discords.

*

*LF a command like" (New-Object -ComObject WScript.Shell).AppActivate((Kill-Process vncviewer).MainWindowTitle) " which would kill only the vncviewer which is the main window atm (normaly this command is exactly the same only swap "Kill-Process" for "get-process" but I just wrote kill process to better descripe what Im looking for) and would leave the overview console open.

*Get a command like .SendKeys for MouseClicks so I could work with fix "Set mouse coordinate" commands in PowerShell and then just simulate a mouseclick to close the window.

*Do a "Get-Process | Out-File" and a "Get-Content" in the next line to write and read the processes which are running atm, to terminate the ProcessID of the session of nvcviewer to kill it via "Stop-Process "ProcessID"".
But couldnt find a command for "Get-Content | Where-Object_Name = "nvcviewer"" or smth like this to know what ProcessID its running atm, problem would be I would get 2 process IDs without knowing which one to kill.
Would be great to get some help on this, sorry for my bad english/grammar its not my native language and I'm rly new to coding etc so if you have a answer for me would be great to get this explained for an 5year old ^^ + I'm not allowed to install 3rd party software so all needs to be in PowerShell.


text:
Q: Cannot read property 'post' of undefined, in nuxt js I am making registration form in nuxt js, it takes data from api, I have installed axios and auth module, I wrote base url in nuxt.config.js file. It shows TypeError: Cannot read property 'post' of undefined
```template>
    <div>
       <section class="content">
           <div class="register_form m-auto text-center form-group">
                <form method="post" @submit.prevent="register" >
                    <h1 class ="register_title">REGISTER</h1>
                    <h2 class="register_text">PLEASE REGISTER TO USE THIS WEBSITE</h2>
                    <input class="form-control" type="text" placeholder = 'USERNAME' v-model="username" name="username" required>
                    <input class="form-control" type="password" placeholder = 'PASSWORD' v-model="password" name="password" required>
                    <button type="submit" to="#" class="register_btn">
                        REGISTER
                    </button>
                </form>
           </div>
       </section>
    </div>
</template>

<script>
export default {
    layout: 'loginLayout',
    data(){

        return {
            username: '',
            password: ''
        }
    },
    methods: {
    async register() {
      try {
        await this.$axios.post('register', {
          username: this.username,
          password: this.password
        })
        this.$router.push('/')
      }

      catch (e) {
        console.log(e)
      }
    }
}
}
</script>```

A: try to use
await this.$axios.$post instead of await this.$axios.$post


text:
Q: Is there a way to run code during an update for an iOS app? I have recently discovered an error in an app I have previously released for iOS. I am saving something with an incorrect metadata variable which causes a notification to be monthly instead of daily.
This is trivial to fix, it just involves looping through all the currently saved objects and changing a 1 to a 0. However it would be preferable to me to be able to do this during the update that fixes the error. Is there a way then of running code as part of an update?
Otherwise I imagine the next best way of solving the problem would be to run the loop the next time the app is opened.
I have looked around online and have only found solutions which involve running one off code on app start up. I am therefore wondering if I am missing something because this seems to be the sort of thing that a lot of apps will need to have happen to them if they need to reconfigure how their data is saved or equivalent.

A: If you are not using core data and overriding the light weight migration to make an changes needed there, then the only way is to use User Defaults and check for a var you know does not exist, run the code, then add the var so as to not run it again.
func updateDB() {
    if !UserDefaults.standard.bool(forKey: MyProject.DBFixKey) {
        // Fix DB

        UserDefaults.standard.set(true, forKey: MyProject.DBFixKey)
    }
}


text:
Q: How to launch a Python file on Windows 7? this is the first time I have used Python.
I downloaded the file ActivePython-2.7.1.4-win32-x86
and installed it on my computer; I'm using Win7.
So when I tried to run a python program, it appears and disappears very quickly. I don't have enough time to see anything on the screen. I just downloaded the file and double-cliked on it.
How do I launch this file? I know that it is a long file for a first Python tutorial.

A: Add the line
input()

to the end of the program, with the correct indentation. The issue is that after the data is printed to the console the program finishes, so the console goes away. input tells the program to wait for input, so the console won't be closed when it finishes printing.
I hope you're not using that program to learn Python; it's pretty complicated!

A: go to Start > All programs > Accessories  and click on Command Prompt. then drag the python file from the explorer view into this command line and press Enter...
now you can watch the output of the script execution !

A: run it from a command prompt:
> python myscript.py

You can also start only the python interpreter from the command prompt (or by running python.exe) and then try some commands:
> python
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
>>> a = 2
>>> b = 7
>>> print a+b
9
>>>

A: Or run it from a batch file:
myprog.py
pause

Has the advantage that you can specify a different version of Python too.

A: Just a bit more on this.
You have a script myscript.py in a folder C:\myscripts. This is how to set up Windows 7 so that you can type > myscript  into a CMD window and the script will run.
1) Set your PATH variable to include the Python Interpreter.
Control Panel > System and Security > System > Advanced Settings > Environment Variables. You can set either the System Variables or the User Variables. Scroll down till you find PATH, select it, click Edit.The Path appears selected in a new dialog. I always copy it into Notepad to edit it though all you need do is add ;C:\Python27 to the end of the list. Save this.
2) Set your PATH variable to include C:\myscripts
3) Set your PATHEXT variable to include ;.PY.  (This is the bit that saves you from typing myscript.py)
This may now just work. Try opening a command window and typing myscript
But it may not. Windows can still mess you about. I had installed and then uninstalled a Python package and when I typed myscript Windows opened a box asking me which program to use. I browsed for C:\python27\python.exe and clicked that. Windows opened another command window ran the script and closed it before I could see what my script had done! To fix this when Windows opens its dialog select your Python and click the "Always do this" checkbox at the bottom. Then it doesn't open and close another window and things work as they should. Or they did for me.
Added: Above does not say how to pass arguments to your script. For this see answer Windows fails to pass arguments to python script


text:
Q: Power BI Connector for to prepare Power BI user activities dashboard We want to create Power BI dashboard highlighting statistics of user activities related to Power BI for last 30/90 days.
Below are the high level statistics we want to capture:

*

*Created Power BI dashboard

*Created Power BI report

*Edited Power BI dashboard

*Edited Power BI report

*Printed Power BI dashboard

*Shared Power BI dashboard

*Viewed Power BI dashboard

*Viewed Power BI report

*Statistics of Power BI active users

Would want to know if there is any available solution or OOB Power BI connector for the same.
Thanks

A: You can analyze statistics of user activities using the Power BI Activity log. You can download the activities by using a REST API or PowerShell cmdlet. You can also filter the activity data by date range, user, and activity type. In order to be able to do this, you should be a Power BI Service Admin. You have to install the Power BI Management cmdlets locally or use the Power BI Management cmdlets in Azure Cloud Shell.
You will find more details here : https://powerbi.microsoft.com/en-us/blog/the-power-bi-activity-log-makes-it-easy-to-download-activity-data-for-custom-usage-reporting/

A: To check 30 days statistics Power BI has "Usage metrics" features for every report. Other than this you can use your O365 data if you are an admin of Power BI services


text:
Q: PHP: foreach - reverse 1 iteration Let's say I've a code:
foreach($array as $key => $value)
{
    //do something
    if($var === true) //"reverse"
}

is it possible to "reverse" foreach, so it'll "run" with the same array's element it was "running" when called to "get back" ;)?

A: You will have to use a normal for loop and make the last parameter (the modifying part) depend on a variable.
Expr3 in the following manual entry: http://php.net/manual/en/control-structures.for.php

A: Not with a foreach, no.  You could do this:
$array = range(1,10);

for (
    $dir = 1, reset($array);
    $val = current($array); // for keys, use list($key,$val) = each($array)
    $dir == 1 ? next($array) : prev($array)
) {
    echo "{$val}\n";
    if ($val == 7) {
        $dir = -1;
    }
}


text:
Q: Mixing primary Rust crate with workspaces (sub-crates) as sub-directories I have a bin crate with a standard Rust crate structure.  I would like to add a few more lib crates to the same repo, without moving the existing code to a sub-directory.  It seems Cargo.toml can have both the workspaces and regular values in the same file, but I couldn't find any documentation for such usage, or if there are any issues with this dir structure:
/myapp
|- Cargo.toml
|- src/
|- lib1/
|    |- Cargo.toml
|    |- src/
|- lib2/
|    |- Cargo.toml
|    |- src/

the top-level Cargo.toml for the myapp crate would have this content:
[workspace]
members = ["lib1", "lib2"]

[package]
name = "myapp"
version = "0.1"
edition = "2021"
...

A: You can view documentation for The Manifest Format and Workspaces in the Cargo Book. The latter describes two expected uses of workspaces:

The [workspace] section
To create a workspace, you add the [workspace] table to a Cargo.toml:
[workspace]
# ...

At minimum, a workspace has to have a member, either with a root package or as a virtual manifest.
Root package
If the [workspace] section is added to a Cargo.toml that already defines a [package], the package is the root package of the workspace. The workspace root is the directory where the workspace's Cargo.toml is located.
[workspace]

[package]
name = "hello_world" # the name of the package
version = "0.1.0"    # the current version, obeying semver
authors = ["Alice <a@example.com>", "Bob <b@example.com>"]

Virtual workspace
Alternatively, a Cargo.toml file can be created with a [workspace] section but without a [package] section. This is called a virtual manifest. This is typically useful when there isn't a "primary" package, or you want to keep all the packages organized in separate directories.
# [PROJECT_DIR]/Cargo.toml
[workspace]
members = ["hello_world"]

# [PROJECT_DIR]/hello_world/Cargo.toml
[package]
name = "hello_world" # the name of the package
version = "0.1.0"    # the current version, obeying semver
authors = ["Alice <a@example.com>", "Bob <b@example.com>"]

So yes, extending your existing Cargo.toml to support more packages is expected and will work just fine.
I think the only thing to keep in mind that you may have in your existing Cargo.toml that will affect your new member Cargo.tomls as well is any [patch], [replace], or [profile.*] sections. In Overriding Dependencies and Profiles they say:

Cargo only looks at the {patch settings / replace settings / profiles} in the Cargo.toml manifest at the root of the workspace. {Patch settings / Replace settings / Profiles} defined in dependencies will be ignored.


text:
Q: Convert strings to "0" in php I have a list of strings and some of them have texts in them. Ultimately I want the strings to be added up. The strings that have texts in them, I want to convert them to "0". So what is the right and easy way to do this?
<?php

$str_1 = "4";
$str_2 = "A.I";
$str_3 = "8";
$str_4 = "Sky";
$str_5 = "Sa";

$total = intval ($str_1) + intval ($str_2) + intval ($str_3) + intval ($str_4) + intval ($str_5);

?>

Ofc the above code won't work. So how does one automatically convert the str2, str3 and str4 to 0?

A: You can achieve this with a function that has a variable-length argument list:
<?php

/*

Question Author: Vika
Question Answerer: Jacob Mulquin
Question: Convert strings to "0" in php
URL: https://stackoverflow.com/questions/74613261/convert-strings-to-0-in-php
Tags: php

*/

function addIfNumeric(...$strings)
{
    $sum = 0;
    foreach ($strings as $string) {
        if (is_numeric($string))
            $sum += $string;
    }
    return $sum;
}

$str_1 = "4";
$str_2 = "A.I";
$str_3 = "8";
$str_4 = "Sky";
$str_5 = "Sa";

$sum = addIfNumeric($str_1, $str_2, $str_3, $str_4, $str_5);

echo $sum . PHP_EOL;

Yields
12


text:
Q: Confused about the definition of the Kahn-Priddy map The Kahn-Priddy map is defined in various papers as follows:
Define $i:\mathbb {RP}^{n-1}\rightarrow O(n)$ by taking $\ell\in \mathbb {RP}^{n-1}$ to the reflection across $\ell^\perp.$ Define $j:O(n)\rightarrow \Omega^nS^n$ by identifying $S^n=\mathbb R^n\cup \{\infty\}$ with basepoint $\infty$, and extending the orthogonal self-maps of $\mathbb R^n$ to this one-point compactification. Then the Kahn-Priddy map $\lambda:\Sigma^n\mathbb {RP}^{n-1}\rightarrow S^n$ is the adjoint of $j\circ i:\mathbb {RP}^{n-1}\rightarrow \Omega^nS^n$.
This uses the pointed mapping adjunction $$\text{Map}_*(\Sigma^n \mathbb {RP}^{n-1},S^n)=\text{Map}_*(S^n\wedge \mathbb {RP}^{n-1},S^n)=\text{Map}_*\big(\mathbb{RP}^{n-1},\text{Map}_*(S^n,S^n)\big)=\text{Map}_*\big(\mathbb{RP}^{n-1},\Omega^nS^n\big)$$
However, for any $\ell\in \mathbb{RP}^{n-1}$, the map $j\circ i(\ell)\in \Omega^nS^n$ has degree $-1$ and thus cannot be homotoped to a constant map, one of which is the natural choice of base-point in $\Omega^nS^n$.
In some other papers, I have seen this discussed in terms of a map $\mathbb{RP}^{n-1}\rightarrow SO(n)$ (not explicitly defined, just attributed to either Hopf or James). This makes me think that the appropriate map to define $\lambda$ needs to be modified from $j\circ i$, and the obvious choice seems to be "pick a basepoint $\ell_{\!0}\in \mathbb{RP}^{n-1}$ and compose each map with $i(\ell_{\!0})$."
But I don't know if that's correct, particularly because I don't understand a lot of the algebraic topology that goes into the Kahn-Priddy theorem. In fact, I just want to understand this map to describe the symmetric square of $S^n$ (see this question), but I want to make sure that I'm actually using the correct map. Technically, the description of $\text{Sym}^2(S^n)$ uses a map from the unreduced suspension, which may be easier to define. But I would still like to see what I'm missing in the definition of the Kahn-Priddy map as well.


text:
Q: Pegasus automatic summarization - partial failure to summarize. PROBLEM: "All images are copyrighted." I've written some code in python that scrapes a news website homepage to take all of the URLs, each linking to the different stories on the page.
The code then parses each individual story using BeautifulSoup.  The final output is a list of strings - each string being the headline and text from each story.  This string is saved to a variable, story_list.
The reason I'm not bothering to show this part of the code is because it works.  I've tested it repeatedly and examined the output in minute detail.  All of the stories are there in full.
At no point in any of the strings does the phrase "All images are copyrighted" appear.  This is important, because it is the crux of the problem.
Below is the code I've written to use Pegasus automatic summarization.  All libraries and dependencies are already installed, which is why they're not displayed below.
The output from this code is mostly working.  It takes each string from the list of stories and generates a one-line summary.  Most of the stories (about 25 out of 30) appear in a summarized form in the output.
Two examples of the output:
<pad>First-time buyers may struggle to save as rising energy bills and rent threatens to eat into their savings, or prevent them from saving in the first place.</s>

<pad>British Gas owner Centrica sees profits of £2.8BIL after Ukraine war - huge surge on previous year.</s>

Each was originally a much longer story prior to summarization.
However, the few remaining stories, which are randomly dispersed, are not being summarized.  In their place, the text
"<pad>All images are copyrighted.</s>"

appears - despite the fact that that particular phrase cannot be found in any of the strings.
I tried to use a different website to see if it helped, but the result was the same.
Anyone encountered this before and found the solution?
Thanks in advance.
THE CODE:
from transformers import PegasusForConditionalGeneration, PegasusTokenizer

tokenizer = PegasusTokenizer.from_pretrained("google/pegasus-xsum")
model = PegasusForConditionalGeneration.from_pretrained("google/pegasus-xsum")

text = ""

for story in story_list:
    text = story
    tokens = tokenizer(text, truncation=True, padding="longest", return_tensors="pt")
    summary = model.generate(**tokens)
    print(tokenizer.decode(summary[0]))

EDIT:
Because it might help clarify the problem, here is the absolute entirety of my code:
import requests
import bs4
from bs4 import BeautifulSoup
from requests_html import HTMLSession
import os

# create session object
s = HTMLSession()

homepage = 'https://www.gbnews.uk/money'

# we're checking if each a tag has a child h2 tag with a class of 'headline' using the find method.
# If the a tag meets this condition, we then get the href attribute and append it to the links list, as before.
def get_story_links(page):
    url = page
    links = []
    r = s.get(url)
    for link in r.html.find('a'):
        if link.find('h2.headline', first=True):
            href = link.attrs.get('href')
            if href and href.startswith('http'):
                links.append(href)
    return links

# let's test the function and save the results to a page variable
urls = get_story_links(homepage)
#print(urls)

def parse_story(url):
    source = requests.get(url).text
    soup = BeautifulSoup(source, 'lxml')
    headline = soup.h1.text
    # THIS IS NECESSARY TO ADD A FULL STOP TO THE HEADLINE OTHERWISE IT RUNS INTO THE REST OF THE TEXT
    headline = headline + '. '
    paragraphs = soup.find_all('p')
    story_one = ""
    for paragraph in paragraphs[:-3]:
        story_one += paragraph.text.strip()
        # THIS IS NECESSARY TO ADD A FULL STOP TO THE BEGINNING OF THE STORY OTHERWISE THE PRECEDING TEXT RUNS INTO IT
        story_one = story_one + '. '
    full_story = headline + story_one
    return full_story

#     THIS WILL PRINT THE HEADLINE AND ARTICLE ON SEPARATE LINES IN JUPYTER - BUT NOT USEFUL FOR SUMMARIZING
#     full_story = f"\n{headline}\n\n{story_one}"
#     print(full_story)

test = parse_story('https://www.gbnews.uk/money/state-pension-age-could-rise-to-above-average-life-expectancy-in-parts-of-uk-literally-working-into-our-graves/430559')
#test

urls = get_story_links(homepage)

# TEST TO SEE ENTIRE OUTPUT
for url in urls:
    print(parse_story(url))

# SUMMARIZING ALL STORIES WITH A LOOP

from transformers import PegasusForConditionalGeneration, PegasusTokenizer

tokenizer = PegasusTokenizer.from_pretrained("google/pegasus-xsum")
model = PegasusForConditionalGeneration.from_pretrained("google/pegasus-xsum")

text = ""

for story in story_list:
    text = story
    tokens = tokenizer(text, truncation=True, padding="longest", return_tensors="pt")
    summary = model.generate(**tokens)
    #print(tokenizer.decode(summary[0]))
    summary_text = tokenizer.decode(summary[0])
    # THIS ELIMINATES THE ANNOYING TAGS AT THE END OF EACH LINE
    summary_text = summary_text.replace("<pad>", "").replace("</s>", "")
    print(summary_text)
    # THIS ADDS AN EMPTY LINE BELOW EACH LINE OF OUTPUT
    print()


text:
Q: Why does List implement IList, ICollection and IEnumerable? If you go to definition of List<T> you would see the following:
public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>

IList<T> already inherits from both ICollection<T> and IEnumerable<T>.
Wouldn't it have been sufficient if List<T> only implemented IList<T>?

A: Yes it would. IList<T> itself implements the other two.
The object browser shows you all the interfaces the class implements, whether directly (IList<T>) or indirectly (ICollection<T>, IEnumerable<T>, through IList<T>).

A: That's not the way it was actually coded behind the scenes.  That's just what tools like Reflector show you when it turns the IL back into C#.

A: If you looked at the source code:
https://referencesource.microsoft.com/#mscorlib/system/collections/generic/list.cs
You can observe that the signature is:
public class List<T> : IList<T>, System.Collections.IList, IReadOnlyList<T>

This can only mean that the metadata browser de-normalizes the inheritance hierarchy for us.

A: Yes, it makes no difference in this case. In some cases it can make a difference, if you're using a base class which already implements an interface but you wish to reimplement it yourself explicitly - but in this case there's no base class (other than the implicit object) and it would have behaved exactly the same way.
Contrary to my recollections, I don't believe there's a difference in the way the class is represented in metadata whether the code explicitly declares all the interfaces or not. Here's an example:
interface IFoo {}
interface IBar : IFoo {}

class FooBar1 : IBar {}
class FooBar2 : IBar, IFoo {}

Both ildasm and Reflector show the same information for FooBar1 and FooBar2... it shows both of them implementing IBar and IFoo.
In other words, we can't tell whether the original source code for List<T> actually specifies all the interfaces or not. Maybe it does, maybe it doesn't - but it doesn't matter either way.
EDIT: For completeness, I also checked the cases where you're extending two interfaces with another interface. I can't find a difference in the metadata in that case, either. I'm sure I remember some situation in which it was evident, but I can't find it now.


text:
Q: image uploading errors So I have this issue with my errors not showing up when I test to see if they are showing up when they are supposed to. When I select an file, my script is only supposed to accept image files as well as nothing bigger than 2MB. I haven't written the part that actually uploads the images to the database and the albums that I created but regardless, I should get some sort of error instead of just passing anything through..I need help! Thanks in advance!
Here is the file that processes the image and will eventually upload:
<?php
include 'init.php';

if(!logged_in()){
header('Location: index.php');
exit();
}

include 'template/header.php';
?>

Upload Image

<?php

if(isset($FILES['image'], $_POST['album_id'])){
$image_name = $_FILES['image']['name'];
$image_size = $_FILES['image']['size'];
$image_temp = $_FILES['image']['tmp_name'];

$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$image_ext = strtolower(end(explode('.', $image_name)));

$album_id = $_POST['album_id'];

$errors = array();

if (empty($image_name) || empty($album_id)){
    $errors[] = 'Something is missing';
} else {

    if(in_array($image_ext, $allowed_ext) === false){
        $errors[] = 'File type not allowed';
    }

    if($image_size > 2097152){
        $errors[] = 'Maximum file size is 2MB';
    }

    if(album_check($album_id) === false){
        $errors[] = 'Couldn\'t upload to that album';
    }

}

if(!empty($errors)){
    foreach ($errors as $error){
        echo $error, '
';
    }
} else {
    // upload image
}
}

$albums = get_albums();

if(empty($albums)){
echo '
You don\'t have any albums. Create an album
';
} else {
?>

<form action="" method="post" enctype="multipart/form-data">

Choose a file:
<input type="file" name="image" />

Choose an album:

<select name="album_id">
    <?php
    foreach ($albums as $album){
        echo '<option value="', $album['id'], '">', $album['name'], '</option>';
    }
    ?>
</select>

<input type="submit" value="Upload" />

</form>

<?php
}

include 'template/footer.php';
?>

I think my issue is around my errors but I'm not sure, again any help is appreciated! Thanks!
-TechGuy24

A: Change if(isset($FILES['image'], $_POST['album_id'])){
To if(isset($_FILES['image'], $_POST['album_id'])){


text:
Q: Questions on STM implementations I've read two quite different accounts of how STM is implemented.  Perhaps both are valid, or one is mistaken, and I hoping someone can shed light.
Take 1 (wikipedia): all threads are allowed to modify shared memory, but every read and write within the transaction is logged.  At the end of the transaction the system checks that other threads have not concurrently made changes to memory.  If no changes were made, transaction is committed.  Otherwise, transaction is restarted.

*

*Q: If this is a valid implmentation, then it seems useless to allow two threads to execute within the same transaction.  They will read each other's writes and the computation within the transaction block will be malformed.

Take 2 (can't find source): When a program enters transaction, it gets a copy of all variables contained within and can go to town on them.  At the end of the transaction the system tries to update the master with the copy.  If the master hasn't changed since the copy was first made, then the transaction is committed.  Otherwise, transaction is restarted.
Also, what happens when two threads enter the same transaction at the same time?  Doesn't this cause a race condition of sorts?  Since both are attempting to modify the same shared memory, both will need to be restarted and the issue continue ad infinitum unless the system steps in and tell one thread to cool it (sort of like a lock =)  I'm sure I'm missing a concept here.

A: I'm not an expert but have read a few papers.  As is common with proposals for new technologies, it looks like one group proposed STM, but subsequent work by other groups looked at variations.  There are more than the two you mention. For example, this paper gives a mechanism that has blocking locks on transactions rather than the aggressive non-blocking approach in both of yours:  http://pages.cs.wisc.edu/~david/courses/cs758/Fall2007/papers/saha-mcrt-ppopp-2007.pdf
The only common thread among implementation techniques seems to be the database-like transaction semantics. So the central question of the research is about whether these semantics lead to better programs and/or more efficiency in general. How they're implemented is up for grabs.

Also, what happens when two threads enter the same transaction at the same time? Doesn't this cause a race condition of sorts? Since both are attempting to modify the same shared memory, both will need to be restarted...

Not really. The system always makes progress because when 2 or more commits are in conflict, the log allows all to be rolled back to the point where the conflicting transactions started.  Then the threads can be allowed to proceed and commit sequentially.  You're right this causes duplicate work, especially when a single object is in high demand.  However avoiding this would be worthwhile only when its more costly than a context swap.  The STM folks are betting that memory conflicts are comparatively rare. The Wikipedia scheme is particularly aggressive in this assumption.

A: Here is a link to an answer which outlines the TL2 STM algorithm and which provides links to a couple of fairly readable papers on implementing it and how to mechanically transform normal code into STM code:
Stackoverflow: How do you implement Software Transactional Memory?
Clearly it is an active research area and so there are lots of approaches. The one that may work best for a given problem depends on the concurrency and read/write ratio of the problem at hand.
With respect to the TL2 algorithm your question:

... it seems useless to allow two threads to execute within the same
  transaction. They will read each other's writes and the computation
  within the transaction block will be malformed.

Its about what data is seen (the read-set) or updated (the write-set) during transactions not what code they are executing. The TL2 algorithm allows speculative work to happen with no locks held keeping the write-set private to each thread until commit. At commit time the transaction takes write locks then does a final versions check that the read-set versions still match the master value versions (the public committed values) before it flushes the updates to the master values incrementing their versions. Of course the transaction can see its own private updates before commit and any committed master values but different tx dont see each others unflushed write-set. If some other transaction has in the meanwhile committed and changed the master versions from what was seen in the read-set the tx is aborted. This enforces consistency without holding of locks whilst the application logic is running. The papers at the link above have a lot more details and optimisations.

Also, what happens when two threads enter the same transaction at the
  same time? Doesn't this cause a race condition of sorts?

Yes threads race with TL2 when doing different work if they are reading values which the other thread will update. Work can be thrown away due to aborting at the final consistency checks. You should code to retry a number of times when this happens until you get a consistent read which finally leads to a successful commit. The hope is that if you have many cores on your server you will get more total throughput by occasionally throwing the work of a core away than you would have by using course grained locks which block cores. The other hope is that STM can be more straight forward than hand crafting an optimal fine grained locking approach that avoids deadlock. Clearly throughput depends on the actual application logic and collisions.

Since both are attempting to modify the same shared memory, both will
  need to be restarted and the issue continue ad infinitum unless the
  system steps in and tell one thread to cool it (sort of like a lock =)

The livelock you mention is avoided by taking locks on the master values at commit time. Take all the locks in ascending memory order of the master values memory addresses and you will not get deadlock. One of the two threads will get all the locks it needs first. The other will block. The first thread will then do its read-set consistency checks, flush it's write-set incrementing the master values, then release the locks. The second thread will finally get all it's locks, then do its read-set consistency checks, and abort the transaction due to seeing that thread one has incremented the version of a master value it used in its application logic.
Clearly this commit time locking strategy blocks threads but locks are not held whilst arbitrary application logic is running. This critical section can be aggresively tuned. The papers even make mention of processor instructions which request that a thread is left to run uninterrupted whilst it is holding those locks.


text:
Q: Using Postman tool to create nodes in Neo4j I have just started using Neo4j and Cypher. I am trying to create a node from Postman using Rest API calls.
When I send the postman call, I get a Status: 201 Created, which is great.
But when I send the MATCH call to check if the node has been created, I get an empty response.
CREATE REST CALL

Response:
{
  "commit": "http://localhost:7474/db/data/transaction/43/commit",
  "results": [
    {
      "columns": [],
      "data": [],
      "stats": {
        "contains_updates": true,
        "nodes_created": 1,
        "nodes_deleted": 0,
        "properties_set": 2,
        "relationships_created": 0,
        "relationship_deleted": 0,
        "labels_added": 1,
        "labels_removed": 0,
        "indexes_added": 0,
        "indexes_removed": 0,
        "constraints_added": 0,
        "constraints_removed": 0
      }
    }
  ],
  "transaction": {
    "expires": "Mon, 06 Feb 2017 21:03:06 +0000"
  },
  "errors": []
}

But if I create it from the Web Client, I can see those in my get call from REST API.

A: Aah.. got the answer. The URL for CREATE is
http://localhost:7474/db/data/transaction/commit
instead of
http://localhost:7474/db/data/transaction/
Also, if you need to get the object back in the same call, you could do this
{
  "statements": [
    {
      "statement": "CREATE (a:Person { name: 'Adam', title: 'some guy' }) RETURN a",
      "parameters": {},
      "resultDataContents": [
        "row",
        "graph"
      ],
      "includeStats": true
    }
  ]
}


text:
Q: Type mismatch in function arguments I'm trying to write this small piece of code but I can't get it work. I have a very little experience in Rust, especially with lifetimes.
I have reproduced the error in a smaller script:
fn main() {
    let app = App {
        name: &String::from("Davide"),
    };
    app.run();
}

struct App<'a> {
    name: &'a String,
}

impl<'a> App<'a> {
    fn run(self) {
        let result = App::validator_1(App::validator_2(App::box_command()))(self);
        println!("{}", result)
    }

    fn validator_1(next: Box<Fn(App) -> String>) -> Box<Fn(App) -> String> {
        Box::new(move |app: App| -> String { next(app) })
    }

    fn validator_2(next: Box<Fn(App) -> String>) -> Box<Fn(App) -> String> {
        Box::new(move |app: App| -> String { next(app) })
    }

    fn box_command() -> Box<Fn(App) -> String> {
        Box::new(App::command)
    }

    fn command(self) -> String {
        format!("Hello {}!", self.name)
    }
}

When I compile it, I get this error:
error[E0631]: type mismatch in function arguments
  --> src/main.rs:27:9
   |
27 |         Box::new(App::command)
   |         ^^^^^^^^^^^^^^^^^^^^^^ expected signature of `for<'r> fn(App<'r>) -> _`
...
30 |     fn command(self) -> String {
   |     -------------------------- found signature of `fn(App<'_>) -> _`
   |
   = note: required for the cast to the object type `for<'r> std::ops::Fn(App<'r>) -> std::string::String`

error[E0271]: type mismatch resolving `for<'r> <fn(App<'_>) -> std::string::String {App<'_>::command} as std::ops::FnOnce<(App<'r>,)>>::Output == std::string::String`
  --> src/main.rs:27:9
   |
27 |         Box::new(App::command)
   |         ^^^^^^^^^^^^^^^^^^^^^^ expected bound lifetime parameter, found concrete lifetime
   |
   = note: required for the cast to the object type `for<'r> std::ops::Fn(App<'r>) -> std::string::String`

I understand that the problem is somehow related to the lifetime of name in App but I don't know how to fix it.

A: The signature of the command function does not match with what box_command is expected to return.
box_command should have the following body:
fn box_command() -> Box<Fn(App) -> String> {
    Box::new(move |app: App| -> String { app.command() })
}

The compiler is expecting an invocation which returns a String. The above change will allow self from the following statement to be passed as the app argument. Thus app.command() satisfies the entire flow and returns String from the invocation chain.
let result = App::validator_1(App::validator_2(App::box_command()))(self);


text:
Q: C++, Libsodium sodium_malloc generates an exception I am reallizing a small code in C++ to cryptograph and decrypt messages, to do this I use Libsodium.
Since the length of the text is not constant I have to make use of dynamic memory, and to cope with the safety of the data allocated in memory I make use of the sodium_malloc function.
After writing my code I tested it, but at the point where I allocate memory with sodium_malloc it generates an exception for me, here is an excerpt:
int main()
{
     unsigned char* text;
     text = (unsigned char*)sodium_malloc(sizeof(unsigned char) * (12)); // hello worold --> lenth: 11 + 1 ('\0')

     sodium_free(text);

     system("pause");
     return 0;
}

It generates this exception for me:
Unhandled Exception in 0x00007FFDBE61286E (ucrtbase.dll) in DEF (Console).exe: Exit was requested from the program causing an unrecoverable error.

A: A quick google finds this
From that 'bug report' we get this

The library must be initialized with sodium_init() before any other
function is called.


text:
Q: Windows 10 Universal App Mobile Full Screen I am trying to allow my Windows 10 Universal app to utilize the screen space at the top of the phone where the Windows icons for Battery, Time, Wifi, etc. normally reside. I know it is possible because there are other apps that utilize that top space (for example: Candy Crush). Please see the screenshot of my app below. I am speaking of the region labeled "Unused Space."

I cannot find any MSDN documentation on this subject, and was concerned that it may have to do with my hard requirement to use a non-standard app bar. However, I created a project with a CommandBar and the unused space still exists. That said, I am at a loss as to how to regain that real estate.


text:
Q: Kivy: How to change the attribute's value like text of label from current screen in another screen I tried to change the text of another screen from current screen. But it didn't work
from kivy.app import App
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.properties import ObjectProperty
from kivy.lang.builder import Builder

Builder.load_string("""
<Input_Screen>:
    input: input
    BoxLayout:
        orientation : "vertical"
        TextInput:
            id: input
            text: "Changed"
        Button:
            text: "Enter"
            on_press : root.clicked()

<Display_Screen>:
    nice: nice
    BoxLayout:
        orientation : "vertical"
        Label:
            id: nice
            text: "NotChanged"

""")

class Input_Screen(Screen):
    input = ObjectProperty(None)
    def clicked(self):
        Display_Screen().change()

class Display_Screen(Screen):
    nice = ObjectProperty(None)
    def change(self):
        print(self.nice.text) #Checking the Current text of The Label
        print(Input_Screen().input.text) #Checking What do we want to change
        self.nice.text = Input_Screen().input.text
        print(self.nice.text) #Checking if it has change or not
        MyApp().sm.current = "Ds" #Changing Screen to Display_Screen
        print(self.nice.text) #Checking if it has change or not

class MyApp(App):
    sm = ScreenManager()
    def build(self):
        self.sm.add_widget(Input_Screen(name="Is"))
        self.sm.add_widget(Display_Screen(name="Ds"))
        return self.sm

MyApp().run()

What I get in My console:
NotChanged #Checked the Current text of The Label
Changed #Checked What do we want to change
Changed #Checked if it has change or not
Changed #Checked if it has change or not

It says that my Label's text has been changed but when it goes to the next screen it hasn't been changed.
Display_Screen
Anyone knows whats the problem? Help me please

A: Whenever you use a construction like ClassName(), you are creating a new instance of ClassName. You are doing this in your change() method and in your clicked() method. Whenever you do that, you are referencing that new instance, and not the instance that is in your GUI.
To fix that, change:
def clicked(self):
    Display_Screen().change()

to:
def clicked(self):
    self.manager.get_screen('Ds').change()

and in your change() method, replace:
Input_Screen()

with:
self.manager.get_screen('Is')

and replace"
MyApp()

with:
App.get_running_app()


text:
Q: Issue with JSON parsing: "q\r\nq" I needed to parse some data and pass with the request body,
Data I need to keep in request body contains carriage return/ line change, which is creating a problem when parsing the same,
I don't understand why it cannot be parsed into a JS native object when it's a valid JSON.

let x= "q\r\nq"

let y= "q\\r\\nq"

JSON.parse(x)

JSON.parse(y)

as both x and y are the valid JSONs.

A: Your JSON's content doesn't include quotes. Strings in JSON need to be quoted.
This works:
>> JSON.parse('"q\\r\\nq"')
"q
q"

A: Add quotes:
JSON.parse('"q\\r\\nq"')

A: Use a real JSON
let x= "{\"value\": \"q\\r\\nq\"}"
JSON.parse(x)


text:
Q: partial derivative with respect to $\overline{z}$ In my text on complex analysis, they give the definition of $\frac{\partial f}{\partial \overline{z}}$ for suitable $f : \mathbb{C} \rightarrow \mathbb{C}$. However, I do not understand how to make formal the fact that if you write $f$ 'in terms of' $z$ and $\overline{z}$, $\frac{\partial f}{\partial \overline{z}}$ is just the partial derivative with respect to $\overline{z}$ of $f$, as if you substituted $x=z$ and $y=\overline{z}$ and then took the partial with respect to $y$. The book uses this without proof, I would like to understand why this works. Thanks in advance.

A: The reason your book uses the expressions $\frac{\partial f}{\partial z}$ and $\frac{\partial f}{\partial \overline{z}}$ without proof is that they are not actual partial derivatives, they are only derivatives in a symbolic sense. They are formal expressions that can help in understanding and communicating the behavior of a complex function.
If we write $x = \frac12(z + \overline{z})$ and $y = \frac{1}{2i}(z - \overline{z})$, thus expressing $x$ and $y$ as functions of $z$ and $\overline{z}$, and think of $f(z) = f(x,y)$ as a function of two real variables, then by supposing the rules of calculus apply we obtain
$$
\frac{\partial f}{\partial z} = \frac 12 \left(\frac{\partial f}{\partial x} - i \frac{\partial f}{\partial y} \right)
$$
and
$$
\frac{\partial f}{\partial \overline{z}} = \frac 12 \left(\frac{\partial f}{\partial x} + i \frac{\partial f}{\partial y} \right).
$$
If $\frac{\partial f}{\partial \overline{z}} = 0$ for a particular function, then this is equivalent with saying that $f$ satisfies the Cauchy-Riemann equations. So in a formal sense we could say that an analytic function is a function of $z$ alone and independent of $\overline{z}$, thinking of them independent variables. (Ahlfors)


text:
Q: Windows 8.1 RDP -shadow session Is it possible to establish RDP shadow session in Win 8.1 Pro VM on Win 8.1 Pro Host?
I can RDP into the VM  from an external client (credentials saved):
 mstsc.exe /v:68.560.92.1

In the VM I get the session Id using query session  yielding rdp-tcp#20
Then on another external client I do
 mstsc.exe /v:68.560.92.1 /shadow:rdp-tcp#20      Result: "This computer name is invalid"
 mstsc.exe /v:68.560.92.1 /shadow:20              Result: "This computer name is invalid"
 mstsc.exe /v:68.560.92.1                         Result: Success, but kicks off other client

Some things I've done:

*

*disabled entire firewall  on VM (for testing)

*Set HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Control/TerminalServer/AllowRemoteRDC  to 1

*Enabled File and Printer sharing on VM
Is this specifically not available without Win Server or full VDI deployment?

A: No, it is not possible. Even if you found a "hack" solution that allowed for it, that would be violating Microsoft's EULA. What you are trying to do (shadow an RDP session) is only possible on a server OS and this is very much by design. Sorry.


text:
Q: Outlook 2010 autocomplete stream ( cached contacts) I'm currently trying to develop an outlook plugin. As to implement a non functional requirenment I need to access outlook cached contacts which are stored in .nk2 file. I refered to this post but couldn't figure out how to do it.
Edited (Answer):
Microsoft.Office.Interop.Outlook.Application oApp = Globals.ThisAddIn.Application;
        Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = oApp.GetNamespace("MAPI").GetDefaultFolder(OlDefaultFolders.olFolderInbox);

        StorageItem storage = inboxFolder.GetStorage("IPM.Configuration.Autocomplete", OlStorageIdentifierType.olIdentifyByMessageClass);

        //IPM.Configuration.Autocomplete

        PropertyAccessor propertyAcc = storage.PropertyAccessor;

        byte[] got = propertyAcc.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x7C090102");

Currently I'm stuck in accessing byte array, When I accesing the array the values are different than how it's mentioned in this post

A: Microsoft.Office.Interop.Outlook.Application oApp = Globals.ThisAddIn.Application;
Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = oApp.GetNamespace("MAPI").GetDefaultFolder(OlDefaultFolders.olFolderInbox);

StorageItem storage = inboxFolder.GetStorage("IPM.Configuration.Autocomplete", OlStorageIdentifierType.olIdentifyByMessageClass);

PropertyAccessor propertyAcc = storage.PropertyAccessor;

byte[] got = propertyAcc.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x7C090102");

use the description here to access the fields in the byte[]. I completed the code it's working correctly. You just have to loop through each byte and check for data types when accessing .

A: Edit:
Can you use a object instead of a byte array (if that doesn't work, hover your mouse over the GetProperty during debugging and see what return type it expects). eg:
Dim objPropAcc As Outlook.PropertyAccessor
Dim result As Object
objPropAcc = BindingStorageItem.PropertyAccessor
result = objPropAcc.GetProperty("http://schemas.microsoft.com/mapi/id/{00062040-0000-0000-C000-000000000046}/8A48001E").ToString();

Ref: how to get a sharepoint calendar url from outlook?
Old:
Here is a Microsoft KB article How to import .nk2 files into Outlook 2010

Outlook 2007 and 2010 interact with the nickname cache, also known as
  the "autocomplete stream." The autocomplete stream is where Outlook
  persists the autocomplete list, which is the list of names that
  displays in the To, Cc, and Bcc edit boxes while a user is composing
  an email. This topic
  here describes
  how Outlook 2007 and Outlook 2010 interact with the autocomplete
  stream and also discusses the binary format of the file and the
  recommended ways for interacting with the autocomplete stream.

Also have a look at some of the sample's over here: http://ol2010mapisamples.codeplex.com/, I think this codeplex project is run by the MAPI expert Stephen Griffin.


text:
Q: Update value for a repeating UILabel with loop I have labels that will hold the name and value of an array items = [MyItems](). Where
struct MyItems {
    name: String!
    value: Int!
}

The labels are titleLabel1 and valueLabel1. I have 6 of these labels that take a value from the array which has more than 6 values.
Currently I am using a for loop like:
var items = [MyItems]()
func viewDidLoad() {
    super.viewDidLoad()
    items = loadItemsFromAPI()
    populateFields()
}
func populateFields() {
    for var i = 0; i < 6 && i < items.count; i++ {
      switch i {
           case 0:
               titleLabel1.text = items[i].name
               valueLabel1.text = "items[i].value"
           case 1:
               titleLabel1.text = items[i].name
               valueLabel1.text = "items[i].value"
           case 2:
               titleLabel1.text = items[i].name
               valueLabel1.text = "items[i].value"
           case 3:
               titleLabel1.text = items[i].name
               valueLabel1.text = "items[i].value"
           case 4:
               titleLabel1.text = items[i].name
               valueLabel1.text = "items[i].value"
           case 5:
               titleLabel1.text = items[i].name
               valueLabel1.text = "items[i].value"
           default:
               print("Unexpected value encounteredValue: \(i)")
               break
           }
      }
}

My question is is there any way to loop over the labels to assign the values instead of this lengthy way?
like
for var i = 0; i < 6; i++ {
    titleLabel + "i-1".text = items[i].name
}

In theory that's what I have in mind only if it was possible to have a short cleaner code.

A: Have the labels in an array:
let titleCollection = [titleLabel1, titleLabel2, titleLabel3, titleLabel4, titleLabel5, titleLabel6]
let valueCollection = [valueLabel1, valueLabel2, valueLabel3, valueLabel4, valueLabel5, valueLabel6]

Using zip to add the text to the labels safely:
zip(titleCollection, items).forEach { $0.0.text = $0.1.name }
zip(valueCollection, items).forEach { $0.0.text = String($0.1.value) }

You should either use a collection of @IBOutlet or have the text fields in an array. I believe there is a way to access your properties using a String but from what I've read it's not reliable or not intended so I wouldn't recommend you to do that. Correct me if I'm wrong though.

A: If you're trying to loop through many labels and change their values, you may want to try this:
var i = 0
for view in self.view.subviews {
    if view is UILabel {
        titleLabel.text = items[i]
        valueLabel.text = items[i]
        i++
    }
}

Or, if you're trying to update 1 label's text a bunch of times rapidly, you should us an NSTimer:
NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "update", userInfo: nil, repeats: true)

var i = 0
func update() {
    labels.text = items[i]
    i++
}


text:
Q: Multiple layers android Animation I am working on an android application that requires multiple views which will overlap each other in one main view (FramLayout).  Each of those 3 views will be the same size and have different kinds of animations.  As far as the design, what would be the best approach?  I would prefere to do this programmatically.  Is there an example of different views being overlapped with animations?

A: The best solution I had was have 3 views with view inflators wihtin the framelayout, Have the main animations with a surface view in the front then have less animations with the othe views behind them. This will allow you to easily update one of the previous layers :)


text:
Q: Linux 3.x fails assigning PCI BAR memory I got an IBM x3850 type 8864 machine, I can successfully boot using a 2.6.32 kernel but when I try to use a 3.10 kernel or newer the kernel fails to initialize all PCI slots (I can fix this (manually), see below):
pci 0000:19:00.0: BAR 14: can't assign mem (size 0x1a00000)
pci 0000:19:00.0: BAR 13: can't assign io (size 0x3000)
pci 0000:19:00.0: BAR 14: can't assign mem (size 0x1600000)
pci 0000:19:00.0: BAR 13: can't assign io (size 0x3000)
pci 0000:1a:00.0: BAR 14: can't assign mem (size 0x1600000)
pci 0000:1a:00.0: BAR 13: assigned [io  0x7000-0x8fff]
pci 0000:1b:02.0: BAR 14: can't assign mem (size 0xa00000)
pci 0000:1b:04.0: BAR 14: can't assign mem (size 0xa00000)
pci 0000:1b:02.0: BAR 13: assigned [io  0x7000-0x7fff]
pci 0000:1b:04.0: BAR 13: assigned [io  0x8000-0x8fff]
...

Which causes that my network card is not successfully loaded as the PCI bus is obviously not correctly instantiated.
lspci yields the following:
00:00.0 Host bridge: IBM Calgary PCI-X Host Bridge (rev 04)
00:01.0 VGA compatible controller: Advanced Micro Devices, Inc. [AMD/ATI] RV100 [Radeon 7000 / Radeon VE]
00:03.0 USB controller: NEC Corporation OHCI USB Controller (rev 43)
00:03.1 USB controller: NEC Corporation OHCI USB Controller (rev 43)
00:03.2 USB controller: NEC Corporation uPD72010x USB 2.0 Controller (rev 04)
00:0f.0 Host bridge: Broadcom CSB6 South Bridge (rev a0)
00:0f.1 IDE interface: Broadcom CSB6 RAID/IDE Controller (rev a0)
00:0f.3 ISA bridge: Broadcom GCLE-2 Host Bridge
01:00.0 Host bridge: IBM Calgary PCI-X Host Bridge (rev 04)
01:01.0 Ethernet controller: Broadcom Corporation NetXtreme BCM5704 Gigabit Ethernet (rev 10)
01:01.1 Ethernet controller: Broadcom Corporation NetXtreme BCM5704 Gigabit Ethernet (rev 10)
01:02.0 RAID bus controller: Adaptec AAC-RAID (rev 02)
02:00.0 Host bridge: IBM Calgary PCI-X Host Bridge (rev 04)
06:00.0 Host bridge: IBM Calgary PCI-X Host Bridge (rev 04)
0a:00.0 PCI bridge: IBM CalIOC2 PCI-E Root Port (rev 01)
0f:00.0 PCI bridge: IBM CalIOC2 PCI-E Root Port (rev 01)
14:00.0 PCI bridge: IBM CalIOC2 PCI-E Root Port (rev 01)
19:00.0 PCI bridge: IBM CalIOC2 PCI-E Root Port (rev 01)
1a:00.0 PCI bridge: Integrated Device Technology, Inc. [IDT] PES12N3A PCI Express Switch (rev 0c)
1b:02.0 PCI bridge: Integrated Device Technology, Inc. [IDT] PES12N3A PCI Express Switch (rev 0c)
1b:04.0 PCI bridge: Integrated Device Technology, Inc. [IDT] PES12N3A PCI Express Switch (rev 0c)
1c:00.0 Ethernet controller: Intel Corporation 82576 Gigabit Network Connection (rev 01)
1c:00.1 Ethernet controller: Intel Corporation 82576 Gigabit Network Connection (rev 01)
1d:00.0 Ethernet controller: Intel Corporation 82576 Gigabit Network Connection (rev 01)
1d:00.1 Ethernet controller: Intel Corporation 82576 Gigabit Network Connection (rev 01)

FIX
I can actually fix it by removing the root PCI bus 19:00.0 PCI bridge: IBM CalIOC2 PCI-E Root Port (rev 01) via echo 1 > /sys/bus/pci/devices/0000\:19\:00.0/remove and a rescan afterwards: echo 1 > /sys/bus/pci/rescan
which causes the following output:
pci _bus 0000:1c: busn_res: [bus 1c] is released
pci _bus 0000:1d: busn_res: [bus 1d] is released
pci _bus 0000:1b: busn_res: [bus 1b-1d] is released
pci _bus 0000:1a: busn_res: [bus 1a-1d] is released
pci  0000:19:00.0: [1014:0308] type 01 class 0x060401
pci  0000:19:00.0: supports D1 D2
pci  0000:19:00.0: PME# supported from D0 D1 D2 D3hot D3cold
pci  0000:1a:00.0: [111d:8018] type 01 class 0x060400
pci  0000:1a:00.0: PME# supported from D0 D3hot D3cold
pci  0000:19:00.0:     pci  bridge to [bus 1a-1d] (subtractive decode)
pci  0000:19:00.0:   bridge window [mem 0xea800000-0xea9fffff 64bit pref]
pci  0000:19:00.0:   bridge window [mem 0xea800000-0xebcfffff] (subtractive decode)
pci  0000:19:00.0:   bridge window [io  0x7000-0x8fff] (subtractive decode)
pci  0000:1b:02.0: [111d:8018] type 01 class 0x060400
pci  0000:1b:02.0: PME# supported from D0 D3hot D3cold
pci  0000:1b:04.0: [111d:8018] type 01 class 0x060400
pci  0000:1b:04.0: PME# supported from D0 D3hot D3cold
pci  0000:1a:00.0:     pci  bridge to [bus 1b-1d]
pci  0000:1a:00.0:   bridge window [io  0x7000-0x8fff]
pci  0000:1a:00.0:   bridge window [mem 0xea800000-0xea9fffff 64bit pref]

....

pci  0000:1b:04.0:   bridge window [mem 0xea900000-0xea9fffff 64bit pref]
pci  0000:1b:02.0: bridge window [mem 0x00100000-0x001fffff 64bit pref] to [bus 1c] add_size 100000
pci  0000:1b:04.0: bridge window [mem 0x00100000-0x001fffff 64bit pref] to [bus 1d] add_size 100000
pci  0000:1b:02.0: res[15]=[mem 0x00100000-0x001fffff 64bit pref] get_res_add_size add_size 100000
pci  0000:1b:04.0: res[15]=[mem 0x00100000-0x001fffff 64bit pref] get_res_add_size add_size 100000
pci  0000:1a:00.0: bridge window [mem 0x00100000-0x002fffff 64bit pref] to [bus 1b-1d] add_size 200000
pci  0000:19:00.0: bridge window [io  0x1000-0x2fff] to [bus 1a-1d] add_size 1000
pci  0000:1a:00.0: res[15]=[mem 0x00100000-0x002fffff 64bit pref] get_res_add_size add_size 200000
pci  0000:19:00.0: bridge window [mem 0x00100000-0x002fffff 64bit pref] to [bus 1a-1d] add_size 200000
pci  0000:19:00.0: bridge window [mem 0x00200000-0x015fffff] to [bus 1a-1d] add_size 200000
pci  0000:19:00.0: res[14]=[mem 0x00200000-0x015fffff] get_res_add_size add_size 200000
pci  0000:19:00.0: res[15]=[mem 0x00100000-0x002fffff 64bit pref] get_res_add_size add_size 200000
pci  0000:19:00.0: res[13]=[io  0x1000-0x2fff] get_res_add_size add_size 1000
pci  0000:19:00.0: BAR 14: can't assign mem (size 0x1600000)
pci  0000:19:00.0: BAR 15: assigned [mem 0xea800000-0xeabfffff 64bit pref]
pci  0000:19:00.0: BAR 13: can't assign io (size 0x3000)
pci  0000:19:00.0: BAR 14: assigned [mem 0xea800000-0xebbfffff]
pci  0000:19:00.0: BAR 15: can't assign mem pref (size 0x200000)
pci  0000:19:00.0: BAR 13: assigned [io  0x7000-0x8fff]
pci  0000:19:00.0: BAR 14: can't assign mem (size 0x1400000)
pci  0000:19:00.0: failed to add 200000 res[14]=[mem 0xea800000-0xebbfffff]
pci  0000:19:00.0: BAR 13: can't assign io (size 0x2000)
pci  0000:19:00.0: failed to add 1000 res[13]=[io  0x7000-0x8fff]
pci  0000:1a:00.0: res[15]=[mem 0x00100000-0x002fffff 64bit pref] get_res_add_size add_size 200000
pci  0000:1a:00.0: BAR 14: assigned [mem 0xea800000-0xebbfffff]
pci  0000:1a:00.0: BAR 15: can't assign mem pref (size 0x400000)
pci  0000:1a:00.0: BAR 13: assigned [io  0x7000-0x8fff]
pci  0000:1a:00.0: BAR 14: assigned [mem 0xea800000-0xebbfffff]
pci  0000:1a:00.0: BAR 15: can't assign mem pref (size 0x200000)
pci  0000:1b:02.0: res[15]=[mem 0x00100000-0x001fffff 64bit pref] get_res_add_size add_size 100000
pci  0000:1b:04.0: res[15]=[mem 0x00100000-0x001fffff 64bit pref] get_res_add_size add_size 100000
pci  0000:1b:02.0: BAR 14: assigned [mem 0xea800000-0xeb1fffff]
pci  0000:1b:04.0: BAR 14: assigned [mem 0xeb200000-0xebbfffff]
pci  0000:1b:02.0: BAR 15: can't assign mem pref (size 0x200000)
pci  0000:1b:04.0: BAR 15: can't assign mem pref (size 0x200000)
pci  0000:1b:02.0: BAR 13: assigned [io  0x7000-0x7fff]
pci  0000:1b:04.0: BAR 13: assigned [io  0x8000-0x8fff]
pci  0000:1b:02.0: BAR 14: assigned [mem 0xea800000-0xeb1fffff]
pci  0000:1b:04.0: BAR 14: assigned [mem 0xeb200000-0xebbfffff]
pci  0000:1b:02.0: BAR 15: can't assign mem pref (size 0x100000)
pci  0000:1b:04.0: BAR 15: can't assign mem pref (size 0x100000)
pci  0000:1c:00.0: reg 184: [mem 0xea800000-0xea803fff 64bit pref]
pci  0000:1c:00.0: reg 190: [mem 0xea820000-0xea823fff 64bit pref]
pci  0000:1c:00.0: reg 184: [mem 0xea800000-0xea803fff 64bit pref]
pci  0000:1c:00.0: reg 184: [mem 0xea800000-0xea803fff 64bit pref]
pci  0000:1c:00.0: reg 190: [mem 0xea820000-0xea823fff 64bit pref]
pci  0000:1c:00.0: reg 184: [mem 0xea800000-0xea803fff 64bit pref]
pci  0000:1c:00.0: reg 190: [mem 0xea820000-0xea823fff 64bit pref]
pci  0000:1c:00.1: reg 184: [mem 0xea840000-0xea843fff 64bit pref]
pci  0000:1c:00.0: reg 184: [mem 0xea800000-0xea803fff 64bit pref]
pci  0000:1c:00.0: reg 190: [mem 0xea820000-0xea823fff 64bit pref]
pci  0000:1c:00.1: reg 190: [mem 0xea860000-0xea863fff 64bit pref]
pci  0000:1c:00.0: reg 184: [mem 0xea800000-0xea803fff 64bit pref]
pci  0000:1c:00.0: reg 190: [mem 0xea820000-0xea823fff 64bit pref]
pci  0000:1c:00.1: reg 184: [mem 0xea840000-0xea843fff 64bit pref]
pci  0000:1c:00.0: res[7]=[mem 0xea800000-0xea7fffff 64bit pref] get_res_add_size add_size 20000
pci  0000:1c:00.0: res[10]=[mem 0xea820000-0xea81ffff 64bit pref] get_res_add_size add_size 20000
pci  0000:1c:00.1: res[7]=[mem 0xea840000-0xea83ffff 64bit pref] get_res_add_size add_size 20000
pci  0000:1c:00.1: res[10]=[mem 0xea860000-0xea85ffff 64bit pref] get_res_add_size add_size 20000
pci  0000:1c:00.0: BAR 1: assigned [mem 0xea800000-0xeabfffff]
pci  0000:1c:00.1: BAR 1: assigned [mem 0xeac00000-0xeaffffff]
pci  0000:1c:00.0: BAR 0: assigned [mem 0xeb000000-0xeb01ffff]
pci  0000:1c:00.1: BAR 0: assigned [mem 0xeb020000-0xeb03ffff]
pci  0000:1c:00.0: BAR 3: assigned [mem 0xeb040000-0xeb043fff]
pci  0000:1c:00.0: reg 184: [mem 0xea800000-0xea803fff 64bit pref]
pci  0000:1c:00.0: BAR 7: assigned [mem 0xeb044000-0xeb063fff 64bit pref]
pci  0000:1c:00.0: reg 190: [mem 0xea820000-0xea823fff 64bit pref]
pci  0000:1c:00.0: BAR 10: assigned [mem 0xeb064000-0xeb083fff 64bit pref]
pci  0000:1c:00.1: BAR 3: assigned [mem 0xeb084000-0xeb087fff]
pci  0000:1c:00.1: reg 184: [mem 0xea840000-0xea843fff 64bit pref]
pci  0000:1c:00.1: BAR 7: assigned [mem 0xeb088000-0xeb0a7fff 64bit pref]
pci  0000:1c:00.1: reg 190: [mem 0xea860000-0xea863fff 64bit pref]
pci  0000:1c:00.1: BAR 10: assigned [mem 0xeb0a8000-0xeb0c7fff 64bit pref]
pci  0000:1c:00.0: BAR 2: assigned [io  0x7000-0x701f]
pci  0000:1c:00.1: BAR 2: assigned [io  0x7020-0x703f]
pci  0000:1b:02.0:     pci  bridge to [bus 1c]
pci  0000:1b:02.0:   bridge window [io  0x7000-0x7fff]
pci  0000:1b:02.0:   bridge window [mem 0xea800000-0xeb1fffff]
pci  0000:1d:00.0: reg 184: [mem 0xea900000-0xea903fff 64bit pref]
pci  0000:1d:00.0: reg 190: [mem 0xea920000-0xea923fff 64bit pref]
pci  0000:1d:00.0: reg 184: [mem 0xea900000-0xea903fff 64bit pref]
pci  0000:1d:00.0: reg 184: [mem 0xea900000-0xea903fff 64bit pref]
pci  0000:1d:00.0: reg 190: [mem 0xea920000-0xea923fff 64bit pref]
pci  0000:1d:00.0: reg 184: [mem 0xea900000-0xea903fff 64bit pref]
pci  0000:1d:00.0: reg 190: [mem 0xea920000-0xea923fff 64bit pref]
pci  0000:1d:00.1: reg 184: [mem 0xea940000-0xea943fff 64bit pref]
pci  0000:1d:00.0: reg 184: [mem 0xea900000-0xea903fff 64bit pref]
pci  0000:1d:00.0: reg 190: [mem 0xea920000-0xea923fff 64bit pref]
pci  0000:1d:00.1: reg 190: [mem 0xea960000-0xea963fff 64bit pref]
pci  0000:1d:00.0: reg 184: [mem 0xea900000-0xea903fff 64bit pref]
pci  0000:1d:00.0: reg 190: [mem 0xea920000-0xea923fff 64bit pref]
pci  0000:1d:00.1: reg 184: [mem 0xea940000-0xea943fff 64bit pref]
pci  0000:1d:00.0: res[7]=[mem 0xea900000-0xea8fffff 64bit pref] get_res_add_size add_size 20000
pci  0000:1d:00.0: res[10]=[mem 0xea920000-0xea91ffff 64bit pref] get_res_add_size add_size 20000
pci  0000:1d:00.1: res[7]=[mem 0xea940000-0xea93ffff 64bit pref] get_res_add_size add_size 20000
pci  0000:1d:00.1: res[10]=[mem 0xea960000-0xea95ffff 64bit pref] get_res_add_size add_size 20000
pci  0000:1d:00.0: BAR 1: assigned [mem 0xeb400000-0xeb7fffff]
pci  0000:1d:00.1: BAR 1: assigned [mem 0xeb800000-0xebbfffff]
pci  0000:1d:00.0: BAR 0: assigned [mem 0xeb200000-0xeb21ffff]
pci  0000:1d:00.1: BAR 0: assigned [mem 0xeb220000-0xeb23ffff]
pci  0000:1d:00.0: BAR 3: assigned [mem 0xeb240000-0xeb243fff]
pci  0000:1d:00.0: reg 184: [mem 0xea900000-0xea903fff 64bit pref]
pci  0000:1d:00.0: BAR 7: assigned [mem 0xeb244000-0xeb263fff 64bit pref]
pci  0000:1d:00.0: reg 190: [mem 0xea920000-0xea923fff 64bit pref]
pci  0000:1d:00.0: BAR 10: assigned [mem 0xeb264000-0xeb283fff 64bit pref]
pci  0000:1d:00.1: BAR 3: assigned [mem 0xeb284000-0xeb287fff]
pci  0000:1d:00.1: reg 184: [mem 0xea940000-0xea943fff 64bit pref]
pci  0000:1d:00.1: BAR 7: assigned [mem 0xeb288000-0xeb2a7fff 64bit pref]
pci  0000:1d:00.1: reg 190: [mem 0xea960000-0xea963fff 64bit pref]
pci  0000:1d:00.1: BAR 10: assigned [mem 0xeb2a8000-0xeb2c7fff 64bit pref]
pci  0000:1d:00.0: BAR 2: assigned [io  0x8000-0x801f]
pci  0000:1d:00.1: BAR 2: assigned [io  0x8020-0x803f]
pci  0000:1b:04.0:     pci  bridge to [bus 1d]
pci  0000:1b:04.0:   bridge window [io  0x8000-0x8fff]
pci  0000:1b:04.0:   bridge window [mem 0xeb200000-0xebbfffff]
pci  0000:1a:00.0:     pci  bridge to [bus 1b-1d]
pci  0000:1a:00.0:   bridge window [io  0x7000-0x8fff]
pci  0000:1a:00.0:   bridge window [mem 0xea800000-0xebbfffff]
pci  0000:19:00.0:     pci  bridge to [bus 1a-1d]
pci  0000:19:00.0:   bridge window [io  0x7000-0x8fff]
pci  0000:19:00.0:   bridge window [mem 0xea800000-0xebbfffff]

QUESTION
Is it somehow possible to tell the kernel (e.g. via a parameter) to automatically do this? What is causing this issue in the first place?
Thank you in advance!
Update
As the described fix fails on a 4.x system (actually starting with 3.12 I suppose), I had a look at the kernel and found that if I disable PCI ASPM (which was already disabled by ACPI (t can also be forced by pcie_aspm=off in kernel boot parameter)), the following small fix (on a 4.4.0) resolves a kernel null pointer dereference:
--- a/drivers/pci/pcie/aspm.c
+++ b/drivers/pci/pcie/aspm.c
@@ -552,11 +552,12 @@ static struct pcie_link_state *alloc_pcie_link_state(struct pci_dev *pdev)
 void pcie_aspm_init_link_state(struct pci_dev *pdev)
 {
        struct pcie_link_state *link;
-       int blacklist = !!pcie_aspm_sanity_check(pdev);
-
+       int blacklist;
        if (!aspm_support_enabled)
                return;

+       blacklist = !!pcie_aspm_sanity_check(pdev);
+
        if (pdev->link_state)
                return;

Kind of odd that a sanity check is performed if the feature itself is deactivated, the actual null pointer dereference happend in pcie_aspm_sanity_check in this line list_for_each_entry(child, &pdev->subordinate->devices, bus_list) {. Is this a kernel bug?

A:
Is it somehow possible to tell the kernel (e.g. via a parameter) to automatically do this?

Try booting with pci=realloc we had similar issues hotplugging NVMe drives on ancient motherboards until we passed in that parameter.


text:
Q: Fields not addable to related list I have Item object to which Opportunity Product object has look up. What I wanted is to add related list to Item with all of Opp Products, but I can't add columns for the fields Account or Opportunity, which are standard fields with FLS set as read/write for all, and accessibility is as required. There is antoher standard field, Product, which I can add and I see no difference between them.
So my question is: what requirements does the field need to meet to be addable to related list?

A: To add a field to a related list, it must either:
1. Be on the child object itself
2. Be on a (different)parent record to that child object where the relationship from child to (different) parent is master-detail.
Account is not on the OpportunityProduct object, so you won't see it in the related list. You should see Opportunity, though. If you don't see that as an option, that is surprising, but the relationship between OpportunityProduct and Opportunity on the back-end in Salesforce is not standard. It was the part of the first-ever double master-detail roll-up summary field, allowing OppProd -> Opp -> Account, and as such, the platform dev team had to do a lot of work with it.
I hope this helps somewhat.
For a workaround, put a formula field on Opportunity Product that displays the Opportunity Name, and another that displays the Account Name. Then you can put both on the custom object's Opportunity Products related list.


text:
Q: creative ways of inputting date and time i am working on a small experimental app where part of the form will be users entering date and time.
Apart from the calendars ...are there any creative ways of inputting date and time that you have come across?
maybe have a text field with analog clock on top. when data is inputted in text fields and tabbed out the analog clock would show the time change.

A: I actually think the timpickr plugin for jQuery UI has a novel approach to inputting time data.

A: I personally like the datejs (jquery plugin) style of smart text box.

A: Microsoft Outlook reminder window has a "remind me" field in which you can enter relative times in English free text, such as "1 day before" or "30 minutes from now".
For some things, that's more natural than having to do the math in your head and enter an absolute time or date.

A: How about left click=set long arm - right click=set short arm - shift-click=second hand? :)

A: How about letting the user move the hands of a clock.


text:
Q: JQuery : BoxShadow and Color Change using "OnChange" I'm new to Javascript and JQuery so please be patient. I want to make a box-shadow that changes color when using a color picker. For this I'm using Jscolor.js. It's my understanding that I need to use a Onchange function and use +this.color to select the current color.
However I can't seem to get the code to work, I've tried reading everywhere but there isn't much information on the subject I need. I have created a JsFiddle as a example.
Thank you very much for the help in advance.
CODE:
JAVASCRIPT:
$(document).ready(function(){
    $('#content').css('boxShadow', '+this.color inset 0 200px 400px -200px');
    $('#content').css('boxShadowColor', '+this.color');
});

HTML:

         <input class="color" onchange="$('#content').css('boxShadow','+this.color');" />

 This is a example.

CSS:
.content {
    -webkit-box-shadow: inset 0 200px 400px -200px #000);
    -moz-box-shadow: inset 0 200px 400px -200px #000);
    box-shadow: inset 0 200px 400px -200px #000;
}

A: FIDDLE
HTML

        <input class="color" onchange="addNewBoxShadowStylesToHead('#frontcontent', '#'+this.color);" />

 This is a example.

This div will have the effect

JS
var head = document.head || document.getElementsByTagName('head')[0];

function addNewBoxShadowStylesToHead(selector,color) {
    var css = selector + '{-webkit-box-shadow: inset 0 200px 400px -200px ' +color+ ';' +
        '-moz-box-shadow: inset 0 200px 400px -200px ' + color + ';'+
        'box-shadow: inset 0 200px 400px -200px ' + color + '; }',
        style = document.createElement('style');

    style.type = 'text/css';
    if (style.styleSheet){
        style.styleSheet.cssText = css;
    } else {
        style.appendChild(document.createTextNode(css));
    }

    head.appendChild(style);
}

OR Simpler JS
function applyboxshadow(selector, color) {
    $(selector).css({
         '-webkit-box-shadow' : 'inset 0 200px 400px -200px ' + color,
        '-moz-box-shadow': 'inset 0 200px 400px -200px '+ color,
        'box-shadow': 'inset 0 200px 400px -200px '+ color
    });
}

call it like so
<input class="color" onchange="applyboxshadow('#frontcontent', '#'+this.color);" />


text:
Q: Tcpdump command shows 10 requests per second on SSH When I type "tcpdump" on any VPS server I own I get many requests apparently from my own machine to the SSH port. Is this normal?

A: Tcpdump will output to the terminal. Terminal is created by ssh and anything on it is transferred over ssh between your vps and your client machine. This is basically what you see in tcpdump.
So yes, this is normal.

A: Without seeing the actual tcpdump commandline and filter options:
You're probably accessing your VPS over SSH to run tcpdump...
Each bit of output from the tcpdump command itself will need to be transmitted over SSH to your screen and gets registered by tcpdump (again generating more SSH traffic)
So that is completely expected.


text:
Q: C++ Good practices for a client-server multiplayer game Please note I'm new to both threading and WinSock.
For a college project I have to create a simple multiplayer game writeen in C/C++ using WinSock for communication and WinAPI threads to handle multiple clients (maximum of 4).
The game is pretty straight forward, players move their dots along the board and leave their traces behind. The player who managed to cover the biggest area in a given time, wins the game.
On the client-side application I'm running 2 threads. First one sends information about pressed keys to the server. Second one receives data from the server (coords of all the players) and draws the world.
On the server-side Im running 1 thread for each client to receive his input, then update his coords on server. There is also another thread that does the logic (check for collisions, check if player didn't go off the screen etc.) and constantly sends players coords to all the clients.
Im using blocking sockets on both sides.
I tested the game for 2 players, server and clients were all on different machines in the same network and as it turns out players experience noticable lags and do not move smoothly.
Is my approach totally wrong? What's the best way to create server and client apps for multiplayer game?

A: Sockets normally try to combine multiple small messages into one transmission to improve network efficiency. But this slows down transmission of most messages because they sit in a buffer for a while hoping to get some more data before transmission. This is the "Nagle algorithnm."  You can try turning it off using SetSocketOpt with TCP_NODELAY.  That should reduce latency.
For a few players on a local network you could consider a peer-to-peer communication scheme instead of using a server. Routing everything through a server at least doubles the communication delays.


text:
Q: jQuery Replace value in select depending on other select box I have the following array:
var LWTable = [];
LWTable.push([6,200,200,220]);
LWTable.push([8,220,220,240]);
LWTable.push([10,240,240,260]);
LWTable.push([12,260,260,290]);
LWTable.push([15,290,310,340]);
LWTable.push([18,330,360,400]);
LWTable.push([21,385,420,460]);

And the following html:
<select name="plength" id="plength">
  <option value="6" selected>6 in.</option>
  <option value="8">8 in.</option>
  <option value="10">10 in.</option>
  <option value="12">12 in.</option>
  <option value="15">15 in.</option>
  <option value="18">18 in.</option>
  <option value="21">21 in.</option>
</select>
<select name="pwidth" id="pwidth">
  <option value="Width1" selected>Width 1 (xw1x)</option>
  <option value="Width2">Width 2 (xw2x)</option>
  <option value="Width3">Width 3 (xw3x)</option>
</select>

What I want is, that when I select value 8 for plength, that in the pwidth select box, the xw1x, xw2x and xw3x strings are replaced by the values from the MinLoadTable, so that in this example it would show 220, 220 and 240.
When I pick 21, it will automatically replace that text with 385,420,460.
Is this possible and if so how? I tried to look up some examples, but didn't get anywhere...
Any help or direction would be appreciated!

A: If its possible to change the data structure in the JS code to an object you can make this very striaghtforward. Firstly you can create the plength select options on load from the keys of the object. Then on change of plength you can use the selected value to find the key in the object and populate the options of pwidth. Try this:

var LWTable = {
  '6': [200, 200, 220],
  '8': [220, 220, 240],
  '10': [240, 240, 260],
  '12': [260, 260, 290],
  '15': [290, 310, 340],
  '18': [330, 360, 400],
  '21': [385, 420, 460],
}

var plengthOptions = '';
Object.keys(LWTable).forEach(function(key) {
  plengthOptions += '<option value="' + key + '">' + key + ' in.</option>';
});

$('#plength').append(plengthOptions).change(function() {
  var pwidthOptions = '';
  LWTable[this.value].forEach(function(width, i) {
    pwidthOptions += '<option value="Width' + (i + 1) + '">Width' + (i + 1) + ' (' + width + ')</option>';
  });
  $('#pwidth').html(pwidthOptions);
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="plength" id="plength"></select>
<select name="pwidth" id="pwidth"></select>

A: You could try something like the following:

$(function(){

    var LWTable = [];
    LWTable.push([6,200,200,220]);
    LWTable.push([8,220,220,240]);
    LWTable.push([10,240,240,260]);
    LWTable.push([12,260,260,290]);
    LWTable.push([15,290,310,340]);
    LWTable.push([18,330,360,400]);
    LWTable.push([21,385,420,460]);

    $("#plength").change(function(){
        var ele = $(this)
        var length = ele.val();
        var widths = LWTable.find(function(item){
            return item[0] == length;
        });
        if(widths){
            var $pWidth = $("#pwidth");
            $pWidth.empty();
            $.each(widths.slice(1), function(key,value) {
                var txt = 'Width'+(key+1)+' ('+value+')';
                $pWidth.append($("<option></option>")
                       .attr("value", value)
                       .text(txt));
            });
        }
    });

   $("#plength").trigger("change");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="plength" id="plength">
  <option value="6" selected>6 in.</option>
  <option value="8">8 in.</option>
  <option value="10">10 in.</option>
  <option value="12">12 in.</option>
  <option value="15">15 in.</option>
  <option value="18">18 in.</option>
  <option value="21">21 in.</option>
</select>
<select name="pwidth" id="pwidth">
  <option value="Width1" selected>Width 1 (xw1x)</option>
  <option value="Width2">Width 2 (xw2x)</option>
  <option value="Width3">Width 3 (xw3x)</option>
</select>


text:
Q: Update controls based on edit box change in Inno Setup How can I capture changes in text box value?
I'm researching how to use OnChange event function but i don't know how to use it.
[Code]
var
  Page: TInputQueryWizardPage;

procedure InitializeWizard();
begin
  Page := CreateInputQueryPage(wpWelcome,
    'Personal Information', 'Who are you?',
    'Please specify your name and the company for whom you work, then click Next.');

  Page.Add('Server:', False);
  Page.Add('NAME:', False);
  Page.Add('LOCATION:', False);

  Page.Values[0] := ('test0');
  Page.Values[1] := ('test1');
  Page.Values[2] :=  ('string')+Page.Values[0]+('string')+Page.Values[1];
end;

A: Handle OnChange event like:
var
  Page: TInputQueryWizardPage;

procedure EditChange(Sender: TObject);
begin
  Page.Values[2] := 'string' + Page.Values[0] + 'string' + Page.Values[1];
end;

procedure InitializeWizard();
begin
  Page := CreateInputQueryPage(...);

  Page.Add('Server:', False);
  Page.Add('NAME:', False);
  Page.Add('LOCATION:', False);

  Page.Values[0] := 'test0';
  Page.Values[1] := 'test1';

  Page.Edits[0].OnChange := @EditChange;
  Page.Edits[1].OnChange := @EditChange;
  { Reflect the initial values }
  EditChange(nil);
end;

Note that the Edit[2] can be changed by the user, so maybe you want to set it read only.
  Page.Edits[2].ReadOnly := True;
  Page.Edits[2].Color := clBtnFace;

Or you may actually want to use TLabel instead.


text:
Q: How to save MS Outlook attachments from specific sender and date using Python I am a bit new to coding and I am trying to understand how to get Python to save MS Outlook attachments from a specific sender. I currently receive the same email from the same person each day regarding data that I need to save to a specific folder. Below are the requirements I am trying to meet:

*

*I want to open MS Outlook and search for specific sender

*I want to make sure that the email that I am opening from the specific sender is the most current date

*I want to save all attached files from this sender to a specific folder on my desktop

I have seen some posts on using win32com.client but have not had much luck getting it to work with MS Outlook. I will attach some code I have tried below. I appreciate any feedback!
import win32com.client
outlook=win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox=outlook.GetDefaultFolder(6)
messages=inbox.Items
for message in messages:
    attachments = message.attachments
    for attachment in attachments:
        pass

A: You almost got it, add filter to the sender email address
import win32com.client

Outlook = win32com.client.Dispatch("Outlook.Application")
olNs = Outlook.GetNamespace("MAPI")
Inbox = olNs.GetDefaultFolder(6)

Filter = "[SenderEmailAddress] = '0m3r@email.com'"

Items = Inbox.Items.Restrict(Filter)
Item = Items.GetFirst()

for attachment in Item.Attachments:
    print(attachment.FileName)
    attachment.SaveAsFile(r"C:\path\to\my\folder\Attachment.xlsx")

Python 3.8 on windows

A: def saveAttachments(email:object):
        for attachedFile in email.Attachments: #iterate over the attachments
                try:
                        filename = attachedFile.FileName
                        attachedFile.SaveAsFile("C:\\EmailAttachmentDump\\"+filename) #Filepath must exist already
                except Exception as e:
                        print(e)

for mailItem in inbox.Items:
        #Here you just need to bould your own conditions
        if mailItem.Sender == "x" or mailItem.SenderName == "y":
               saveAttachments(mailItem)

The actual conditions you can change to your liking. I would recommend referring to the Object model for Outlook MailItem objects: https://learn.microsoft.com/en-gb/office/vba/api/outlook.mailitem
Specifically its Properties


text:
Q: Accuracy of comparison of runtime All, I am wondering whether the following will give me an accurate assesment of the runtimes of these functions. I would be confident of the result if I knew whether the replications were done sequentially, but I don't. Thanks.
system.time(replicate(8000,function1(4,5)))
system.time(replicate(8000,function2(4,5)))
system.time(replicate(8000,function3(4,5)))

A: If you check the source code of replicate you will see that is this:
> replicate
function (n, expr, simplify = "array")
sapply(integer(n), eval.parent(substitute(function(...) expr)),
    simplify = simplify)
<bytecode: 0x000000000b3b1ee8>
<environment: namespace:base>

Since it uses sapply in its source code then yes it is sequential as sapply is actually a for-loop written in C. So, yes it is quite an accurate assessment in this respect.
You could also try the microbenchmark package which would calculate even more precisely the running times.


text:
Q: UrlFetchApp Variable Errors I'm trying to make a proxy with the UrlFetchApp Google Scripts API. However, with a query string of ?url="https://google.com", it gives me this error:
Exception: Invalid argument: "https://google.com" (line 3, file "Code")

But when I substitute param in my code below for https://google.com, the exact value of param, it works perfectly fine for some reason.
Here's my code:
function doGet(e) {
 var param = e["parameter"]["url"];
 var response = UrlFetchApp.fetch(param);
 return HtmlService.createHtmlOutput(response);
}

Thank you for any help!

A: How about this modification?
I think that in your Web Apps script, the double quotes are not required.
From:
?url="https://google.com"

To:
?url=https://google.com

or, when the URL encode is used, it becomes as follows.
?url=https%3A%2F%2Fgoogle.com


text:
Q: Scala: Creating Options from Seq/Tuple and add to a Sequence Edit:
Suppose I have a Seq:
Seq(Some("Earth"),Some("Mars"))

I need to add few more elements at start of this sequence. Values to be added are generated based on an Option value.
So I try to do as:
 val o = ....//Option calculated here
 Seq(o.map(myFunction(_)),"Earth","Mars")

 def myFunction(s: String) = s match {
     case "x" => Seq(Some("Jupiter"), Some("Venus"))
     case "y"  => Seq(Some("PLuto"), Some("Mercury"))
 }

But map would give me Some(Seq(.....)).

A: For this kind of problem I recommend checking the Scaladoc and following a technique called type-tetris.
You need this:
def prependIfDefined(data: Option[A], previousElements: Seq[Option[B]]): Seq[Option[B]] =
  data.fold(ifEmpty = Seq.empty[Option[B]])(getNewData) ++ previousElements

def getNewData(a: A): Seq[Option[B]] = ???


text:
Q: How to see view that is too big? If you have an element such as a UITextView that is bigger than the scene it is on, you won't see some of the resizing handles for the UITextView.
Besides dragging the element around and eventually getting it sized correct, is there some way to see the parts of the element that have fallen off the scene?

A: Constrain it to fit the screen using AutoLayout, or put the whole view in a UIScrollView


text:
Q: How to enable google play store app if it has been remove from some country? I am android app developer.
My one app has been removed from google play store in some country reason for alleged trademark infringement. i use name as picart.
So is there any solution for re enable my app in all country?


text:
Q: How to connect ORACLE DB, error The Network Adapter could not establish the connection How to connect ORACLE DB in virtual machine windows 7 with IntelliJ IDEA.I have jdbc7.jar in the libraries and I try that way. Shows me this error :
java.sql.SQLRecoverableException: Error input-output: The Network Adapter could not establish the connection
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:673)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:711)
Caused by: oracle.net.ns.NetException: The Network Adapter could not establish the connection
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:445)
at oracle.net.resolver.AddrResolution.resolveAndExecute(AddrResolution.java:464)
... 12 more
Caused by: java.net.SocketException: Network is unreachable: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
... 17 more

and
Class.forName("oracle.jdbc.driver.OracleDriver");
    String serverName = "000.000.000.000";
    String portNumber = "1521";
    String sid = "abcd";
    String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
    String username = "user";
    String password = "pass";
    Connection conn = DriverManager.getConnection(url, username, password);


text:
Q: How to setup and use yowsup-cli to to get Whatsapp authentication code? I've tried following the same way mentioned everywhere, but something is wrong.
sudo apt-get install python python-dateutil python-argparse
sudo wget https://github.com/tgalal/yowsup/archive/master.zip
sudo unzip master.zip
cd yowsup-master/src
cp config.example yowsup-cli.config
vi yowsup-cli.config #(Write the following according to you)
#cc=34
#phone=34123456789 #(Phone number with country code)
#id=
#password=
chmod +x yowsup-cli
./yowsup-cli --requestcode sms --config yowsup-cli.config
#status: sent
#retry_after: 3605
#length: 6
#method: sms

I have realized that the current archive master.zip is different from the one that I am supposed to find, an update maybe,
(the folder yowsup-master/src doesn't exist)
I tried working with the file yowsup-master/yowsup-cli which seemed to be the configuration file. I followed the same steps on that file but this is what I get:
./yowsup-cli.config --requestcode sms --config yowsup-cli.config
Traceback (most recent call last):
File "./yowsup-cli.config", line 5, in <module>
import sys, argparse, yowsup, logging
ImportError: No module named yowsup

I think maybe there is a new update, has the process changed or something?

A: I don't know where the "everywhere" is from where you got the instructions that you followed, but the yowsup page is pretty explicit on Linux installation:
Install using setup.py to pull all python dependencies

Linux

You need to have installed python headers (from probably python-dev package) and ncurses-dev, then run

sudo python setup.py install

You should not have to download master.zip as root (sudo), nor extract master.zip as root, but you should follow the instructions to run setup.py, otherwise yowsup will not be installed in your dist/site-packages and python cannot import the package. You should have done:
mkdir tmp
cd tmp
wget https://github.com/tgalal/yowsup/archive/master.zip
unzip master.zip
cd yowsup-master
python setup.py install
cd ..

After that you can invoke python:
$ python
>>> import yowsup

without an error.
The setup.py as used by yowsup has several other problems, e.g. installing argparse even if you are running newer than python2.6. argparse has been in the standard library since 2.7, and it is customary to test the python version before adding it to the dependency list (now, if you install using pip27, argparse will be pulled from PyPI although you don't need it).
I am not sure where your instruction got the information about copying a config file, this file is no longer available (but that has nothing to do with the actual error you encountered, and which should be solve by following the instructions).
Please file a complained with the authors of the instructions you posted about their unnecessary and potentially dangerious abuse of sudo

A: Current 'master' branch does not include    /src    , because the developer now working on yowsup2. And many blogposts - as i found - wrote on old yowsup install tutorial. But if you still want your hands dirty with old stuff, you may download the 'legacy' branch at Github.


text: Q: How can i apply primefaces tabview dynamic attribute to individual tabs Is there any way to make certain tabs of tabview in primefaces are dynamic. As of now either all tabs are dynamic or all tabs are static.