text:
Q: How to compare two dataframe columns(same data not required)? I want to compare if the columns of two dfs are same not the data/Values
df1
         A       B

    0   45      25

    1   46      26

    2   47      27

df 2
        B       A

    0   45      25

    1   46      26

    2   47      27

I just want to check if both dfs have same columns and not data
I have tried to convert into list and series objects and then compare
Its giving me
    ValueError: Can only compare identically-labeled dataframe objects

A: you can get column names into a set and compare the sets:
print(set(df1.columns) == set(df2.columns))

Full example:
import pandas as pd
from io import StringIO

df1 = pd.read_csv(StringIO("""
         A       B

    0   45      25

    1   46      26

    2   47      27"""), sep="\s+")

df2 = pd.read_csv(StringIO("""
        B       A

    0   45      25

    1   46      26

    2   47      27"""), sep="\s+")

print(set(df1.columns) == set(df2.columns))

Output:
True

A: Try this:
df1.columns.difference(df2.columns).size == 0


text:
Q: Exception in thread "main" java.lang.NoClassDefFoundError: com/twitter/chill/KryoBase I am writing a simple spark-cassandra program in java with datastax cassandra but getting below exception

Exception in thread "main" java.lang.NoClassDefFoundError:
  com/twitter/chill/KryoBase   Caused by:
  java.lang.ClassNotFoundException: com.twitter.chill.KryoBase

pom.xml
 <dependency>
        <groupId>com.datastax.dse</groupId>
        <artifactId>dse-spark-dependencies</artifactId>
        <version>5.1.1</version>
        <exclusions>
            <exclusion>
                <groupId>com.datastax.dse</groupId>
                <artifactId>dse-java-driver-core</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.apache.solr</groupId>
                <artifactId>solr-solrj</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

App.java
 SparkConf conf = new SparkConf().setMaster("local").setAppName("SparkJavaFirst")
                    .set("spark.cassandra.connection.host", "localhost");
JavaSparkContext sc = new JavaSparkContext(conf);
JavaRDD<CassandraRow> cassandraJavaRDD =  CassandraJavaUtil.javaFunctions(sc).
                    cassandraTable("my_keyspace","my_table" ).
                    select("my_column");

Program fails at  JavaSparkContext sc = new JavaSparkContext(conf);
Any help will be appreciated.

A: This issue got resolved as I removed the exclusion of
 <groupId>com.datastax.dse</groupId>
  <artifactId>dse-java-driver-core</artifactId>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Export HTML Table to PDF using mPDF I have am using mPDF to convert and export the data from my html table to PDF. The button on my table works and the data can be exported. However the code only passes one variable. I want to pass all the variables. I cannot pinpoint what else is missing in my code. Can anyone help me?
Here is the link button from index.php:
while($row = mysqli_fetch_array($result)){
         echo "
";
         echo "" .$row['eventvolunteerID'] . "	";
         echo "" .$row['eventTitle'] . "	";
         echo "" .$row['rollno'] . "	";
         echo "" .$row['eventDate'] . "	";
         echo "" .$row['eventTime'] . "	";
         echo "" .$row['eventLimit'] .  "	";
         echo "Create PDF	";
         echo "
";

Here is my code for processing the PDF (makepdf2.php):
<?php
require_once __DIR__ . '/vendor/autoload.php';
if(isset($_GET['eventvolunteerID'])) {

$eventvolunteerID = $_GET['eventvolunteerID'];
$eventTitle = $_GET['eventTitle'];
$rollno = $_GET['rollno'];
$eventDate = $_GET['eventDate'];
$eventTime = $_GET['eventTime'];
$eventLimit = $_GET['eventLimit'];

$mpdf = new \Mpdf\Mpdf();

$data = '';
$data .= 'Event Volunteer ID: ' . $eventvolunteerID . '
';
$data .= 'Event Title: ' . $eventTitle . '
';
$data .= 'Roll no.: ' . $rollno . '
';
$data .= 'Event Date: ' . $eventDate . '
';
$data .= 'Event Time: ' . $eventTime . '
';
$data .= 'Event Limit: ' . $eventLimit . '
';
$mpdf->WriteHTML($data);
$mpdf->Output('myfile.pdf', 'D');
}
?>

Please do help. Thank you.

A: You have added button to each row of table and when it's clicked you pass the id of data that row has and hence you export only single row.
You suppose to do add button on Top of HTML table. By clicking it you supposed to pass all the variable values to makepdf2.php and write the same Database query to fetch all the data.
require_once __DIR__ . '/vendor/autoload.php';

if(isset($_GET['checkyouraction'])) {

    // Write your Database query here to get $result

    $data = '';
    while($row = mysqli_fetch_array($result)){
        $data .= 'Event Volunteer ID: ' . $row['eventvolunteerID'] . '
';
        $data .= 'Event Title: ' . $row['eventTitle'] . '
';
        $data .= 'Roll no.: ' . $row['rollno'] . '
';
        $data .= 'Event Date: ' . $row['eventDate'] . '
';
        $data .= 'Event Time: ' . $row['eventTime'] . '
';
        $data .= 'Event Limit: ' . $row['eventLimit'] . '
';
    }

    $mpdf = new \Mpdf\Mpdf();

    $mpdf->WriteHTML($data);
    $mpdf->Output('myfile.pdf', 'D');
}

Above code generate you all the records. If you wish to display data in tabular format you can use same HTML table/tr/td structure.


text:
Q: loading JS files in spring mvc
Is there any way if i can load javascript and css files in spring mvc, such that it is not readable whenever someone view source of the web page ?

I want to do this without doing minification.
I also looked for other options like  &  dont know which one to user.

A: NO. Well, not really.
You can't add js and css to the DOM and have it work without being in the DOM. You could dynamically load them, but they will still be visible in the DOM inspector in any browser, but will not be visible to your run of the mill user right clicking and doing view source.


text:
Q: What do you use to develop for PowerShell? I don't see a Visual Studio plugin for it (although I didn't look that hard, so I might have missed it), and searches turn up random third-party solutions, but is there something that comes with PowerShell or something that plugs into Visual Studio?

A: Visual Studio templates are available here.  And there are samples in the Server 2008 SDK for developing providers and hosts.
If you are talking about an IDE for scripting, see this question (How to Get Started with PowerShell)

A: I mostly use PowerGui Script Editor.  It allows me to use multi-file editing and debugging as well as straight command-line stuff.

A: PowerShell v2 CTP has a nice GUI interface which includes the ability to run multiple runspaces, and edit and run scripts. The script editor has syntax highlighting which is very helpful. PSH v2 also has other useful features such as script cmdlets. It's very cool. PowerGUI is supposed to be pretty neat too although I haven't personally used it. Before PSH v2 thhough, I used to use Textpad with a syntax file that was created for the pre-release version of PowerShell - Monad.

A: Have you seen powershell.com which has a couple of excited reviews.

A: The beauty of PS is the command line. To be honest with you, I do the vast majority of my development at the command line. With the PowerTab snapin from //\O//, I have as good intellisense as I have found in any IDE for PS. Once I have all the parts worked out at the command line then I use VIM to put it all into a script.

A: PrimalScript by Sapien is good. It's pay though.

A: Depends on what you mean by "develop."
PowerShell can be used quite effectively from the command line without scripting. However, if you do get into scripting, products include PowerShell Plus, PrimalScript, and PowerGUI.
If you're developing cmdlets and snap-ins, Visual Studio doesn't require any plug-ins, although you do need the reference assemblies available in the Windows SDK.
Visual Studio has no plans to host PowerShell as a script editor - the Visual Studio team feels that most admins wouldn't have Visual Studio, and that their goal is to make better development tools, not scripting tools (which is pretty distinct in terms of features that you need to be more efficient). So don't look for PowerShell scripting to show up in Visual Studio, at least not in the immediate future. There are some third-party stuff to get it in there, but nothing as good as the dedicated script editors I listed above.

A: ISE is what comes with PowerShell(so you don't need to install anything). This is how you can get to it.

*

*From Start menu go to Powershell command line.

*Type ise , you should see something like this:

A: I actually find that Notepad++ is very useful to me when scripting in Powershell.  I find it easier to navigate and visually understand the overall flow of a script with the intelligent markup, which includes If-Then-Else and For loop marking.

A: Sapiens Powershell Studio 2012 - hands down the best Powershell specific IDE.
http://www.sapien.com/software/powershell_studio


text:
Q: Creating buffer based on occurrence frequency using ArcGIS Desktop? I am using ArcMap 10.4.1.
I have several point shapefiles containing different occurrence data for two different species of flower (from multiple sources, hence the multiple shapefiles). I want to create a buffer from a central point that includes a quantity of at least 50 each of each species. I'm familiar with the general buffer tool, so for example, I can create a buffer of a certain size and clip to it, but what I'm hoping to do is create a buffer that contains at least 50 occurrences of each species regardless of the size, from a certain point (i.e. a city).
I'm hoping this can actually be done in ArcMap? I've been searching Stack Exchange and elsewhere, and can't find this anywhere.
I've attached a screenshot of what the occurrence distribution looks like. Attribute tables consist simply of long/lat values. One of the species I am studying is protected, so I can't get more detailed than that. The primary study site is a natural area just outside of a major city, so we chose the city as an arbitrary "central point" to create the buffer from.
As of now, I have eight sources providing occurrence data, so eight different point shapefiles, that I created - so they should all be the same. I have an "Advanced" license, and the following extensions: 3D Analyst, ArcScan, Geostatistical Analyst, Network Analyst, Publisher, Schematics, Spatial Analyst, Tracking Analyst.

A: I created a Tool a while back which I was using to find people in proximity to boreholes. Tweaking it I have something you can use.
Create a text file and save it as "Species.py", copy the code below into it.
The code is messy, as it has been butchered from my old code.
import arcpy
import os

arcpy.env.overwriteOutput = True
arcpy.env.workspace = "in_memory"

source = arcpy.GetParameterAsText(0)
PopPoint1 = arcpy.GetParameterAsText(1)
PopPoint2 = arcpy.GetParameterAsText(2)
OutPutFolder = arcpy.GetParameterAsText(3)
SPP1 =arcpy.GetParameterAsText(4)
SPP2 =arcpy.GetParameterAsText(5)
Interval = arcpy.GetParameterAsText(6)
Distance = 1

x = 1

arcpy.AddMessage('Population Difference ' + str(x))

# SPP 1

while x <= int(SPP1):
    arcpy.SelectLayerByLocation_management(PopPoint1, "WITHIN_A_DISTANCE",source, Distance , "NEW_SELECTION")
    pop = int(arcpy.GetCount_management(PopPoint1).getOutput(0))

    arcpy.AddMessage("Selected " + str(pop) + "Looking for Spp1:  " + str(SPP1))
    arcpy.AddMessage("Increasing buffer to " + str(Distance))
    Distance += int(Interval)
    x = int(pop)

    arcpy.AddMessage("x is: " + str(x))
mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]

