text:
Q: React Native: Execution failed for task ':app:checkDebugDuplicateClasses' I am getting the next error appearing on running npx react-native run-android. It came out of nowhere  - no changes have been committed.
Execution failed for task ':app:checkDebugDuplicateClasses'.
A failure occurred while executing com.android.build.gradle.internal.tasks.CheckDuplicatesRunnable

Duplicate class kotlin.collections.jdk8.CollectionsJDK8Kt found in modules jetified-kotlin-stdlib-1.8.0 (org.jetbrains.kotlin:kotlin-stdlib:1.8.0) and jetified-kotlin-stdlib-jdk8-1.7.20 (org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.7.20)

Duplicate class kotlin.internal.jdk7.JDK7PlatformImplementations found in modules jetified-kotlin-stdlib-1.8.0 (org.jetbrains.kotlin:kotlin-stdlib:1.8.0) and jetified-kotlin-stdlib-jdk7-1.7.20 (org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.7.20)

Duplicate class kotlin.internal.jdk7.JDK7PlatformImplementations$ReflectSdkVersion found in modules jetified-kotlin-stdlib-1.8.0 (org.jetbrains.kotlin:kotlin-stdlib:1.8.0) and jetified-kotlin-stdlib-jdk7-1.7.20 (org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.7.20)

Duplicate class kotlin.internal.jdk8.JDK8PlatformImplementations found in modules jetified-kotlin-stdlib-1.8.0 (org.jetbrains.kotlin:kotlin-stdlib:1.8.0) and jetified-kotlin-stdlib-jdk8-1.7.20 (org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.7.20)

Duplicate class kotlin.internal.jdk8.JDK8PlatformImplementations$ReflectSdkVersion found in modules jetified-kotlin-stdlib-1.8.0 (org.jetbrains.kotlin:kotlin-stdlib:1.8.0) and jetified-kotlin-stdlib-jdk8-1.7.20 (org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.7.20)

What I tried:

*

*Follow again the installation steps on official react native documentation page: https://reactnative.dev/docs/environment-setup
 brew install node
 brew install watchman
 brew tap homebrew/cask-versions
 brew install --cask zulu11

*Uninstall and install Android Studio

*Set kotlinVersion = "1.8.0" in android/build.gradle:
 buildToolsVersion = "32.0.0"
 minSdkVersion = 21
 compileSdkVersion = 33
 targetSdkVersion = 33
 // here
 kotlinVersion = "1.8.0"

It looks like if I get rid of "react-native-inappbrowser-reborn": "^3.7.0" library the error is gone and the app launches successfully. But what if I need react-native-inappbrowser-reborn in my project?
Thank you mates in advance!

A: This is caused by the Kotlin plugin update. You can fix it easily by using configure below:
dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    //noinspection GradleDynamicVersion
    implementation "com.facebook.react:react-native:+"  // From node_modules
    implementation 'com.android.support:multidex:2.0.1'
    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"

    // Add this line here
    implementation platform('org.jetbrains.kotlin:kotlin-bom:1.8.0')

    //...omit some code
}

You can refer this one: Kotlin Document

A: Add this to android/app/build.gradle
configurations.all {
resolutionStrategy {
    eachDependency {
        if ((requested.group == "org.jetbrains.kotlin") && (requested.name.startsWith("kotlin-stdlib"))) {
            useVersion("1.6.10")
        }
    }
}

}

A: For me, it was a combination of the react-native-iap and the react-native-onesignal packages that was causing the issue.
Upgrading react-native-onesignal didn't work, so I upgraded react-native-iap as far as I could go without breaking changes, and for me, that was v7.5.6.
After upgrading iap to 7.5.6, I also had to add this to my ../android/app/build.gradle file for it to compile:
defaultConfig {
    ...
    missingDimensionStrategy 'store', 'play'
}

Edit: I think what's happening is that one of your packages has a loose dependency, which caused an unexpected update. So each case could be different.

A: In your android/app/build.gradle file set kotlin-stdlib to use the same verion
for example:
configurations.all {
    resolutionStrategy {
        eachDependency {
            if ((requested.group == "org.jetbrains.kotlin") && (requested.name.startsWith("kotlin-stdlib"))) {
                useVersion("1.7.20")
            }
        }
    }
}


text:
Q: PHP: Maximum amount of uploadable files, $_FILES maxed out at 25 entries I have a rather old page, where a lot of file upload input fields reside. The problem is, only the first 25 upload field's data gets populated after the post.
I'm using nginx+php5.3-fpm
max_file_uploads is set to 200, so that can't be the problem. There are also a lot of other input fields besides the file inputs, and they arrive just fine, all of them.
Any ideas, where should I look?

A: I GOT IT! It was suhosin's own restriction in effect:
suhosin.upload.max_uploads is set to 25

redpajama_set_name: RedPajamaStackExchange


text:
Q: send javascript variable into html selector I'm trying to send my variable: username into my selector (display username in my selector) and send my variable userid as value in my selector.
Can you help me ? Here is my code :
<select id="mySecond" name="continent">
    <option value="">-----------------</option>
    <option  value="">-----------------</option>
    </select>

<script>

function displayuser() {
    var x = document.getElementById("mySelect").value;
    document.getElementById("demo").innerHTML = "Mon id: " + x;

  $.ajax({
      url: "https://cubber.zendesk.com/api/v2/organizations/"+x+"/users.json",
      type: 'GET',
      dataType: 'json',
            contentType:'application/json',
            secure: true,
            beforeSend: function (xhr) {
                xhr.setRequestHeader ("Authorization", "Basic " + btoa("claire.pagniez@cubber.com"));
            },
            success: function (data){
                for (i = 0; i < data.users.length; i++) {
                console.log(data.users[i].name);
                var username = data.users[i].name;
                console.log(data.users[i].id);
                var userid = data.users[i].id;
                }
            },
  });
}

</script>

A: try this:
success: function (data)  {
  $.each(data, function(){
        $("#mySecond").append('<option value="'+ this.userid +'">'+ this.username +'</option>')
   })
}


text:
Q: Passing RadioButton Value to Controller I am trying to pass a radiobutton value to a controller. However I cannot seem to figure out how to get the value I pass through. I am not sure what to do with the controller.
Model that I use to keep the value
public class PendingTasksModel
{
    public string environmentName { get; set; }
}

View

             @Html.RadioButtonFor(model => model.environmentName, "OAK")
             OAK

             @Html.RadioButtonFor(model => model.environmentName, "QA")
             QA

             @Html.RadioButtonFor(model => model.environmentName, "PROD")
             PROD

Controller
public ActionResult InitializeService(PendingTaskModel model)
    {
        _binding = new BasicHttpBinding();
        if (model.environmentName == "OAK")
        {
            _endpointAddress = new EndpointAddress(ConfigurationManager.AppSettings["OAK"]);
        }
        else if (model.environmentName == "PROD")
        {
            _binding.Security.Mode = BasicHttpSecurityMode.Transport;
            _endpointAddress = new EndpointAddress(ConfigurationManager.AppSettings["PROD"]);
        }
        else
        {
            _binding.Security.Mode = BasicHttpSecurityMode.Transport;
            _endpointAddress = new EndpointAddress(ConfigurationManager.AppSettings["QA"]);
        }
        _channel = new ChannelFactory<IEisIntegrationService>(_binding, _endpointAddress);

        try
        {
            _target = _channel.CreateChannel();

        }
        catch
        {
            if (_target != null)
            {
                ((ICommunicationObject)_target).Abort();
            }
        }
        return View();
    }

A: In order for the MVC infrastructure to automatically wire up form fields to your controllers, you need to ensure that your parameter names and types match up.  Try changing your string option parameter to PendingTasksModel model and then check model.environmentName in your if statements.  Alternately, change string option to string environmentName


text:
Q: Does modifying my weapon view to left-handed change how other players see me? Does setting my weapon view in Valve's first-person shooter game Counter-Strike: Source to "left-handed"(in first person it puts your weapon on the left side of the screen) change how other players see me? Will it change how my gun is held in third person mode? Is it only clientside?

A: No it does not change how others see you.
However, it will change everyone for you.
If you're viewing yourself as left handed, you'll also see everyone else as left handed.
It works the same way for right handedness, everyone else will see you as they see themselves.
The 3rd person character model does not change at all either way.

A: Changing to 'left-handed' does not affect the character model. Your gun will still appear to be held in the right hand.


text:
Q: How to stop SSAS cube processing programatically? We are using Microsoft.AnalysisServices library to access our SSAS database (on SQL Server 2014) and programatically process cubes.
The code looks like this:
using (var server = new Server())
{
    server.Connect("someserver");

    if (server.Connected)
    {
        var db = server.Databases.FindByName("somedb");

        if (db != null)
        {
            db.Process(ProcessType.ProcessFull);
        }
    }
}

The problem is, full cube processing may take a long time (in our case over 1h). And we need a way to gracefully stop/cancel it if necessary (the code above is a part of complex Windows Service that sometimes needs to be restarted).
It is completely acceptable that interrupting the task results in cube not being processed.
Is there a way to write the code above so it is non-blocking? Or pass a callback somehow? I could not find anything relevant in MSDN documentation:
https://msdn.microsoft.com/en-us/library/microsoft.analysisservices.database.aspx

A: Can you try getting rid of the using block and making your serverobject a class level member. Then try this on the cancel thread:
server.CancelSession(server.SessionID);


text:
Q: how to check if an input date is a business end of month I have a code asks the user to input a date:
date_entry = input('Inserisci la data di fine mese del lancio del MAI in formato DD-MM-YYYY: ')
year, month, day = map(int, date_entry.split('-'))
date1 = pd.to_datetime(pd.Series(datetime.date(day, month, year)))

then I have to check if that date is a business end of month, if yes the code continues if not it exists.
I tried this:
if date1 == BMonthEnd():
    pass
else:
    print("Ricontrolla: " + str(date1) + " non è un fine mese")
    exit(0)

here I get the error as if I input 29-05-2020 the code exit even if this date is a business end of month (its a friday). Thanks. Luigi

A: you could use the rollforwardmethod to check if you get the same date returned as date1:
import pandas as pd

date1 = pd.to_datetime('28-05-2020', dayfirst=True)

bm_end = pd.tseries.offsets.BMonthEnd()

if date1 == bm_end.rollforward(date1):
    pass
else:
    print("Ricontrolla: " + str(date1) + " non è un fine mese")

# prints
# Ricontrolla: 2020-05-28 00:00:00 non è un fine mese


text:
Q: How to initialize a generic element to an arbitrary value? I have a piece of code with the structure
template <typename T>
{
    // ...
    T t;
    if (foo(t)) // foo is of the form bool foo(T &)
    {
       // ...
    }
    // ....
}

