text:
Q: Argument labels for initialization parameters in Swift 3.1 Apple's book "The Swift Programming Language (Swift 3.1)" states the following:

As with function and method parameters, initialization parameters can have both a parameter name for use within the initializer's body and an argument label for use when calling the initializer.
However, initializers do not have an identifying function name before their parentheses in the way that functions and methods do. Therefore, the names and types of an initializer's parameters play a particularly important role in identifying which initializer should be called. Because of this, Swift provides an automatic argument label for every parameter in an initializer if you don't provide one.

I don't understand the last sentence, as I didn't notice any difference between functions/methods and initializers when it comes to parameters names/labels. How is the argument label automatically provided for an initializer?

A: The feature being described is this: Given a struct:
struct Point {
    let x: Double
    let y: Double
}

Swift will automatically generate Point.init(x: Double, y: Double). If you add an init method of your own in the main struct definition, then Swift won't create that automatic init. (If you add an init in an extension, then you will get an automatic init. This is why people often add convenience init in an extension for structs.)
The point the last paragraph is trying to make is that Point(x:y:) is preferable to Point(_:_:). The labels in an initializer are even more valuable than labels in method names, because all initializers have the same "base" name ("init"). They're just explaining why they didn't choose a more implicit default that some people might expect coming from other languages.
In short, sometimes unlabeled parameters make sense in methods depending on what the name of the method is and how unambiguous that makes the first parameter. But in init, unlabeled parameters should be eyed with strong suspicion.


text:
Q: Should the forward lookup zone target host FQDN be my application or web front end server? As the title suggests, when creating the forward lookup zone for hosting SharePoint Apps (Add-ins) should the target host be the FQDN of my application server or my web front end server?
My current farm has the following servers:

*

*SPA1 - Hosts Central Admin, UPSA etc... (spa1.example.com)

*SPW1 - Web front end server (spw1.example.com)

*SPDB1 - Sql Server

A: The target host should be those that serve your content web applications to the end users.
This would usually be the web front end server in a farm with only a single web front end, or the NLB address if using multiple web front end servers.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Инверсия чисел? В одном учебнике встретил такой термин:
Существует старый трюк с использованием побитового оператора НЕ — ~. Он преобразует число в 32-разрядное целое со знаком (signed 32-bit integer). Дробная часть, в случае, если она присутствует, отбрасывается. Затем все биты числа инвертируются.

*

*Можно объяснить на простом языке, что значит "Затем все биты числа
инвертируются"?

alert( ~2 );
alert( ~1 );
alert( ~0 );
alert( ~-1 );

A: Инверсия чисел - это побитовая операция, которая по сути делает вот что:
~a = -(a + 1).
Её часто используют в условиях вхождения подстроки в строку, так как если это вхождение не найдено, то indexOf вернет -1
Вот пример применения, но это не лучщий пример для повторения, так как код станет сложнее понимать
Пример:

let index = 'test'.indexOf('y'); //index = -1
if(~index)
   alert('Есть');
else
  alert('Нет');

A: Бит 0 заменяется на 1, а 1 на 0: 0010 → 1101.


text:
Q: Difference between = and := I wanted to know the difference between two operators:
=  and  :=
I couldn't find the ":=" operator on the list at https://reference.wolfram.com/language/tutorial/Operators.html
Can someone help?
Thanks.

A: You need to understand the difference of "Set" and "Set Delay" :
Let's make an example which illustrates this clearly.
I have a function:
f[x1_,x2_]:= x1+x1*x2

and I want to find it's derivative according to x2 at specific locations of x1 and x2.
m[x1_,x2_] = D[f[x1,x2],x2]

*

*If you use use ":" before the "=", (Set Delay), it evaluates the function when it is needed, hence it will evaluate the function only when values for x1 and x2 are given.

*The function definition without ":" before the "=" (Set) evaluates the function before it is used and the output is assigned to m[x1_,x2_], so if you input values in m[x1_,x2_] they are put into the already-differentiated equation.
If now, you would decide to put a ":" in front of the "=" for m[x1_,m2_],it will not work, since one cannot differentiate a function with respect to a numerical value (5 for example).
I hope that this helps you.
P.S. I encountered the same question once:
How To First Evaluate A Differential Equation And Then To Input The Function Parameters?


text:
Q: python API coding for tidal music Hi currently a student working on a project for school.
I'm looking to use a music API to work with, and have found TidalAPI. However, my code can't seem to run.
Below is my code:
import tidalapi

def logindetails():
    username = input("What is your Tidal username? ")
    password = input("What is your Tidal password? ")
    session = tidalapi.Session()
    session.login(username, password)

def gettingalbum():
    logindetails()
    album_id = input("What is the album ID? ")

    tracks = session.get_album_tracks(album_id)
    print("Tracks in this album are:")
    x = 0
    for track in tracks:
        x = x+1
        print(x,track.name)

gettingalbum()

NameError: name 'session' is not defined for session.get_album_tracks(album_id)
how can I link my first module with the second?
(It works if I combine both codes into one module, but I have to split them into 2 modules)

A: I'd suggest making logindetails() return the logged-in session you can then pass into other functions. (The other option would be to make it a global variable.)
I also took the liberty of adding the use of  enumerate() for printing the track indexes.
import tidalapi

def logindetails():
    """
    Ask for login details and return a logged-in session.
    """
    username = input("What is your Tidal username? ")
    password = input("What is your Tidal password? ")
    session = tidalapi.Session()
    session.login(username, password)
    return session

def gettingalbum(session):
    album_id = input("What is the album ID? ")

    tracks = session.get_album_tracks(album_id)
    print("Tracks in this album are:")
    for x, track in enumerate(tracks, 1):
        print(x, track.name)

session = logindetails()
gettingalbum(session)


text:
Q: Creating a nav bar from scratch, but having issues with floating links to the right and the alignment I am trying to create a homemade nav bar for a website and want my name to appear to the far left and have the links float to the far right. I used CSS to format everything under Nav, but when I use float for the links, it is out of alignment and they appear backwards from how I typed the html for them.
I know I have a major problem with how I'm using CSS, but looking for some insight or maybe a better practice.
I'm avoiding bootstrap or anything predefined so I can get some practice and hardcode it from the ground up.

nav {
  border-bottom: 1px solid rgb(196, 196, 196);
  background-color: #F7F9F9;
  padding: 10px;
  width: 100%;
}

.navbar a {
  float: right;
  text-decoration: none;
}

Rick Wilson

      Experience
      Projects
      Technology Stack
      Contact

A: You could use the new way of aligning: grid.
AND
Let me explain, with grid you can align two div so that you do not have to depend on aligno float.
To achieve this you have to generate two divs: one for the logo and one for the links.
Then you declare at the beginning: display: grid to use this property and in turn the logo div is positioned as first ( grid-column: 1 / 2) and in the links as the second (grid- column: 2 / 2).
One of the advantages of using a grid is that it is partly responsive.
More info

*

*W3School

*Complete-guide-grid

    .navbar {
        display: inline-grid;
        grid-template: 20% 30%;
        background-color: #F7F9F9;
        border-bottom: 1px solid #c4c4c4;
        padding: 10px;
        width: 100%;
    }
    .logo {
        grid-column: 1/2;
        background-color: #F7F9F9;
    }
    .links {
        grid-column: 2/2;
    }
    .links a {
        text-decoration: none;
    }

Rick Wilson

        Experience
        Projects
        Technology Stack
        Contact

A: As noted in the comments, flexbox is a nice way to handle things like this. In this case, you can wrap your links in another div and then use justify-content: space-between. For example:

nav {
  background-color: #F7F9F9;
  border-bottom: 1px solid rgb(196, 196, 196);
  padding: 10px;
  width: 100%;
}

.navbar {
  display: flex;
  justify-content: space-between;
}

.navbar a {
  text-decoration: none;
}

Rick Wilson

        Experience
        Projects
        Technology Stack
        Contact

A: div tags are going to be block elements unless specified otherwise. For a nav bar, you could use something like an h1 tag. Adding "display: inline" to the h1 tag will align everything to look in a line.
Another tip: to add spacing between your links ("a" tags), you can add padding-left. See below (padding-left: 10px;)

nav {
  border-bottom: 1px solid rgb(196, 196, 196);
  background-color: #F7F9F9;
  padding: 10px;
  width: 100%;
}

.navbar h1{
  display: inline;
}

.navbar a {
  float: right;
  text-decoration: none;
  padding-left: 10px;
}

Rick Wilson

      Experience
      Projects
      Technology Stack
      Contact

A: You HTML is a little off in terms of semantics. I'd do something like:

Rick Wilson

Experience

Projects

Technology Stack

Contact

CSS Grid would be ideal for this, but if you can't because of browser requirements, Flexbox would be the way to go:
header {
   display: flex;
   align-items: center;
   justify-content: space-between;
   padding: 10px 20px;
   border-bottom: 1px solid #ccc;
   background-color: #F7F9F9;

   ul {
      margin: 0;
      padding: 0;
      list-style-type: none;
      display: flex;
   }

   li {
      margin-left: 1.5em;
   }

   a {
      text-decoration: none;
   }
}

https://codepen.io/md/pen/LqQeLE


text:
Q: Is there a way to know how many spirits are left in Adventure Mode? I just completed light world and unlocked dark world, and I would like to clean up light world before I enter dark world.
How do I know how many spirits are left to find in Adventure Mode and how can I find them quickly? Is there some counter of sorts? Does the game tell me if I have completed the entire map?

A: For the overworld, there's no real way to see which spirits you still need besides using the right thumbstick to browse around the map.
For dungeons however, indicated by the swirling icon on the minimaps (key: L), you'll know when all the spirits are gone when you see a star icon appear next to the dungeon icon.


text:
Q: Populating a data frame with corresponding values from another I have a data frame containing values read in from an experiment with independent variables A and B which doesn't cover all possible permutations of A and B. I need to create a data frame which does contain all permutations, with zeros in those places where that particular pair of values isn't present in the data.
To create some sample data,
interactions <- unique(data.frame(A = sample(1:5, 10, replace=TRUE),
                                  B = sample(1:5, 10, replace=TRUE)))
interactions <- interactions[interactions$A < interactions$B, ]
interactions$val <- runif(nrow(interactions))

possible.interactions <- data.frame(t(combn(1:5, 2)))
names(possible.interactions) <- c('A', 'B')

which creates
interactions
A B       val
1 5 0.6881106
1 2 0.5286560
2 4 0.5026426

and
possible.interactions
A B
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5

and I want to output
A B  val
1 2  NA
1 3  0.5286560
1 4  NA
1 5  0.6881106
2 3  NA
2 4  0.5026426
2 5  NA
3 4  NA
3 5  NA
4 5  NA

What is the fastest way to do this?

A: Here is a base solution that is much faster (~10x) than merge:
possible.interactions$val <- interactions$val[
  match(
    do.call(paste, possible.interactions),
    do.call(paste, interactions[1:2])
) ]