Out1 = "in_memory" + "\\Spp1Final"

arcpy.Buffer_analysis(source,Out1,Distance)

# SPP 2
x = 0
Distance = 1
pop = 0
while x <= int(SPP2):
    arcpy.SelectLayerByLocation_management(PopPoint2, "WITHIN_A_DISTANCE",source, Distance , "NEW_SELECTION")
    pop = int(arcpy.GetCount_management(PopPoint2).getOutput(0))

    arcpy.AddMessage("Selected " + str(pop)+ "Looking for Spp2: " + str(SPP2))
    arcpy.AddMessage("Increasing buffer to " + str(Distance))
    Distance += int(Interval)
    x = int(pop)

    arcpy.AddMessage("x is: " + str(x))

Out2 = "in_memory" +"\\Spp2Final"
arcpy.Buffer_analysis(source,Out2,Distance)
Out3 = OutPutFolder

inMerge = Out1 + " ; " + Out2
arcpy.Merge_management(inMerge, Out3)

Once copied into the *.py file, save it.
Open ArcMap and Open your "Catalog" window.
Scroll to your working directory and right-click on a folder where you can save a Toolbox. From the right click menu select "New" then "Toolbox". Give it a name. Then in this newly created Toolbox, right click and "Add a script".
Give the script a name and fill in the details as you wish. Click next.
Where it asks for a script file, choose the *.py you just saved.
The next screen is VERY important.
See below:

From line 1 to 7

*

*Input City: Data Type - Feature Layer ; Type - Required ; Direction - Input

*Species 1: Data Type - Feature Layer ; Type - Required ; Direction - Input

*Species 2: Data Type - Feature Layer ; Type - Required ; Direction - Input

*Output File: Data Type - Shapefile ; Type - Required ; Direction - Output

*Lines 5  6 are the number of species you are looking for. The Data Type are all Double. This lets you change the number of species you want per species type (in case you need to later on).

*Line 7 is how much you want to increease the search distance by on each iteration. Data Type is Double ; Type - Required ; Direction - Input

Running the Tool
Once you have set up the Toolbox, double click the Tool.
Select your input point (the point from which you want the buffer drawn). This can only be a single point, do not use a point file with more than 1 point. I haven't tested it on a selection, but there is no harm in trying.
Select your 1st Species
Select your 2nd Species
Select where you want the output buffer saved
select the number of Species 1 you want to find
Select the number of Species 2 you want to find
Select the increment in distance you want the buffer to grow (the search distance). Bearing in mind the smaller the increment the more accurate the final counts will be, but the longer the tool will take.
The final output is a combined buffer of the maximum distance required to meet the species count you have identified.
Notes
The dataframe and all data within the map must be the same projection. The units of the project must be a distance unit - I use the metric system, so I have only tested this with metres.
The final output may be off by 1 or 5 counts. This is due to the increment of the search distance.
Use this as a starting point at least.

A: One option could be using spatial analysis toolset. You can first convert your points to a binary raster where there is any occurrence of species it gets 1 and you can use Focal Statistics tools by SUM operator. Then you can test your proximity definition (i.e., neighbourhood), which would be circle until you find the maximum value of 50.

A: I assume you'd like to pick minimum distance from town that will contain at least 50 birds of each specie.
I suggest using NEAR (analysis) tool for that.
Input:

Workflow:
arcpy.Near_analysis("merged_species", "TOWN")
arcpy.Sort_management("merged_species","./species_sorted.shp", "NEAR_DIST ASCENDING")
arcpy.AddField_management("species_sorted", "GROUP_NO", "LONG")

Use field calculator from here to populate above field by sequential number for indiv.specie.
arcpy.SelectLayerByAttribute_management("species_sorted","NEW_SELECTION",""""GROUP_NO" = 5""")

This is your answer (5 birds at least in below example):


text:
Q: Why is the time period of a pendulum with a spring of force constant $k$ and a bob of significant mass $m$ the same on the Moon as on the Earth? A question I came across in class today:

How will the time period of a loaded spring change when it is taken to the Moon?

What I've been told:

The formula for the time period of a loaded spring
$$ T = 2\pi (\frac{m}{k})^\frac{1}{2}$$
$T$ in this expression is independent of $g$. As such, the time period of the loaded spring on the Moon will be the same as its time period on the Earth.

My thoughts
I think the value of $k$ for a spring hung upside down depends on gravitational pull. From Hooke's law, we have that the restoring force in the spring depends linearly on displacement.
$$ F(x) = -k(x) \\ k = \frac{-F(x)}{x} $$
When the mass is hung vertically, $x$ depends on gravitational pull $g$.
$$ x^2 \propto g $$
The same goes for the downward force, $F(x)$. When the spring-bob system is in equilibrium,
$$ F(x) \propto g $$
Therefore,
$$ k = \frac{-F(x)}{x} \propto \sqrt{g} $$
From the formula for a loaded spring,
$$ T \propto (\frac{1}{g})^\frac{1}{4} $$
So the time period will be a little greater on the Moon than on the Earth. Could someone tell me if I've worked this out right?

A: Please note that mass $m$ and the spring constant $k$ are both the same on earth as they are on the moon. Consequently, the time period of the spring does not depend upon differences due to the acceleration due to gravity. Hence it will not change when it's taken to the moon.

I think the value of  for a spring hung upside down depends on gravitational pull

No. It's a constant. The mathematical argument you have provided contains many errors, but suffice to say that the period of a loaded spring will not be different.
The only thing that will differ is the equilibrium position of the mass in which case it will be higher on the moon.

A: To illustrate the independence of the value of the gravitational field one could set up the spring mass system on a horizontal table and with no friction present the period of oscillation would still be $2\pi \sqrt{\frac mk}$ provided the spring could undergo compression as well as extension.
The reason for this independence is that the restoring force, $F$, depends on the displacement of the mass from its equilibrium position, no net force acting on it, which is not a function of gravitational field and the mass $m$, is also not dependent on the gravitational field, thus the acceleration of the mass $a=\frac Fm$ is gravitational field independent.
The $l$ and $g$ relationship which appears to show the dependence of the period on the gravitational field strength does not show this because $l$ and $g$ are not independent of one another being liked by the equation $kl=mg$, so a $g$ increases so does $l$ in the same proportion.

A:
... we have that the restoring force in the spring depends linearly on displacement.
$$F(x) = -k(x) \\ k = \frac{-F(x)}{x}$$

This calculation of the force is wrong.
Actually the force ($F$) has two parts:

*

*The restoring force of the spring ($-kx$)
which is proportional to the current displacement ($x$).
And the spring constant $k$ is still a constant.

*The gravitational force ($mg$)
which is independent of the current displacement ($x$)

So we have the total force
$$F=-kx+mg. \tag{1}$$
According to Newton's second law ($m\ddot{x}=F$) we get the equation of motion
$$m\ddot{x}=-kx+mg. \tag{2}$$
The most general solution of (2) can be found to be
$$x(t)=\frac{mg}{k}+A\sin\left(\sqrt{\frac{k}{m}}\ t+\phi\right) \tag{3}$$
where $A$ (the amplitude) and $\phi$ (the initial phase) are arbitrary constants.
You can verify the correctness of this solution by plugging it into differential equation (2).
From solution (3) you see two features.

*

*The oscillation period $T$ can be determined from
$\frac{2\pi}{T}=\sqrt{\frac{k}{m}}$.
Thus $T$ is independent of $g$.

*The equilibrium displacement is $\frac{mg}{k}$.
Thus it depends on $g$.
On the moon it is smaller than on the earth.


text:
Q: org.springframework.beans.factory.NoSuchBeanDefinitionException: @Autowired not working in Spring Boot I am currently working on a Spring Boot application, and @Autowired does not work for my main classes, only the test classes. I have already tried other solutions, but nothing has been working for me so far.
The errors I get are
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.johndoe.handler.MyHandler' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
and
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.johndoe.repos.MyDataRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}.
My current project structure can be abstracted to this:
MyProject
|- Some other folders and files
|- MyApplicationFolder
   |- build.gradle
   |- bin
   |- build
   |- src
      |- main
         |- java
            |- com
               |- johndoe
                  |- repos
                     |- MyDataRepository.java
                  |- data
                     |- MyData.java
                  |- myapp
                     |- MyApplication.java
                  |- handler
                     |- MyHandler.java
                  |- request
                     |- MyRequest.java
         |- resources
      |- test

In MyApplication.java:
package com.johndoe.myapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication(scanBasePackages = {"com.johndoe", "com.johndoe.repos", "com.johndoe.data", "com.johndoe.myapp", "com.johndoe.handler", "com.johndoe.request"})
@EnableJpaRepositories("com.johndoe.repos")
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

In MyData.java:
package com.johndoe.data;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Data
@Entity
@Table(name = "my_table")
public class MyData {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private String id;

    // More data members
}

In MyDataRepository.java:
package com.johndoe.repos;

import com.johndoe.data.MyData;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.*;

@Repository
public interface MyDataRepository extends CrudRepository<Tour, Long> {
    List<MyData> findAll();

    // More functions
}

In MyRequest.java:
package com.johndoe.request;

import org.springframework.stereotype.Component;

@Component
public class MyRequest {
    // More code
}

In MyHandler.java:
package com.johndoe.handler;

import com.johndoe.request.MyRequest;
import com.johndoe.data.MyData;
import com.johndoe.repos.MyDataRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MyHandler {
    @Autowired
    private MyDataRepository repo;
    @Autowired
    private MyRequest req;

    // More code
}

In build.gradle:
apply plugin: 'org.springframework.boot'

dependencies {
    compile project(':<other folder in MyProject>')
    compile("org.springframework.boot:spring-boot-starter-data-jpa:1.5.6.RELEASE")
    compile("org.springframework.boot:spring-boot-starter-test")
    compile("org.hsqldb:hsqldb:2.3.0")
    compile("org.springframework.boot:spring-boot-starter-web") {
        exclude module: "spring-boot-starter-tomcat"
    }
    compile("org.springframework.boot:spring-boot-autoconfigure")
}

Building this will result in the aforementioned errors and I am not sure why. I am not sure what I am doing wrong here.

A: Try to move MyApplication from com.johndoe.myapp to com.johndoe
Your MyApplication class should look like:
package com.johndoe;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

Make sure that you do not have other classes with annotation @SpringBootApplication in your dependencies:
compile project(':<other folder in MyProject>')

Spring boot can find this class and use it for the scan (@SpringBootApplication annotation contains @ComponentScan. The default behavior of @ComponentScan is to look for classes within the same package and all sub-packages of the annotated class)