and Visual Studio is angry because it thinks t needs to be initialized for the function foo to work (which isn't true). Is there some way I can initialize a generic element?

A: You can write T t{}; in C++11.


text:
Q: DataNitro - copying from the shell into an editor I'm using DataNitro and would like to be able to copy output from the Excel Shell and paste into my editor. However, I can't find a way to do that. Any idea how I might do that?

A: Right click in the shell, click "mark", highlight the region you want to copy, and press enter. It'll then be in your clipboard and you can paste it into an editor.
(This is the way to copy things from a windows command prompt in general, which is where the shell is running.)


text:
Q: connection with LDAP Server using java swing application I am trying to make a tool in swing for end user to use some specific web services..!! but got stucked in first phase..User authentication !! I want to authenticate the user with LDAP ..Please provide some efficient code snippet or Idea that i can authenticate my user for furthure processing. i have been working with swings only so still no idea of JNDI and LDAP. trying to get an idea about LDAP and JNDI ..but time is most important concern. plz give it a thought.
Thanks in advance !!

A: You can try Apache Shiro, an application security framework that can handle LDAP.


text:
Q: How to divide data into chunks where the first chunk is large but the rest of data divided as equally same size of chunks? I want to split the data into chunks where the first chunk is large and then comes the rest of the data after taking the first chunk which is divided into equal sizes of chunks
here is my code:
def chunk_data(dataset, size=10):
    if size > len(dataset):
          raise TypeError("size must be less than length of dataset")

    rest = []
    half_size = size // 2
    first_chunk = dataset[: half_size]
    rest_data = len(dataset) - len(first_chunk)
    num_chunks = rest_data // half_size

    for i in range(num_chunks):
          rest.append(dataset[i * half_size:(i + 1) * half_size])
    return rest

how can I modify it to do this

A: You should create a rest_data variable then can apply numpy.array_split(). You can then merge first large chunk with the rest as follows:
Code:
import numpy as np

def chunk_data(dataset, chunk_counts=10):
    len_dataset = len(dataset)
    if chunk_counts > len_dataset:
        raise TypeError("chunk_counts must be less than length of dataset")

    half_size = len_dataset // 2
    first_chunk = [dataset[: half_size].tolist()]
    rest_data = dataset[half_size:]
    rest_chunks_np = np.array_split(rest_data, chunk_counts-1)
    rest_chunks = [arr.tolist() for arr in rest_chunks_np]
    return first_chunk + rest_chunks

if __name__ == '__main__':
    data = np.random.randint(2, size=1000)
    chunks = chunk_data(data)
    print(f"[main] # chunks: {len(chunks)}")
    for chunk_id, chunk in enumerate(chunks):
        print(f"[main] # items in chunk-{chunk_id}: {len(chunk)}")

Result:
[main] # chunks: 10
[main] # items in chunk-0: 500
[main] # items in chunk-1: 56
[main] # items in chunk-2: 56
[main] # items in chunk-3: 56
[main] # items in chunk-4: 56
[main] # items in chunk-5: 56
[main] # items in chunk-6: 55
[main] # items in chunk-7: 55
[main] # items in chunk-8: 55
[main] # items in chunk-9: 55

A: As stated in the comments, you can use np.split() for this:
x = np.random.randint(0, 9, (12, 5))

num_chunks = 3
first_half, second_half = np.split(x, 2)
chunks = np.split(second_half, num_chunks)

If you don't want the first partition to be exactly half, then use slicing:
n = 8  # size of largest chunk

large_chunk = x[:n]
small_chunks = np.split(x[n:], num_chunks)


text:
Q: Making Google-Translate plugin not track visitors unless they ask it to I want to implement GoogleTranslate plugin on my personal website. However, I don't want Google to be able to track all visitors of my site, through their script; unless my visitors decide to use that functionality.
I include Google's code below, as I am supposed to paste it in the body of my page:

I would appreciate to have specific code to use, not just an explanation. Basically, I want Google's script to load only when a visitor decides s/he wants to use it and actually clicks on it.

A: This code below will not load the script from Google's servers until the "Load Google Translate" button is pressed.

      <button onclick="window.loadGoogleTranslate()">Load Google Translate</button>

You can verify that the Google script is not loaded until the button is clicked by watching network traffic (in the "Network" tab of Chrome's DevTools for example).
Note you can also just create a link like this one that users can click on to access a translated version of your page, no fancy Javascript required:
https://translate.google.com/translate?hl=&sl=en&tl=ar&u=https%3A%2F%2Fstackoverflow.com%2Fq%2F55643969%2F3063273
I bolded the parts you'll need to worry about:

*

*en is the "from" language (English in this case)

*ar is the "to" language (Arabic in this case)

*long string of text is the URL-encoded form of the page to translate. Google "URL encode" if you want to learn how to do that. Javascript has a built-in function that might help

P.S. You probably got a downvote from someone because they don't like "write-my-code" types of questions. If you had instead included a minimal, complete, and verifiable example (MCVE) then you probably wouldn't have been downvoted, but creating an MCVE can be really difficult if you have no idea where to even start. Here's some additional reading on that subject if you want to learn more about the culture around here: https://meta.stackoverflow.com/a/345249/3063273
P.P.S. If you want to use the above fancy-pants Javascript code, keep in mind that you can't use it in an iframe. If you don't know what an iframe is then don't worry about this.


text:
Q: Kivy Python FileChooser() I want to make a filechooser button, which will choose a image file an display it on the window to classify the image.
I just made an image recognition in kivy python, but want to add a button where user can choose a image file from there own system.
Please help me, in adding the filechooser button in this below code:
main.py file:
import kivy.app
import Fruits
from kivy.uix.popup import Popup
from kivy.uix.tabbedpanel import TabbedPanel
from kivy.properties import ObjectProperty, StringProperty
from kivy.lang import Builder

class FirstApp(kivy.app.App):
    def classify_image(self):
        img_path = self.root.ids["img"].source

        img_features = Fruits.extract_features(img_path)

        predicted_class = Fruits.predict_output("c:\\Users\\aakip\\Documents\\Python\\face_recognition school project\\weights.npy", img_features, activation="sigmoid")

        self.root.ids["label"].text = "Predicted Class : " + predicted_class

if __name__ == "__main__":

    firstApp = FirstApp(title="Fruits 360 Recognition.")
    firstApp.run()

Fruits.py:
import numpy
import PIL.Image

def sigmoid(inpt):
    return 1.0/(1.0+numpy.exp(-1*inpt))

def relu(inpt):
    result = inpt
    result[inpt<0] = 0
    return result

def predict_output(weights_mat_path, data_inputs, activation="relu"):
    weights_mat = numpy.load(weights_mat_path,allow_pickle=True) #allow_pickle=True
    r1 = data_inputs
    for curr_weights in weights_mat:
        r1 = numpy.matmul(r1, curr_weights)
        if activation == "relu":
            r1 = relu(r1)
        elif activation == "sigmoid":
            r1 = sigmoid(r1)
    r1 = r1[0, :]
    predicted_label = numpy.where(r1 == numpy.max(r1))[0][0]
    class_labels = ["Apple", "Raspberry", "Mango", "Lemon"]
    predicted_class = class_labels[predicted_label]
    return predicted_class

def extract_features(img_path):
    im = PIL.Image.open(img_path).convert("HSV")
    fruit_data_hsv = numpy.asarray(im, dtype=numpy.uint8)

    indices = numpy.load(file="c:\\Users\\aakip\\Documents\\Python\\face_recognition school project\\indices.npy")
    #indices  = numpy.load(file="indices.npy")

    hist = numpy.histogram(a=fruit_data_hsv[:, :, 0], bins=360)
    im_features = hist[0][indices]
    img_features = numpy.zeros(shape=(1, im_features.size))
    img_features[0, :] = im_features[:im_features.size]
    return img_features

.kv file:
#:kivy 1.10.0
BoxLayout:
    orientation: "vertical"
    Label:
        text: "Predicted Class Appears Here."
        font_size: 30
        id: label
    BoxLayout:
        orientation: "horizontal"
        Image:
            source: "apple.jpeg"
            id: img
    Button:
        text: "Classify Image."
        font_size: 30
        on_press: app.classify_image()

<FileChoosePopup>:
    title: "Choose a .jpeg File"
    size_hint: .9, .9
    auto_dismiss: False

    BoxLayout:
        orientation: "vertical"
        FileChooser:
            id: filechooser
            FileChooserIconLayout

        BoxLayout:
            size_hint: (1, 0.1)
            pos_hint: {'center_x': .5, 'center_y': .5}
            spacing: 20
            Button:
                text: "Cancel"
                on_release: root.dismiss()
            Button:
                text: "Load"
                on_release: root.load(filechooser.selection)
                id: ldbtn
                disabled: True if filechooser.selection==[] else False

THANK YOU!

A: did you try to check the Kivi documentation? https://kivy.org/doc/stable/api-kivy.uix.filechooser.html
I believe this is part you are looking for.
class Root(FloatLayout):
    loadfile = ObjectProperty(None)
    def show_load(self):
        content = LoadDialog(load=self.load, cancel=self.dismiss_popup)
        self._popup = Popup(title="Load file", content=content,
                            size_hint=(0.9, 0.9))
        self._popup.open()
    def load(self, path, filename):
            with open(os.path.join(path, filename[0])) as stream:
                self.text_input.text = stream.read()

            self.dismiss_popup()


text:
Q: JSP/XML : XML parse error - invalid XML I'm using Apache Tomcat 7.0.39, Eclipse Java EE Juno, Java JRE 7 & Java JDK 1.7.0_13.
I have a problem with the XML, a parse error :
Error: Invalid XML:
<?xml version="1.0" encoding="utf-8"?>
   <data>
       <time>9</time>
       <instances>3</instances>
   </data>

My purpose is to get some information from a database and put them in a Google Chart.
There is my code :
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.*" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.DriverManager" %>
<%
String idData = request.getParameter("idData");
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testcd","root","");

if(conn != null)
{
    Statement stmt = conn.createStatement();
    stmt.execute("SELECT Id,number FROM numberInstances WHERE ID='"+ idData +"'");
    ResultSet rs = stmt.getResultSet();
    out.println("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
    out.setContentType("text/xml");
    out.println("<data>");
    while(rs.next())
    {
        out.println("<time>" + rs.getString(1) + "</time>");
        out.println("<instances>" + rs.getInt(2) + "</instances>");
    }
    out.println("</data>");

    conn.close();
}
%>

Can someone help me? I have this problem since yesterday and all the information I got from my researches on Google didn't help
If you need more information, please ask me

A: Finally, I changed my code to use text response instead of xml response.
JSP code to get the data :
Statement stmt = conn.createStatement();
stmt.execute("SELECT number FROM numberInstances WHERE ID='"+ idData +"'");
ResultSet rs = stmt.getResultSet();
while(rs.next())
{
    out.println(rs.getInt(1));
}
conn.close();

And the JSP code to get the response :
$.ajax({
type: "GET",
url: "resources/jsp/getInstances.jsp",
data: {idData:(cptData)},
dataType: "text",
complete: function(text)
{
    instance = text.responseText*(1010);
}
});


text:
Q: Running OpenOffice as a Daemontools service not picking up the user My problem is that, when started with Daemontools, files created by OpenOffice (which runs in server mode) are owned by root (and in the root group). When I start the Daemontools 'run' script manually, OpenOffice correctly creates file with the permissions I want (i.e. the 'oinstall' group in this case).
I have a unix user called 'oracle' who is a member of a group 'oinstall'. The oracle user is able to start/stop OpenOffice server, which is controlled by a Daemontools service. The permissions on the service look like this:
[oracle@try1 pdf]$ ls -l /service/
drwxrwsr-x 3 root oinstall 4096 Dec  3  2012 OpenOfficePROD

[oracle@try1 pdf]$ ls -l /service/OpenOfficePROD/
-r--rws--- 1 root oinstall  175 Dec  3  2012 run
drwxrws--- 2 root oinstall 4096 Sep  2 15:31 supervise

[oracle@try1 pdf]$ ls -l /service/OpenOfficePROD/supervise/
prw-rws--- 1 root oinstall  0 Sep  2 15:31 control
-rw-rws--- 1 root oinstall  0 Sep  4  2012 lock
prw-rws--- 1 root oinstall  0 Sep  4  2012 ok
-rw-r--r-- 1 root oinstall 18 Sep  2 15:31 status

When I manually start OpenOffice server, by running the 'run' script as the oracle user, I get files generated with the desired permissions e.g.

-rw-r----- 1 oracle oinstall 20956 Sep  2 15:48 myfile.pdf

But when I use daemontools to start the OpenOffice server (even as the Oracle user), the files get created like this:

-rw-r----- 1 root root 20956 Sep  2 15:28 myfile.pdf

Here is my run script:
#!/bin/sh

exec 2>&1
export HOME=/home/oracle
exec /usr/bin/soffice -invisible -nologo -headless -nofirststartwizard -accept="socket,port=8099;urp;StarOffice.ServiceManager"

A: You might want to use setuidgid in the /service/OpenOfficePROD/run script to have daemontools start your service as the correct user.
#!/bin/sh
exec 2>&1
export HOME=/home/oracle
exec setuidgid oracle /usr/bin/soffice -invisible -nologo -headless -nofirststartwizard -accept="socket,port=8099;urp;StarOffice.ServiceManager


text:
Q: Get the total number of group names where there are multiple group names in a single cell surrounded by random text This is regarding an export of a list from a Sharepoint site where I do not have access to exporting feature, but I can refresh the information in order to gather new information when is added on the Sharepoint site.
The excel list has several columns, out of which one of them is containing names of groups that were created.
There are several thousands of rows, with cells where each cell might contain this kind of data.
I want to be able to only count the number of groups in my excel sheet.
I was initially thinking to find a way to export somehow the data as text and to then try to remove any parts in the string BEFORE the rows (again, all these rows are in the same cell) in order to make the data uniform and to have only the name of the groups and then to try count in a different column the number of items in each cell and to have a sum.
"Please delete following CORP group:

PRD.12.SYOS.EXOA.XW12LAPP0171.TWSUSERS
PRD.12.SYOS.XW12LAPP0171.Administrators
PRD.12.SYOS.EXOA.XW12LAPP0063.TWSAGENT
PRD.12.SYOS.EXOA.XW12LAPP0063.TWSUSERS
PRD.12.SYOS.VM4P.XW12LAPP0063.ADMINISTRATORS
PRD.12.SYOS.VM4P.XW12LAPP0063.RDP
PRD.12.SYOS.XW12LAPP0063.Administrators"

I am a beginner in excel and in coding. I tried using functions in excel like RIGHT, LEFT, MID, LEN but I am still unable to produce anything close to what I need.
I need the total number of the groups in the sheet.

A: with a helper column you could extract the part after the last dot with
=MID(A1,LOOKUP(9^9,FIND(".",A1,ROW(1:999)))+1,50)

and then count the number of unique group names, which occur with
=SUMPRODUCT((E1:E99<>"")/COUNTIF(E1:E99,E1:E99&""))

Be aware of the fact, that each Administrators and Administrators" get counted as a unique group. You need to strip off unnecessary chars with SUBSTITUTE if you dont want that behaviour.

A: When your list doesn't have doublures you could use a rather simple formula like:
=LEN(A1)-LEN(SUBSTITUTE(A1,CHR(10),""))-1

It would also be a nice issue to use REGEX on, like so for example:
Function CountGroup(RNG As Range) As Double

Dim regex As Object
Set regex = CreateObject("VBScript.RegExp")
With regex
    .Pattern = "(?=.*\d)[^\n " & Chr(34) & "]+"
    .Global = True
End With
Set Matches = regex.Execute(RNG.Value)
CountGroup = Matches.Count

End Function

Or when your list can contain doublures:
Function CountGroup(RNG As Range) As Double

Dim regex As Object, ARR1() As String, X As Long, ARR2() As String
Set regex = CreateObject("VBScript.RegExp")
With regex
    .Pattern = "(?=.*\d)[^\n " & Chr(34) & "]+"
    .Global = True
End With
Set matches = regex.Execute(RNG.Value)
ReDim ARR1(X)
For Each HIT In matches
    ARR2 = Filter(SourceArray:=ARR1, Match:=HIT.Value, Include:=True, Compare:=vbTextCompare)
    If UBound(ARR2) = -1 Then
        ReDim Preserve ARR1(X)
        ARR1(X) = HIT.Value
        X = X + 1
    End If
Next HIT

If IsEmpty(ARR1) Then
    CountGroup = 0
Else
    CountGroup = UBound(ARR1) - LBound(ARR1)
End If

End Function

Call in sheet through =CountGroup(A1)


text: Q: You have 6 green chips, 6 black, and 6 yellow. You randomly select a sample of 3 chips without replacement. You have 6 green chips, 6 black, and 6 yellow. You randomly select a sample of 3 chips without replacement. What is the probability that the sample contains at least one chip of each color?


text:
Q: How do I abstract a WHERE clause condition? I'm wondering how a condition in a commonly used WHERE clause can be abstracted away so that it can be safely changed.
Say I have data like
ColA | ColB | ColC
==================
  1  |   2  | ABC
  1  |   3  | ABD
  1  |   4  | ABE
  2  |   2  | ACC
  3  |   2  | ACD
  4  |   2  | ACE

I have an example query something like
SELECT ColA, ColB FROM MyTable WHERE ColC LIKE 'AB%'

This clause appears in many selections of varying complexity.
The problem I have is that the ColC codes are going to be changed incrementally into different values, e.g. ABE may be changed to ZBE.Throughout this period, the existing query results have to remain the same - i.e. ABC, ABD and ABE would have to become ABC, ABD and ZBE. Then ABD may change to ZBF and so on. Oh, and the database must have minimal down-time.
My gut instinct would be to change all occurrences of this clause into a function now when time-pressure is low, so that when data starts being transformed, I can change that function into whatever hideous thing it needs to be without having to worry about making lots of complex, messy changes quickly.
However, I've been reading up and come across many recommendations that I shouldn't be doing this as it will be inefficient (which I can totally see).
So, what would be the best way to do this? If I have to accept a period of inefficiency during this transition period, then so be it, but I'd rather not.
Thanks.

A: OK 5 years later, here's a possible solution.
If this is your database and you are allowed to change its structure, I would

*

*Create 2 new fields; OldC and NewC.

*Update all OldC values with the value of ColC.

*When ready to calculate, update all NewC values with the new value.

*When ready to migrate, update all ColC with NewC.

If during this time, you need to know whether ColC is the old or new value, compare it to the 2 new fields.


text:
Q: Iframe não respeita max-width O iframe fica responsivo e funciona perfeitamente quando o faço em protótipo. Porém nesse caso não sei por que ele não obedece o max-width de seu nó pai. Ele sempre fica bem menor do que o espaço que eu libero para ele em max-width de seu nó pai.
Eu queria que ele fosse responsivo e preenche-se o nó pai(#contatoendereco) inteiro o quanto puder.
Obs: reparei que sempre que retiro o nó avó(#containercontato) ele funciona! não sei porque.
edit: quando digo iframe, assume-se erradamente que é o #map-resposive(iframe encapsulado).
-------JSFiddle-------

#containercontato {
    display: flex;
    flex-flow: row wrap;
    width: 100%;
}

#contatoendereco {
    display: flex;
    flex-flow: column;
    max-width: 600px;
    border: 1px solid;
}

#map-responsive {
    width: 100%;
    height: 100%;
    border: 1px solid black;
}

#map-responsive iframe {
    height: 100%;
    width: 100%;
}

Endereço

Av. Bernardino de Campos,

98

São Paulo,

SP 12345-678

info@meusite.com


text:
Q: Complexity of specific function So I need to analyze the complexity of this function and express it as a function of "x" and "epsilon". I tried to express it through a log with base epsiolon and x as parameter but to no avail.
double exhaustiveSquareRoot(double x, double epsilon)
{
    double result, step;
    step = epsilon * epsilon;
    result = 0.0;

    while (abs(result*result - x) > epsilon && result < x)
        result += result+step;

    return result;
}


text:
Q: Magento 2.4.4 / MACOS 10.13 High Sierra / MAMP - Could not validate a connection to Elasticsearch. No alive nodes found in your cluster now when I fixed the MySQL problem with Magento 2 and MAMP I got a new problem trying to install Magento 2 via the command line
The command I run for installation
php -d memory_limit=-1 bin/magento setup:install \
--base-url=http://localhost/magento2_learning_codilar \
--db-host=localhost \
--db-name=magento2_learning_codilar \
--db-user=root \
--db-password=root \
--admin-firstname=Stefan \
--admin-lastname=Momcilovic \
--admin-email=office@stefan-momcilovic.com \
--admin-user=admin \
--admin-password=admin123 \
--language=en_US \
--currency=USD \
--timezone=Europe/Belgrade \
--use-rewrites=1 \
--elasticsearch-host=elasticsearch

And I get this

But I have got elastic search installed I checked with the command
curl -X GET 'http://127.0.0.1:9200'

And I get a response
{
  "name" : "Stefans-MacBook-Pro.local",
  "cluster_name" : "elasticsearch_stefanmomcilovic",
  "cluster_uuid" : "I06MWrU8TnSIacw9SGw3-A",
  "version" : {
    "number" : "7.17.4",
    "build_flavor" : "default",
    "build_type" : "tar",
    "build_hash" : "79878662c54c886ae89206c685d9f1051a9d6411",
    "build_date" : "2022-05-18T18:04:20.964345128Z",
    "build_snapshot" : false,
    "lucene_version" : "8.11.1",
    "minimum_wire_compatibility_version" : "6.8.0",
    "minimum_index_compatibility_version" : "6.0.0-beta1"
  },
  "tagline" : "You Know, for Search"
}

So now can someone explain to me what is the problem I also tried to run this command to disable elastic search and try installation again
php bin/magento module:disable {Magento_Elasticsearch,Magento_InventoryElasticsearch,Magento_Elasticsearch6,Magento_Elasticsearch7}

But I also got an error that the elastic search module isn't enabled and installation cannot proceed further.

So now can anyone help me fix this, what is the problem I don't understand?

A: I just tried to install it all over again Magento from composer delete this old one and now it works it installed successfully I don't know what is happening but ok now it works


text:
Q: Intelij Plugin Development add eventListener so when i press esc all line highlighters disappear I have this code
private static void highlightElement(int lineNum,Project project,VirtualFile virtualFile) {

    final FileEditorManager editorManager =
            FileEditorManager.getInstance(project);
    final Editor editor = editorManager.getSelectedTextEditor();
    final TextAttributes textattributes = new TextAttributes(null, new Color(239, 43, 18), null, EffectType.LINE_UNDERSCORE, Font.PLAIN);
    editor.getMarkupModel().addLineHighlighter(lineNum, HighlighterLayer.CARET_ROW, textattributes);
    editor.getMarkupModel().
    final WindowManager windowManager = WindowManager.getInstance();
    final StatusBar statusBar = windowManager.getStatusBar(project);
    statusBar.setInfo("Press Esc to remove highlighting");
}

The code works as intended but what i want is to attach an event listener so when i press esc the function  editor.getMarkupModel().removeAllHighlighters(); will be called.Thank you in advance!

A: Instead of adding your highlighters via MarkupModel.getLineHighlighter(), use HighlightManager.addRangeHighlight(). Then they will be removed automatically when the user presses Esc; you don't need to do anything extra.


text: Q: React Native DatePicker NativeBase - How to disable specific dates Is it possible to disable specific dates using the DatePicker of NativeBase in React Native? I looked in the docs, and only found that is possible to specify a minimumDate and minimumDate, but I'm trying to disable some dates in this interval. Thanks!


text:
Q: HTML Message Sender I am trying to make a button that will allow me to send a preset message to an email address. I don't want it to be a form, or an email tab that sends the message. I just want to be able to click a button, so that I can send this premade message. Is there any way that I could do that?

A: This may not be the exact answer you're look for, but an easy alternative would be:
Send Message

Make sure you replace spaces with %20

A: You can add an  tag with a mailto: href:

   Click here to email me

A: Yeah, but you're going to need some sort of backend, like Python, .NET, Rails, or PHP. When you click the button, it would have to be either a link or a form submit button that sends a request to some backend page that handles actually sending the email.
Each backend has its own specific way of doing this. You would need to specify which language you wish to use for anyone to provide further help.

A: You would need to write a serverside script to send the email. Your button could fire an AJAX request to the serverside script to send the email that way.
Unfortunately there is no way to send emails strictly using HTML or javascript (with Node being the exception).


text:
Q: Editing all day fullCalendar event converts it to a non allDay event When I edit an allDay event, fullCalendar (2.0.2) is converting it to a non-all day event. When the event is clicked in the calendar view, I load a modal which allows users to edit the details. Selecting allDay or time is not part of this, but date is. Upon clicking submit I fire an AJAX call which updates the event server-side then returns JSON data containing the event id. I then query fullCalendar to get the correct event. At this point allDay and _allDay are both still true:
theEvent = $('#calendar').fullCalendar('clientEvents', data.id)[0];
> theEvent.allDay
true
> theEvent._allDay
true

I then update fullCalendar with the edited event object:
calendar.fullCalendar('updateEvent', theEvent);

After the edit finishes, the event displays in the calendar with 12a displaying immediately before the event title.
I'm able to track it down to the mutateEvent function in the fullCalendar which appears to override my settings within the following conditional:
// current values are:
// event.allDay: true
// oldAllDay: true
// newStart: Moment object - Mon Jan 19 2015 00:00:00 GMT-0600 (CST)
// newEnd: null

// detect new allDay
if (event.allDay != oldAllDay) { // if value has changed, use it
    newAllDay = event.allDay;
} else { // otherwise, see if any of the new dates are allDay
    newAllDay = !(newStart || newEnd).hasTime();
}

I don't think I'm doing anything wrong, but I can't be sure. Anyone have input on this? Please and thanks. At this time I'm not able to upgrade to a more recent version as this version (2.0.2) appears to be somewhat tied in to the Ace Admin Bootstrap theme selected by my client.
Alternately, I'd love to be able to only allow allDay events so that I don't have to worry about this in the future.

A: While this doesn't truly solve the problem, this answer resolves my issue.
Simply set the fullCalendar timeFormat property to ''. In my case I only ever have all day events, so I'll never need a time.
http://fullcalendar.io/docs/text/timeFormat/
$('#calendar').fullCalendar({
    events: [
        {
            title:  'My Event',
            start:  '2010-01-01T14:30:00',
            allDay: false
        }
        // other events here...
    ],
    timeFormat: ''
});

A: This seems to be a bug that was fixed in a later version. The latest version does it differently.
What's happening is that it sets allDay=false when you change the start or end date and the changed date has a time. Problem reproduced here.
The solution is pretty simple, remove the time part of the start/end when the event is allday. It shouldn't be there anyway.
var fcEvent = $('#calendar').fullCalendar("clientEvents",id)[0]; //get the event

// Change the start date and turn it into a string, stripping off the time.
fcEvent.start = moment().format("YYYY-MM-DD");

$('#calendar').fullCalendar("updateEvent",fcEvent);

JSFiddle Demo
Make it conditional, if(fcEvent.allDay), and it should fix the problem without breaking other functionality.


text:
Q: UiTableView not scrolling to bottom with static table swift 3 I'm using a TableViewController with static tables cell and int not scrolling to the end. It scroll but not stay.

A: The problem was solved setting all flags in Autoresizing.


text:
Q: Editable Datatable RowKey Null I have an editable Primefaces Datatable configured to call an onCellEdit() method when a cell is edited. Everything works great except that CellEditEvent.rowKey is always null in spite of setting it explicitly to a valid value in the Datatable declaration with 'rowKey='. The Primefaces Datatable documentation leads me to believe that I need the rowKey to get the contents of the row containing the cell being edited. I need the entire row's contents so I can compare the displayed data with the same data in the database to determine if the persisted data had been changed by another client since the Datatable was rendered, catching concurrent edits.

A: After reading a dozen or more posts on the rowKey being null with row-selectable Datatables I finally realized that rowKey is populated on row select, not on cell edit. rowIndex, however, is not null on cell edit, and reliably gives me the row number (zero-based) so I can retrieve the entire row's contents, and the values of the object used to populate the row (which in my case includes the value I wanted to put into rowKey) from Datatable.getValue(). The purpose of rowKey is not clear in the documentation (to me), so I thought I would share this for anyone encountering a similar problem.

A: The root cause has been explained by @snakedog already. I will add the code for remedying the issue.
Here is the attribute that you should put within p:datatable:

selectionMode="single"

If you do not want the selection highlight to be seen visually, add disabledSelection="true" as well.


text:
Q: Multiple degree distribution on the same plot I generated 500 random bipartite networks using the code below. I would like to plot the degree distribution (log-log plots with power law line) of atleast 10 of these networks on a single plot to compare them with the log-log plot of my scale free network visually. I know how to plot the degree distribution of a single network at a time but multiple plots on the same graph is getting to be elusive.  Also if possible, I could also use an excel sheet with the pearson correlation coefficient and the slope values of all 500 networks. .
set.seed(1)
    gs1 <- list()
    for (x in seq_len(500L))
    {
      gs1[[x]] <- sample_bipartite(358, 27, type = "gnm",m = 827, directed = TRUE)
    }

EDIT: I am looking for a power law line with the degree distribution.
Any help is appreciated. Thank you to  you all.

A: I think that I am making the plot that you are looking for. If not please explain how it differs.
You can plot the first distribution and then add to it using lines. Because each distribution has a different number of degrees, I go through all of them once to find the upper limit.
library(igraph)

## Reproduce your data, paramterizing the number of graphs
NumG = 500L
set.seed(1)
gs1 <- list()
for (x in seq_len(NumG)) {
      gs1[[x]] <- sample_bipartite(358, 27, type = "gnm",m = 827, directed = TRUE)
}

## Find upper limit on degrees
MaxDeg = rep(0,NumG)
for(i in 1:NumG) {
    DD = degree_distribution(gs1[[i]])
    MaxDeg[i] = length(DD)
}
MaxMax = max(MaxDeg)

## Plot first distribution
plot(1:MaxDeg[1], degree_distribution(gs1[[1]]),
    xlim=c(1,MaxMax), log="xy", type="l",
    xlab="Log-Degree", ylab="LogFrequency")

## Plot all the rest
for(i in 2:NumG) {
    lines(1:MaxDeg[i], degree_distribution(gs1[[i]]), col=rainbow(NumG)[i])
}

You can see the two pieces for the two types of nodes. Overall,  these seem pretty consistent.
Adding a little detail
There are two different types of nodes. From your generating statement
gs1[[x]] <- sample_bipartite(358, 27, type = "gnm",m = 827, directed = TRUE)

there are 358 nodes that only have links leaving them (Sources). There are also 27 nodes that have no links leaving them (Sinks). Here is a plot of the first graph on your list, gs1[1].
LO = layout_as_bipartite(gs1[[1]])
plot(gs1[[1]], layout=LO, vertex.size=8,
    edge.arrow.size=0.3, vertex.label=NA)

The sources are on top and the sinks are on the bottom. The two types of nodes have quite distinct degree distributions. By construction, all of your graphs have 827 links. These leave the 358 sources and go to the 27 sinks. On average, each source will have 827/358 = 2.31 links. On average, the sinks will have
858/27 = 30.63 links. It is easy to see these two distinct distribution in the above degree distribution plot.
It does not appear to me that the degree distributions follow a power law,
neither with the sources and sinks together nor either one separately.
I am not sure what correlation coefficients you want to compute. So I have no help for you on those topics.


text:
Q: How to test a subject and observable return value in Angular Jasmine Spec? In Angular 9, I have a loader service like below.
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

export interface LoaderState {
  show: boolean;
}

@Injectable({
  providedIn: 'root'
})
export class LoaderService {

  private loaderSubject = new Subject<LoaderState>();

  loaderState = this.loaderSubject.asObservable();

  constructor() { }

  show() {
      this.loaderSubject.next({show: true} as LoaderState);
  }

  hide() {
      this.loaderSubject.next({show: false} as LoaderState);
  }
}

I want to test the show() and hide() methods. For that, I have written a spec like below.
it('should show', (done) => {
      spyOn(loaderService, 'show').and.callThrough();
      loaderService.show();
      expect(loaderService.show).toHaveBeenCalled();
      loaderService.loaderState.subscribe((state) => {
          expect(state).toBe({show: true});
          done();
      });
  });

But I get below error when I run this

Chrome 86.0.4240 (Windows 10.0.0) LoaderService should show FAILED
Error: Timeout - Async callback was not invoked within 5000ms (set by jasmine.DEFAULT_TIMEOUT_INTERVAL)

I have searched a lot before asking this question. But can not seem to find the right solution. I am new to Jasmin Unit testing. Any help is appreciated.
Edit: Posting complete spec file for reference.
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { LoaderComponent } from './loader.component';
import { LoaderService } from './loader.service';

describe('LoaderService', () => {
  let component: LoaderComponent;
  let fixture: ComponentFixture<LoaderComponent>;
  let loaderService: LoaderService;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ LoaderComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(LoaderComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    loaderService = TestBed.inject(LoaderService);
  });

  it('should be create', () => {
    expect(loaderService).toBeTruthy();
  });

  it('should show', (done) => {
      spyOn(loaderService, 'show').and.callThrough();
      loaderService.show();
      expect(loaderService.show).toHaveBeenCalled();
      loaderService.loaderState.subscribe((state) => {
          expect(state).toBe({show: true});
          done();
      });
  });
});