This produces (note, different to what you expect b/c you didn't set seed):
#    A B        val
# 1  1 2 0.59809242
# 2  1 3 0.92861520
# 3  1 4 0.64279549
# 4  1 5         NA
# 5  2 3 0.03554058
# 6  2 4         NA
# 7  2 5         NA
# 8  3 4         NA
# 9  3 5         NA
# 10 4 5         NA

This assumes A & B do not contain spaces and that interactions has no duplicate A-B pairs (will always match to first).
And the data.table version:
possible.DT <- data.table(possible.interactions)
DT <- data.table(interactions, key=c("A", "B"))
DT[possible.DT]

Though this is only worthwhile if your tables are large or you have uses for other benefits of data.table.  I've found speed to be comparable to match in simple cases if you include the overhead of creating and keying the tables.  I'm sure there are cases where data.table is much faster, especially if you key once and then use that key a lot.
For completeness, here is the merge version:
merge(possible.interactions, interactions, all.x=T)

A: If order is important to you, I recommend using join from the plyr package. As opposed to merge which does not provide an intuitive ordering when there are unmatched elements.
library(plyr)
join(interactions,possible.interactions,type="right")

Joining by: A, B
   A B         val
1  1 2          NA
2  1 3          NA
3  1 4 0.007602083
4  1 5 0.853415110
5  2 3          NA
6  2 4 0.321098658
7  2 5          NA
8  3 4          NA
9  3 5          NA
10 4 5          NA


text:
Q: Plotly: changing axis range in surface subplots I have the following minimal reproducible example and can't find how to change the z-axis range for the subplots
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import numpy as np

main_fig = make_subplots(
rows= 4,
cols= 4,
specs = [[{'type': 'surface'} for k in range(4)] for j in range(4)],
horizontal_spacing = 0.05,
vertical_spacing=0.05)

axis = np.arange(50)
for k, spec in enumerate(range(16)):
    fig = go.Surface(x=axis, y=axis, z=axis[:,None] * axis[None,:], showscale=False)
    main_fig.append_trace(fig, row = k//4 + 1, col = k%4 + 1)

main_fig.update_traces(showlegend=False)
main_fig.update_layout(height=800, width=800)

I tried with variations of fig.update_layout inside the loop, so far without luck.

A: To adjust the 3D axes, adjust the xyz axis in the section called scene, respectively. Please refer to the reference for examples. I set all z-axes manually, but I am sure there are more efficient codes.
main_fig.update_layout(
    scene=dict(zaxis=dict(nticks=4, range=[0,1000])),
    scene1=dict(zaxis=dict(nticks=4, range=[0,1000])),
    scene2=dict(zaxis=dict(nticks=4, range=[0,1000])),
    scene3=dict(zaxis=dict(nticks=4, range=[0,1000])),
    scene4=dict(zaxis=dict(nticks=4, range=[0,1000])),
    scene5=dict(zaxis=dict(nticks=4, range=[0,1000])),
    scene6=dict(zaxis=dict(nticks=4, range=[0,1000])),
    scene7=dict(zaxis=dict(nticks=4, range=[0,1000])),
    scene8=dict(zaxis=dict(nticks=4, range=[0,1000])),
    scene9=dict(zaxis=dict(nticks=4, range=[0,1000])),
    scene10=dict(zaxis=dict(nticks=4, range=[0,1000])),
    scene11=dict(zaxis=dict(nticks=4, range=[0,1000])),
    scene12=dict(zaxis=dict(nticks=4, range=[0,1000])),
    scene13=dict(zaxis=dict(nticks=4, range=[0,1000])),
    scene14=dict(zaxis=dict(nticks=4, range=[0,1000])),
    scene15=dict(zaxis=dict(nticks=4, range=[0,1000])),
    scene16=dict(zaxis=dict(nticks=4, range=[0,1000]))
)

A: The short solution to set some attributes of each scene is as follows:
main_fig.update_scenes(zaxis=dict(nticks=4, range=[0,1000]))

Now print(main_fig.layout) to inspect the scenes new settings.


text:
Q: how can i print a string only once? Need to print Unterschiede gefunden: only once
while(sc.hasNextLine() || sc1.hasNextLine()) {
        i++;

        try {
            text1 = sc.nextLine();``
            text2 = sc1.nextLine();
        if(!text1.equals(text2)){

            System.out.println("Unterschiede gefunden:");
            System.out.printf("Zeile %d :\n",i);
            System.out.println(text1);
            System.out.println(text2);
        }
        }catch(NoSuchElementException nse) {
            text2 = " ";
        }
    }

A: Detecting if one text file differs from another. Once you have detected that one file line is different than the other file line then inform the User (as you are doing) and break out of the while loop from within your IF code  block so as to stop processing files lines, for example:
if(!text1.equals(text2)){
    System.out.println("Unterschiede gefunden:"); // Difference Detected!
    System.out.println("Zeile " + i + ":\n");     // At file line #.
    System.out.println("File A: " + text1);       // Text line in File A.
    System.out.println("File B: " + text2);       // Text line in File B.
    break;                                        // Break out of the WHILE loop.
}

You have also taken into consideration the fact that File A could contain more or less lines than File B which is good but you should really exit the while loop at this time as well since you now are certain that File A is different from File B, for example:
// These two variables are used to see which file
// contains more of fewer lines.
int fileACount = 0;
int fileBCount = 0;

// Read the two files...
while (sc.hasNextLine() || sc1.hasNextLine()) {
    try {
        String fileAText = sc.nextLine();
        fileACount++;
        String fileBText = sc1.nextLine();
        fileBCount++;
        if (!fileAText.equals(fileBText)) {
            System.out.println("Unterschiede gefunden:");
            System.out.printf("Zeile %d :\n", fileACount);
            System.out.println(fileAText);
            System.out.println(fileBText);
            break;
        }
    }
    catch (NoSuchElementException nse) {
        // Using a Ternary Operator below so as to
        // indicate which file contains more lines.
        String fileWithMoreLines = fileACount > fileBCount ? "A" : "B";
        System.out.println("Files are different! File " +
                fileWithMoreLines + " contains MORE Lines.");
        break;
    }
}

Don't forget to close your files.


text:
Q: After Mar-Vell was murdered, how come the Tesseract got transported back to her secret laboratory? I believe that when Yon-Rogg attempted to kill Danvers, she responded immediately by shooting right at the heart of the light speed engine where the Tesseract was located. The sudden explosion then unleashed a massive outburst of Tesseract energy which was absorbed by Danvers into her genetic code leaving her with newly gained cosmic powers. Then Minn-Erva intercepted and informed Rogg that the energy core has been destroyed. Then they took Danvers to Hala.
I think at that time,  the Tessaract which is indestructible was somewhere on Earth where those incident took place. And in the later scenes I wonder how the tesseract got spotted in Mar-Vell's laboratory instead of being at the same place where Mar-Vell was murdered. How come the Tessaract got to Mar-Vell's lab? Who took it there? How was it transported?

A: The core, or Tesseract, was never in the ship that was shot down by Yon-Rogg and later blown up by Carol.  Rather, the ship used an engine that was developed using the Tesseract as its power source. This is made a bit clearer later on when talking to Talos:

Talos: She wanted you to help us find the core.
Carol: Well, I already destroyed it.
Talos: No, you destroyed the engine. The core that powered it is in a remote location. If you help us decode those coordinates, we can find it.
Captain Marvel


text:
Q: Visual studio 2019 is getting 'access denied' on restoring packages on mac Im trying to restore solution packages in visual studio 2019 on my mac and i get 'access denied' on some folders. This error doesn't seem to have any pattern as some packages are actually restored in the same folder!
I have tried to run the app as sudo through the terminal and i still get the same error
Installing Microsoft.EntityFrameworkCore.InMemory 3.1.6.
Acquiring lock for the installation of System.Text.Encodings.Web 4.7.0
Acquired lock for the installation of System.Text.Encodings.Web 4.7.0
Installing System.Text.Encodings.Web 4.7.0.
Access to the path '/Users/georgemukwewa/.nuget/packages/system.runtime.compilerservices.unsafe/4.3.0' is denied.

Can someone help me with this please!!


text:
Q: How do you set the style for multiple Separators in JavaFX using css? I have a layout where I have five horizontal Separators. I want them to all have the same default style but with the option to change any one of them at a later date.
The default style I want is a solid single pixel height black line.
I don't have a custom class for the Separators so I don't think a style class is appropriate. Therefore I thought that ids might be the better idea. So I have something like this:
Separator topSeparator = new Separator();
topSeparator.setId("top-separator");
Separator middleSeparator = new Separator();
middleSeparator.setId("middle-separator");
etc...

and then in my css this:
#top-separator .line{
-fx-border-color: black;
-fx-border-width: 1 0 0 0;
}
#middle-separator .line{
-fx-border-color: black;
-fx-border-width: 1 0 0 0;
}
etc...

Is this the best way of specifying a single pixel solid black line?
Is using ids appropriate over style classes, and if so, is there anyway I can specify a parent style so that I don't have to repeat the -fx-border-color: black; and -fx-border-width: 1 0 0 0; five times?

A:
Is this the best way of specifying a single pixel solid black line?

This is a perfectly good way to do it, assuming it gives you what you need.

Is using ids appropriate over style classes, and if so, is there
  anyway I can specify a parent style so that I don't have to repeat

Ids should be unique, whereas multiple Nodes can share the same class. Use ids if there is a specific style you want for one particular Node and classes if there is (or perhaps could be) a collection of Nodes that should be styled the same way.
You can use both techniques together, if you need:
Separator topSeparator = new Separator();
topSeparator.setId("top-separator");
topSeparator.getStyleClass().add("my-separator");
Separator middleSeparator = new Separator();
middleSeparator.setId("middle-separator");
middleSeparator.getStyleClass().add("my-separator");

and then:
.my-separator .line {
  -fx-border-color: black ;
  -fx-border-width: 1 0 0 0 ;
}

#top-separator .line {
  /* rules specific to top separator */
}

#middle-separator .line {
  /* rules specific to middle separator */
}
/* etc ... */


text:
Q: Javascript image change causes embeded UserControls to flicker I have a n html page being displayed in IE.  It has some buttons made up of images with mouseover/mouseout events on them in JavaScript, and a bunch of embedded .Net UserControls.
When the mouseover/mouseout events fire, I change the images src to something else (simple rollover effect).  The problem is that the UserControls often (but not always) flicker when this happens.
To be clear, the images don't flicker, and the rest of the page doesn't flicker, just the embedded controls.  This page is local, not coming from a server or anything.
So, any ideas?
More information : I've noticed that highlighting text does it too...

A: If you didn't preload the images, you could see this kind of problem.
To preload the images, just add a special div with the wanted urls.

In your css:
#preload { display:none; }

That's it !


text:
Q: Operator overloading?  MyClass & operator=(const MyClass &rhs);

What is the meaning of "&"? Why not is My Class instead of MyClass & ?