text:
Q: how to convert html to pdf using javascript I have a SharePoint list on which a workflow is attached that adds the list item to a HTML page. I want to convert this html page to pdf and save it on click of a button through javascript.

A: There are open source / third party libraries to help with this. Perhaps check out jsPDF or PDFMake.

A: Content inside a
....
 can be downloaded as pdf with styles using jspdf & html2canvas.
You need to refer both js libraries,

Then call below function,
//Create PDf from HTML...
function CreatePDFfromHTML() {
    var HTML_Width = $(".html-content").width();
    var HTML_Height = $(".html-content").height();
    var top_left_margin = 15;
    var PDF_Width = HTML_Width + (top_left_margin * 2);
    var PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2);
    var canvas_image_width = HTML_Width;
    var canvas_image_height = HTML_Height;

    var totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1;

    html2canvas($(".html-content")[0]).then(function (canvas) {
        var imgData = canvas.toDataURL("image/jpeg", 1.0);
        var pdf = new jsPDF('p', 'pt', [PDF_Width, PDF_Height]);
        pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, canvas_image_width, canvas_image_height);
        for (var i = 1; i <= totalPDFPages; i++) {
            pdf.addPage(PDF_Width, PDF_Height);
            pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height*i)+(top_left_margin*4),canvas_image_width,canvas_image_height);
        }
        pdf.save("Your_PDF_Name.pdf");
        $(".html-content").hide();
    });
}

Ref: pdf genration from html canvas and jspdf.


text:
Q: Angular Reactive Forms map only part of object to formControlName I have a select input that chooses from a list of objects, displays a name, and also binds it into a form's field. However, I need that whole object available for the change event. Changing formControlName is not really an option.
HTML:
<form [formGroup]="form">

  <select formControlName="userName" (change)="process($event.target.value)">
    <option [value]="user.name" *ngFor="let user of users">{{ user.name }}</option>
  </select>

</form>

The value is: {{ form.get('userName').value }}

TS:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  form: FormGroup;

  users = [
    { id: 1, name: 'John' },
    { id: 2, name: 'Mary' },
    { id: 3, name: 'Michael' }
  ]

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.form = this.fb.group({ userName: [null] });
  }

  process(userName) {
    console.log(userName);
  }

  // Here I need the entire user object
  processUser(user) {
    // do stuff
  }

  // I can always do this (in my case names are guaranteed to be unique)
  // but it's a really ugly workaround
  processUserWorkaround(userName) {
    const user = this.users.find(u => u.name == userName);
    //do stuff
  }
}

Full Stackblitz

A: You can access the selected index on the change event with $event.target.selectedIndex.  You can use this index to get the whole object from the users array and passed that object to processUser method.
Example
<select
  formControlName="userName"
  (change)="processUser(users[$event.target.selectedIndex])"
>
  <option *ngFor="let user of users" [value]="user.name">{{ user.name }}</option>
</select>

Stackblitz
https://stackblitz.com/edit/angular-7kjrps


text:
Q: Force package uninstall when it fails I have a system with some broken dependencies, but when trying to uninstall them, via apt-get purge or via dpkg --purge --force-all, the process fails with errors were encountered while processing.
More specifically, I have a linux-image-extra package and it's linux-image dependency is no longer isntallable. I have more recent kernels installed so removing this should not be a problem, but the uninstall process always fails.
So can I force remove that package so there are no more conflicts and I can update my system again?

The errors while uninstalling:
sudo dpkg --purge --force-all linux-image-extra-3.19.0-51-generic
(Reading database ... 229019 files and directories currently installed.)
Removing linux-image-extra-3.19.0-51-generic (3.19.0-51.58) ...
depmod: FATAL: could not load /boot/System.map-3.19.0-51-generic: No such file or directory
run-parts: executing /etc/kernel/postinst.d/apt-auto-removal 3.19.0-51-generic /boot/vmlinuz-3.19.0-51-generic
run-parts: executing /etc/kernel/postinst.d/initramfs-tools 3.19.0-51-generic /boot/vmlinuz-3.19.0-51-generic
update-initramfs: Generating /boot/initrd.img-3.19.0-51-generic
WARNING: missing /lib/modules/3.19.0-51-generic
Ensure all necessary drivers are built into the linux image!
depmod: ERROR: could not open directory /lib/modules/3.19.0-51-generic: No such file or directory
depmod: FATAL: could not search modules: No such file or directory
sed: can't read /usr/share/plymouth/themes/kubuntu-text/kubuntu-text.plymouth: No such file or directory
E: /usr/share/initramfs-tools/hooks/plymouth failed with return 2.
update-initramfs: failed for /boot/initrd.img-3.19.0-51-generic with 2.
run-parts: /etc/kernel/postinst.d/initramfs-tools exited with return code 2
dpkg: error processing package linux-image-extra-3.19.0-51-generic (--purge):
 subprocess installed post-removal script returned error exit status 1
Errors were encountered while processing:
 linux-image-extra-3.19.0-51-generic

A: There's no general procedure, but needs a case-by-case approach.  As you can see from these pages, there's a recommended approach which does not always work:

*

*How to remove/install a package that is not fully installed?

*How to delete broken packages in ubuntu

*How to remove an incomplete package by using apt-get?
If you have tried the recommended procedures, then you're in the realm of troubleshooting.
Sometimes you can appease the uninstall-script by adding dummy files or directories.  This is a case where you could do that:
depmod: ERROR: could not open directory /lib/modules/3.19.0-51-generic: No such file or directory

However, in this case,
depmod: FATAL: could not load /boot/System.map-3.19.0-51-generic: No such file or directory

is hard to work around because that would be a file with a given format.  (You could try making a zero-length file, but likely that will not work).
Alternatively, reinstalling the broken package sometimes works, by getting the missing pieces back into some order that the uninstaller can handle.


text:
Q: How to remove unused git branches How can one remove unused git bracnhes from Tortoise-Git? These branches have been removed both locally and remotely, i'd like to not see them anymore when using this dropdown

A: You need to run git remote prune origin. This will get rid of remote tracking branches which no longer represent a branch on the remote.

A: As of TortoiseGit 2.4.0.2 there is a way to let it execute git remote prune origin. In the Sync window you can select "Clean up stale remote branches" which then will remove all already removed remote branches from your local cache.
I don't know if this already exists in previous versions, because I normally use the command line ^^

A: Maybe you just pruned/removed the branches and the cache is not up-to-date. You could kill the tgitcache.exe process to reset the cache.

A: You can do 'view log' and then scroll down to where you see the branch marker, right-click and ask to delete it.  Typically you will see it twice as foo and origin/foo and you may want to delete both.
I have not found a way to do the equivalent of git remote prune origin from the TortoiseGit GUI.


text:
Q: Facebook api with monotouch I'm having troubles using the facebook binding from here ( https://github.com/mono/monotouch-bindings/tree/master/facebook ) and the problem is that the authorize ( login ) function doesn't work on the device.  On the simulator it's working perfect, but from the device instead of the webbrowser login window it launches the official facebook app ( installed on the phone ).
The same thing happens with the sample provided with the binding.
Any ideeas how can I use the browser to login ( if I unninstall the official facebook app it works ok on the device also ) instead of the facebook app?
The code I use:
class SessionDelegate : FBSessionDelegate
{
    AppDelegate container;
    NSAction onLogin;

    public NSAction OnLogin {
        get {
            return this.onLogin;
        }
        set {
            onLogin = value;
        }
    }

    public SessionDelegate (AppDelegate container)
    {
        this.container = container;
    }

    public override void DidNotLogin (bool cancelled)
    {
        Console.WriteLine("did not login");
        //container.SaveAuthorization ();
        if( OnLogin != null ) OnLogin.Invoke();
    }

    public override void DidLogin ()
    {
        Console.WriteLine("login !");
        container.SaveAuthorization ();
        if( OnLogin != null ) OnLogin.Invoke();
    }

    public override void DidLogout ()
    {
        Console.WriteLine("logout !");
        container.ClearAuthorization();
    }
}

And:
var sessionDelegate = new SessionDelegate (this);
facebook            = new Facebook (LocalSettings.FacebookAppId, sessionDelegate);
var defaults = NSUserDefaults.StandardUserDefaults;
if (defaults ["FBAccessTokenKey"] != null && defaults ["FBExpirationDateKey"] != null)
{
         facebook.AccessToken    = defaults ["FBAccessTokenKey"] as NSString;
         facebook.ExpirationDate = defaults ["FBExpirationDateKey"] as NSDate;
}

and for login:
facebook.Authorize(new string [] { "email", "publish_stream", "read_friendlists", "user_photos" });

A: Okay, so I found the answer myself.  The problem was in the facebook developer app settings, the iOS Bundle ID didn't was the same with the one in monodevelop identifier :)

A: This functionality is the developer's intend. First I don't understand why you don't want this and Second this is a open-source library. you can walk through the code and find the piece of code that makes it. Then change it to what you want. I am now searching for this in this library. As long as I got the answer I reply it. But my guess is that they have used UIApplication.SharedApplication.* to open up Facebook app if it is available.
Sincerely yours,
Peyman Mortazavi

A: FWIW: you'll get the same error if you are in the sandbox and try to logon with a real user.


text:
Q: How to extract the required protocol from event log file of honeypot? I tried multiple ways as per my code knowledge. But not able to extract the required protocols (HTTP, MODBUS, SNMP, FTP, Bacnet).
Header: timestamp, IP, IP Country, Request

Input Raw