A: The problem is that you're calling subscribe after the actual method call. So when you call show(); there is nothing subscribed to that event, and since the done() callback is inside of it... it's never called.
it('should show', (done) => {
    service.loaderState.subscribe((state) => { //subscribe first
      expect(state).toEqual({show: true}); // change toEqual instead of toBe since you're comparing objects
      done();
      });

    spyOn(service, 'show').and.callThrough();
    service.show(); // invoke after
    expect(service.show).toHaveBeenCalled();
  });

A: Here's my solution to this pattern:
Service Class
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';

@Injectable({

  providedIn: 'root'

})

export class MyService {

  private myServiceEvent = new Subject<any>();

  constructor() { }

  success(): Observable<any> {
    return this.myServiceEvent.asObservable();
  }

  doSomething(someData: any): void {
    // stuff
    this.myServiceEvent.next(someData);
  }
}

Component that uses the service (the observable would be triggered by some other component or service calling the doSomething method on the service)
import { Component, OnInit } from '@angular/core';
import { MyService } from ./my-service.ts

@Component({
  selector: 'app-mycomponent',
  templateUrl: './app-mycomponent.component.html',
  styleUrls: ['./app-mycomponent.component.scss']
})
export class AppMyComponent implements OnInit {

    private test = '';

  constructor(
    private myService: MyService,
  ) {  }