A: The & simply means that the return value of operator = is a reference.
This has nothing to do with operator overloading.  It's the same syntax with a normal function definition:
MyClass& foo()
{
  return *this; // returns a reference to MyClass instance
}

MyClass foo()
{
  return *this; // returns a copy of MyClass instance
}

A: returning MyClass& is just to make operator '=' work in chain.
Returning MyClass& or something different doesn't add any effect in overloading '='.
Returing MyClass& helps us use '=' similar the way we use it on built-in data types.
eg.
int x = y = z = 123;

For similar discussion, refer Thinking in C++, (Discussion on iostreams).


text:
Q: MDP concerning two states systems
A system can take only two states 1 and 2. We wish to compare two decisions D1 and D2 causing transitions between these two states. Each of these decisions entails given costs (in €) in the following table:

In the long term what is the best decision?
Here is my work:
I deduced the following transition matrices:
T1 = [0.22 0.78; 0.78 0.22]
T2 = [0.78 0.22 ;0.22 0.78]
Since T1 and T2 are ergodic, they admit respectively unique fixed points Q1o [1/2 1/2; 1/2 1/2] and Q2o [1/2 1/2; 1/2 1/2].
Can we deduce that D2 is more expensive knowing that both systems have the same chance of having status 1 or 2 and that the respective sums of costs are 25 and 27?
Thanks!

A: It sounds like you have a reward / cost structure and decisions (i.e. actions)associated with your system. A Markov Chain would not be sufficient to explicate this. You can achieve this by modelling it as a Markov Decision Process.
In a nutshell, A Markov Decision Process (MDP) model contains:

*

*A set of possible world states S

*A set of possible actions A

*A real valued reward function R(s,a)

*A description T of each action's effects in each state.

For an intro, take a look at Wikipedia and here.


text:
Q: Selenium Python not locating element I have a Selenium python code that I am running on an internal Dynamic CRM website to download data.
For the most part the code works until the last step where it does not locate the element "Export Data". Export Data comes up in a new ribbon on the toolbar triggered by our previous step. Below is the code and HTML.
Also attached the HTML portion of the Export. What am I doing wrong?
Please help and let me know if you need more information
Screen 1 CRM shows the Results button when clicked takes us to Screen 2 that is a new tab on the toolbar:

Screen 2 with the new tab on toolbar

HTML code of Export

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import time
from bs4 import BeautifulSoup
import requests
import pandas as pd
import os
from pathlib import Path
import shutil

#--| Chrome Setup
options = webdriver.ChromeOptions()
# options.add_argument("--headless")
options.add_argument('--disable-gpu')
options.add_argument('--log-level=3')
prefs={"download.default_directory":r"

#Setup Chrome preferences
options.add_experimental_option("prefs",prefs)
browser = webdriver.Chrome(chrome_options=options)

#Direct Link to NGL Five year Forecast Data Only
browser.get('<URL>')
browser.maximize_window()

# Store current window position
window_before = browser.window_handles[0]

wait = WebDriverWait(browser, 30)

#Key in Email
web_loginscreen = wait.until(EC.element_to_be_clickable((By.ID, 'i0116')))
web_loginscreen.send_keys("<UserName>")

# Next Button
web_loginbutton = browser.find_element_by_xpath('//*[@id="idSIButton9"]')
web_loginbutton.click()

window_before_title = browser.title
print(window_before_title)
#Filter button
web_filter = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="advancedFindLauncher"]/button/span/span')))
web_filter.click()

#browse to newly opened download window
browser.switch_to.window(browser.window_handles[1])
window_after = browser.window_handles[1]
window_after_title = browser.title
print(window_after_title)

# Select Agreements
time.sleep(5)

# locate all elements

frame = browser.find_element_by_xpath('//*[@id="contentIFrame0"]')
browser.switch_to.frame(frame)
#

dropdown = browser.find_element_by_xpath('//*[@id="slctPrimaryEntity"]')
dropdown.click()

agreements = browser.find_element_by_xpath('//*[@id="slctPrimaryEntity"]/option[35]')
agreements.click()
# print(dropdown.text)

# Go back out of iframe to default content
browser.switch_to.default_content()
# Look For Results
web_results = browser.find_element_by_xpath('//*[@id="apttusps.ApplicationRibbon.{!EntityLogicalName}.Button2.Button-Large"]')
web_results.click()

# ribbonframe = browser.find_element_by_id('apttus_apts_agreement|NoRelationship|SubGridStandard|Mscrm.SubGrid.apttus_apts_agreement.MainTab.ExportData')

# # browser.find_element_by_class_name('ms-cui-tabContainer ms-cui-tabContainer-lb')
# ribbonframe.click()

# browser.switch_to.frame(ribbonframe)

# Export to Excel
web_results_excel = browser.find_element_by_xpath('//*[@id="apttus_apts_agreement|NoRelationship|SubGridStandard|Mscrm.SubGrid.apttus_apts_agreement.ExportToExcel-Large"]')
# find_element_by_xpath('//*[@id="apttus_apts_agreement|NoRelationship|SubGridStandard|Mscrm.SubGrid.apttus_apts_agreement.ExportToExcel-Large"]')
web_results_excel.click()

time.sleep(15) #seconds
browser.close()
browser.quit()

A: You may just need a wait in your code for the element:
    web_results = browser.find_element_by_xpath('//*[@id="apttusps.ApplicationRibbon.{!EntityLogicalName}.Button2.Button-Large"]')
web_results.click()

    element = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, "apttus_apts_agreement|NoRelationship|SubGridStandard|Mscrm.SubGrid.apttus_apts_agreement.MainTab.ExportData"))
)

# ribbonframe = browser.find_element_by_id('apttus_apts_agreement|NoRelationship|SubGridStandard|Mscrm.SubGrid.apttus_apts_agreement.MainTab.ExportData')

A: UPDATE:
I was able to resolve the error by removing below line so the program just clicks on the static sheet.
Appreciate your help!
Export to Excel
web_results_excel = browser.find_element_by_xpath('//*[@id="apttus_apts_agreement|NoRelationship|SubGridStandard|Mscrm.SubGrid.apttus_apts_agreement.ExportToExcel-Large"]/a[2]')
web_results_excel.click()
Final Code

# Go back out of iframe to default content
browser.switch_to.default_content()
# Look For Results
time.sleep(5)
web_results = browser.find_element_by_xpath('//*[@id="apttusps.ApplicationRibbon.{!EntityLogicalName}.Button2.Button-Large"]')
web_results.click()

time.sleep(5)

# time.sleep(3)
web_results_staticsheet = browser.find_element_by_class_name('ms-cui-ctl-a1Internal')

# browser.find_element_by_class_name('ms-cui-ctl-a2 ')
web_results_staticsheet.click()

time.sleep(100) #seconds
browser.close()
browser.quit()