2019-08-27 12:11:08,078 TFTP Serving File System at /data/tftp/ in vfs. TFTP data_fs sub directory: /tftp
2019-08-27 12:11:08,081 Found and enabled tftp protocol.
2019-08-27 12:11:08,081 No proxy template found. Service will remain unconfigured/stopped.
2019-08-27 12:11:08,082 Modbus server started on: ('0.0.0.0', 5020)
2019-08-27 12:11:08,083 S7Comm server started on: ('0.0.0.0', 10201)
2019-08-27 12:11:08,083 HTTP server started on: ('0.0.0.0', 8800)
2019-08-27 12:11:08,453 SNMP server started on: ('0.0.0.0', 16100)
2019-08-27 12:11:08,455 Bacnet server started on: ('0.0.0.0', 47808)
2019-08-27 12:11:08,456 IPMI server started on: ('0.0.0.0', 6230)
2019-08-27 12:11:08,456 handle server PID [    1] running on ('0.0.0.0', 44818)
2019-08-27 12:11:08,457 handle server PID [    1] responding to external done/disable signal in object 140147125794088
2019-08-27 12:11:08,458 FTP server started on: ('0.0.0.0', 2121)
2019-08-27 12:11:08,458 Starting TFTP server at ('0.0.0.0', 6969)
2019-08-27 12:12:36,979 New http session from 202.3.77.166 (ca5a29c6-e107-4b18-99c1-08338aabfbc5)
2019-08-27 12:12:36,981 HTTP/1.1 GET request from ('202.3.77.166', 34142): ('/', [('Host', '67.207.87.192'), ('Connection', 'keep-alive'), ('Upgrade-Insecure-Requests', '1'), ('User-Agent', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'), ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3'), ('Accept-Encoding', 'gzip, deflate'), ('Accept-Language', 'en-US,en;q=0.9,bn;q=0.8')], None). ca5a29c6-e107-4b18-99c1-08338aabfbc5
2019-08-27 12:12:36,981 HTTP/1.1 response to ('202.3.77.166', 34142): 302. ca5a29c6-e107-4b18-99c1-08338aabfbc5
2019-08-27 12:12:37,553 HTTP/1.1 GET request from ('202.3.77.166', 34142): ('/index.html', [('Host', '67.207.87.192'), ('Connection', 'keep-alive'), ('Upgrade-Insecure-Requests', '1'), ('User-Agent', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'), ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3'), ('Accept-Encoding', 'gzip, deflate'), ('Accept-Language', 'en-US,en;q=0.9,bn;q=0.8')], None). ca5a29c6-e107-4b18-99c1-08338aabfbc5
2019-08-27 12:12:37,553 HTTP/1.1 response to ('202.3.77.166', 34142): 200. ca5a29c6-e107-4b18-99c1-08338aabfbc5
2019-08-27 12:12:38,760 HTTP/1.1 GET request from ('202.3.77.166', 34142): ('/favicon.ico', [('Host', '67.207.87.192'), ('Connection', 'keep-alive'), ('User-Agent', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'), ('Accept', 'image/webp,image/apng,image/*,*/*;q=0.8'), ('Referer', 'http://67.207.87.192/index.html'), ('Accept-Encoding', 'gzip, deflate'), ('Accept-Language', 'en-US,en;q=0.9,bn;q=0.8'), ('Cookie', 'path=/')], None). ca5a29c6-e107-4b18-99c1-08338aabfbc5
2019-08-27 12:12:38,761 HTTP/1.1 response to ('202.3.77.166', 34142): 404. ca5a29c6-e107-4b18-99c1-08338aabfbc5
2019-08-27 12:13:08,778 Session timed out: ca5a29c6-e107-4b18-99c1-08338aabfbc5
2019-08-27 12:14:17,470 New http session from 165.16.37.187 (d39c9889-d4ab-41f2-b4c4-6d16ce34c830)
2019-08-27 12:14:17,471 HTTP/1.1 GET request from ('165.16.37.187', 56987): ('/', [('Host', '67.207.87.192:80'), ('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'), ('Content-Length', '0')], b''). d39c9889-d4ab-41f2-b4c4-6d16ce34c830
2019-08-27 12:14:17,471 HTTP/1.1 response to ('165.16.37.187', 56987): 302. d39c9889-d4ab-41f2-b4c4-6d16ce34c830
2019-08-27 12:14:47,488 Session timed out: d39c9889-d4ab-41f2-b4c4-6d16ce34c830
2019-08-27 12:15:51,814 New modbus session from 202.3.77.166 (b6f3d1ea-dd32-452f-9dab-ab996dfeca5a)
2019-08-27 12:15:51,814 New Modbus connection from 202.3.77.166:39755. (b6f3d1ea-dd32-452f-9dab-ab996dfeca5a)
2019-08-27 12:15:51,816 Exception caught: Modbus Error: Exception code = 2. (A proper response will be sent to the peer)
2019-08-27 12:15:51,818 Modbus traffic from 202.3.77.166: {'request': b'00010000004f0110000000244861626364656667685aee12a9881234edccffff56781234b85241b2b852c1b241112152ffffffffbeefdead56781234beefdea

I build the code. But the code have too much bug or I used very wrong coding technique. Please help me. It will improve my way of understanding code.

Code:

import pandas as pd
import re
import datetime
from datetime import datetime

http=[]
time=[]

def reader(file):
    with open(file, 'r') as f:
        for line in f:
            line_split=line.split(" ")
            Timestamp=line_split[0:2]
            Timestamp=str(Timestamp[0])+" "+str(Timestamp[1])
            Timestamp=Timestamp.split(",")[0]
            main_line=line_split[2:]
            #time.append(Timestamp)
            print(main_line[1])

            if (
               main_line[0]=="HTTP/1.1" or main_line[0]=="Modbus" or main_line[0]=="Modbus" or main_line[0]=="Bacnet" and
               main_line[1]=="http" or main_line[1]=="modbus" or main_line[1]=="Bacnet" or main_line[1]=="ftp"

                 ):
               http.append(Timestamp)
               http.append(main_line)
               print(main_line,"====>", Timestamp)
               continue

            database = ({'Timestamp':http[0], 'Request':http})
            dataframe = pd.DataFrame(database)
            print(dataframe.head())
            dataframe.to_csv('task_raw1.csv', index=False)

  if __name__ == "__main__":
    reader("/content/drive/MyDrive/task2.log")

Output:

Timestamp,Request
2019-08-27 11:58:07,2019-08-27 11:58:07
2019-08-27 11:58:07,"['Conpot', 'modbus', 'initialized\n']"
2019-08-27 11:58:07,2019-08-27 11:58:07
2019-08-27 11:58:07,"['Conpot', 'Bacnet', 'initialized', 'using', 'the', '/home/conpot/.local/lib/python3.6/site-packages/conpot-0.6.0-py3.6.egg/conpot/templates/default/bacnet/bacnet.xml', 'template.\n']"
2019-08-27 11:58:07,2019-08-27 11:58:07
2019-08-27 11:58:07,"['Modbus', 'server', 'started', 'on:', ""('0.0.0.0',"", '5020)\n']"
2019-08-27 11:58:07,2019-08-27 12:05:46
2019-08-27 11:58:07,"['Conpot', 'modbus', 'initialized\n']"
2019-08-27 11:58:07,2019-08-27 12:05:46
2019-08-27 11:58:07,"['Conpot', 'Bacnet', 'initialized', 'using', 'the', '/home/conpot/.local/lib/python3.6/site-packages/conpot-0.6.0-py3.6.egg/conpot/templates/default/bacnet/bacnet.xml', 'template.\n']"
2019-08-27 11:58:07,2019-08-27 12:05:46
2019-08-27 11:58:07,"['Modbus', 'server', 'started', 'on:', ""('0.0.0.0',"", '5020)\n']"
2019-08-27 11:58:07,2019-08-27 12:11:08
2019-08-27 11:58:07,"['Conpot', 'modbus', 'initialized\n']"
2019-08-27 11:58:07,2019-08-27 12:11:08
2019-08-27 11:58:07,"['Conpot', 'Bacnet', 'initialized', 'using', 'the', '/home/conpot/.local/lib/python3.6/site-packages/conpot-0.6.0-py3.6.egg/conpot/templates/default/bacnet/bacnet.xml', 'template.\n']"
2019-08-27 11:58:07,2019-08-27 12:11:08
2019-08-27 11:58:07,"['Modbus', 'server', 'started', 'on:', ""('0.0.0.0',"", '5020)\n']"
2019-08-27 11:58:07,2019-08-27 12:12:36
2019-08-27 11:58:07,"['HTTP/1.1', 'GET', 'request', 'from', ""('202.3.77.166',"", '34142):', ""('/',"", ""[('Host',"", ""'67.207.87.192'),"", ""('Connection',"", ""'keep-alive'),"", ""('Upgrade-Insecure-Requests',"", ""'1'),"", ""('User-Agent',"", ""'Mozilla/5.0"", '(X11;', 'Linux', 'x86_64)', 'AppleWebKit/537.36', '(KHTML,', 'like', 'Gecko)', 'Chrome/76.0.3809.132', ""Safari/537.36'),"", ""('Accept',"", ""'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3'),"", ""('Accept-Encoding',"", ""'gzip,"", ""deflate'),"", ""('Accept-Language',"", ""'en-US,en;q=0.9,bn;q=0.8')],"", 'None).', 'ca5a29c6-e107-4b18-99c1-08338aabfbc5\n']"
2019-08-27 11:58:07,2019-08-27 12:12:36
2019-08-27 11:58:07,"['HTTP/1.1', 'response', 'to', ""('202.3.77.166',"", '34142):', '302.', 'ca5a29c6-e107-4b18-99c1-08338aabfbc5\n']"
2019-08-27 11:58:07,2019-08-27 12:12:37
2019-08-27 11:58:07,"['HTTP/1.1', 'GET', 'request', 'from', ""('202.3.77.166',"", '34142):', ""('/index.html',"", ""[('Host',"", ""'67.207.87.192'),"", ""('Connection',"", ""'keep-alive'),"", ""('Upgrade-Insecure-Requests',"", ""'1'),"", ""('User-Agent',"", ""'Mozilla/5.0"", '(X11;', 'Linux', 'x86_64)', 'AppleWebKit/537.36', '(KHTML,', 'like', 'Gecko)', 'Chrome/76.0.3809.132', ""Safari/537.36'),"", ""('Accept',"", ""'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3'),"", ""('Accept-Encoding',"", ""'gzip,"", ""deflate'),"", ""('Accept-Language',"", ""'en-US,en;q=0.9,bn;q=0.8')],"", 'None).', 'ca5a29c6-e107-4b18-99c1-08338aabfbc5\n']"
2019-08-27 11:58:07,2019-08-27 12:12:37
2019-08-27 11:58:07,"['HTTP/1.1', 'response', 'to', ""('202.3.77.166',"", '34142):', '200.', 'ca5a29c6-e107-4b18-99c1-08338aabfbc5\n']"

Required Output

Timestamp, IP, IP Location, Request

2019-08-27 11:58:07, 202.3.77.166, India, HTTP

2019-08-27 11:58:07, 172.3.77.166, US, MODBUS

2019-08-27 11:58:07, 202.3.77.168, India, HTTP

2019-08-27 11:58:07, 172.13.77.198, India, HTTP


text:
Q: How to set up DataSources for GraphQL Subscriptions in Apollo without long running cache I'm using RESTDataSource as the basis for all REST backend operations in Apollo server. This works fine for Queries and Mutations, and in particular the ability to use cached responses within a single request is working as expected.
I want to use my RESTDataSource implementations in the context of Subscriptions as well, in case the client asks for detail that is not present in the "native" payload of the subscription message (in which case Apollo will call the appropriate resolver to go get it).
Currently I am initialising my RESTDataSources as part of the context callback function used by ApolloServer, and adding them to the returned context (I am only doing this if the callback is passed a connection object).
The problem is that this is called on establishment of the subscription, rather than on arrival of each message over that subscription. So the natural caching behaviour of the RESTDataSource kicks in for as long as the subscription is held open, and this may be too long to be comfortable with cached responses.
I'd be interested in any advice as to how to overcome this; possibly instantiating the data sources in some way as to disable caching in this particular case, or somehow reinitialising the datasources in the context on the arrival of each message (although I couldn't see a suitable entry point for that).


text: Q: How do I modify the value of jQuery countdown for WordPress plugin? I'am working on a countdown WordPress plugin for products offers I have a user form to set the countdown witch contain days labels, hours label, minutes label.  I have a sample named "classy-countdown" and this is the link. I want know how do i define the "end" variable to get values inserted by user.


text:
Q: Increase color saturation with sass mixin I'm trying to write looped mixin that iteratively increases the saturation of a background-color.  Here's the latest mixin code:
@mixin generateBackgroundSteps($cell-count, $color) {
    @for $i from 0 through $cell-count - 1 {
        $percent: (5 * $i) + "%";
        $new-color: saturate($color, $percent);

        &[setting-id="#{$i}"] {
            background-color: $new-color;
        }
    }
}

No matter how I've altered this, the produced css just keeps looking like this:
.rubric-design .rubric .create-new-criteria .create-criteria-initial-
settings .create-criteria-setting[setting-id="2"] {
      background-color: saturate(#90afc8);
}

Maybe it's the way I'm forming $percent.  It must be something obvious!

A: Try using percentage function.
percentage function in SCSS
$percent: percentage((5 * $i) / (5 * $cell-count));

@mixin generateBackgroundSteps($cell-count, $color) {
@for $i from 0 through $cell-count - 1 {
    $percent: percentage((5 * $i) / (5 *$cell-count));
    $new-color: saturate($color, $percent);

    &[setting-id="#{$i}"] {
        background-color: $new-color;
    }
 }
}


text:
Q: If $ X = \underset{1\le i\le n}{\max} X_i$, then show that $ E [X] = O(\log{n})$ I have a follow-up question based on my question here please Question.
Let the random variable $X_i$ denote the number of probes required by the ith insertion (insert an item $i$ into a hash table of size $m$ and $n$ elements total. Given that  $Pr\{X_i> 2 \log{n}\} \le \frac{1}{n^2}$ . Let the random variable $X = \underset{1\le i\le n}{\max} X_i$ denote the maximum number of probes required by any of the $n$ insertions.
Here we would like to show that if $ X = \underset{1\le i\le n}{\max} X_i$, then show that $ E [X] = O(\log{n})$.
Given: $X_i's$ are independent. Also given that $P(\underset{1\le i\le n}{\max} X_i \le 2 \log{n}) \le 1$ and $P(\underset{1\le i\le n}{\max} X_i > 2\log{n}) = \frac{1}{n}$.
From what I got,
$$
\begin{align}
$ E[X] = E\left[\underset{1\le i\le n}{\max} X_i\right]=\sum_{k=1}^{n}\left(k\times P(\underset{1\le i\le n}{\max} X_i=k) \right)\\
=\sum_{k=1}^{2\log{n}}\left(k\times P(\underset{1\le i\le n}{\max} X_i=k) \right) + \sum_{k=2\log{n} +1 }^{n}\left(k\times P(\underset{1\le i\le n}{\max} X_i=k) \right)\\
\le =\sum_{k=1}^{2\log{n}}\left(2\log{n}\times P(\underset{1\le i\le n}{\max} X_i=k) \right) + \sum_{k=2\log{n} +1 }^{n}\left(n\times P(\underset{1\le i\le n}{\max} X_i=k) \right)\\
=2\log{n}\times \sum_{k=1}^{2\log{n}}\left(P(\underset{1\le i\le n}{\max} X_i=k) \right) + n\times \sum_{k=2\log{n} +1 }^{n}\left( P(\underset{1\le i\le n}{\max} X_i=k) \right)\tag{1} \label{1}\\
=2\log{n}\times \left(P(\underset{1\le i\le n}{\max} X_i \le 2\log{n}) \right) + n\times \left(P(\underset{1\le i\le n}{\max} X_i > 2\log{n}) \right) \tag{2} \label{2}\\
\end{align}
$$
Problems:

*

*Where did the sum disappear in \ref{2} from \ref{1} please?

*Can you please show in \ref{2}, how we got $\le 2 \log{n}$ and $> 2 \log{n}$ please?

A: Note than the symbol $=$ becomes $\leq$ and $>$ because:
$$\sum_{k=1}^a\mathbf{P}(Y=k)=\mathbf{P}(Y\leq a)=F_Y(a)$$
$$\sum_{k=a+1}^\infty\mathbf{P}(Y=k)=\mathbf{P}(Y>a)=1-F_Y(a)$$
where $F_Y(\cdot)$ is the cdf of Y. Is it understood how to complete the proof?


text:
Q: It is possible to take incremental backup in mongoDB Shard cluster? without opsmanager Shard MongoDB Cluster:

*

*3-router

*3-config

*2-shard (3-replica's per shard)

We are trying to take incremental backup for every one hour. We gone through few google links, but no luck. As per our above setup, to achieve incremental backup we need to take mongodump with oplogs sperately from config, shard1 and shard2 secondary servers and we will store it in s3. But the problem is with restoration part. To restore, all those dump (config, shard1 and shard2) needs to be downloaded from s3 and restore it to its specific replicaset. which means config dump to config and shard dump to shard.
Is this the correct process or we have any other option to take incremental backup with single query?
Thanks


text:
Q: making an object move without cocos2d? I am trying to make a button move in my application without having to implement the cocos2d framework in my application. I am making a data application and dont want to add any other game elements except for a button that moves. Does anyone know how to do this?

A: To move any object you simply have to give it a new frame by setting
myView.frame = CGRectMake( x, y, width, height );

You can even easily have the phone animate it for you without any added frameworks by wrapping it with [UIView beginAnimation...] blocks.
Here's an example:
[UIView beginAnimations:@"moveButton" context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
[UIView setAnimationDuration:0.5];

someButton.frame = CGRectMake( newX, newY, newWidth, newHeight );

[UIView commitAnimations];

A: You can move a view directly using
[theview setFrame:CGRectMake(x,y,w,h)];

or you can use animations to do so a in cooler way (this should be the iOS 4.x Way)
[UIView animateWithDuration:2.0
                          delay:0.0
                        options:UIViewAnimationOptionLayoutSubviews
                     animations:^{ [theview setFrame:CGRectMake(x,y,w,h)]; }
                     completion:^(BOOL finished){
                         [self iAmDoneAnimatingNowICanDoSomethingElse]; }];


text:
Q: ProgressBar in ActionBar appcompat I am trying to use appcompat in my application. But ProgressBar in ActionBar very big. How I can do ProgressBar less?
http://itmages.ru/image/view/1451590/2f1dfa13
code manifest
<activity
 android:screenOrientation="portrait"
 android:name="com.example.ok1.MainActivity"
 android:theme="@style/Theme.AppCompat.Light"
 android:label="@string/app_name" >

A: <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="@dimen/abc_action_button_min_width"
    android:minWidth="@dimen/abc_action_button_min_width">

   <ProgressBar
       style="@style/Widget.AppCompat.ProgressBar"
       android:layout_width="32dp"
       android:layout_height="32dp"
       android:layout_gravity="center"/>

</FrameLayout>

This may help you..

A: Please use style in progressbar
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="?android:attr/android:progressBarStyleSmall" />


text:
Q: Trying to use variables from variable file in ansible playbook Hello I am having a hard time using variables from a variable file in my playbook. I am using a variable file snapshot that is on the same This is my code I am just trying to loop through one item in the list I have.
snapshotvar.yml
kvm1
  - vm1
  - vm2
kvm2
  - vm4
  - vm3
  - vm5

kvmsnapshot.yml
---
- hosts: kvm2
  vars_files:
    - snapshot.yml
  tasks:
  - name: Create kvm snapshot
    ovirt_snapshot:
      vm_name: "{{ item }}"
      description: prepatch
    loop: "{{ kvm2[2] }}"

A: you have some error in your var file: (you forget :) and give the correct name (snapshot.yml)
kvm1:
  - vm1
  - vm2
kvm2:
  - vm4
  - vm3
  - vm5

after if you  just want to use the item with second index, no need to loop:
---
- hosts: kvm2
  vars_files:
    - snapshot.yml
  tasks:
  - name: Create kvm snapshot
    ovirt_snapshot:
      vm_name: "{{ kvm2[2] }}"
      description: prepatch

if you want to loop over all values of kvm2:
---
- hosts: kvm2
  vars_files:
    - snapshot.yml
  tasks:
  - name: Create kvm snapshot
    ovirt_snapshot:
      vm_name: "{{ item }}"
      description: prepatch
    loop: "{{ kvm2 }}"

A: There is a couple of syntax errors.

*

*Fix YAML of the file snapshotvar.yml

shell> cat snapshotvar.yml
kvm1:
  - vm1
  - vm2
kvm2:
  - vm4
  - vm3
  - vm5

*Fix the name of the file snapshotvar.yml and the name of the variable kvm2 that you want to iterate

- hosts: localhost
  vars_files:
    - snapshotvar.yml
  tasks:
    - debug:
        var: item
      loop: "{{ kvm2 }}"

gives
  item: vm4
  item: vm3
  item: vm5

Fit the task to your needs.


text:
Q: Взаимодействие сервлета с компонентой enterprise java beans Каким образом получить ссылку на объект локального интерфейса java beans в сервлете.
Локальный интерфейс:
package model;

import javax.ejb.Local;

@Local
public interface GenericBeanLocal {

    public String info();
}

Класс Java beans:
package
    model;
import java.util.Date;

import javax.ejb.Stateless;

@Stateless(mappedName = "genbean")
public class GenericBean implements GenericBeanRemote, GenericBeanLocal {

    public GenericBean() {}
    public String info() {
        return ""+new Date();
    }

}

Сервлет в котором необходимо получить ссылку на локальный интерфейс компоненты java beans:
package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.GenericBeanLocal;

public class CheckAvtorization extends HttpServlet {
    @EJB
    private GenericBeanLocal ejblocalinter;
    public CheckAvtorization() {
        System.out.println("CheckAvtorization Constructor()");
                            }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setCharacterEncoding("UTF8");
        PrintWriter out = resp.getWriter();
            System.out.println("CheckAvtorization doPost()");

    String pass = req.getParameter("pas");
    String log = req.getParameter("log");

    Connection conn = my.service.db.MySqlConnector.getConnection(log,pass);
    if(conn!=null){
        out.println("Авторизация выполнена "+log);
    }else{
        out.println("Пшол Вон"+log+"/"+pass);
    }
    out.println("<hr> EJB JenericBeanLocal Interface : "+ejblocalinter);

    try {
        conn.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    }

}

Tomcat выдает ошибку связанную с невозможностью получить объект интерфейса GenericBeanLocal.
Код ошибки:
HTTP Status 500 - Error instantiating servlet class servlets.CheckAvtorization

type Exception report

message Error instantiating servlet class servlets.CheckAvtorization

description The server encountered an internal error that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: Error instantiating servlet class servlets.CheckAvtorization
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852)
    java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    java.lang.Thread.run(Unknown Source)
root cause

javax.naming.NameNotFoundException: Name [servlets.CheckAvtorization/ejblocalinter] is not bound in this Context. Unable to find [servlets.CheckAvtorization].
    org.apache.naming.NamingContext.lookup(NamingContext.java:820)
    org.apache.naming.NamingContext.lookup(NamingContext.java:168)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852)
    java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    java.lang.Thread.run(Unknown Source)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.42 logs.

Apache Tomcat/7.0.42

A: А Вы уверены что "Tomcat выдает ошибку связанную с невозможностью получить объект интерфейса GenericBeanLocal."? ;)
Я бы попробовал изменить модификатор доступа метода сервлета.
Параметры "log" и "pas" конечно-же заявлены в Context сервлета? Кстати а какой объект у Вас соответствует ссылочной переменной "ejblocalinter" и какую функцию у Вас выполняет блок try{}catch{}?


text:
Q: Is the $ L^{p}$$[0,1]$ norm continuous in p? I ran into the following problem when I was doing my homework, and I have no thoughts on where I should start with:
(1) If $f\in L^{2}$, show that $\displaystyle \lim_{p \rightarrow 1^{+}}\int_{[0,1]}|f|^{p}=\int_{[0,1]}|f|$
(2) If $0<p$, show that $\displaystyle \lim_{q\rightarrow p^{-}}||f||_{q}=||f||_{p}$
My first thought was Generalized LDCT, but it didn't seem to work. I also made some other attempts but none of them were successful... Can anybody give me some hints on how I should look at this question?
Also, I know if $p\rightarrow\infty$ then $||f||_{p}\rightarrow||f||_{\infty}$ on $[0,1]$, but does similar continuity in p holds for other $L^{p}[0,1]$ norms in general?
Thank you!
Edit:
Sorry if I did not make it clear enough in the question. All $L^{p}$ refers to $L^p[0,1]$.
The first question is found here (thanks to t.b.), but the second question remains, mainly because $f$ is not guaranteed to be in any $L^{p}$.

A: For (2), you've addressed all cases except $f \notin L^p$ with $p &lt \infty$.  As $q \to p^-$, we have $|f|^q \to |f|^p$ pointwise, so by Fatou's lemma
$$\liminf_{q \to p^-} \int |f|^q \ge \int |f|^p = \infty.$$
This means $\int |f|^q \to \infty$ as $q \to p^-$.  Putting the powers of $1/q$ back in is left as an exercise :)

A: I was thinking about this: if $q&ltp$ and $f \in L^p(0,1)$, then $f \in L^q(0,1)$. Just Hölder inequality. In case (2), you have to consider two cases: (i) $f \in L^p$ and $\|f\|_p=+\infty$.


text:
Q: what is replacement of sem_getvalue() in MacOS? I have a code that use unnamed semaphore with thread join. I wanted to compile it in MacOS but I figured out unnamed semaphore is not supported in MacOS and dispatch semaphore is a replacement for it.
In my code there is a point that I want to post semaphore till semaphore counter become equal zero so I use sem_getvalue() function. Here is my code
sem_getvalue(&(event), &res);
while (res <= 0) {
   sem_post(&(tcp_client->resp_event));
   res++;
}

1.Is there any way to handle this with dispatch semaphore?
2.Is there any better way to replace unnamed semaphore in MacOS?

A: This is a very suspect thing to want to do with a semaphore. It suggests that you should be using some other synchronization mechanism, perhaps a condition lock.
That said, no, dispatch semaphores don't directly provide a mechanism like this. But a semaphore is a very basic synchronization primitive on which almost any other synchronization scheme can be built. In order for us to suggest something, though, we'd need to know what you're using it for. For example, under what circumstances are you "resetting" your semaphore like this and why?


text:
Q: Vue.js v-model inside v-html I want to store html inside variable. Example:
data: function() {
  return {
    my_html: '<input type="text" v-model="data"'
  }
}

And I want to receive in data the value that user enters in the field. But this connection does not work
Full example:
var test = new Vue({
  el: '#some_id',
  data: function() {
    return {
      data: '',
      my_html: '<input type="text" v-model="data" />'
    }
  },
  template:
    '

      <input type="text" v-model="data" />
      <input type="text" v-model="data" />

'
});

In this example, the first two inputs will normally link with data and with each other, but the third (the one inside span) won't

A: According to the official doc :

The contents of the span will be replaced with the value of the rawHtml property, interpreted as plain HTML - data bindings are ignored. Note that you cannot use v-html to compose template partials, because Vue is not a string-based templating engine. Instead, components are preferred as the fundamental unit for UI reuse and composition

for more details try to check @RoyJ's answer


text:
Q: how to use char values as signed variable I am coding in arduino IDE, so basically C++. and I need to use a variable with only 1 byte for transmission purposes, but I need this to be signed.
More specifically I need to send an int(2byte) but this int has 2 values in it, one is a byte since I don't care of the sign since its always positive, but the other I need it to have negatives included.
I'm doing something like this.
turn = -120
int PromedioD_turn = PromedioD << 8 | (turn  & 0b11111111);
Serial.println("test");
Serial.println(PromedioD);
Serial.println(turn & 0b11111111,DEC);      //this is printing as 136
Serial.println(PromedioD_turn);

I cant understand why or how to solve this, I need to be able to send the value and also break it down later.

A: Thanks to @bolov by using int8_t i could convert it bach to signed value
int PromedioD_turn = PromedioD << 8 | turn & 0b11111111;
Serial.println("test");
Serial.println(PromedioD);
Serial.println(turn);
Serial.println(PromedioD_turn);
Serial.println(int8_t(PromedioD_turn &0b11111111));


text:
Q: Is there a file manager with Mac Os like column view for Linux?
Is there a file manager that supports navigating the folders and sub folders in the same window as finder does in OSX?

A: Yes. It's Elementary OS's Pantheon File manager. Install it using this ppa
sudo add-apt-repository ppa:elementary-os/stable
sudo apt-get update
sudo apt-get install pantheon-files

Activate this option by clicking the third button on the left hand side of the location bar.

A: I got the following working on ubuntu 18.04
sudo add-apt-repository ppa:elementary-os/daily
sudo apt-get update
sudo apt-get install pantheon-files

If the install fails, try manual installation of dependencies from here
References:
[1] How to install Pantheon Files on Ubuntu and Linux Mint


text:
Q: MongoDB $graphLookup until a condition is met (included) I am looking for how to use $graphLookup and its match condition to return all nodes until a condition is met, including matches breaks the condition in the recursion stack. the first node that satisfies the condition in the recursion stack on each separate branch.
This should work for an arbitrary topology.
EDIT: as Asya highlights, it's the first time that the condition is satisfied on each branch, and not on the entire recursion stack.
Example (note: "_id" fields in docs are omitted for brevity):
Data:
[
  {
    "key": 1,
    "parent": null,
    "name": "tom"
  },
  {
    "key": 2,
    "parent": 1,
    "name": "tom"
  },
  {
    "key": 3,
    "parent": 2,
    "name": "jack"
  },
  {
    "key": 4,
    "parent": 3,
    "name": "jonny"
  },
  {
    "key": 5,
    "parent": 1,
    "name": "jack"
  },
  {
    "key": 6,
    "parent": 5,
    "name": "jack"
  }
]

Query:
db.collection.aggregate([
  {
    "$match": {
      "parent": null
    }
  },
  {
    "$graphLookup": {
      "from": "collection",
      "startWith": "$key",
      "connectFromField": "key",
      "connectToField": "parent",
      "as": "children",
      "restrictSearchWithMatch": {
        "name": "jack"
      },
      "matchType":"firstHitAlongEachBranch"      // made-up option
    }
  }
])

Desired result:
[
  {
    "children": [
      {
        "key": 2,
        "name": "tom",
        "parent": 1
      },
      {
        "key": 3,
        "parent": 2,
        "name": "jack"
      },
      {
        "key": 5,
        "parent": 1,
        "name": "jack"
      },
    ],
    "key": 1,
    "name": "tom",
    "parent": null
  }
]

The result returns only the first of the three nodes (as expected).
Thank you

A: Apparently it's not possible to date.
There's an open Jira for it.


text:
Q: MDX (how to have various Date Dimensions in a single X Axis?) I have a cube containing facts each containing at least one Date Dimension :
Fact             :  Fact_Sales    , Fact_Leads        , Fact_Budget
Dimension Column :  FactorDateID  , LeadIssueDateID   , BudgetDateID
Now I need a Bar-chart with dates in X Axis and measures from all these facts in Y Axis (as Bar Values). Would you please guide me how to do that?
**I am forced to have all facts in a single cube and also i have to deploy different date usages for these different Dates(budgetdate,factordate,...) because they really differ from each other.


text:
Q: Store data on server and set in array for local function I work's on the ShoopingApp in Angular and for backend I using FireBase.
I have model category:
import { ProductModel } from "./product.model";

export class CategoryModel {

public id: number;
public name: string;
public description: string;
public image: string;
public products?: ProductModel[];

constructor(id: number, name: string, desciption: string, image: string, products: ProductModel[]) {
    this.id = id;
    this.name = name;
    this.description = desciption;
    this.image = image;
    this.products = products;
}
}

I setup service data-storage-service.ts for catching  and storing data from FireBase.
const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
    'Authorization': 'my-auth-token'
  })
}