  ngOnInit() {
    this.myService.success().subscribe(data => {
        test = data;
    });
  }
}

Spec that tests the component using the service's Observable response.  Note the construction of the service mock and how the Subject variable is used to trigger the Observable.
import { CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA } from '@angular/core';
import { waitForAsync, ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';
import { Observable, Subject } from 'rxjs';

import { AppMyComponent } from './app-my.component';
import { MyService } from ./my-service.ts

describe('AppMyComponent', () => {
  let component: AppMyComponent;
  let fixture: ComponentFixture<AppMyComponent>;

  const myServiceSubject = new Subject<any>();

  const myServiceMock = jasmine.createSpyObj('MyService', [], {
    success: () => myServiceSubject.asObservable()
  });

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      schemas: [ CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
      declarations: [ AppMyComponent ],
      providers: [
        { provide: MyService, useValue: myServiceMock }
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should execute subscription to MyService success event', fakeAsync(() => {
    myServiceSubject.next('somedata');
    tick();
    expect(componenet.test).toEqual('somedata');
  }));


text:
Q: My Python multi-module package won't distribute with a py.typed file I've created a package for Pip that contains multiple modules, which I am using for some other projects. On one of those projects, I recently added MyPy as Pylance was missing some potential errors, but when I import those modules, MyPy flags them as errors as they are missing a py.typed file. I have added one of these files to each submodule, so that the directory structure is as follows:
* MyRepo:
    * src
    |   * modulea
    |   |   * __init__.py
    |   |   * modulea.py
    |   |   * py.typed
    |   * moduleb
    |   |   * __init__.py
    |   |   * moduleb.py
    |   |   * py.typed
    * setup.cfg

I have also specified in setup.cfg to include package data, using the include_package_data = True flag.
[metadata]
# Other details

[options]
packages = find:
package_dir =
    =src
python_requires = >=3.9.1
include_package_data = True

[options.packages.find]
where = src

However when I distribute the package, it doesn't include any of the py.typed files. I have no idea why this is, and it's especially confusing considering that when I install it manually, using pip install -e ., I don't get any errors. I'd massively appreciate any help fixing this, as I am completely stumped.

A: I'm not 100% sure this is correct since I don't have the package in front of me but I'll take a crack at it.
I believe since py.typed is not a Python file, you need to specifically specify that you want to include it. For that, in your top level package, you need a MANIFEST.in. See the MANIFEST.in link for the default files that are normally included by default in a package distribution - py.typed is not in there. In the MANIFEST.in file, you would write a line such as:
global-include py.typed

I believe include_package_data being set to true causes the package manager to look at the MANIFEST.in for any additional files that need to be distributed that are not python files.
I might also consider including and init.py in the src directory, and then just having one py.typed file there.


text:
Q: ERROR: could not access file "$libdir/postgis-3": No such file or directory With postgres 10 in ubuntu I'm trying to open spatial data table and it is showing error:could not access file "$libdir/postgis-3": No such file or directory.
It is showing the same error while I'm taking backup of the Database


text:
Q: F# types with units of measure vs System.Math I defined my own unit of measure to represent radians:
[<Measure>]
type rad

Then I realized that having a value e.g. of type float<rad> I can't use many of the functions defined in System.Math (as they work with 'plain' floats)
let valueWithUnit = 5.45<rad>
let absValue = Math.Abs valueWithUnit // <--- error!!

I created a naive piece of code that allows functions to handle float<rad> values as well:
let liftToRadFunc (f : float -> float) (arg : float<rad>) =
    arg * 1.</rad>
    |> f
    |> (*) 1.<rad>

let result = (liftToRadFunc Math.Abs) valueWithUnit // <--- now works fine

but the problem with it is that it's totally non-generic. Assuming I'd like to introduce an unit to represent degrees as well - what then ? Would I need to copy the code and change all the units from "rad" to "deg" ? Or maybe there's a better solution ?

A: The core operators of F# are mostly unit-of-measure aware. For example, abs works with units of measure and renders System.Math.Abs redundant.
It is possible to generalize the function from the question in terms of the units used:
let liftToKeepUnits f (arg : float<'u>) : float<'u> =
    float arg |> f |> LanguagePrimitives.FloatWithMeasure

Though this simply keeps the units, which is only correct if the function has no effect on the units. So I'd use this lifting function to create specific, unit-aware functions, rather than lifting functions where they are used.
In my experience, the most useful tool is the ability to make types and functions generic in terms of units of measure. Type inference will not always do this on its own, but adding unit-of-measure type annotations will often do the trick. In more complicated cases, LanguagePrimitives.FloatWithMeasure and LanguagePrimitives.Float32WithMeasure allow, together with a type annotation, to add units where one would otherwise run into the constraint that forbids non-zero values with generic unit-of-measure arguments.
Also, types can have unit-of-measure arguments like this:
type MyType<[<Measure>] 'u> ...

When using all of these features, functions that aren't aware of units become the exception, and it's not a big problem to manually add or remove units in the remaining cases.


text:
Q: RxJava and long running listener Okay, so I am new to RxJava2 (well, I don't know RxJava either) and am trying to develop an Android app using RxJava2 and MVP structure.
In that app, I am making async calls to a library that uses listeners.
I set the listener using a "standard" setListener / registerListener method.
One of the method is returning values "realtime" -> I call the start() method of my library, and then will be notified on my listener at each modification of the list (when there is an add/remove of the items).
I don't really grasp how I can achieve this behavior using RxJava, as the listener is subscribed in the definition of the emitter / subscriber?
Where should I declare the listener ? Where should I unsubscribe ? What object should I be using?
I started the dev using Nucleus, but can switch to another boilerplate or do one myself.
Here is some pseudo-code illustrating my question:
Before
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...

    mMyLib.setListener(this);
    mMyLib.startDiscovery();
}

@Override
public void itemListChanged(List<Dummy> items) {
    // update the UI with the list items
}

@Override
protected void onDestroy() {
    super.onDestroy();
    mMyLib.setListener(null);
}

Using Nucleus, in my presenter
Where should I unsubscribe if I want to receive modifications of the list as long as my activity / presenter are alive? Am I even using the right syntax/ objects?
private static final int REQUEST_ITEMS = 1;
private PublishSubject<Integer> pageRequests = PublishSubject.create();

...

@Override
public void onCreate(Bundle savedState) {
    super.onCreate(savedState);

    restartableReplay(REQUEST_ITEMS,
            () -> Observable.create(e ->
                    {
                        mMyLib.setListener(new MyLib.Listener() {
                            @Override
                            public void itemListChanged(List<Dummy> items) {
                                Log.d(TAG, "meh itemListChanged");
                                e.onNext(items);
                                e.onComplete();
                            }
                        });
                        mMyLib.startDiscovery();
                    }
            )
            ,
            MainFragment::onItems,
            MainFragment::onNetworkError);
}

void request() {
    start(REQUEST_ITEMS);
}

A: You're in the right direction, this is a valid way to wrap the async callbacks with RxJava, few comments:

*

*Your'e calling e.onComplete() on itemListChanged, this is wrong, as it will end your Observable sequence, you might not need to call onComplete() at all, as it is never ending notifications from outer source, or call it once upon real end of notifications (outer source finish to produce items), do not confuse it with unsubscribing from source.

*For unsubscription logic to do something you should define it in your create(), call e.setCancellable() with your cancellation logic (mMyLib.setListener(null) or any additional clean up resources code)

*it's seems in this case that you have only 1 subscriber, but otherwise consider to use share(), to have a 'hot' Observable that can multicast to several subscribers.

*as for Nucleus library, as far as I remember restartableReplay, will cache your'e Observable and replay emitted items, this is might be wrong with this kind of 'hot' stream of events (unless you need to replay maybe last emission or something), additionally, cache will be problematic as you will lose unsubscription ability, so just be sure to use Nucleus right here.

Where should I unsubscribe if I want to receive modifications of the list as long as my activity / presenter are alive? Am I even using the right syntax/ objects?

You simply need to unsubscribe wherever you want to stop getting notifications, whether it is at onStop() or onDestory() depends is up to you.


text:
Q: Inflating layout from XML vs from Java code It is a well-known fact that inflating from XML requires accessing the disc, so it should be normally slower than inflating the UI layouts from Java code via creating View instances.
I was trying to find any ready solutions for generating Java layouts from XML but didn't find any. So I made my own measurements and to my big surprise I discovered that on fast devices (S6 and Nexus5 with Android 6.0) complex RelativeLayouts with nested elements are getting inflated even faster from XML, than from Java code!
Do you have any idea why this is happening?


text:
Q: Sql server Row to column pivot, known column names unknown row data values I've seen some posts on row to column pivots that require knowing 1) the possible values in the row to pivot, or 2) the number of values to pivot is the same for each pivot group. Here is my situation. I have a table that describes real property:
PARCEL     LEGAL                ACREAGE
1001       PORTION NW1/4        0
1001       AND SW1/2 38-9       0
1001       ACC. TO PLAT #882    320.00
1002       PORTION 38-10        320.00

The list of entries that correspond to a single distinct value of Parcel could be from 1 to 5. The last entry always has the actual acreage for that property, so I don't need the 0's. I want it to become like this:
PARCEL     LEGAL01              LEGAL02           LEGAL03              LEGAL04         LEGAL05          ACRES
1001       PORTION NW1/4        AND SW1/2 38-9    ACC. TO PLAT #882    <NULL>           <NULL>          320
1002       PORTION 38-10        <null>             <null>               <null>         <null>            320

Any insight is greatly appreciated.

A: Use Row_number
select *
from
(select parcel, legal,
        SUM(acreage) over (partition by parcel) acres,
        ROW_NUMBER() over (partition by parcel order by legal ) rn
 from yourtable) src
pivot (max(legal) for rn in ([1],[2],[3],[4],[5])) p


text:
Q: The difference between the two functions in Scala,the foreach cannot accumulate the outer Map I'm a fresh learner, I want to count the number of different words from a file.
This works fine
val filePath = "C:\\Users\\76274\\Desktop\\yaml.txt"
def exercise2(file:String): HashMap[String,Int] ={
  Source.fromFile(file).getLines().foldLeft(HashMap[String,Int]())(
  (result,str) =>
    str.split("\\W+").foldLeft(result)(
      (result,word) => result + (word.toLowerCase -> (result.getOrElse(word.toLowerCase,0) + 1))))
}

And this will return an empty Map
val filePath = "C:\\Users\\76274\\Desktop\\yaml.txt"
def exercise2(file:String): HashMap[String,Int] ={
Source.fromFile(file).getLines().foldLeft(HashMap[String,Int]()){
  (result,str) => {
    str.split("\\W+").foreach(word => {
    result + (word.toLowerCase -> (result.getOrElse(word.toLowerCase,0) + 1))
    println(result)
  })}
  result
}
}

I don't know why the later one doesn't work. As a Java programmer, I think it should work fine, too. I hope you can explain it, Thanks!

A: The reason why the second one does not work, is because the + method isn't really adding elements to the Map, but instead it is creating a new Map with the given element added/updated - scaladoc.
If you want the second one to work using a MUTABLE map, you can use the += method - scaladoc. BTW, if you're going for a mutable solution I wouldn't bother to use fold in the first level neither, but instead another foreach.
However, In Scala we prefer to be immutable, that's why we would go for the first one with an IMMUTABLE map.
PS: Not really related to this, but unless you really need it to be a HashMap, prefer the Map trait (which by default is immutable) or scala.collection.mutable.Map (which is mutable). Also to create an empty collection is more common to call the empty method, instead of an empty apply (). e.g Map.empty[String, Int].


text:
Q: Regular Expressions on array I am trying to edit the first entry in a array before it placed in another file.
This is it:
(["\"NAMES\":\"cs.js\"},[

I want to turn it into this:
([{"NAMES":"cs.js"},[

I'm using an online regex generator, but so far I've only managed to edit to this point with /.["[\]/ and substituting with ([{:
([{"NAMES\":\"cs.js\"},[

Any help given will be appreciated.
EDIT:
Here is some of the code:
var initialCourseArray = new Array()
initialCourseArray.push(["\"NAMES\":\"cs.js\"},[
{"COURSE_ID":"ENGL 1013"},
{"COURSE_ID":"FAH1"},
{"COURSE_ID":"USHG1"},
{"COURSE_ID":"TECH 1001"},
{"COURSE_ID":"COMS 1403"},
{"COURSE_ID":"COMS 1411"},
{"COURSE_ID":"ENGL 1023"},
{"COURSE_ID":"SS1"},
{"COURSE_ID":"MATH 2914"},

The stuff after is the rest of the values in the array and they do not look like this one so I'm not worried about them.
Second EDIT:
Since there is some confusion about the code that I honestly should have placed in here first, I am using a php file to retreive course data from a test database and then encoding it into JSON, formatting it, and then using fopen and fprintf to place it inside a javascript file. The part I'm giving you is what ends up inside the javascript file.
Third EDIT:
here is the code I am using to format the array. It is very messy because my leader keeps changing the format he wants the result to be in:
$row1 = "\"NAMES\"";
$colon = ":";
$row2 = "\"".$major.".js\"";
$major_name = $row1.$colon.$row2;

//The course data is already loaded into the table. This why I am using array_unshift to place the major_name inside.
array_unshift($major_array, $major_name);

array_push($major_array, "false");
$json_string = json_encode($major_array);

$re = "/.,/";
$subst = "},\r\n";
$json_string = preg_replace($re, $subst, $json_string);

$re2 = "/\,(?=[^.]*$)/";
$subst2 = ",[";
$json_string = preg_replace($re2, $subst2, $json_string, 1);

$first_string = "var initialCourseArray = new Array()";
$second_string = "initialCourseArray.push(";
$end_bracket = "]";
$end_parentheses =")";

A: If you just want to apply it to that line,
find /"?\\"/ and replace " will do it.

A: There are several issues:
1. Don't manipulate JSON strings
You should never manipulate a string that is the result of json_encode, because you will very likely make the JSON text invalid, which is actually happening in your case.
So using this kind of statements:
$json_string = preg_replace($re, $subst, $json_string);

is asking for trouble. Once you have a $json_string, it should be final. Anything you want to happen to the structure must happen before you call json_encode.
Even if you just want to add line breaks inside a JSON string, don't do it that way. json_code provides a "pretty print" option which will do it for you:
json_encode(...., JSON_PRETTY_PRINT);

2. JavaScript does not have associative arrays
A second problem is that in JavaScript you cannot have something like
["NAMES":"cs.js" ...]

So json_encode will never generate anything like that. If you want named keys in JavaScript (like "NAMES"), you cannot define it as an array, but should define it as an object:
{"NAMES":"cs.js" ...}

json_encode will do that for you if you provide it the corresponding PHP structure (i.e. an associative array) and let it do its job without tampering.
3. Don't add "false"
It does not seem useful to add "false" as an element to the courses array. In JavaScript you can easily check how many elements there are in an array, so there is no need to put a kind of stop-sign at the end.
Anyway, if in JavaScript you refer to an element in an array that does not exist, you get undefined, which you can verify, much like verifying for the value "false".
I would strongly suggest to leave that out.
Suggested code
The PHP code you provided in your question could be replaced with this:
// Add the names element as a separate item next to the courses array,
// which we put in the "courses" property.
$major_array = array(
    "names" => $major,
    "courses" => $major_array
);

// Turn into JSON text with added line breaks and indentation:
$json_string = json_encode($major_array, JSON_PRETTY_PRINT);

// Don't touch the JSON text anymore, but output it:
echo "var initialCourse = $json_string;";

The output (JavaScript) would be something like:
var initialCourse = {
    "names": "cs",
    "courses": [
        {
            "COURSE_ID": "ENGL 1013"
        },
        {
            "COURSE_ID": "FAH1"
        },
        {
            "COURSE_ID": "USHG1"
        },
        {
            "COURSE_ID": "TECH 1001"
        },
        {
            "COURSE_ID": "COMS 1403"
        },
        {
            "COURSE_ID": "COMS 1411"
        },
        {
            "COURSE_ID": "ENGL 1023"
        },
        {
            "COURSE_ID": "SS1"
        },
        {
            "COURSE_ID": "MATH 2914"
        }
    ]
};

As I mentioned above, this is an object structure, not an array structure, because JavaScript does not allow named keys in an array notation. If in JavaScript you need to iterate over the courses in the above structure, you would address the courses property (which is an array), like this:
for (var course of initialCourse.courses) {
    console.log('course id: ' + course.COURSE_ID);
}

More concise structure
I must say it is a bit of an over-kill to have objects with just one property. This structure would be more concise and efficient:
var initialCourse = {
    "names": "cs",
    "courses": [
        "ENGL 1013",
        "FAH1",
        "USHG1",
        "TECH 1001",
        "COMS 1403",
        "COMS 1411",
        "ENGL 1023",
        "SS1",
        "MATH 2914"
    ]
};

In JavaScript you would iterate over these courses like this:
for (var course of initialCourse.courses) {
    console.log('course id: ' + course);
}

If this interests you, you should just add this line to your PHP code, before any of the PHP code I suggested above:
$major_array = array_map(function ($course) { return $course["COURSE_ID"]; }, $major_array);


text:
Q: how to execute struts tags inside js file I am able to execute struts tags code in following manner. But the same code when I put inside js file, it does not work. Please help
 <script language='JavaScript' type='text/JavaScript'>
var a, b;
<s:iterator value="abclist" var="myBean">
    a = '<s:property value="#myBean.a"/>';
    b = '<s:property value="#myBean.b"/>';
</s:iterator>

A: I'd suggest you to avoid this type of approach. As it is can have strange side effects and reduce legibility of the javascript. I'd prefer using a ajax request to get data and consume it in my JS.
But if you want to generate dynamic js files with struts you will have to configure the struts to process urls that point to js files or return "application/javascript" content-type from a struts processed url and use it as a script.
This answer explains how to configure content-type of response:
https://stackoverflow.com/a/1683169/1496916
<action name="..." class="...">
  <result name="SUCCESS">
    <param name="contentType">application/javascript</param>

Then just use this action as a src in a script tag .


text:
Q: Hide/show inner divs on hover in an accordion with jQuery kindly take a look at my HTML code below:

 CONTENT HERE

 CONTENT HERE

 CONTENT HERE

 CONTENT HERE

 CONTENT HERE

 CONTENT HERE

 CONTENT HERE

 CONTENT HERE

 CONTENT HERE

Basically it's an accordion powered by a jQuery plugin. It has 3 boxes and depending on which box the user is hovering on, I wish to have the inner divs (normal, expanded, hidden) shown or hidden. Here are the scenarios:

*

*On default, all div.normal will be shown by default, div.expanded and div.hidden will be hidden.

*When user hovers on li.box1 for example, its div.expanded will be shown and div.normal and div.hidden will be hidden. For li.box2 and li.box3 then however, only div.hidden will be shown respectively, the rest of the divs will be hidden.

I have begun with the code but I don't think it's going anywhere. (I am a designer, you see.)
It sounds complicated but I know it can be easily done via jQuery, to anyone who can help, I'd really appreciate it.
UPDATE:
Here's what I've done so far.
$(document).ready(function () {
  $(".accordion li").hover(function () {

    $(this).siblings().children(".normal").hide();
    $(this).siblings()..children(".hidden").delay(700).show();
    $(this).children(".expanded").delay(700).show();

    }, function () {

    $(this).siblings().children(".normal").delay(700).fadeIn("fast");
    $(this).siblings().children(".hidden").fadeOut("fast");
    $(this).children(".expanded").fadeOut("fast");

  });
});

A: $(document).ready(function(){

        $('.expanded').hide();

        $('.box1').hover(function(){
                    $('.expanded').show();
        });
});

This is how you can hide and show DOM elements in jQuery. Please get that set according to the way you want it to be.

A: You can initially hide divs by using style='display:none'
for hover event;
  $("li.box1").hover(function(){
     $(this).find('.expanded').show();
     $(this).find('.hidden').show();
    $(this).find('.normal').hide();
 });


text:
Q: Why does nodes npm execute local programs from package.json? I am new to Node and I noticed that the npm package manager is also used to start and execute programs that are referenced in package.json. I tried to find the historic reasons, but can anyone explain me why npm - a package manager has this functionality? For me it feels like I use apt-get to trigger e.g. a webserver or a linter.
npm lint
npm start
Why is this not a separate program that handles that?

A: The "historic" reason why this is handled by npm is because the dependencies managed by npm can contain some scripts themselves. If you look inside the node_modules folder of a node project there will often be a .bin folder with some scripts that can be executed by npm.
For example if you install eslint, there will be an eslint executable in node_modules/.bin/eslint. As a result if you want to run eslint you have different options:

*

*Run ./node_modules/.bin/eslint, which is not nice

*Install it globally, but it is not recommended because different projects might require different version and it is hard to work with other contributors that might use incompatible versions

*Add ./node_modules/.bin to the $PATH, but that's hard to manage and potentially a security risk for your machine.

*To use npx, but npm scripts predate the introduction of npx

So having a "scripts": { "lint": "eslint ." } in the package.json is really handy, as any scripts executed by npm will have the .bin folder as part of the PATH automatically.
Another reason that contributed a lot to the popularity of npm scripts, is that the javascript community is very large, and there is usually more than one common library/framework for a given task (lint, test, web servers...).
So it is easier to run npm test than to read the package.json to figure out which test framework is used by the project and run the framework-specific command to run the tests.
Of course all of this can be abused in different ways, and the package.json should not be bloated of irrelevant scripts.


text:
Q: Install modules with perlbrew and cpm - perlbrew switch does not change @INC during docker build I'd like to use fast cpm module installer instead of cpanm in my projects.
Also I install target perl version using perlbrew.
According documentation of cpm -g option will install modules into current @INC
How to force perlbrew change @INC in Dockerfile ?
Below is part of my Dockerfile
RUN perl -le 'print for @INC' && \
    perlbrew switch perl-5.31.0 && \
    perl -le 'print for @INC' && \
    cpm install -gv CGI && \
    perlbrew list-modules

When I build Dockerfile output of perl -le 'print for @INC' is same both times:
/etc/perl
/usr/local/lib/x86_64-linux-gnu/perl/5.22.1
/usr/local/share/perl/5.22.1
/usr/lib/x86_64-linux-gnu/perl5/5.22
/usr/share/perl5
/usr/lib/x86_64-linux-gnu/perl/5.22
/usr/share/perl/5.22
/usr/local/lib/site_perl
/usr/lib/x86_64-linux-gnu/perl-base

But if I do same manually result is ok:
$ docker run -it pavelsr/xxxhub
root@1a34ea34a3fb:/# perl -le 'print for @INC'
/etc/perl
/usr/local/lib/x86_64-linux-gnu/perl/5.22.1
/usr/local/share/perl/5.22.1
/usr/lib/x86_64-linux-gnu/perl5/5.22
/usr/share/perl5
/usr/lib/x86_64-linux-gnu/perl/5.22
/usr/share/perl/5.22
/usr/local/lib/site_perl
/usr/lib/x86_64-linux-gnu/perl-base
.
root@1a34ea34a3fb:/# perlbrew switch perl-5.31.0

A sub-shell is launched with perl-5.31.0 as the activated perl. Run 'exit' to finish it.

root@1a34ea34a3fb:/# perl -le 'print for @INC'
/usr/local/perlbrew/perls/perl-5.31.0/lib/site_perl/5.31.0/x86_64-linux
/usr/local/perlbrew/perls/perl-5.31.0/lib/site_perl/5.31.0
/usr/local/perlbrew/perls/perl-5.31.0/lib/5.31.0/x86_64-linux
/usr/local/perlbrew/perls/perl-5.31.0/lib/5.31.0
root@1a34ea34a3fb:/# cpm install -g CGI
DONE install HTML-Tagset-3.20
DONE install HTML-Parser-3.72
DONE install CGI-4.44
3 distributions installed.
root@1a34ea34a3fb:/# perlbrew list-modules
CGI
HTML::Parser
HTML::Tagset
Perl

A: For starters, "A sub-shell is launched with ..." indicates you have an incorrectly setup perlbrew. You were instructed to add the following to your shell's startup script:
source "${PERLBREW_ROOT:-$HOME/perl5/perlbrew}"/etc/bashrc

Without this, a fallback mechanism is used to try to provide the desired functionality, but it's completely useless outside of interactive shells.

Secondly, this is a rather dubious use of perlbrew. If your docker script worked as intended, it would have far reaching consequences. That's not a good thing. You could use perlbrew use, but you could instead use the correct perl build directly using
RUN "${PERLBREW_ROOT:-$HOME/perl5/perlbrew}"/perls/perl-5.31.0/bin/perl -S cpm install -gv CGI

In your case, this should resolve to
RUN /usr/local/perlbrew/perls/perl-5.31.0/bin/perl -S cpm install -gv CGI

for you.


text:
Q: C# WPF Token is not valid on BrushConverter I am converting a System.Media.Brush to a System.Drawing.Brush, but after I change the color. It throws a "Token is not valid" error on the converter.
    private Brush DrawingColorToBrush(System.Drawing.Color color)
    {
        Brush ret;

        BrushConverter m;

        m = new BrushConverter();
        ret = (Brush)m.ConvertFromString(color.ToArgb().ToString("X8"));

        return ret;
    }

The color is coming from a System.Windows.Forms.ColorDialog

A: Your code will work if you change your method to this...
    private Brush DrawingColorToBrush(System.Drawing.Color color)
    {
        Brush ret = null;
        BrushConverter m = new BrushConverter();
        string s = "#" + color.ToArgb().ToString("X8");
        if (m.CanConvertFrom(typeof (string)))
        {
            ret = (Brush) m.ConvertFromString(s);
        }
        return ret;
    }

The key is to prepend the string with the '#' character.


text:
Q: Avoiding making a UIButton transparent/see-through when disabling it I want to disable my UIButton, so I call:
button.enabled = FALSE;

However this makes the button see-through and I can see the elements underneath it. I don't mind that it changes colour, I just don't want it to be see-through.
I've tried ticking the boxes for 'opaque' and 'clip subviews' in IB, but no joy.
Is there an easy way to fix this? I suppose I could put a UIImageView with the same button image behind it, but it's hardly an elegant solution.

A: You can also do:
button.adjustsImageWhenDisabled = NO;

A: Try userInteractionEnabled property:
button.userInteractionEnabled = NO;

A: In interface builder select your button and then take a look at the button attributes. There is a drop down menu for default, highlighted, selected or disabled state configurations -  select disabled and then adjust the alpha property.


text:
Q: Why can a function be defined in JSON? I am reading a React doc, https://reacttraining.com/react-router/web/example/auth-workflow, and trying to understand the following piece of code:
Looks like a the function definition happens in a json object, but my understanding is that we can't have funciton inside json
const fakeAuth = {
  isAuthenticated: false,
  authenticate(cb) {
    this.isAuthenticated = true;
    setTimeout(cb, 100); // fake async
  },
  signout(cb) {
    this.isAuthenticated = false;
    setTimeout(cb, 100);
  }
};

A: In true JSON you cannot have a function, and there are no vars. It's a format just used to hold data (based on JavaScript). You can have a function that is a property of an Object in JavaScript.

A: if you are referring to the whole const fakeAuth = {...} code, that is not a JSON object.. rather that is a creating a fakeAuth object has a property (isAuthenticated) and functions with parameters(authenticate, signout)

A: As mentioned in the comments, this isn't JSON, it's a Javascript object literal. It's using the ES6 shorthand syntax for function properties.
authenticate(cb) {
  this.isAuthenticated = true;
  setTimeout(cb, 100); // fake async
},

is short for:
authenticate: function(cb) {
  this.isAuthenticated = true;
  setTimeout(cb, 100); // fake async
},


text:
Q: Printing to PDF from Excel w/bookmarks I'm programmatically creating many sheets in an Excel workbook. When I'm done I need to print the workbook to a pdf. That is working using this code
oBook.PrintOut(Type.Missing, Type.Missing, Type.Missing, Type.Missing, "Adobe PDF", true, Type.Missing, filename)
Process.Start(filename)

So, I print to postscript using the Adobe PDF printer instance and then open the .ps file to distill it. Everything works fine. What I need to do, however, is add bookmarks to the PDF file. All I need is the name of each sheet as a bookmark. Can I do that using the above method?
I know it can be done using the "Create PDF" option from Excel, which appears to use PDFMaker. Is there a way to call that from .NET?
Thanks for any help, I really appreciate it.
Thanks,
Nick


text:
Q: Is the fifth dimension of Interstellar the same as Block Universe theory? Is the movie Interstellar (2014) referring to Block Universe theory of space-time with its concept of a fifth dimension?

A: Kip Thorne addresses this in his book The Science of Instellar. The fifth dimension is a fourth spatial dimension i.e. in Interstellar the universe has four dimensions of space and one time dimension.
This is unrelated to the idea of the block universe.
As you'd expect given Kip Thorne's background, there is theoretical support for a fifth dimension, and indeed several extra dimensions, but note that at present there is no experimental evidence for any extra dimensions - their existance is purely in the fevered minds of theoreticians. String theory requires nine spatial dimensions to work (plus one time dimension), so if string theory is correct there will be fifth, sixth, seventh, eighth, nineth and tenth dimensions as well as the four we are familar with.


text:
Q: cannot connect to Postgres (pg) database from my Ruby Script using gem "pg"(This is not rails, just pure ruby) I downloaded the postgres.app for my Mac OSX machine. I have a rails app that has connected and used the postgres DB that came with the postgres app.
Now I am writing a pure Ruby test script (Not Rails, pure Ruby, not even Active Record) to try to connect to the postgres database instance. These are the steps I followed to set this up
 1) ran this command on the terminal:
    gem install pg -- --with-pg-config=/Applications/Postgres.app/Contents/MacOS/bin/pg_config

 2) Added this code to the test script:

   #!/usr/bin/env ruby
   #encoding: utf-8
   require "pg"

    @conn = PG.connect(
    :dbname => 'oData',
    :user => 'am',
    :password => '')

    @conn.exec("CREATE TABLE programs (id serial NOT NULL, name character varying(255);");

I got this from this link
When I ran this script I get the following error:
   /Users/am/.rvm/gems/ruby-2.0.0-p247/gems/pg-0.16.0/lib/pg.rb:38:in `initialize': could
    not connect to server: No such file or directory (PG::ConnectionBad)
Is the server running locally and accepting
connections on Unix domain socket "/var/pgsql_socket/.s.PGSQL.5432"?

My Debug efforts:
  My postgres.app is up and running.

  I looked at the pg gem [documentation][2] and my syntax seemed OK.

  The location of my postgres DB is entered in my bash script like so
   PATH="/Applications/Postgres.app/Contents/MacOS/bin:$PATH"

Not sure what to do next. Any help would be appreciated, Thanks.

A: are you sure postgres is listening on a socket? are you sure the username and password is right?
I would be inclined to try something like
require 'pg'

puts PG::Connection.ping(:dbname => 'oData',:user => 'am',:password => '')
puts "trying with tcp"
puts PG::Connection.ping(:dbname => 'oData',:user => 'am',:password => '', :port => 5432)

A: I used active record gem to make the connection work and it was fine

A: Settings to connect works for me.
But that code should look like

@conn.exec("CREATE TABLE programs (id serial NOT NULL, name
  character(255))")


text:
Q: How to recall a figure without rewriting it I'm writing a long document and sometimes I need to recall a figure and show it (not just a \ref in the document). Right now every time I need this I rewrite the LaTeX code for showing  the figure. Is there a way to recall a figure without rewriting it?

A: You could define an entire float as the argument of a command such as \repeatedfigure. In the MWE below, this command takes an argument, which is the label to be assigned to the figure; if no extra label is desired, just specify an empty argument, {}. Oh, and I've assigned the h! location specifier to the repeated float as I'm assuming that you will wish to place it in very specific locations. If you're OK with LaTeX's default decision rules for placing floats, just remove the [h!] directive.
\documentclass{article}
\usepackage[margin=1in]{geometry}
\usepackage[demo]{graphicx} % leave off demo option in real program
\usepackage{lipsum} % for filler text

\newcommand{\repeatedfigure}[1]{%
  \begin{figure}[h!] %
  \caption{Repeated caption} % replace with real caption text...
  \label{#1}
  \centering
  \includegraphics{demo.jpg} % use real filename if available
  \end{figure}}

\begin{document}
\lipsum[2]
\repeatedfigure{fig:repfig}
\lipsum[2]
\repeatedfigure{}
Here's a cross-reference to Figure~\ref{fig:repfig}.

\lipsum[2]
\repeatedfigure{}
\end{document}

Addendum: This setup assumes that you want each instance of the repeated figure to have its own caption and entry in the List of Figures. If that's not the case, you could define the \repeatedfigure macro as follows:
\newcommand{\repeatedfigure}[1]{%
  \begin{minipage}{\textwidth}
  \centering
  \includegraphics{demo.jpg}
  \end{minipage}}

A: Just an alternatively solution to the other answers. I would create a "factory" macro
to create commands for image and caption storage. Consider a graphic with the filename
"amato":
\documentclass{article}
\usepackage[demo]{graphicx}
\usepackage{caption}
\def\imagefactory#1#2{%
\expandafter\def\csname#1\endcsname{%
  \includegraphics{#1}%
 }
 \expandafter\def\csname#1fig\endcsname{%
  \includegraphics{#1}%
  \captionof{figure}{#2}
 }
 \expandafter\def\csname#1float\endcsname{%
  \figure[htbp]
  \centering
  \includegraphics{#1}%
  \caption{#2}
  \endfigure
 }
}

\begin{document}
\imagefactory{amato}{This is a caption.}

\amato
\amatofig
\amatofloat

\end{document}

The MWE creates three commands a) just to store and provide a shorthand to includegraphics, the second essentially is a "here macro + caption" and the last a proper float. Stick the macros to a list and you have an image DB. Depending to what you need you can re-adjust the
macros to do what you want (including references avoiding duplicating references - as per Dave's brilliant solution etc).

A:
Updated to avoid duplicating the caption and label information.
\documentclass{article}

\usepackage{graphics}

\makeatletter
\def\savefloat#1{%
\expandafter\def\expandafter\@endfloatbox\expandafter{%
\@endfloatbox
\global\setbox#1\copy\@currbox}}

 % Stephan Lehmke's \leaders trick to stop multiple writes.
\def\usefloat#1{%
\leavevmode\leaders\copy#1\hskip\wd#1\relax}

\makeatother

\newsavebox\myfloat

\begin{document}

aaaa

\begin{figure}

\fbox{\begin{tabular}{l}a\\b\\c\end{tabular}}
\caption{hmmm}
\end{figure}

aaaa

\begin{figure}

\fbox{\begin{tabular}{l}a\\b\\c\end{tabular}}
\caption{hoooo}\label{xx}
\savefloat\myfloat
\end{figure}

bbbb

it looked like this

\fbox{\scalebox{.25}{\usefloat\myfloat}}

\end{document}


text:
Q: How to get nested JSON data in vue.js I have a JSON file like this, and this is 'pproduct' array
[
        {
        "id": 2,
        "title": "Domena .pl, com.pl lub .eu 0 z\u0142 przez pierwszy rok.",
        "slug": "domena-pl-0zl-1rok",
        "pubickdate": "2018-08-20",
        "price": 150,
        "mainphoto": null,
        "pcontent": null,
        "created_at": "2018-08-20 10:14:42",
        "updated_at": "2018-08-20 10:14:42",
        "deleted_at": null,
        "pcategories": [
            {
                "id": 1,
                "pcategoryname": "Pakiet internetowy",
                "pcslug": "pakiet-internetowy",
                "created_at": "2018-08-20 10:04:41",
                "updated_at": "2018-08-20 10:04:41",
                "deleted_at": null,
                "pivot": {
                    "pproduct_id": 2,
                    "pcategory_id": 1
                }
            }
        ]
    },
    {
        "id": 1,
        "title": "Indywidualny projekt serwisu spe\u0142niaj\u0105cy wymagania User Center Design dostosowany do bran\u017cy firmy",
        "slug": "indywidualny-projekt-serwisu",
        "pubickdate": "2018-08-20",
        "price": 600,
        "mainphoto": null,
        "pcontent": null,
        "created_at": "2018-08-20 10:11:04",
        "updated_at": "2018-08-23 07:02:05",
        "deleted_at": null,
        "pcategories": [
            {
                "id": 1,
                "pcategoryname": "Pakiet internetowy",
                "pcslug": "pakiet-internetowy",
                "created_at": "2018-08-20 10:04:41",
                "updated_at": "2018-08-20 10:04:41",
                "deleted_at": null,
                "pivot": {
                    "pproduct_id": 1,
                    "pcategory_id": 1
                }
            }
        ]
    }
]

How to get nested data like: pcategoryname, pcslug in vue.js. Any suggestions on how to display this data in the v-for loop.
I would like to display: title, price, pcategoryname, pcslug.
When I use {{ pproduct.pcategoryname }} I get 'undefined' error.
Here is my vue.js template
<template>

Pakiet Internetowy

                       {{ pproduct.title }}
                       Kategoria: {{ pproduct.pcategoryname }}
                       {{ pproduct.price }} zł

</template>

A: You have an array of categories in your product object and you are trying to access them  using pproduct.pcategoryname, pcategoryname is a property of a category not a product.
Iterate over the categories of a product too.

new Vue({
  el: "#app",

  data() {
    return {
      pproducts: [{
          id: 2,
          title: 'Domena .pl, com.pl lub .eu 0 z\u0142 przez pierwszy rok.',
          slug: 'domena-pl-0zl-1rok',
          pubickdate: '2018-08-20',
          price: 150,
          mainphoto: null,
          pcontent: null,
          created_at: '2018-08-20 10:14:42',
          updated_at: '2018-08-20 10:14:42',
          deleted_at: null,
          pcategories: [{
            id: 1,
            pcategoryname: 'Pakiet internetowy',
            pcslug: 'pakiet-internetowy',
            created_at: '2018-08-20 10:04:41',
            updated_at: '2018-08-20 10:04:41',
            deleted_at: null,
            pivot: {
              pproduct_id: 2,
              pcategory_id: 1,
            },
          }, ],
        },
        {
          id: 1,
          title: 'Indywidualny projekt serwisu spe\u0142niaj\u0105cy wymagania User Center Design dostosowany do bran\u017cy firmy',
          slug: 'indywidualny-projekt-serwisu',
          pubickdate: '2018-08-20',
          price: 600,
          mainphoto: null,
          pcontent: null,
          created_at: '2018-08-20 10:11:04',
          updated_at: '2018-08-23 07:02:05',
          deleted_at: null,
          pcategories: [{
            id: 1,
            pcategoryname: 'Pakiet internetowy',
            pcslug: 'pakiet-internetowy',
            created_at: '2018-08-20 10:04:41',
            updated_at: '2018-08-20 10:04:41',
            deleted_at: null,
            pivot: {
              pproduct_id: 1,
              pcategory_id: 1,
            },
          }, ],
        },
      ],
    }
  },
})

Vue.config.productionTip = Vue.config.devtools = false
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

del {
  color: rgba(0, 0, 0, 0.3);
}

Products:

        Product: {{ product.title }}

        Categories:

            {{ category.pcategoryname }}

A: note that your categoryname is an array that you you need to loop through. if you know that you'll only have one, you can use {{product.pcategories[0].pcategoryname}}, however this will cause issues if you have not categories, and will only show one even when there are more
here are two options of dealing with this
Option 1 - use v-for to loop through categories and add dom element for each

    {{ pproduct.title }}
    Kategoria: {{ pcategory.pcategoryname }}
    {{ pproduct.price }} zł

Option 2 - extract the name only for all categories using a map().join(), this will return a String that you can display.

    {{ pproduct.title }}
    Kategoria: {{ product.pcategories.map(c=>c.pcategoryname).join(', ') }}
    {{ pproduct.price }} zł


text:
Q: Sharepoint Hosted App- Get HostwebUrl and AppwebUrl on navigation Can anyone provide a sample code for getting HostWebUrl and AppWebUrl when redirect from Default page to another page. How can we do this ?
 I am using the following code its work for Default but not for another page-
hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));

var scriptbase = hostweburl + "/_layouts/15/";
var context = new SP.ClientContext(appweburl);

appContextSite = new SP.AppContextSite(context, hostweburl);
web = appContextSite.get_web();

A: The issue is that when you navigate to another page you're losing the query strings in the URL.
I get around this by appending the query strings to my hyperlinks in the onclick attribute:
onclick="window.location='time.aspx'+window.location.search;"

So full example:
Time Application

Of course you'll need to replace 'time.aspx' with the name of the page you're navigating to.
This might not be ideal for you, but it was an acceptable workaround in my case.

A: I use a function like this to add the standard tokens to a URL.
Pluralsight.UrlUtils.addStandardTokens = function(url) {
    var tokens = ["SPHostUrl", "SPAppWebUrl", "SPLanguage", "SPClientTag", "SPProductNumber"];

    for (var i = 0; i < tokens.length; i++) {
        var token = tokens[i];
        var value = GetUrlKeyValue(token);
        if (SP.ScriptUtility.isNullOrEmptyString(value) == false) {
            url = SetUrlKeyValue(token, value, true, url);
        }
    }

    return url;
}

// Calling code ******************************************

addLink.click(function () {
      var url = "ProductAdd.aspx";
      url = Pluralsight.UrlUtils.addStandardTokens(url);
      SP.Utilities.HttpUtility.navigateTo(url);
})

Note: GetUrlKeyValue and SetUrlKeyValue are built-in SharePoint functions


text:
Q: Need to evaluate the series $\sum_{i = 0}^n i^5$ I need help in evaluating the following sum:
$$\sum_{i = 0}^n i^5 $$
I can evaluate series when they are arithmetic or geometric but I don't know how to solve this one.

A: Main Idea: Knowing the closed form of $\sum\limits_{k=1}^n k^{1},\ldots,\sum\limits_{k=1}^n k^{r}$ let's you determine the closed form of $\sum\limits_{k=1}^n k^{r+1}$.
The Procedure: We begin with the formula :
$$(k+1)^6-k^6=6 k^5+15 k^4+20 k^3+15 k^2+6 k+1.$$
Writing it for $k=1,\ldots,n$ and adding we obtain :
$$\begin{array}{rcl}
2^6-1^6 &=& 6\cdot 1^5+15\cdot 1^4+20\cdot 1^3+15\cdot 1^2+6\cdot 1+1 \\
3^6-2^6 &=& 6\cdot 2^5+15\cdot 2^4+20\cdot 2^3+15\cdot 2^2+6\cdot 2+1 \\
\cdot &&\\
\cdot &&\\
\cdot &&\\
(n+1)^6-n^6&=&6\cdot n^5+15\cdot n^4+20\cdot n^3+15\cdot n^2+6\cdot n+1 \\ \hline
(n+1)^6-1&=&6[1^5+\cdots+n^5]+15[1^4+\cdots+n^4]+20[1^3+\cdots+n^3]\\&&+15[1^2+\cdots+n^2]+6[1+\cdots+n]+[\underbrace{1+\cdots+1}_{n\,\rm times}].
\end{array}$$
Knowing that
$$\sum_{k=1}^n1=n,\qquad \sum_{k=1}^n k=\frac{n(n+1)}{2},\qquad \sum_{k=1}^nk^2=\frac{n(n+1)(2n+1)}{6},\qquad\\ \sum_{k=1}^nk^3=\dfrac{n^2(n+1)^2}{4},\qquad\sum_{k=1}^nk^4=\dfrac{n(n+1)(2n+1)(3n^2+3n-1)}{30},$$
you can solve for $1^5+\cdots+n^5$, although that is a tedious task.

A: HINT:
Use $(r+1)^{m+1}-r^{m+1}=\binom{m+1}1r^m+\binom{m+1}2r^{m-1}+\cdots+\binom{m+1}{m-1}r^2+\binom{m+1}mr+1$
To know $\sum_{r=1}^nr^u,$ set $m=u$
Assumption : $\sum_{r=1}^nr^v,0\le v\le u-1$ are known

A: Take a look at Faulhaber's formula on wikipedia.
Note that even though finding the result is difficult, once it has been found is pretty easy to show that it's correct using induction
To answer your question,
$$\sum_{i=0}^n i^5 = \frac{n^2(n+1)^2(2n^2+2n-1)}{12}$$