text:
Q: Checking network connection using vba Is there any way to check NEtwork connection in vba?
I am using this command:
If Dir("O:\") = "" Then
    MsgBox "you have network connection"
Else
    MsgBox "No Connection"
End If

but it doesnt work and I am getting a run time error

A: What you are doing is almost correct except flip the if and else parts,
i.e. when Dir("O:\") = ""  = You are not connected
and when it returns something means you have a connection.
The Dir function is used to return the first filename from a specified directory, and list of attributes.
Sub Test_Connection()

 If (Len(Dir("O:\"))) Then
  MsgBox "Connected"
 Else
  MsgBox "No Connection"
 End If

End Sub

A: This is similar to St3ve's answer, but in function form that returns True if the drive is connected, and False if not.
Function TestNetwork() As Boolean
On Error Resume Next 'ignore errors

If Len(Dir("O:\", vbDirectory)) = 0 Then
    TestNetwork = False
Else
    TestNetwork = True
End If

On Error GoTo 0 'reset error handling
End Function

I found that the Len(Dir("O:\")) method works for external drives, like a flash disk, but didn't work for a mapped network drive. The function works around this with On Error Resume Next, so if O:\ is a disconnected mapped drive, the system hides the Error 52 and goes to the TestNetwork = False line.
Call the function in your code like this:
If TestNetwork() = True Then
    'Code if connected
Else
    'Code if not connected
End If

You can generalize this code to test different directories by naming the function Function TestNetwork(DirAddress As String) As Boolean and replace "O:\" with DirAddress. Then use TestNetwork("O:\"), or any other directory address in quotes when you call it.

A: I tested the solution from this link in Access 2007 VBA.
http://www.vbaexpress.com/forum/showthread.php?42466-Pinging-IP-addresses-in-Access-2007
It works as a function call that can be used anywhere in your VBA code to detect the availibility of a network resource by name or IP and reuturn a boolean value as the result.

A: I don't know if your problem is solved. Anyway I had a similar issue using Excel VBA.
Having a diskstation on my network, I mapped a shared folder of this station as a network folder in Windows, using letter M. Generally, after starting my Windows, and of course diskstation is up and running, the network drive shows in Windows Explorer, but it has a red cross (not connected) instead of the icon with some green color (connected). Only after I manually click this network location in Explorer it becomes green. I first expected the connection could also be established via my Excel VBA programs, when issuing the first time a statement like Dir("M:\abc"). However there is no result, and the icon remains red. I always needed first to click manually in Explorer.
Finally I found a solution in VBA, using prior to the Dir a dummy "shellexecute ... explore M: ...", making the network drive automatically connected.
Declare Function ShellExecute Lib "shell32.dll" Alias _
  "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation _
  As String, ByVal lpFile As String, ByVal lpParameters _
  As String, ByVal lpDirectory As String, ByVal nShowCmd _
  As Long) As Long
'...
Dim RetVal As Long
Dim hwnd As Long
RetVal = ShellExecute (hwnd, "explore", "M:", vbNullString, vbNullString, SW_SHOWNOACTIVATE)
'...
a = Dir("M:\abc")

A: I know this is a very old question and that my answer is not super clean (cause it uses a label), but I find it really simple and reliable.
Instead of using  DLL files I just wanted to let the code run past the 52 runtime error, so I used a 'on error goto' and a label.
This way if the folder is not available, you don't get the error message (which was unacceptable for me, since I needed others to use the macros comfortably), the code just falls into the IF statement, where I thought it would go if the len function returned a 0.
On Error GoTo len_didnt_work 'this on error handler allow you to get past the 52 runtime error and treat the situation the way you want, I decided to go with a msgbox and to stop the whole sub

If Len(Dir("O:\Test\**", vbDirectory)) = 0 Then 'this is the test others have proposed, which works great as long as the folder _is_ available. If it is not I'd always just get the 52 runtime error
len_didnt_work: 'this is the label I decided to use to move forward in the code without the runtime 52 error, but it is placed inside the IF statement, it just aids it to work 'properly' (as I'd expect it to)
    MsgBox "Sorry, your folder is not available",vbcritical 'msgbox to notify the user
    On Error GoTo 0 'reset error handling
    Exit Sub 'end sub, since I wanted to use files from my "O:\Test\" folder
End If
On Error GoTo 0`'reset error handling in case the folder _was_ available

A: I want to give an another spin on this as it is the issue.
I use Scripting.FileSystemObject!
The will check is a folder exist and do not require an error handling.
It works with network drive mapped and network folder.
Just will not detect if a network computer is their for example :"\server"
But "\server\folder" or "Y:" is working.
Dim Serverfolder As String
Serverfolder = "O:\"
Dim fdObj As Object
Set fdObj = CreateObject("Scripting.FileSystemObject")
If fdObj.FolderExists(Serverfolder) = False Then '= False is not needed!
'folder do not exists
else
'Folder exists
End if


text:
Q: Amazon AWS SES SNS integration for different aws accounts I have two aws accounts, "A" and "B". I want to use SES from account "A" and publish the bounces on SNS of account "B".
On account B, I created a topic with name test1234. The arn of the topic is "arn:aws:sns:us-west-2:123456789:test1234". Then I used aws cli to grant permission to account A like this:
aws sns add-permission --topic-arn arn:aws:sns:us-west-2:123456789:test1234 --label 0987654321 --aws-account-id 0987654321 --action-name Publish

After this, I go to ses of account A and in Notification tab I put the arn above but I get an error which is:

SNS topic arn:aws:sns:us-west-2:123456789:test1234 is invalid.
  (Service: AmazonSimpleEmailService; Status Code: 400; Error Code:
  InvalidParameterValue; Request ID:
  635fa1f9-a0d8-11e5-ba0a-57f0be7a91f1)

A: the problem is that when you add a permission it does not update the __default_policy_ID Condition of the topic to allow new account id


text:
Q: Changing colour of toolbar in window in Mac using Swift code There is a requirement to change the colour of the tool bar item to red in colour for the NSWindow.
Any suggestion to do so. We use Swift code.

A: In order to change the background color of the toolbar do the following:
self.toolbar.isTranslucent = false

self.toolbar.barTintColor = UIColor.red


text:
Q: I have some question about fiber in windows I want to know about fiber that window provides.
Let's assume I created 4 fibers.
------------thread-----------------
fiber1 - fiber2 - fiber3 - fiber4
   ^
Fiber 1 now thread execute.

*

*One thread can run only one fiber at the same time. It's right?

*If a thread terminates fiber1, then another all fibers are terminated too?

*I know fiber is Non-preemptive. Then if I want to switch fiber1 to fiber2, there is no way but call SwitchToFiber in fiber1?

*If I call SwitchToFiber in fiber1 during executing some task, then fiber1 sleep immediately? or sleep after complete its task?

*There is no shared space in fiber1 to fiber4?

*And there is no shared space, then there is no need to lock in fiber. it's right?
I read MSDN documents, but I can't understand something. So I ask here.

A: SwitchToFiber is like longjmp, and CreateFiber is like an extended version of setjmp that allocates extra stack space. DeleteFiber is like a free of the context block allocated by setjmp. And most importantly, givers do nothing by themselves, and longjmp is like an extended version of C's goto, e.g. similar to gcc's "computed goto" extension, except that it can switch stack as it jumps. You could easily emulate fibers (non-portably) with setjmp, longjmp and some alloca.


text:
Q: Tried multiple solutions onsite, none worked: Play  on Konami code This is my first question on Stack Overflow! :D
There appear to be multiple similar questions, but I have tried each solution and none of them are working, and yet I'm determined to get to the bottom of this. The goal is to play audio upon successful konami code entry.
The simplest attempt is as follows (the scripts are found within the head, and the audio within the body. I have tried each solution with and without encapsulating them within a window.onload=function(){ } ):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://konami-js.googlecode.com/svn/trunk/konami.js"></script>

<script type="text/javascript">
  konami = new Konami(function() {
    document.getElementById('audio').play();
  });
</script>

<audio id="audio">
  <source src="js/ZipZipper.ogg" type="audio/ogg">
    <source src="js/ZipZipper.mp3" type="audio/mpeg">
</audio>

Another attempt looked like this:
var konami = new Konami(function() {
  var audioElement = document.createElement('audio');
  audioElement.setAttribute('src', 'js/ZipZipper.ogg');
  audioElement.load();
  audioElement.addEventListener("load", function() {
    audioElement.play();
  }, true);
});

And another, like so, again using the html audio tag
        konami = new Konami(playsong);
        playsong = function play() {
          var audio = document.getElementById("audio");
          audio.play();
        }

I am at a loss as to why nothing works. Everything seems to be in place!

A: According to the docs, you can do it like this:
konami = new Konami();
konami.code = function(){
    document.getElementById('audio').play();
};
konami.load();

Fiddle Demo
Note: not sure if this is how konami sequence must be, but the working sequence is up, up, down, down, left, right, left, right, b, a, enter


text:
Q: Unexpected Behaviour shown while opening the pop up screen in iPad usingjquery mobile I am opening a pop up screen on clinking the header button actually after open of pop up I fill my field than my keyboard will open. Along with black screen also open. How to remove this unnatural behaviour. Actually the the theme move upward when open the keyboard.
I used simple code :
http://jsfiddle.net/ravi1989/jDKDW/

My Cases

                Setting
                Add
                Edit

                    Cancel

Case Information

                    Add

                        Case Name:
                        <input name="text-12" id="text-12" value="" type="text" class="caseName_h" >

                        Case Date:

                        <input name="mydate" id="mydate" type="date" data-role="datebox" data-options='{"mode": "datebox", "useNewStyle":true}'/>

                        Textarea:
                        <textarea cols="40" rows="8" name="textarea-12" id="text-12" class="caseTextArea_h"></textarea>


text:
Q: Insert into collection if checkbox input is checked What I'm trying to do:
I'm using a checkbox in a form that when checked and submitted using a button, it will create a new item in a collection.
Checkbox > Checked > Form Submit > Create new item in a collection.
Checkbox > Unchecked > Form Submit > Do not create the collection.
I have a collection Schema with the following:
value: {
    Type: Boolean,
    ...
}

With a default of false. This is fine.
What I have tried
I have tried two different ways to pass this through to Meteor server side to insert the new collection:

*

*On change of checkbox, update DB value and on submit, check the value in db, if false, don't make collection, if true, make it.

*On submission of form, check if checkbox is checked or unchecked and create the new collection based on this.
Neither worked as I don't know how to pass the content from the HTML to the js file within Meteor. I know how to do this via JavaScript etc.
I'm using a simple if(value) { } but it seems this is only checking if the input exists and is always return true.
I've tried document.getelementbyID, this returns undefined on document. I've tried using it as an event, this returns that events is undefined.
My question:
How do I pass a checked/unchecked value into the Meteor Javascript?

A: You can pass any value into the server side by submitting the form or using an ajax request. I think your question is how to get the checkbox' status: checked or unchecked, am I correct?
So, if you're using jQuery, you can get it with one call:
$(":checkbox").prop("checked");

And if you're using the original js:
document.getElementById("checkboxId").checked;

Hope this can help you.


text:
Q: Añadir HTML en un div con un foreach Js espero podais ayudarme.
Tengo un div en el que quiero mostrar una serie de registros.

Estoy haciendo una peticion XMLHttpRequest a mi base de datos, esta me devuelve un conjunto de registros, y lo que quiero hacer es imprimir por cada registro dentro de un div un fragmento de HTMl, el problema es que es un codigo algo largo.

{{ $Paciente->nombre." ".$Paciente->apellidos}}

{{ $Paciente->carnet }}

            <button class="btn-atender" onclick="attendPatient({{ $Paciente->ID }})"> Atender</button>
            <button class="btn-ver"  data-toggle="modal" data-target="#verPacienteModal" onclick="showPatient({{ $Paciente->ID }})"> Ver</button>

             <button class="btn-ausente" onclick="absentPatient({{ $Paciente->ID }})"> Ausente</button>

             <button class="btn-derivar" data-toggle="modal" data-target="#derivarPacienteModal" onclick="loadModalDerive({{ $Paciente->ID }})"> Derivar</button>

EN ESPERA

El problema, como es un código largo no se como poder imprimirlo. Y otro problema es que como uso un foreach estaba intentando usar el INNERHtml, pero este solo me imprime uno, el ultimo, por que cada vez que va a imprimir otro, borra el anterior y lo sobrescribe.
Use anteriormente esto, para rellenar un combobox, pero no se como rellenar un Div.
let especialidades = JSON.parse(this.responseText);
let input = document.getElementById('Especialidades');
especialidades.forEach(especialidad => {
     i = i+1;
     input.options[i]   = new Option(especialidad.especialidad,especialidad.ID);
});

Necesito algo parecido para rellenar mi div.

A: he encontrado la siguiente solución, no se si es la mas optima, pero funciona.

//Seleccionamos el Div que lo contendram y luego lo limpiamos.
let container = document.querySelector('#Pacientes');
container.innerHTML = "";

//Con el foreach recorreremos el JSON y luego aplicaremos el innerHTML con
lo signos += esto es importante porque es lo que empezará a sumar campos en
lugar de solo reemplazarlos.
 Y luego usamos la comillas de los acentos, para contener el HTML que deseamos mostrar.

Pacientes.forEach(date => {
   container.innerHTML += `Aquí puedes escribir todo tu código HTML y  las variables serian  date.nombrecampo `;
});

Ese seria la solución que encontré yo. Espero les sirva


text:
Q: Convertir formato de columna de un df en R Tengo el siguiente df:

y lo que busco es crear un nuevo dataframe donde por cada grupo de TIMESTAMP y CUSTOMER.ZONE se repita tantas veces tenga el vector de la métrica asociada, por ejemplo la primera fila debe quedar así:

.
.
.
y así con todas la filas del df...
He intentado con:
df2 <- data.frame(t(lapply(df,c)))
df2 <- data.frame(t(sapply(df,c)))
df2 <- as.data.frame(do.call(rbind, df))
df2 <- as.data.frame(do.call(cbind, df))
df2 <- as.data.frame(do.call(cbind, df))

pero sin lograr lo esperado.

A: Suponiendo un data.frame similar al tuyo:
df <- data.frame(TIMESTAMP=c(1,2,3),
                 CUSTOMER_ZONE=c('A', 'B', 'C'),
                 metrica=t(rbind(list(c(1,3,1,7,3), c(1), c(6)))))

  TIMESTAMP CUSTOMER_ZONE       metrica
1         1             A 1, 3, 1, 7, 3
2         2             B             1
3         3             C             6

Una forma muy sencilla es usar unnest()
library(tidyverse)

df %>%
  unnest(metrica)

# A tibble: 7 x 3
  TIMESTAMP CUSTOMER_ZONE metrica
      <dbl> <fct>           <dbl>
1         1 A                   1
2         1 A                   3
3         1 A                   1
4         1 A                   7
5         1 A                   3
6         2 B                   1
7         3 C                   6

Sino, la versión R base, adaptada de aqui:
do.call('rbind',
        lapply(1:nrow(df),
               function(x) data.frame(TIMESTAMP = df[x, 1],
                                      CUSTOMER_ZONE = df[x, 2],
                                      metrica = unlist(df[x, -c(1,2)]),
                                      row.names = NULL)
               )
        )


text:
Q: Having a platformed game level in a storyboard I was wondering how in Games when the character goes forward the screen moves with them and the level continues on, past the extent of a storyboard (Like the background is longer then the storyboard. Does anyone know how? (Not using a game engine)

A:
I was wondering how in Games when the character goes forward the screen moves with them and the level continues on, past the extent of a storyboard

The objects on the game board generally aren't laid out in a storyboard file. The view that is the game board could certainly be part of the storyboard, but the content that that view draws is typically generated by the game's code. For example, it's common to use a sprite framework like SpriteKit or Cocos2D to draw objects using sprites. The data that the game manages is the collection of objects that appear in the game, and a sprite might be used to represent each of those objects.
Consider a platform jumping game like Doodle Jump, where the player hops from one platform to the next. The platforms keep coming and coming and coming as long as the player doesn't fall. Those platforms aren't laid out visually in the storyboard editor. Instead, a list of platform positions is somehow generated -- they could be read from a file, or calculated using some function, or create by some algorithm. A sprite is created for each platform as needed to fill the screen, and probably destroyed after it scrolls off the screen.


text:
Q: C# ASP Directory exists true when it doesn't I've got a problem checking Directory.Exists which always return true while directory doesn't exist. At least these are my assumptions based on the error log.
Note: problem is not occurring local development environment, only on production environment.
So to start of, here is the error message:
Message: Could not find a part of the path 'd:\home\site\wwwroot\media\cdn'.

Exception type: System.IO.DirectoryNotFoundException
Stack Trace:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileSystemEnumerableIterator`1.CommonInit()
at System.IO.FileSystemEnumerableIterator`1..ctor(String path, String originalUserPath, String searchPattern, SearchOption searchOption, SearchResultHandler`1 resultHandler, Boolean checkHost)
at System.IO.Directory.GetFiles(String path, String searchPattern)
at CMS.AzureStorage.Directory.GetFiles(String path, String searchPattern)
at CMS.IO.Directory.GetFiles(String path, String searchPattern)
at CMS.AzureStorage.DirectoryInfo.GetFiles(String searchPattern, SearchOption searchOption)

Related functions (stripped down to the relevant piece of code):
public override string[] GetFiles(string path, string searchPattern)
{
  List<string> stringList = new List<string>();
  if (Directory.ExistsInFileSystem(path))
  {
    foreach (string file in System.IO.Directory.GetFiles(path, searchPattern))
      stringList.Add(Directory.GetCaseValidPath(file, new bool?()));
  }
  ...
}

public static bool ExistsInFileSystem(string path)
{
  return System.IO.Directory.Exists(path);
}

As you can see, it is getting to System.IO.Directory.GetFiles, but what I don't understand is how the line if (Directory.ExistsInFileSystem(path)) is getting bypassed when directory doesn't exist?
I am very confused and hope someone can explain what is going on.

A: You are trying to access the folder outside of your site root folder.
If the production environment is "Cloud" then you need to provide the access to directory.
Providing access is depends on your cloud environment

*

*If you are using VM then you can directly go to IIS and provide the directory access.

*For other models you need provide access through code.

Below is code for providing read and write access to the wwwroot folder.
You can call your code after below code
string file = @"d:\home\site\wwwroot";
DirectoryInfo dInfo = new DirectoryInfo(file);
DirectorySecurity dSecurity = dInfo.GetAccessControl();
dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
dInfo.SetAccessControl(dSecurity);


text:
Q: Immediate address transfer inconsistently SPLINT I have a code segment here, but SPLINT is giving me a warning here
"tcpuip\dhcpc\dhcpc.c: (in function send_discover)
tcpuip\dhcpc\dhcpc.c(219,21): Immediate address &m->options[4] passed as only
                                 param: add_msg_type (&m->options[4], ...)
  An immediate address (result of & operator) is transferred inconsistently.
  (Use -immediatetrans to inhibit warning)
"

    static void send_discover(void)
    {
            u8_t *end;
            struct dhcp_msg *m = (struct dhcp_msg *)uip_appdata;

        create_msg(m);

        end = add_msg_type(&m->options[4], DHCPDISCOVER);   //line 219
        end = add_req_options(end);
        end = add_end(end);

        uip_send(uip_appdata, end - (u8_t *)uip_appdata);
}

I am trying to work around this problem, please anyone can through some light on it. I have been googling for like 3 hrs, hav'nt found a soln.


text:
Q: How to reduce data by extracting subsets (considering unique identifiers and minimal values) My data consists of values (x,y,z) plus identifier (id).
d <- data.frame( x=c( 11, 12, 13, 14, 15, 16, 17, 18, 19),
                 y=c( 21, 22, 23, 24, 25, 26, 27, 28, 29),
                 z=c(101,212,307,304,206,102,230,145,315),
                 id=c( 1,  2,  3,  3,  2,  1,  2,  1,  3)
                )
d
   x  y   z id
1 11 21 101  1
2 12 22 212  2
3 13 23 307  3
4 14 24 304  3
5 15 25 206  2
6 16 26 102  1
7 17 27 230  2
8 18 28 145  1
9 19 29 315  3

I need a subset of this data where id is unique and z is minimum within equal id
(e.g.: 101 is the smalest value for z, where id == 1)
   x  y   z id
1 11 21 101  1
4 14 24 304  3
5 15 25 206  2

I've found a solution  using unique() to create a vector of unique identifiers, then using a for() loop, extracting subsets by id and searching for minimal z-values. But since the amount of data is huge this is'nt fast enough.
Any smarter ideas?

A: data.table is really fast when it comes to such operations. For your question, this seems to work:
library(data.table)
#.SD reflects the group and which.min finds the index of the minimum
setDT(d)[, .SD[which.min(z)], by = 'id']
#   id  x  y   z
#1:  1 11 21 101
#2:  2 15 25 206
#3:  3 14 24 304


text:
Q: Get identical Array from increments to 2 values I want to find the minimum number to be subtracted to get from an array like this
[8, 10, 5]

to an array like this
[3, 3, 3]

I am only allowed to change the values of TWO indexes (in this case either index 0 and 1 OR index 1 and 2). I am only allowed to subtract values and have to subtract the same value over both indexes(ex. If I wanted to subtract 5 I'd have to do it on two indexes, either index 0 and 1 or index 2 and 3).
Edit: Clarification #1: There is no "base value". Just that all indexes are identical through the lowest number of subtraction values (not operations, but values subtracted.)
Clarification #2: At any given time, I am only allowed to subtract the same value from 2 indexes, and only 2
I am not sure of how to tackle this problem, any smallest hints and advice would be greatly appreciated.

A: If you want to make all the values identical, that means your lowest and highest value should be equal.
for example, in your array
arr[] = {8,5,10};

You need to first sort it.
 arr[] = {5,8,10};

Now, you see that the difference between the highest and lowest is 5,
therefore you subtract 5 from the 2 maximum elements
 arr[] = {5,3,5};

then again you sort it
arr[] = {3,5,5};

now the difference between maximum and minimum 2, therefore you subtract it from the maximum 2 elements present in your array .
and your array becomes this
  arr[] = {3,3,3};

The idea is to bring the maximum number closest to the smallest number and that happens if you subtract the difference between them from the maximum number.


text:
Q: String was not recognized as a valid date time String was not recognized as a valid datetime in vb.net?

A: It may be because you are converting a date which is represented as a string and is not on the standard date format. Ex,
Dim _dateString As String = "22-2009-11"
Dim _date As DateTime = = DateTime.Parse(_dateString);

throws an exception because _dateString is non-standard date format. The best thing you will do is to use DateTime.ParseExact
Dim _dateString As String = "22-2009-11"
Dim _date As DateTime =  DateTime.ParseExact(_dateString,"dd-yyyy-MM",CultureInfo.InvariantCulture);


text:
Q: Creating global variables in Vue vs state What is the best way to create global variables in Vue? Is it to use Vuex?
I can access the Vuex state like so:
{{ store.$state.myvar }}

This is a bit messy. I would rather do:
{{ myvar }}

Is this possible?

A: Add a computed property in your components:
computed: {
   myVar: {
      get() { return this.$store.state.myVar; },
      set(value) { this.$store.commit('updateMyVar', value); }
   },
}

This allows you to use it like any other property in your components.

A: You can do anything you want. You should try and organise your state so that "there's a place for everything, and everything is in its place".
Of course you can create and reference global variables in Vue. You could, say, do var myVar = store.$state.myvar, and you've got a global alias to your var in Vuex. But, big but, if you've chosen to use Vuex, then you kinda need to follow through on that choice. Creating aliases in global state will quickly lead to collisions and confusion. Vue is vaguely MVVM, inspired by Elm. It wants you to separate your state from your interface components. This can lead to longish paths to reference items of state, but the payoff is well worth it - you don't need to be synchronising and sharing little bits of state all over the place. Does that answer the question?


text:
Q: cURL Paypal Identity API response gives merchant info, not payer I have a paypal identity app with proper email entitlements on the app already, I am attempting to get the users email through this script:
<?php
$clientId = 'myclientid';
$clientSecret = 'myclientsecret';

//SEND CURL API REST REQUEST

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://api.paypal.com/v1/oauth2/token");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $clientId.":".$clientSecret);
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");

$result = curl_exec($ch);

if(empty($result))die("Error: No response.");
else
{
    $json = json_decode($result);
}

$access_token = $json->access_token;

curl_close($ch);

///////////////////////////////////////////////////////////////////////
//GET CURL API REST REQUEST BACK

$cha = curl_init();

curl_setopt($cha, CURLOPT_URL, 'https://api.paypal.com/v1/oauth2/token/userinfo?schema=openid');
curl_setopt($cha, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($cha, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token, 'Content-Type:
application/json'));
curl_setopt($cha, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");

$returnresult = curl_exec($cha);

$data = json_decode($returnresult, true);
$http_code = curl_getinfo($cha, CURLINFO_HTTP_CODE);
if($http_code != 200) {
    throw new Exception('Error : Failed to get user information');

}else{

//STORE RETREIVED VALUES HERE//////////////////

$paypaldata = implode(',',$data);

curl_close($cha);

        if (!empty($paypaldata)) {
          //Do stuff with $paypaldata
        }
}

?>

But the response stored in var paypaldata is the merchant's data, I am looking for the users data who logged in. I am not sure what I am doing wrong, and yes I can ensure I am not logged in as the merchant when performing tests.


text:
Q: product of Hardy functions Let $f,g$ two analytic functions defined on the complex disk, and $f,g \in H^2$ the Hardy space, that is, $f(z) = \sum_{n=0}^{\infty} \hat{f}(n)z^n$ such that $\sum_{n=0}^{\infty}|\hat{f}(n)|^2 < \infty$, and $g$ satisfies the same condition. How do I proof that $fg \in H^2$? (I have some problems to handle with the Cauchy product of power series).

A: Since $f,g \in H^2$ and $[-\pi,\pi]$ is a measurable subset, we are under the conditions of Hölder's inequality, then
$$\int_{-\pi}^{\pi}|f(re^{i\theta})g(re^{i\theta})|d\theta \leq \left(\int_{-\pi}^{\pi}|f(re^{i\theta})|^2d\theta\right)^{\frac{1}{2}}\left(\int_{-\pi}^{\pi}|g(re^{i\theta})|^2d\theta\right)^{\frac{1}{2}}.$$
Besides, a function $f \in H^2$ if, and only if, $$\lim_{r \rightarrow 1^{-}}\dfrac{1}{2\pi} \int_{-\pi}^{\pi} |f(re^{i\theta})|^2d\theta$$ is bounded. Putting together this two assertions, it holds
$$ \lim_{r \to 1^- }\dfrac{1}{2\pi} \int_{-\pi}^{\pi} |f(re^{i\theta})g(re^{i\theta})|^2d\theta \leq \lim_{r \to 1^-}\dfrac{1}{2\pi} \left( \left( \int_{-\pi}^{\pi}|f(re^{i\theta})|^2d\theta \right)^{\frac{1}{2}}\left( \int_{-\pi}^{\pi}|g(re^{i\theta})|^2d\theta\right)^{\frac{1}{2}} \right) $$
which is finite since $f,g \in H^2$.


text:
Q: Visual Studio Code status bar text color I want to change text color on status bar in Visual Studio Code. I've found how to change color of status bar Visual Studio Code status bar color but I need similar solution for text.

A: The two values you need to change for the status bar are
{
  "statusBar.background": "#114F79",
  "statusBar.foreground": "#9DE2FD"
}

And set those to your preference (in settings.json).


text:
Q: Explicit construction of a nonmeasurable set, where only the proof of correctness uses choice? By Solovay's theorem, assuming the existence of an inaccessible cardinal, the axiom of choice is necessary to prove the existence of nonmeasurable sets. In the past, I've thought that one consequence of this theorem is that if I construct a set without using choice (or even merely using dependent choice), then I don't have to worry about it being nonmeasurable.
But now I realize that I was making an unjustified assumption. I'm not sure what the appropriate way to precisely phrase this question is, but I'm wondering: is there a non Lebesgue measurable set $E \subseteq \mathbb{R}$ which can be explicitly defined? I'm imagining that perhaps $E$ can be defined without invoking choice (unlike Vitali sets or their cousins), but then proving that $E$ is nonmeasurable requires choice. Is this possibility also ruled out by Solovay's theorem somehow?

A: If you can prove that your definition defines something, then will in particular define something in Solovay's model, and that something will in particular not be a nonmeasurable set.
So the best you can hope for is an explicit definition of a subset of $\mathbb R$, such that the thing defined will in some models of ZF be a nonmeasurable set.
And this is in fact the case: Since pointwise definable models of ZFC exist, such a model will contain a nonmeasurable set and that set will have an explicit definition in the language of set theory. (In fact, as Asaf points out in comments, we don't need to appeal to pointwise-definable models here; there is a particular formula that picks out the first nonmeasurable subset of $\mathbb R$ in any model of $\mathbf V=\mathbf L$, where "first" is according to the global well-order, and this one formula will work for the $\mathbf L$ of every model of ZF).
We can even arrange that this particular definition always provably defines some subset of $\mathbb R$ -- if our element of the pointwise definable model is the only set that satisfies the formula $\phi(x)$, then
$$ \{ y\in \mathbb R \mid \exists x: \phi(x)\land y\in x \} $$
will define some subset of $\mathbb R$ in every model, and it will at least sometimes be non-measurable.

A: From wikipedia: $\:$ "In particular Krivine (1969) showed there was a model

of ZFC in which every ordinal-definable set of reals is measurable, ..."

Therefore ZFC does not prove that there is a definable nonmeasurable set.
Using an explicit definable well-order on $\mathbb{R}\hspace{-0.04 in}\cap$OD to run a Vitali construction

gives an explicit set which won't be measurable if $\: \mathbb{R} \subset \hspace{.04 in}$OD$\;$.


text:
Q: The total number of locks exceeds the lock table size in MySQL I have a table which is defined like this:

Where ProviderId is the primary key, and StateID is the foreign key, that comes from another table. It is running in my laptop, therefore, it is a local database. In my table I have around 9 million entries. I know for a fact, there are duplicate entries in the table, but they are duplicate only if we compare them with a few of the fields. In order to delete the duplicate entries I ran the query found below:
SET SQL_SAFE_UPDATES=0;
DELETE p1.*
FROM providers AS p1
JOIN (SELECT ProviderName AS PName, Address AS PAddr, StateID, Zip, MIN(ProviderId) AS PId
      FROM providers
      GROUP BY PName, PAddr, StateID, Zip
      HAVING COUNT(*) > 1) AS p2
ON p1.ProviderName = p2.PName
AND p1.Address = p2.PAddr
AND p1.StateID = p2.StateID
AND p1.Zip = p2.Zip
AND p1.ProviderId > p2.PId;

The point is that, it was running for about 4 and a half hours, and it showed me the error message written on the title. You can also see it :

How can I make my query faster, and overcome the error message that I got?

A: I am not sure that I got your goal,
and you should better provide sqlfiddle
but you can try:
SET SQL_SAFE_UPDATES=0;
DELETE p1
FROM providers AS p1
WHERE ProviderId NOT IN  (
      SELECT
        MIN(ProviderId)
      FROM providers
      GROUP BY PName, PAddr, StateID, Zip
)

A: Based on this article I've found, it appears the problem lies in the size of your table.
The query you have will work, but I recommend breaking it down into smaller groups. For example, if your providerID ranges from 1 to 9 million (based on your question) you can just add to your where clause:
WHERE ProviderID <= 1000000;

and then run it again using 2 million, 3 million, etc. I'm not sure how small the groups have to be, that may require trial and error.


text:
Q: How to specifically style th and td only for one table class? I have a really annoying and baffling problem. My website has two different classes of table. One has no border and the other does. But no matter what I do, I cannot separate the th and td styling from the other table.
The first table has no class styling; I default to whatever.
The second table has:
table.t01, th, td {
   border: 4px solid black;
   border-collapse: collapse;
}

However, this affects the styling of th and td for the first table. WTF.
How can I solve this problem?

A: By using commas in your selector, you're saying "this style applies to any table with class t01, but also ANY th and ANY td."
This can be useful to consolidate the styling of many elements that have the same style. For example, the following are equivalent:
// The verbose way
th { color: red; }
td { color: red; }
p.red { color: red; }
div#firstred { color: red; }

// The concise way
th, td, p.red, div#firstred { color: red; }

If what you really looking for is to define a style for th and td descendants of a table with class t01, just separate the terms of the table and th/td selectors with a space:
Try:
table.t01 th, table.t01 td {
   border: 4px solid black;
   border-collapse: collapse;
}

A: What happens if you apply the styling to your selectors more explicitly (see below):
table.t01, table.t01 th, table.t01 td {
    border: 4px solid black;
    border-collapse: collapse;
}

A: Here's another, slightly shorter alternative:
<style>
    #myTable th, td {
        border: 4px solid black;
        border-collapse: collapse;
    }
</style>
...
<table id="myTable">
    ...
</table>


text:
Q: Getting [object Object] error when call JQuery Ajax function for Json data I'm getting the following error when try to read json data from asp.net function, here is the image error

Here is the jQuery code,
<script type="text/javascript">
    $(document).ready(function () {
        $("#getdata").click(function () {
            $.ajax({
                type: "POST",
                url: "Default.aspx/GetData",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    alert(data.d);
                    // $("#company").html(data.d);
                      console.log(data);
                },
                error: function (error) {
                    alert(error);
                }
            });
        });
    });
</script>

what wrong I did to get this error. Appreciate your any help.
getting this error from console log,console.log(error)

A: The reason you are seeing that is that data.d is an object representing the returned JSON text response. When you pass in an object into alert, it displays [object Object].  Whatever you are looking for will be a property of data.d. I would put a breakpoint on that line and see what properties are available. It'll be something like data.d.myProperty which will contain the actual string / HTML you are trying to work with.

A: dont use alert! That will show this only.
Since your response is a Json Object, please try to JSON.stringify it or use console.log to view the data

A: Finally, I found what was the issue, I have to add "[WebMethod()]" declaration just before the  asp.net function. For example,
    [WebMethod()]
    public static string GetData()
    {

        try
        {
            string strjson;
            string connectionstring = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
            SqlConnection Con = new SqlConnection(connectionstring);
            DataSet DS = new DataSet();
            String CmdText = "Select Compname,compadd1,compadd2,compemail from aas_company where compid=@cmpid";
            SqlCommand cmd = new SqlCommand(CmdText, Con);
            cmd.Parameters.Add("@cmpid", SqlDbType.Int).Value = 22;
            Con.Open();
            SqlDataAdapter DA = new SqlDataAdapter(cmd);
            DA.Fill(DS);
            DataTable dTable = DS.Tables[0];
            strjson = GetJSONString(dTable);
            Con.Close();
            return strjson;
        }
        catch (Exception ex)
        {
            throw new System.Exception("Error In Get Data" + ex.Message);
        }
    }

This answer not for experts only for just beginners, thank you.


text:
Q: What the difference between onResize and onResized? In firemonkey (delphi tokyo), what is the difference between onResize and onResized event of Tcontrol ? because both are called AFTER the control size already changed. And the most important, when to use onresized and when to use onresize?
from the delphi source code :
procedure TControl.SetBounds(X, Y, AWidth, AHeight: Single);
var
  SizeChanged: Boolean;
  Moved: Boolean;
  NeedRepaint: Boolean;
  ReductionSize: Boolean;
begin
  Moved := not (SameValue(X, Position.X, TEpsilon.Position) and SameValue(Y, Position.Y, TEpsilon.Position));
  SizeChanged := not (SameValue(AWidth, Width, TEpsilon.Position) and SameValue(AHeight, Height, TEpsilon.Position));
  if Moved or SizeChanged then
  begin
    ReductionSize := False;
    if SizeChanged then
    begin
      ReductionSize := (FSize.Height > AHeight) or (FSize.Width > AWidth);
      SizeChanged := DoSetSize(FSize, False, AWidth, AHeight, FLastWidth, FLastHeight);
    end;
    NeedRepaint := False;

    if Moved or (SizeChanged and (RotationAngle <> 0)) then
    begin
      if Moved or ReductionSize then
        Repaint;
      FPosition.SetPointNoChange(PointF(X, Y));
      FLeft := FPosition.X;
      FTop := FPosition.Y;
      Inc(FUpdating);
      try
        MatrixChanged(Self);
      finally
        Dec(FUpdating);
      end;
      NeedRepaint := True;
    end;

    if Moved or SizeChanged then
    begin
      if (csDesigning in ComponentState) then
        if (FParentControl <> nil) and not (csDestroying in FParentControl.ComponentState) then
          if (TRectF.Union(BoundsRect, FParentControl.LocalRect) <> FParentControl.LocalRect) then
            FParentControl.RecalcUpdateRect;
      UpdateExplicitBounds;
      UpdateAnchorRules;
      RequestAlign;
    end;

    if not (csLoading in ComponentState) and SizeChanged then
    begin
      UpdateSmallSizeControl;
      Resize;
      if FControls <> nil then
        Realign
      else if HasEffect then
        UpdateEffects;
    end;
    if not (csLoading in ComponentState) and not SizeChanged and Moved then
      Move;
    if not (csLoading in ComponentState) and (Moved or SizeChanged) then
    begin
      RecalcUpdateRect;
      NeedRepaint := True;
    end;
    if not (csLoading in ComponentState) and SizeChanged then
      DoResized;
    if NeedRepaint then
      Repaint;
  end;
end;

So it's seam resize and DoResized are both called AFTER the DoSetSize.


text:
Q: what exactly is interface(struc) and interface(struc).function Trying to do go koan, i got stuck in understanding the  interface(struct) syntax, what exactly
does it do ?
I came up with following fun program, which has further confused me on how is interface casting working :
package main

import "fmt"

type foo interface{  fn() }

type t struct { }
type q struct { }

func (_i t ) fn() { fmt.Print("t","\n") }
func (_i q ) fn() { fmt.Print("q","\n")}

func main() {
    _j :=  t{}
    _q :=  q{}

    // This is alright ..
    fmt.Print( _j.fn,"\n")           //0x4015e0
    fmt.Print( _q.fn,"\n")       //0x401610
    _j.fn()              //t
    _q.fn()              //q
    // both pointers same .. why ?
    fmt.Print( foo(_j).fn,"\n")  //0x401640
    fmt.Print( foo(_q).fn,"\n")  //0x401640
    // but correct fns called .. how ?
    foo(_j).fn()             //t
    foo(_q).fn()             //q

    // same thing again ...
    _fj := foo(_j).fn
    _fq := foo(_q).fn
    // both pointers same .. as above
    fmt.Print( _fj,"\n")         //0x401640
    fmt.Print( _fq,"\n")         //0x401640
    // correct fns called .. HOW !
    _fj()                //t
    _fq()                //q
}

The pointer are what i'm getting my machin, YMMV.
My question is .. what exactly does interface(struct) returns ?
and how does interface(struct).func , finds the original struct ...
is there some thunk/stub magic going on here?

A: From here: http://research.swtch.com/interfaces

what exactly does interface(struct) return?

It creates a new interface value (like the one you see on top in the graphic), wrapping a concrete struct value.

how does interface(struct).func find the original struct?

See the data field in the graphic. Most of the time this will be a pointer to an existing value. Sometimes it will contain the value itself if it fits, though.
In the itable you'll see a function table (where fun[0] is).
I assume that on your machine 0x401640 is the address of the respective pointers to fn, which is in that table for foo. Although this is best verified by someone working on the GC compiler suite.
Note that the behaviour you discovered is not strictly defined to be so. Compiler builders can take other approaches to implementing Go interfaces if they like to, as long as the language semantics are preserved.

Edit to answer questions in the comments:
package main

import "fmt"

type foo interface {
    fn()
}

type t struct{}
type q struct{}

func (_i t) fn() { fmt.Print("t", "\n") }
func (_i q) fn() { fmt.Print("q", "\n") }

func main() {
    _j := t{}
    _j1 := t{}

    fmt.Println(foo(_j) == foo(_j))  // true
    fmt.Println(foo(_j) == foo(_j1)) // true
}

On the diagram you see 3 blocks:

*

*The one on the left side labeled Binary is a concrete type instance, like your struct instances _j and _j1.

*The one on the top center is an interface value, this one wraps (read: points to) a concrete value.

*The block on the right lower side is the interface definition for Binary underlyings. This is where the jump table / call forwarding table is (itable).
_j and _j1 are two instances of the concrete type t. So there are two of the lower-left blocks somewhere in memory.
Now you decide to wrap both _j and _j1 in interfaces values of type foo; now you have 2 of the top-center blocks somewhere in memory, pointing back at _j and _j1.
In order for the interface value to remember what its underlying type is and where the methods of those types are it keeps a single instance of the lower-right block in memory, to which both interface values for _j and _j1 respectively point to.
In that block you have a jump table to forward method calls made on the interface values to the concrete underlying type's implementation. That's why both are the same.
It's worth mentioning that unlike Java and C++ (not sure about Python), all Go methods are static and the dot-call notation is only syntactic sugar. So _j and _j1 don't have different fn methods, it's the same exact method called with another implicit first parameter which is the receiver on which the method is called.


text:
Q: Incomplete type works with gcc but not with clang and msvc I have recently learnt about incomplete types and that under certain conditions they can be used as template arguments. In particular, like void, struct incomplete; are both incomplete types. Then I wrote the following program that works with gcc but not with msvc and clang. Live demo
struct incomplete;
template<typename T> struct C
{
    static constexpr T t{};
};

template<class T>
struct myClass {
    C<T> new_t() { return {}; }
};

int main() {
    myClass<incomplete> d;
    d.new_t();
}

As we can see the above program compiles with gcc but not with msvc and clang. So I want to know which is the correct technical behavior.
Clang says:
<source>:4:24: error: constexpr variable cannot have non-literal type 'const incomplete'
    static constexpr T t{};

while msvc says:
<source>(4): error C2027: use of undefined type 'incomplete'
<source>(1): note: see declaration of 'incomplete'

while GCC accepts the code with both c++17 as well as c++20.
Which compiler is correct here?

A: The program is ill-formed and gcc is wrong in accepting the code because even though the definition of the static data member is not instantiated(because it is not odr-used), it's declaration will still be instantiated due to the implicit instantiation of C<incomplete> as per temp.inst#3. More importantly, if a declaration uses constexpr or inline (since C++17) specifier, the member must be declared to have complete type.
From temp.inst#3:

The implicit instantiation of a class template specialization causes:

*

*the implicit instantiation of the declarations, but not of the definitions, of the non-deleted class member functions, member classes, scoped member enumerations, static data members, member templates, and friends; and

(emphasis mine)
This means that the implicit instantiation C<incomplete> will cause the implicit instantiation of the declaration of the static data member.
Further from static data member documentation:

However, if the declaration uses constexpr or inline (since C++17) specifier, the member must be declared to have complete type.

(emphasis mine)
This means that since the implicitly instantiated declaration, declares a member of an incomplete type, the program is ill-formed.

Here is the gcc bug report:
static constexpr incomplete (depedent) data member of a class template and in-member initialized incorrectly accepted


text:
Q: get_absolute_url is not working--gives this error NoReverseMatch error I get this error when trying to user get_absolute_url--what i am doing wrong?
NoReverseMatch at /mega_archive/books/

Reverse for 'book' with arguments '('',)' not found. 1 pattern(s) tried: ['mega_archive/book/(?P<book>[-a-zA-Z0-9_]+)/\\Z']

views.py
def books(request):
    books = Book.objects.all()
    return render(request, 'mega_archive/books.html',{
                'books':books
        })

def book(request, book):
    book = get_object_or_404(Book, slug=book)
    return render(request, 'mega_archive/book_details.html', {
                'book':book
        })

urls.py
    path('books/', views.books, name='books'),
    path('book/<slug:book>/', views.book, name='book'),

models.py
    def get_absolute_url(self):
        return reverse('mega_archive:book', args=[self.slug])

    def __str__(self):
        return self.title

html
{% for book in books %}

    {{book}}

{% endfor %}

can anyone point to what I did wrong?

A: get_absolute_url() resolves URL named 'mega_archive:book', which expects a slug argument. Based on the error message, the slug argument was not provided.  Could it be None in the book object?


text:
Q: Yii nested dropDownList with optiongroup i started to learn yii a few days ago and now i'm stuck with the following problem for hours...
I want to generate a dropDownList like
<div class="cars-select">
    <?php echo CHtml::dropDownList('Cars', 'car_id', array(
        'Mazda'=>array(
            'mazda-rx7'=>'RX7',
            'mazda-rx5'=>'RX5',
        ),
        'Volvo'=>array(
            'volvo-b9tl'=>'B9TL',
            'volvo-l90e-radlader'=>'L90E Radlader',
        ),
    )); ?>
</div>

But i get the data from the Database with following table-structure:
Table Studycourse:
id, coursename, extension_of

1, Law, 0
2, Economics, 0
3, Business Law, 1
4, Macro Economics, 2

My DropDownList without option group is working:
$courseExt = Studycourse::model()->findAll("extension_of IS NOT NULL", array('order' => 'id'));
echo $form->dropDownList($model, 'studycourse_id', GxHtml::listDataEx($courseExt));

But how can i populate a dropdownlist with option groups?
It should generate the following html:
<select name="studycourse" id="course">
        <optgroup label="Law">
            <option value="law-business">Business Law</option>
        </optgroup>
        <optgroup label="Economics">
            <option value="economics-macro">Macro Economics</option>
        </optgroup>
</select>

A: Category Table:
id   name          grp
1    Ms Office     Software
2    Photo shop    Software
3    C++           Programming
4    Java          Programming
5    PHP           Programming
$category = CHtml::listData(Category::model()->findAll(), 'id', 'name','grp');
echo CHtml::dropDownList('location', '', $location);


text:
Q: Angular 2 How to get data passed by router in change event Below is sample of my route
{ path: 'calendar', component: CalendarComponent, canActivate: [CanActivateViaAuthGuard], data: { title: 'Calendar' } },
I want to get the data in router change event. Below is my event,
this._router.events
.filter(event => event instanceof RoutesRecognized)
.subscribe((event: any) => {})

I am able to get data by following way,
event.state._root.children[0].value._routeConfig.data
I believe this is not a proper way to get data. What is the proper way to get data here?

Basically I want to set title of the page, so when I am in calendar page, my HTML page title should have 'Calendar'. I don't want this code to be done in every page. So I am making a general component which can take data from every route and change title of page.
EDIT
I can always get the data in component itself but that would be redundant. I will have to code in every component to set title. I want this exercise to be done in one place, so I am avoiding in component.

A: You can send data as an argument in the path. Then your route looks like this:
{ path: 'calendar/:title', component: CalendarComponent }

In the calendar component you can subscribe to this param like this
ngOnInit() {
  this.route.params.subscribe(params => {
    var title = params['title'];
    ...
  });
}

Your function will be called initially and every time the param changes.

A: For Angular 4+
if you want to access the route custom data on child or lower level components for which you've defined the route custom data you can do the following in that component considering you're passing route custom data data: {title: 'somedata'}:
 public constructor(private route:ActivatedRoute, private router:Router) {
      console.log(route.snapshot.data['title']);
  }

But, if you want to access the route custom data globally from a parent or upper level component to access the change in the route custom data then you've to listen to router events particularly RoutesRecognized or NavigationEnd events. I'm gonna show two procedures with AppComponent with two events:
First Approach:
   export class AppComponent implements OnInit, AfterViewInit {

    constructor(private activatedRoute: ActivatedRoute, private router: Router) { }

    ngOnInit() {
         this.router
        .events
        .filter(event => event instanceof NavigationEnd)
        .map(() => {
          let child = this.activatedRoute.firstChild;
          while (child) {
            if (child.firstChild) {
              child = child.firstChild;
            } else if (child.snapshot.data && child.snapshot.data['custom_data']) {
              return child.snapshot.data['custom_data'];
            } else {
              return null;
            }
          }
          return null;
        }).subscribe( (customData: any) => {
          console.log(customData);
       });
    }
 }

Second Approach is using:
this.router.events
.filter(event => event instanceof RoutesRecognized)
.map( (event: RoutesRecognized) => {
    return event.state.root.firstChild.data['custom_data'];
})
.subscribe(customData => {
    console.log(customData);
});

Note: Even though last one is shorter and usually works, but, if you have nested routes then it is encouraged to use the first one.


text:
Q: UWP keep combobox selection that is already active executable This is a continuation from an earlier question.
I'm trying to work by binding combobox Finally, so I can use it for some settings. after that I want to combine the contents of the textbox with a combobox selection to be executed on the button. how to keep combobox selection that is already active executable?
private void button_Click(object sender, RoutedEventArgs e)
        {
            String satuan = ComboBox.GetIsSelectionActive(combobox).ToString();
                if (satuan.Equals("0"))
                {
                    awal = Convert.ToDouble(textbox.Text);
                    celcius = awal;
                    textbox1.Text = celcius.ToString();
                    reamur = 0.8 * awal;
                    textbox2.Text = reamur.ToString();
                    fahrenheit = (1.8 * awal) + 32;
                    textbox3.Text = fahrenheit.ToString();
                    kelvin = awal + 273;
                    textbox4.Text = kelvin.ToString();
                }

This is the XAML:
<Page
    x:Class="berhasil.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:berhasil"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:converter="using:berhasil.Converter"
    mc:Ignorable="d">

    <Page.Resources>
        <converter:ConverterString x:Key="Converter" />
    </Page.Resources>

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>

        <TextBlock Grid.Row="0" Text="Input Value: " VerticalAlignment="Center"/>
        <TextBox x:Name="textbox"
                 Grid.Row="0"
                 Grid.Column="1"
                 Margin="0,10,0.333,0"
                 Width="154"
                 VerticalAlignment="Center"
                 InputScope="Number"/>
        <StackPanel Grid.Column="2"
                    Grid.Row="0"
                    VerticalAlignment="Center"
                    Margin="20,10,0,10"
                    Orientation="Horizontal">
            <ComboBox x:Name="combobox"
                      ItemsSource="{x:Bind ComboBoxOptions}"
                      SelectedItem="{x:Bind SelectedComboBoxOption, Mode=TwoWay, Converter={StaticResource Converter}}"
                      SelectedValuePath="ComboBoxOption"
                      DisplayMemberPath="ComboBoxOption">
            </ComboBox>
        </StackPanel>
        <Button Grid.Row="1" x:Name="button"
                Content="Conversion"
                HorizontalAlignment="Center" Margin="78,0,0.333,0"
                Width="154" Grid.ColumnSpan="2"
                Click="button_Click"/>
        <TextBlock Grid.Row="2" Text="Celcius: " VerticalAlignment="Center"/>
        <TextBox x:Name="textbox1"
                 Grid.Row="2"
                 Margin="78,10,-23.333,0"
                 Grid.ColumnSpan="3"
                 VerticalAlignment="Center"
                 InputScope="Number"
                 IsReadOnly="True"/>
        <TextBlock Grid.Row="3" Text="Reamur: " VerticalAlignment="Center"/>
        <TextBox x:Name="textbox2"
                 Grid.Row="3"
                 Margin="78,10,-23.333,0"
                 Grid.ColumnSpan="3"
                 VerticalAlignment="Center"
                 InputScope="Number"
                 IsReadOnly="True"/>
        <TextBlock Grid.Row="4" Text="Fahrenheit: " VerticalAlignment="Center"/>
        <TextBox x:Name="textbox3"
                 Grid.Row="4"
                 Margin="78,10,-23.333,0"
                 Grid.ColumnSpan="3"
                 VerticalAlignment="Center"
                 InputScope="Number"
                 IsReadOnly="True"/>
        <TextBlock Grid.Row="5" Text="Kelvin: " VerticalAlignment="Center"/>
        <TextBox x:Name="textbox4"
                 Grid.Row="5"
                 Margin="78,10,-23.333,0"
                 Grid.ColumnSpan="3"
                 VerticalAlignment="Center"
                 InputScope="Number"
                 IsReadOnly="True"/>
    </Grid>
</Page>

And this is the code behind:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Xml.Serialization;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace berhasil
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page, INotifyPropertyChanged
    {
        Double awal, celcius, reamur, fahrenheit, kelvin;
        private ObservableCollection<ComboBoxItem> ComboBoxOptions;
        ApplicationDataContainer roamingSettings = null;

        public MainPage()
        {
            this.InitializeComponent();
            ComboBoxOptions = new ObservableCollection<ComboBoxItem>();
            ComboBoxOptionsManager.GetComboBoxList(ComboBoxOptions);
            roamingSettings = ApplicationData.Current.RoamingSettings;

            var value = (string)roamingSettings.Values["ComboBoxSelection"];
            if (value != null)
            {
                var deserialized = Deserialize<ComboBoxItem>(value);
                // using ComboBoxOption as the primary key field of your object
                SelectedComboBoxOption = ComboBoxOptions.SingleOrDefault(c =>
                            c.ComboBoxOption == deserialized.ComboBoxOption);
            }
            else
            {
                SelectedComboBoxOption = ComboBoxOptions[0];
            }
        }

        public class ComboBoxItem
        {
            public int ComboBoxId { get; set; }
            public string ComboBoxOption { get; set; }

        }

        public class ComboBoxOptionsManager
        {
            public static void GetComboBoxList(ObservableCollection<ComboBoxItem> ComboBoxItems)
            {
                var allItems = getComboBoxItems();
                ComboBoxItems.Clear();
                allItems.ForEach(p => ComboBoxItems.Add(p));
            }

            private static List<ComboBoxItem> getComboBoxItems()
            {
                var items = new List<ComboBoxItem>();

                items.Add(new ComboBoxItem() { ComboBoxId = 1, ComboBoxOption = "Celcius"});
                items.Add(new ComboBoxItem() { ComboBoxId = 2, ComboBoxOption = "Reamur" });
                items.Add(new ComboBoxItem() { ComboBoxId = 3, ComboBoxOption = "Fahrenheit" });
                items.Add(new ComboBoxItem() { ComboBoxId = 4, ComboBoxOption = "Kelvin" });

                return items;
            }
        }

        private ComboBoxItem _SelectedComboBoxOption;
        public ComboBoxItem SelectedComboBoxOption
        {
            get
            {
                return _SelectedComboBoxOption;
            }
            set
            {
                if (_SelectedComboBoxOption != value)
                {
                    _SelectedComboBoxOption = value;
                    roamingSettings.Values["ComboBoxSelection"] = Serialize(value);
                    RaisePropertyChanged("SelectedComboBoxOption");
                }
            }
        }

        public static string Serialize(object obj)
        {
            using (var sw = new StringWriter())
            {
                var serializer = new XmlSerializer(obj.GetType());
                serializer.Serialize(sw, obj);
                return sw.ToString();
            }
        }

        public static T Deserialize<T>(string xml)
        {
            using (var sw = new StringReader(xml))
            {
                var serializer = new XmlSerializer(typeof(T));
                return (T)serializer.Deserialize(sw);
            }
        }

        void RaisePropertyChanged(string prop)
        {
            if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(prop)); }
        }
        public event PropertyChangedEventHandler PropertyChanged;

        private void button_Click(object sender, RoutedEventArgs e)
        {
            String satuan = ComboBox.GetIsSelectionActive(combobox).ToString();
                if (satuan.Equals("0"))
                {
                    awal = Convert.ToDouble(textbox.Text);
                    celcius = awal;
                    textbox1.Text = celcius.ToString();
                    reamur = 0.8 * awal;
                    textbox2.Text = reamur.ToString();
                    fahrenheit = (1.8 * awal) + 32;
                    textbox3.Text = fahrenheit.ToString();
                    kelvin = awal + 273;
                    textbox4.Text = kelvin.ToString();
                }
                else if (satuan.Equals("1"))
                {
                    awal = Convert.ToDouble(textbox.Text);
                    celcius = 1.25 * awal;
                    textbox1.Text = celcius.ToString();
                    reamur = awal;
                    textbox2.Text = reamur.ToString();
                    fahrenheit = (2.25 * awal) + 32;
                    textbox3.Text = fahrenheit.ToString();
                    kelvin = celcius + 273;
                    textbox4.Text = kelvin.ToString();
                }
                else if (satuan.Equals("2"))
                {
                    awal = Convert.ToDouble(textbox.Text);
                    celcius = 0.55555 * (awal - 32);
                    textbox1.Text = celcius.ToString();
                    reamur = 0.44444 * (awal - 32);
                    textbox2.Text = reamur.ToString();
                    fahrenheit = awal;
                    textbox3.Text = fahrenheit.ToString();
                    kelvin = celcius + 273;
                    textbox4.Text = kelvin.ToString();
                }
                else if (satuan.Equals("3"))
                {
                    awal = Convert.ToDouble(textbox.Text);
                    celcius = awal - 273;
                    textbox1.Text = celcius.ToString();
                    reamur = 0.8 * (awal - 273);
                    textbox2.Text = reamur.ToString();
                    fahrenheit = (1.8 * (awal - 273)) + 32;
                    textbox3.Text = fahrenheit.ToString();
                    kelvin = awal;
                    textbox4.Text = kelvin.ToString();
                }
        }
    }
}

A: It seems there is a problem with:

String satuan = ComboBox.GetIsSelectionActive(combobox).ToString();

The Selector.GetIsSelectionActive method gets a value that indicates whether the specified Selector has the focus. And it returns the value is bool type. The Selector.GetIsSelectionActive always return false. Because it has lost focus when you click the button. So the satuan.Equals("0") always returns false too.
You can use Selector.SelectedIndex to get the index of the selected item. Then you can use the index to case the numbers.
For example:
private void button_Click(object sender, RoutedEventArgs e)
{
    string satuan=combobox.SelectedIndex.ToString();
    switch (satuan)
    {
        case "0":
            //To do
            break;
        case "1":
            //To do
            break;
        case "2":
            //To do
            break;
        case "3":
            //To do
            break;
    }
}