@Injectable()
export class DataStorageServiceService {

  private heroesUrl = 'https://ng-recipefirebaseio.com/application.json';
  // URL to web api

  constructor(private http: HttpClient) { }

  storeCategoryList(productList: CategoryModel): Observable<CategoryModel> {
    return this.http.post<CategoryModel>(this.heroesUrl, productList).pipe(
      catchError(this.handleError<CategoryModel>('addCategory'))

    )

  }
  getHeroes(): Observable<CategoryModel[]> {
    return this.http.get<CategoryModel[]>(this.heroesUrl)
      .pipe(
        catchError(this.handleError('getHeroes', []))
      );
  }

  private handleError<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {
      console.error(error); // log to console instead

         return of(result as T);
    };
  }
}

I setup admin component, and i setup Modal from ngx-bootstrap. From this Modals I want send data to server. I using Reactive Forms for validation.
Admin component look :
@Component({
  selector: 'app-admin',
  templateUrl: './admin.component.html',
  styleUrls: ['./admin.component.css']
})
export class AdminComponent implements OnInit {

  category = <CategoryModel>{};

  //  category: CategoryModel[] = [];
  categoryList: CategoryModel[] = []
  categoryForm: FormGroup;
  modalRef: BsModalRef;

  constructor(private productsService: ProductsService, private dataStorageServiceService: DataStorageServiceService, private modalService: BsModalService) { }

  ngOnInit() {
    this.getCategory();
    this.initForm();

  }

  getCategory(): void {
    this.dataStorageServiceService.getCategory()
      .subscribe(category => this.categoryList = category);
  }

  storeCategoryList() {
    const nameCategory = this.categoryForm.value.name;
    const descriptionCategory = this.categoryForm.value.category;
    this.category.name = nameCategory;
    this.category.description = descriptionCategory;
    this.category.id = 1;
    this.category.products = null;
    this.dataStorageServiceService.storeCategoryList(this.category).subscribe(

      (category: CategoryModel) => {
        this.categoryList.push(category)
      }

    )
  }

  openModal(template: TemplateRef<any>) {
    this.modalRef = this.modalService.show(template);
  }

  private initForm() {
    this.categoryForm = new FormGroup({
      'name': new FormControl(null, Validators.required),
      'description': new FormControl(null, Validators.required)
    })
  }

}

I have problem when I want to store data  in list categoryList, eoror is ERROR TypeError: _this.categoryList.push is not a function. And in FireBase store like this:

And method getCategory() return this

A: Judging from the methodname "getCategory" I guess the method returns a single category. This leads to your categoryList not being an array at runtime and thus not having a push method which leads to the error you are getting.


text:
Q: Dynamically load Javascript file one at a time I am creating a loader. Since I use Firebase, I need to load the specific script files dynamically in the exact order. Here are the code in my HTML files. JsPack.js is a loader that will load specific scripts one at a time.
        <script id="loader" src="./header/jsPack.js" resources="firebasejs;firebaseInit;firebaseRef;jQuery"></script>

And here is my current jsPack.js file. This works perfectly in the exact order. However, it cannot load only specific scripts, and just loads all scripts at once.
// Dynamically loading dependancies
let firebasejs = {"url":"https://www.gstatic.com/firebasejs/4.3.1/firebase.js", "type": "text/javascript", "sync": false};
let firebaseInit = {"url":"./js/firebase_init.js", "type": "text/javascript", "sync": true};
let firebaseRef = {"url":"./js/firebase_ref.js", "type": "text/javascript", "sync": true};
let jQuery = {"url":"./js/jquery-3.2.1.js", "type": "text/javascript", "sync": true};
let bootStrap = {"url":"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js", "type": "text/javascript", "sync": false};

function loadingDependancies(target){
    return new Promise((resolve, reject) => {
        try {
            let script = document.createElement("script");
            script.type = target.type;
            script.async = target.async;
            script.src = target.url;
            document.body.appendChild(script);
        } catch (err) { reject(err) };
    });
};

loadingDependancies(firebasejs)
    .then(loadingDependancies(firebaseInit))
    .then(loadingDependancies(firebaseRef))
    .then(loadingDependancies(jQuery))
    .catch(err => {console.log(err)})

Now, I have changed it into something like this.
// Dynamically loading dependancies
let resources = document.getElementById("loader").getAttribute("resources")
let resourcesArr = resources.split(";");
// console.log(resourcesArr);

let list = {
    // JS Resources List
    firebasejs: {"url":"https://www.gstatic.com/firebasejs/4.3.1/firebase.js", "type": "text/javascript", "location": "body"},
    firebaseInit: {"url":"./js/firebase_init.js", "type": "text/javascript", "location": "body"},
    firebaseRef: {"url":"./js/firebase_ref.js", "type": "text/javascript", "location": "body"},
    jQuery: {"url":"./js/jquery-3.2.1.js", "type": "text/javascript", "location": "body"},
    bootStrap: {"url":"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js", "type": "text/javascript", "location": "head"}

    // CSS Resources List
};

function loadingDependancies(resourceName){
    new Promise((resolve, reject) => {
        try {
            let resource = list[resourceName];
            console.log(resourceName);
            let script = document.createElement("script");
            let placement = document.getElementsByTagName(resource.location)[0];
            script.type = resource.type;
            script.src = resource.url;
            placement.appendChild(script);
            console.log("Loaded: ", resource.url);
        } catch (err) { reject(err) };
    });
};

// const loadEachDependancy = async () => {
//     for (resourceName of resourcesArr) {
//         const x = await loadingDependancies(resourceName)
//         // console.log(x);
//     }
// }
// loadEachDependancy();

function forEachDependancy(arr, f){
    var i = 0;
    var nextPromise = function() {
        if (i >= arr.length) return;
        else {
            var newPromise = Promise.resolve(f(arr[i]));
            i++;
            return newPromise.then(nextPromise);
        }
    }
    return Promise.resolve().then(nextPromise);
}

forEachDependancy(resourcesArr, loadingDependancies);

It should have been working. However, all the scripts are loaded at once and the 2nd script cannot get the objects from the 1st. Right now, I do not know what is the problem with my codes. The page loads very fast , proving that those scripts are loaded at the same time. The 2nd script also returns error since it cannot get the objects from the 1st script. However, the console.log states that the scripts are loaded one at a time, which really confuses me.

Please respond if you know what is the problem with my codes. Thank you in advance.

Update: onload() with async works perfectly. Thank you very much. I did not expect we could put async inside script. With this I will not have to use Promise at all.

A: Use the script async attribute
Seems like the problem could be solved easily by setting the async attribute to false.  This way the scripts load in order and Firebase works.  If set to true then the scripts can load in unpredictable order based on size, location, etc. And Firebase may fail because firebase-app.js must always be loaded first. And in fact, you'll see those errors if you set async = true in the snippet.
  script.async = false;

Run the snippet to see the scripts load in order:

  [

    "https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js",
    "https://www.gstatic.com/firebasejs/8.10.1/firebase-analytics.js",
    "https://www.gstatic.com/firebasejs/8.10.1/firebase-app-check.js",
    "https://www.gstatic.com/firebasejs/8.10.1/firebase-auth.js",
    "https://www.gstatic.com/firebasejs/8.10.1/firebase-firestore.js",
    "https://www.gstatic.com/firebasejs/8.10.1/firebase-functions.js",
    "https://www.gstatic.com/firebasejs/8.10.1/firebase-messaging.js",
    "https://www.gstatic.com/firebasejs/8.10.1/firebase-storage.js",
    "https://www.gstatic.com/firebasejs/8.10.1/firebase-performance.js",
    "https://www.gstatic.com/firebasejs/8.10.1/firebase-database.js",
    "https://www.gstatic.com/firebasejs/8.10.1/firebase-remote-config.js",
    "https://code.jquery.com/jquery-3.6.0.min.js",
    "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"

  ].forEach(src => {

    let script = document.createElement('script');
    script.src = src;

    // if set true the scripts load in any order and Firebase may fail
    script.async = false;

    script.onload = console.log(src);

    document.body.append(script);

  });
Loading scripts...

A: I use this function to load script by order, it use onload event

function loadScript(src, callback) {
  var script = document.createElement("script");
  script.src = src;
  if (callback)
    script.onload = callback;
  var doc = document.head || document.body;
  doc.appendChild(script);
}

loadScript('https://www.gstatic.com/firebasejs/4.3.1/firebase.js', function() {
  console.log('firebase.js loaded');
  loadScript('https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js', function() {
    console.log('jquery.js loaded');
    console.log($('#test').val())
  });
})
<input id="test" value="777">


text:
Q: unable to get fancybox to work - opens in new window I have been trying to get fancybox to work in this free template that a nice guy gave away on reddit yesterday but I'm not having much luck. I'm decent with HTML/CSS but not too great at Jquery. If anyone could point me in the right direction I would appreciate it. I'm trying to get the portfolio images to pop up in fancyboxes.  http://jsfiddle.net/yz93H/1/  Thanks in advance for any help.

A: The jsfiddle you posted is a little bit difficult to work with due to all the relative paths, still, one thing I noticed is that you're not linking the Fancybox javascript into your document.
There should be something like:
`
`

Hopefully that will fix it.
EDIT: Sorry, missed your js at the end of the document. On a second look, I found your problem. The snippet you posted should come after jQuery has been loaded. Since your jQuery is only loaded at the end of the document, your code was throwing Object #<HTMLDocument> has no method 'ready'.
I've created a new fiddle with a working version of what you posted. Everything is loaded off CDN's and I've used Twitter's logo as a showcase: http://jsfiddle.net/tiagoespinha/yz93H/4/
Essentially, the only change you need is to put this

after jQuery's script tag.


text:
Q: What does "But it's no more the negroes than I can fly" mean? The following extract appears in Go Set a Watchman by Harper Lee:

They are all trying to tell me in some weird, echoing way that it's all on account of the Negroes… but it's no more the Negroes than I can fly and God knows, I might fly out the window anytime, now.

I don't understand what the bolded part means. What does no more than [verbal phrase] mean?

A: The author is saying that it is ludicrous to blame the Negroes. "It's no more the Negroes than...." She compares believing "It's all on account of the Negroes" to believing that "I can fly." Then she hedges in a mocking tone by indicating that "I might fly out the window." And if she did fly out the window then maybe one could blame the Negroes.

A: I will write an answer that is similar to that already contributed by @karyse, but slightly different.
I read the whole chapter your excerpt is taken from, and I also read a helpful review on Amazon.
The background for your excerpt is that the protagonist is feeling a bit hemmed in (claustrophobic) today, as her aunt is preparing for a women's get-together where the protagonist will be expected to engage in pleasant chit chat with people she never liked and hasn't seen in years, all while going through a major questioning of everything she thought she knew about the people who were close to her in her childhood.  Simple version: She is disappointed to see how little real progress her Southern home town has made in overcoming the racist legacy left by slavery and Jim Crow.  It is the 1950's, and whites in this little town are resisting the civil rights movement in ugly ways.  Even her father has disappointed her, turning out not to be consistent with the anti-racism crusader image she had of him.  She's depressed.

She sank into a deep armchair and considered how all occasions had made her poor indeed. My aunt is a hostile stranger, my Calpurnia won't have anything to do with me, Hank is insane, and Atticus—something's wrong with me, it's something about me. It has to be because all these people cannot have changed.
Why doesn't their flesh creep? How can they devoutly believe everything they hear in church and then say the things they do and listen to the things they hear without throwing up? … Everything I have ever taken for right and wrong these people have taught me—these same, these very people. So it's me, it's not them. Something has happened to me.
They are all trying to tell me in some weird, echoing way that it's all on account of the Negroes… but it's no more the Negroes than I can fly and God knows, I might fly out of the window any time, now.

As the previous answer, and the comments, have said, "it's no more the Negroes than I can fly" means that the the idea that the African Americans in her town are the cause of her malaise, and her home town's malaise, is as absurd as the idea that she can fly.
The next part (which I realize you didn't ask about, but which the previous answer misinterpreted, in my opinion) is "and God knows, I might fly out of the window any time, now." This is basically free association.  The protagonist (first person narrator) jumped from the phrase "I can fly" to imagining herself actually flying, and uses that image to express her feeling of claustrophobia.
Thus, the previous answer's interpretation of the second part of the sentence ("if she did fly out the window then maybe one could blame the Negroes") is incorrect, in my opinion.


text:
Q: Is it possible to access variables without putting "global" in front of them in functions? My code is much more complex than this, but here's the just of it:
$string = "wuddup";

function echothis() {
echo $string;
}

echothis();

Is there an easy way to do this without saying global $string?
Reason being, I have a check login function, with many variables and I have config variables outside the function...

A: Whatever happened to parameters?
function echothis($str) {
    echo $str;
}

echothis($string);

If you are having issues with managing variables and their scope, chances are you need to refactor your code structure.

A: Just Create a class and add static variables to it. You can access it from any where without creating an instance of the class.
class base2 {
public static $var2 = 1;

}
Refer it as below
echo base2::$var2;

A: You could have your function take in the variables as arguments or perhaps an array containing all these arguments.
$all_variables = array(
  "string" => "wuddup",
  "number" => 6,
  "an_array" => array(1, 3, 4)
);

function example_func($args) {
  // does things
}

example_func($all_variables);

Alternatively, you could create a class and reference the variables through $this.

A: You can define config variables as constants and call them inside the function.


text:
Q: Android app white screen freeze before Application class Application freezes with white screen from time to time(1 launch of 20) on every device before even Application/Activity classes call. Desperately need some help.
Gradle:
 apply plugin: 'com.android.application'

    android {
        signingConfigs {
            config {
                storeFile file('somejks')
            }
        }
        compileSdkVersion 23
        buildToolsVersion "23.0.3"
        dexOptions {
            javaMaxHeapSize "4g"
        }
        defaultConfig {
            applicationId "some.package.ddd"
            minSdkVersion 15
            targetSdkVersion 23
            versionCode 11
            versionName "2.1"
            renderscriptTargetApi 20
            renderscriptSupportModeEnabled true
            multiDexEnabled true
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
        productFlavors {
        }
        sourceSets { main { assets.srcDirs = ['src/main/assets', 'src/main/assets/sounds'] } }
    }
    buildscript {
        repositories {
            maven { url 'https://maven.fabric.io/public' }
        }

        dependencies {
            // The Fabric Gradle plugin uses an open ended version to react
            // quickly to Android tooling updates
            classpath 'io.fabric.tools:gradle:1.+'
        }
    }
    apply plugin: 'io.fabric'
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }
    dependencies {
        compile 'com.android.support:appcompat-v7:23.2.0'
        compile 'com.android.support:design:23.1.1'
        compile 'com.android.support:recyclerview-v7:23.2.0'
        compile 'com.android.support:cardview-v7:23.2.0'
        compile 'com.google.android.gms:play-services:8.4.0'
        compile 'com.facebook.rebound:rebound:0.3.8'
        compile 'com.daimajia.swipelayout:library:1.2.0@aar'
        compile 'com.facebook.fresco:fresco:0.10.0'
        compile('io.socket:socket.io-client:0.7.0') {
            exclude group: 'org.json', module: 'json'
        }
        compile 'io.pristine:libjingle:8871@aar'
        compile 'com.squareup:seismic:1.0.2'
        compile 'org.greenrobot:eventbus:3.0.0'
        compile('com.crashlytics.sdk.android:crashlytics:2.5.5@aar') {
            transitive = true;
        }
        compile 'com.google.code.gson:gson:2.6.2'
        compile 'com.android.support:multidex:1.0.1'
    }

Manifest part:
 <application
        android:name=".ApplicationClass"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".ui.activity.SplashActivity"
            android:launchMode="singleTop"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme"
            android:windowSoftInputMode="adjustPan">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>...

Can provide additional info as well, appreciate any help

A: Its happen with me also, I remove below method and its working fine,
@Override
public Context getBaseContext() {
    mContext = getBaseContext();
    return mContext;
}


text:
Q: Free Numpy Memory in Place Is there any way to get cause numpy to release the memory used by an array? I cannot just run del array as the array is referenced elsewhere.
Example of why this matters and why I think this is safe:
def run():
   arr = np.array(....)
   arr2 = process(arr)
   fit(arr2)

I am able to edit process but not run. Right now arr is holding a lot of memory that is no longer needed after process runs. I would like to delete the contents from arr from within process once I have created arr2.

A: You can try to resize the array to a small array:
arr.resize((2,), refcheck=False)

It changes the array in-place:

a.resize(new_shape, refcheck=True)
Change shape and size of array in-place.

...

Notes
This reallocates space for the data area if necessary.
Only contiguous arrays (data elements consecutive in memory) can be
  resized.
The purpose of the reference count check is to make sure you
  do not use this array as a buffer for another Python object and then
  reallocate the memory. However, reference counts can increase in
  other ways so if you are sure that you have not shared the memory
  for this array with another Python object, then you may safely set
  refcheck to False.


text:
Q: How can I implement Scalable Broadcast algorithm in aodv? I am trying to implement Scalable Broadcast algorithm for flooding in aodv. However, I can not understand how I can restrict the transmission to specific nodes only. Is there any predefined function available in inet for this?
Thank you so much for your help.


text:
Q: How to handle large images? I am using tikz to generate an image which is wider than the the available space for the document. The figure will be later added to another document. When I watch the figure in my document reader (evince) it is cut. I tried to use
\special{papersize=200mm,400mm}

without any apparent affect. How can view the entire image then?
Thanks

A: The safest method, in my opinion, is to issue
\usepackage[pass,papersize={200mm,400mm}]{geometry}

With the pass option the package won't change the default margins and overall setup chosen by the class, but will send the appropriate commands for the engine or driver used (pdftex for pdfLaTeX, dvips for LaTeX, xdvipdfmx for XeLaTeX) which are automatically detected. If another driver is used, it can be passed as
driver=dvipdfm
driver=vtex

(for those two particular printing driver and engine).
You can also use geometry for setting everything else about pagination (see the manual).


text:
Q: adding JPanel On JApplet and writing HTML page to run it I have a java applet and I want to add a pre-designed Jpanel on my jpanel as a form. My Jpanel form is in another java file called MyForm.java. my JavaApplet class code is:
public class JavaApplet extends JApplet{
    @Override
    public void init(){
        Container container = this.getContentPane();
        container.add(new MyForm());
    }
     }

My html code to run this page is as simple:

<TITLE>The Palindrome Page</TITLE>

My favorite meat-related palindrome is:

<APPLET CODE="JavaApplet.class" WIDTH=600 HEIGHT=100>
A secret if your browser does not support Java!
</APPLET>

now can I put both .class files (MyForm.clsss & JavaApplet.cleass) in htmls file? Is it necessary to put all of my code in single file?
thank you

A: *

*Add MyForm to a frame instead of the applet.  (You might create a frame in a main method and add it there.)

*Put those classes in a Jar.

*Make a (JNLP) launch file for it.

*Launch the Jar from a link using Java Web Start.

In answer to your specific questions.

now can I put both .class files (MyForm.clsss & JavaApplet.cleass) in htmls file?

If the loose class files are both in the same directory (and package), they should be found.  Safer though, to use a single Jar.

Is it necessary to put all of my code in single file?

Java source code file?  No - definitely not.  Classes?  Recommend 1 Jar.
If using a Jar, you'd need an archive attribute in the applet element.


text:
Q: Pylons root route ('') not behaving as ('/') I'm brand spanking new to Pylons, but I'm novice level with Django and expert level with Rails and CakePHP.
This works:
map.connect('/', controller='hello', action='index')

This doesn't work:
map.connect('', controller='hello', action='index')

Results in:

Not Found
  The resource could not be found.
  WSGI Server

The '' syntax is verbatum from the Pylons "Getting Started" guide and is identical to Django.

A: you should read http://pylonsbook.com/en/1.1/urls-routing-and-dispatch.html.
from my experience you cant set route to be an empty string ("")


text:
Q: Unity3D: Run-time generated AnimationClips leaking I currently create AnimationClips dynamically while my game is running to move some pieces around. You can see what I mean here: https://youtu.be/u1My9JX4K-c?t=8s , when the pieces get grouped together and then open again. I cannot reuse the clip because the pieces will have a different position next time, so all the movements need to be changed.
Right now, I create a new clip whenever I need them to be grouped and separated, and attempt to replace any existing clip with this:
private void ReplaceAndPlay(AnimationClip clip, string name) {
     var old = Anim.GetClip(name);
     if (old != null) {
         Anim.RemoveClip(name);
         Destroy(old);
     }
     Anim.AddClip(clip, name);
     Anim.Play(name);
 }

(Anim just points to the gameObject's Animation component)
But using the profiler, I see that the animation clips just keep accumulating, they don't seem to be garbage collected. Am I missing something or doing something wrong? Can they be garbage collected?


text:
Q: i want to reverse my date column from '26-01-2016' to '2016-01-26' format i want to reverse my date column from '26-01-2016' to '2016-01-26' format.please suggest me the solution for this question.the formate of my date column is 'DD-MM-YYYY' and i want it to be 'YYYY-MM-DD' in mysql

A: Try this
DATE_FORMAT(STR_TO_DATE(`date`, '%d.%m.%y'), '%Y-%m-%d')


text:
Q: I cannot instantly reconnect to ssh server after logout I have a ssh server on an old CentOS 5 installation. I can connect to the server without any problems. However, if i disconnect from the server and want to login again after exiting the previous session, the server is not responding and i got a "connection timed out" error. After a while (must be between 1 and 5 minutes) i can login normally. If i then exit the session, the same timeout happens again.
From the network where the client resides, i can connect to other ssh servers without any problems, so i dont think, this is a firewall issue.
Any suggestions, where i can look for the problem?
I tried to login with key instead of password and i stopped the fail2ban service on the ssh server. Both without any success.

A: I solved my problem:
There is a iptables rule, which is limiting the connections per ip to one attempt per minute. I have whitelisted my ip and now there is no delay when reconnecting.


text:
Q: Using MS mail rest API, how can I track a message among the domain users? For each mail message fetched using MS mail REST API I can get the ConversationId which is used to identify the mail thread for the message in user's folders.
The problem with ConversationId is that it is unique for each user, not for all domain users.
If I want to track the message for all domain users that receives the message. How could I accomplish that using the MS APIs?

A: This is not supported by the API since the o365 Api is for items identified by the server components such as: message id, appointment id, ...etc but not for client generated ids.