Q: Validation for Search box Need a validation for my search box that should allow space and %. The below mentioned letters should not be allowed.
< > ( ) ' " / \  * ; : = { } `(backtick) % + ^ ! - \x00-\x20

I tried by using JS code, please see the code :-
  <script type="text/javascript">
    var specialKeys = new Array();
    specialKeys.push(8); //Backspace
    specialKeys.push(9); //Tab
    specialKeys.push(46); //Delete
    specialKeys.push(36); //Home
    specialKeys.push(35); //End
    specialKeys.push(37); //Left
    specialKeys.push(39); //Right
    function IsAlphaNumeric(e) {
        var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
        var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));
        document.getElementById("error").style.display = ret ? "none" : "inline";
        return ret;
    }
</script>

let me know what needs to be modified or added in the above mentioned code.

A: You Can use Java Script Regular Expression to validate input following code will do what you want
$('input').bind('keypress', function (event) {
        var regex = new RegExp("^[a-zA-Z0-9\b _ _%]+$");
        var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
        if (!regex.test(key)) {
           event.preventDefault();
           return false;
        }
    });

Here is a working js fiddle example
Validation Js Fiddle

A: Try this example:
script
$(function(){
    $("input.rejectSpecial").on('input', function(){
        this.value = this.value.replace(/(\>|\<|\(|\)|\"|\'|\\|\/|\*|;|\:|\=|\{|\}|`|%|\+|\^|\!|\-)/g, '');
    });
})

html
<input type="text" placeholder="special letters not allowed" size="30" class="rejectSpecial"/>
<input type="text" placeholder="does nothing" size="30"/>
<input type="text" placeholder="special letters not allowed" size="30" class="rejectSpecial"/>


Q: Why can I only make GET requests and not POST requests with this python code? I'm trying to get this Etrade stuff up an running.... so far i have:
from rauth import OAuth1Service
import webbrowser

def getSession():
    # Create a session
    # Use actual consumer secret and key in place of 'foo' and 'bar'
    service = OAuth1Service(
              name = 'etrade',
              consumer_key = 'cabf024eaXXXXXXXXX7a0243d8d',
              consumer_secret = '3d05c41XXXXXXXXX1949d07c',
              request_token_url =
'https://etws.etrade.com/oauth/request_token',
              access_token_url =
'https://etws.etrade.com/oauth/access_token',
              authorize_url = 'https://us.etrade.com/e/t/etws/authorize?
key={}&token={}',
              base_url = 'https://etws.etrade.com')

    # Get request token and secret
    oauth_token, oauth_token_secret = service.get_request_token(params =
                              {'oauth_callback': 'oob',
                               'format': 'json'})

    auth_url = service.authorize_url.format('cabf0XXXXXXXXXa0243d8d',
oauth_token)

    webbrowser.open(auth_url)
    verifier = raw_input('Please input the verifier: ')

    return service.get_auth_session(oauth_token, oauth_token_secret,
params = {'oauth_verifier': verifier})

session = getSession()

This authentication process works perfectly fine and allows me to do get/delete requests but when I attempt to make post requests:
url =
'https://etwssandbox.etrade.com/order/sandbox/rest/previewoptionorder'
para = {
    "PreviewOptionOrder": {
     "-xmlns": "http://order.etws.etrade.com",
     "OptionOrderRequest": {
       "accountId": "83550325",
       "quantity": "4",
       "symbolInfo": {
         "symbol": "AAPL",
         "callOrPut": "CALL",
         "strikePrice": "585",
         "expirationYear": "2012",
         "expirationMonth": "07",
         "expirationDay": "21"
       },
       "orderAction": "BUY_OPEN",

                           "priceType": "MARKET",
       "orderTerm": "GOOD_FOR_DAY"
     }
   }
 }
resp = session.post(url,data=para)
resp.text

I get an error:
Unauthorized request: consumer key is missing.

I've tried numerous things (granted I am new to this stuff). I tried authenticating using just requests to no avail and I tried passing the oauth1 object to the posts function as a kw argument. Any ideas?


Q: Order object hold a Customer object or the customers ID or both? If I have an Order object and each Order has a Customer what should the Order object hold, a Customer object or the customers ID or both?
Does it depend on the context or since we are dealing with objects in OOP the Order should ideally hold a Customer object and not just its ID like the database column?
Thanks.

A: Do not mix db thinking with PHP code design.. Regulary the property should be set to the object itself rather then to its id. Like this:
class Order {

    /**
     * @var Contact
     */
    protected $contact;

    public function __construct(Contact $contact) {
        $this->contact = $contact;
    }

}

But there are reasons when it might make sense to just have to id of the contact. The best example would be that the contact has to be fetched from database, but you regulary don't need its information, expect of special cases. Then it might be useful to only have the id as class property and fetch the contact if required. (Known as 'lazy loading'). Note that 'lazy loading' could be hidden behind the scenes by a framework.


Q: PHP for loop to while loop Hey studying for exams and have this loop.
<?php
$ab = 0;
$xy = 1;

echo "
";

for ($i = 0; $i < 5; $i++) {
    echo "
";

    echo "" . $ab . "	" . $xy . "	";
    $ab += $xy;     $xy += $ab;

    echo "
";
}
echo "
";

the question is now how do i rewrite this as while loop ? what to keep in mind,
thanks !

A: $ab = 0;
$xy = 1;
echo "
";
$i = 0;
while ($i < 5) {
    echo "
$ab	$xy
";
    $ab += $xy;
    $xy += $ab;
    $i++;
}
echo "
";

For explanation :
Compared to the "for" loop, you have to initialize the "counter" before opening the loop [ $i = 0 ]
Inside the loop, you specify the condition to continue the loop [ $i < 5 ]
And somewhere into the loop, you increase your "counter" [ $i++ ]
Your "counter" can be increased or decreased, or directly set ; it's all about your code logic and what are your needs.
You can also break the loop whenever you want in case you need to, see an example :
while ($i < 5) {
    echo "
$ab	$xy
";
    $ab += $xy;
    $xy += $ab;
    if ($ab == 22) { // If $ab is equal to a specific value
        /* Do more stuff here if you want to */
        break; // stop the loop here
    }
    $i++;
}

This example also work with the "for" loop.
And there is also another keyword, "continue", used to tell to "jump" to the next loop iteration :
while ($i < 5) {
    $i++; // Don't forget to increase "counter" first, to avoid infinite loop
    if ($ab == 22) { // If $ab is equal to a specific value
        /* Do more stuff here if you want to */
        continue; // ignore this iteration
    }

    /* The following will be ignored if $ab is equal to 22 */
    echo "
$ab	$xy
";
    $ab += $xy;
    $xy += $ab;
}

A: To replace a for loop with a while loop, you can declare a variable before you initiate the while loop which will indicate the current iteration of the loop. Then you can decrement/increment this variable upon each iteration of the while loop. So you would have something like this:
$counter = 0;
while ($counter < 5) {
  echo "";
  echo "" . $ab . "	" . $xy . "	";
  $ab += $xy;
  $xy += $ab;
  echo "
";
  $counter++;
}

in general:
for ($i = 0; $i < x; $i++) {
  do stuff
}

is equivalent to:
$counter = 0;
while ($counter < x){
  do stuff
  counter++;
}


Q: How can I attach the jar produced by one maven module to another module with a classifier? I have a project for which I've done some refactoring (and module names clarifications).
As a consequence, the module that was neo4j-connector-impl has now become neo4j-connector-1.6. Now, for better compatibility, i want to have the jar produced by this project also be available as neo4j-connector-impl (its old name, if you follow me).
I have created a pom typed project under those GAV coordinates, and have tried attaching the jar using a mix of maven-dependency-plugin and build-helper-maven-plugin.
Unfortunatly, each time I build my project, that jar is not in maven repository and maven says
[INFO] Installing C:\Users\ndx\Documents\workspaces\git\neo4j-connector\neo4j-connector-impl-parent\neo4j-connector-impl\neo4j-connector-impl-1.6.jar to C:\Users\ndx\.m2\repository\com\netoprise\neo4j-connector-impl\1.6-SNAPSHOT\neo4j-connector-impl-1.6-SNAPSHOT.jar
[DEBUG] Skipped re-installing C:\Users\ndx\Documents\workspaces\git\neo4j-connector\neo4j-connector-impl-parent\neo4j-connector-impl\neo4j-connector-impl-1.6.jar to C:\Users\ndx\.m2\repository\com\netoprise\neo4j-connector-impl\1.6-SNAPSHOT\neo4j-connector-impl-1.6-SNAPSHOT.jar, seems unchanged

So ... how can I put that jar as a classified dependency ?
For info, here is my pom
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.netoprise</groupId>
        <artifactId>neo4j-connector-impl-parent</artifactId>
        <version>1.6-SNAPSHOT</version>
    </parent>
    <artifactId>neo4j-connector-impl</artifactId>
    <packaging>pom</packaging>
    <description>Compatibility module ensuring previous code can "quite" work</description>
    <properties>
        <dependencies.directory>${project.build.directory}/dependencies</dependencies.directory>
    </properties>
    <dependencies>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>${project.artifactId}-1.6</artifactId>
            <version>${project.version}</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <includeGroupIds>${project.groupId}</includeGroupIds>
                            <excludeTransitive>true</excludeTransitive>
                            <overWriteSnapshots>true</overWriteSnapshots>
                            <stripVersion>true</stripVersion>
                            <outputDirectory>${dependencies.directory}</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <!-- attach all projects artifact to this one in order for user projects
                to have minimum integration work -->
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>build-helper-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>attach-artifact</goal>
                        </goals>
                        <configuration>
                            <artifacts>
                                <!--  for maximum compatibility, the 1.6 version is attached as default jar artifact -->
                                <artifact>
                                    <file>neo4j-connector-impl-1.6.jar</file>
                                    <type>jar</type>
                                </artifact>
                            </artifacts>
                            <basedir>${dependencies.directory}</basedir>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

EDIT 1 Why are there versions numbers in artifacts ? Because that project (neo4j-jca-connector), provides access to neo4j graph database to various JavaEE servers. The neo4j version SHOULD NOT be constrained by this connector. As a consequence, we have to provide users a way to define, for a version of that connector, which neo4j version is used (considering as default - for backwards compatibility version - the 1.6 one).
As a consequence, we have one module for each version of neo4j,n and these modules are aggregated here. For the record, Bouncycastle do so for JDK versions ... in an even worse version, to my mind, as they use the JDK version directly in artifactId, what I plan to do only internaly : exposed artifacts will be neo4j-connector-impl and neo4j-connector-rar ... and classifiers will allow one to select which neo4j version to use.
EDIT 2 For more info, the whole project can be seen on github : https://github.com/Riduidel/neo4j-connector
The parent pom cotnaining the maven-shade-plugin declaration is https://github.com/Riduidel/neo4j-connector/blob/master/neo4j-connector-impl-parent/pom.xml
One version of that connector is https://github.com/Riduidel/neo4j-connector/blob/master/neo4j-connector-impl-parent/neo4j-connector-impl-1.5/pom.xml
And expected aggregator module should be https://github.com/Riduidel/neo4j-connector/blob/master/neo4j-connector-impl-parent/neo4j-connector-impl/pom.xml

A: Ok this is much clearer after reading your comment and EDIT.
So, correct me if I'm wrong.

*

*You want to be able to provide a version of your connector for each neo4j version

*You use module to do so.

What is still not clear to me, is that I cannot see the modules' part of your POM. You say that you want to use classifiers (so, of the same project) but maven modules are different projects...


Q: How can I resolve HTTPSConnectionPool(host='oauth2.googleapis.com', port=443): Read timed out. (read timeout=60) Currently, I have a problem in download data from google cloud storage. Here is the error: HTTPSConnectionPool(host='oauth2.googleapis.com', port=443): Read timed out. (read timeout=60)
Although I increase the timeout to 600 -> The error still shows 60. Here is my code:
storage_client = storage.Client.from_service_account_json(SERVICE_ACCOUNT_JSON_FILENAME)
bucket = storage_client.get_bucket(BUCKET_NAME)

blob = bucket.blob('blob_name')
blob.download_to_filename('dest_name', timeout=600)

Moreover, I also changed the timeout as a tuple (connect_timeout, read_timeout)
blob.download_to_filename('dest_name', timeout=(600, 600))
but, It still not working.
Could you please help me solve this problem?
Thank you


Q: How to plot 3D surface with X, Y, Z when Z is a list of list in Python? In my case, X is a range(0, 100), Y is a range(0, 10), Z is a list of list. Z has the same length as X, which is 100, and each element list inside of Z has the same dimension of Y.
Z = [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], ..., [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]].
I have the following code, but it does not work, it complains two or more arrays have incompatible dimensions on axis 1.
fig = plt.figure(figsize=(200, 6))
ax = fig.add_subplot(1, 2, 1, projection='3d')
ax.set_xticklabels(x_ax)
ax.set_yticklabels(y_ax)
ax.set_title("my title of chart")

surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False)

ax.set_zlim(0, 100)

fig.colorbar(surf, shrink = 0.5, aspect = 5)
plt.show()

I guess the error is due to the data structure of Z, how do I make a compatible structure with X, and Y? Thanks

A: Here is a basic 3D surface plotting procedure. It seems that your X and Y are just 1D arrays. However, X, Y, and Z have to be 2D arrays of the same shape. numpy.meshgrid function is useful for creating 2D mesh from two 1D arrays.
import matplotlib.pyplot as plt
from  matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x = np.array(np.linspace(-2,2,100))
y = np.array(np.linspace(-2,2,10))
X,Y = np.meshgrid(x,y)

Z = X * np.exp(-X**2 - Y**2);

surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False)
fig.colorbar(surf, shrink = 0.5, aspect = 5)

plt.show()


Q: How pointer adds extra value in printf? #include <stdio.h>

int main() {
    int *const volatile p=5;
    printf("%d",5/2 + p);

    return 0;
}

Without pointer, output is 7 and if I add pointer then the output of the answer is 13. Kindly give the step by step explanation of this program.

A: The code is invalid. The type of 5/2 + p is int *, while %d requires an int.

Kindly give the step by step explanation of this program.

   5/2 + p =                     // 5/2 is equal to 2
   2 + p =                       // p has type int
   2 * sizeof(int) + (char*)p =  // p is 5
   2 * sizeof(int) + 5 =         // sizeof(int) if 4 on your platform
   2 * 4 + 5 =
   13


Q: React App in same Server and multiple Domains I need to know if it's possible to maintain a React App on a IP (X.XXX.XXX.XX) server, and based on the URL that points to this server, render a different application.
An example of this would be to keep the application on one server, while several companies point their DNS's to the server's IP, and based on the company name, render the correct application.
I searched the internet if there is any way to do this with React Router but I didn't find

A: Use nginx reverse proxy to redirect based on url which will point to your different applications.
You can maintain the same IP for all of them.


Q: How can I reference existing groups in my VBA code? I have already grouped cells in a spreadsheet using DATA>GROUP.
Based on a menu style system, I want to collapse/uncollapse a series of already created groups in a sheet, so that it only shows the selection chosen via the menu choices. I hope this makes sense.


Q: How to avoid OOM in hsqldb while doing a merge? I have two tables where the first is very large (>50M rows):
CREATE CACHED TABLE Alldistances (
    word1 VARCHAR(70),
    word2 VARCHAR(70),
    distance INTEGER,
    distcount INTEGER
);

and a second that can be also quite large (>5M rows):
CREATE CACHED TABLE tempcach (
    word1 VARCHAR(70),
    word2 VARCHAR(70),
    distance INTEGER,
    distcount INTEGER
);

Both tables have indexes:
CREATE INDEX mulalldis ON Alldistances (word1, word2, distance);
CREATE INDEX multem ON tempcach (word1, word2, distance);

In my java program I am using prepared statements to fill/preorganize data in the tempcach table and then I merge the table to alldistances with:
MERGE INTO Alldistances alld USING (

    SELECT word1,
           word2,
           distance,
           distcount FROM tempcach

    ) AS src (

        newword1,
        newword2,
        newdistance,
        newcount

    ) ON (

            alld.word1 = src.newword1
        AND alld.word2 = src.newword2
        AND alld.distance = src.newdistance

    ) WHEN MATCHED THEN

        UPDATE SET alld.distcount = alld.distcount+src.newcount

    WHEN NOT MATCHED THEN

        INSERT (

            word1,
            word2,
            distance,
            distcount

        ) VALUES (

            newword1,
            newword2,
            newdistance,
            newcount
        );

The tempchach table is then dropped or truncated and filled with new data.
During the merge I get the OOM, which is i guess because the whole table is loaded into memory during the merge. So I will have to merge in batches, but can i do that in SQL or do it in my java program. Or is there a smart way to avoid OOM while merging?

A: It is possible to merge in chunks (batches) in SQL. You need to

*

*limit the number of rows from the temp table in each chunk

*delete those same rows

*repeat

The SELECT statement should use an ORDER BY and LIMIT
SELECT word1,
       word2,
       distance,
       distcount FROM tempcach
       ORDER BY primary key or unique columns
       LIMIT 1000

) AS src (

After the merge, the delete statement will select the same rows to delete
DELETE FROM tempcach WHERE primary key or unique columns IN
      (SELECT primary key or unique columns FROM tempcach
       ORDER BY primary key or unique columns LIMIT 1000)

A: First, just because this kind of thing annoys me, why are you selecting all the fields of the temporary table in a subselect?  Why not the simpler SQL:
MERGE INTO Alldistances alld USING tempcach AS src (
    newword1,
    newword2,
    newdistance,
    newcount
) ON (
        alld.word1 = src.newword1
    AND alld.word2 = src.newword2
    AND alld.distance = src.newdistance
) WHEN MATCHED THEN
    UPDATE SET alld.distcount = alld.distcount+src.newcount
WHEN NOT MATCHED THEN
    INSERT (
        word1,
        word2,
        distance,
        distcount
    ) VALUES (
        newword1,
        newword2,
        newdistance,
        newcount
    );

What you need to have the database avoid loading the whole table into memory is indexing on both tables.
CREATE INDEX all_data ON Alldistances (word1, word2, distance);
CREATE INDEX tempcach_data ON tempcach (word1, word2, distance);


Q: how to design db schema of an e-learning platform in dynamodb? I am designing No-SQL DB schema for an online e-learning platform, plan is to store it in the AWS DynamoDB
This is similar to Udemy, user can access and see all the available courses and users can buy more than one course.
As of now, I am thinking of the schema as below
User

Course

But I am just thinking from the item size limit wise, if in future a single user bought many courses or if a single course have many modules and videos in it which can automatically increases the item size in the AWS Dynamo DB which is max 400KB, I have seen blogs suggesting to split up the item, but wanted to check here for your inputs as well.
So my questions are

*

*DB schema wise is it fine the way that I am thinking of?

*What could be the better way when the entries are many and item size is large?

I am also exploring GraphQL, so that calls will have less latency from the front end, but worry is about the DB design and large items.
Let me know if anyone have their thoughts or valuable suggestions on this :)
Thanks in advance.

A: Modeling one-to-many relationships (e.g. Users to Courses bought) within a single item is a common pattern.  However, if the many side of the relationship can grow large, you will likely want a different approach.  It sounds like you're use case ins't a good fit for this particular pattern.
One way around this limitation is to model the relationship in an item collection.  For example, you could model the user and the courses bought within the same partition.  Keeping the data together makes it easier to fetch the data in a single query operation.

In this data model, I created a global secondary index named courses using the attribute GSIPK as the primary key for the secondary index.  This would let you fetch all courses with a single query of the courses GSI.

Keep in mind that this is just one of many approaches you could take to model your data.  Check out this talk from AWS Re:Invent about DynamoDB data modeling.  It gives a fantastic walkthrough of some of the key concepts that will help you design your data model.


Q: Difference of two DataTables in c# using LINQ II have two data tables as follows
dtOne
-------------------------
  ID  |   Name
--------------------------
 101  |  ABC
 102  |  XYZ
 103  |  MNO
 104  |  PQR
--------------------------

dtTwo
-------------------------
  ID  |   Name
--------------------------
 101  |  FGH
 102  |  XYZ
 104  |  GPS
--------------------------

I just want the result as data which is in dtOne and  not in dtTwo (dtOne-dtTwo)
dtResult
-------------------------
  ID  |   Name
--------------------------
 103  |  MNO
--------------------------

How can i achieve this .
I have used except method of LINQ but that is giving the result like this
     101  |  ABC
 103  |  MNO
 104  |  PQR
 101  |  FGH

 104  |  GPS

Thats means matching both column in except method

A: If you are trying to find rows that meet criteria based on multiple columns in the DataTable, try something like the following
string stationToFind = "ABC";
DateTime dateToFind = new DateTime(2016, 5, 26);
var result = dataTable.AsEnumerable().Where(row => row.Field<string>("station") == stationToFind
                 && row.Field<datetime>("date") == dateToFind).ToList();

If you are only expecting one row, then you can use .FirstOrDefault() instead of .ToList()

A:         DataTable dt = new DataTable();
        dt.Columns.Add("station", typeof(string));
        dt.Columns.Add("max_temp", typeof(double));
        dt.Columns.Add("min_temp", typeof(double));

        dt.Rows.Add("XYZ", 14.5, 3.5);
        dt.Rows.Add("XYZ", 14.5, 3.5);
        dt.Rows.Add("XYX", 13.5, 3.5);
        dt.Rows.Add("ABC", 14.5, 5.5);
        dt.Rows.Add("ABC", 12.5, 3.5);
        dt.Rows.Add("ABC", 14.5, 5.5);

        var maxvalue = dt.AsEnumerable().Max(s => s.Field<double>("max_temp"));

        var coll = dt.AsEnumerable().Where(s => s.Field<double>("max_temp").Equals(maxvalue)).
            Select(s => new { station = s.Field<string>("station"), maxtemp = s.Field<double>("max_temp"), mintemp = s.Field<double>("min_temp") }).Distinct();

        foreach (var item in coll)
        {
            Console.WriteLine(item.station + " - " + item.maxtemp + " - " + item.mintemp);
        }


Q: Macro to remove highlighting from hyperlinks in Word I'm writing a macro to remove all highlight colors in a Word document except wdGray25 (whose HighlightColorIndex equals 15). The problem arises when macro runs into a hyperlink highlighted with wdGray25, whose hyperlink/field isn't highlighted when revealed by Alt+F9. In that case Do While .Execute loop goes into an infinite loop and never exits.
How can I rewrite the code so that .Execute method wouldn't go into an infinite loop? I appreciate your help.
color_array = Array("2", "3", "4", "5", "6", "7", "9", "10", "11", "12", "13", "14")

For Each color_number In color_array

With Selection
.HomeKey Unit:=wdStory
With Selection.Find
  .Highlight = True
  .Text = ""

  Do While .Execute
   If Selection.Range.HighlightColorIndex = color_number Then
      Selection.Range.HighlightColorIndex = wdNoHighlight
      Selection.Collapse wdCollapseEnd
    End If
  Loop

End With
End With
Next

A: Instead of searching, we can just *loop** through each Hyperlink in the Hyperlinks collection:
Sub RemoveHighlightFromHyperlinks()
    Dim a As Hyperlink
    For Each a In ActiveDocument.Hyperlinks
        If a.Range.HighlightColorIndex <> 15 Then a.Range.HighlightColorIndex = wdAuto
    Next a
End Sub

It loops through all hyperlinks in the document. If HighlightColorIndex <> 15 then remove HighlightColorIndex (by setting to wdAuto.)

More Information:

*

*MSDN : Hyperlinks Collection (Word)

*MSDN : Hyperlink Object (Word)

*MSDN : Range.HighlightColorIndex Property (Word)


Q: Download a Word editable document from an aspx page I currently have an aspx page returning a html form (with images and css). I would like get a download Word editable version of this form without rewrite all the code. Is it possible ?
An example : I Have a page 'WebForm2.aspx' with a simple content like this.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs"
Inherits="WebApplication15.WebForm2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

    <form id="form1" runat="server">

Title

        <asp:CheckBox runat="server" ID="myTest" Text="Doc 1" />

        <asp:CheckBox runat="server" ID="myTest2" Text="Doc 2" />

        <asp:CheckBox runat="server" ID="myTest3" Text="Doc 3" />

        <asp:CheckBox runat="server" ID="myTest4" Text="Doc 4" />

    </form>

I would like that from an other page for example a button that lets you download the contents of 'WebForm2.aspx' in an editable Word document.
I Add this in Page_PreRender method
Response.AddHeader("Content-Type", "application/msword");

It's partially work. If I save the document css and images aren't loaded but if I only open the downloadable content css and images are loaded.

A: MS Word can edit html document so by adding Content-Type=application/msword record in header will make browser open your page in browser unfortunately without css and images.
Add following code in prerender event on your page
    Response.AddHeader("Content-Type", "application/msword");


Q: Many-to-one prediction using LSTM in Keras, reshaping data I have multiple pandas dataframes containing multiple users, with for each user, a sequence of sequential timestamps of multiple features. It looks something like the following:
      user    day    feature_1    ...    feature_n
0     1       0      6            ...    5
1     1       1      7            ...    4
2     1       2      6            ...    7
3     1       3      7            ...    8
4     1       4      6            ...    4
5     1       5      4            ...    3
6     1       6      3            ...    5
7     1       7      4            ...    6
8     1       8      3            ...    7
9     1       9      4            ...    7
10    2       0      3            ...    5
11    2       1      5            ...    4

I want to predict the value of feature_1, one timestamp ahead, given seven timestamps of information, per user: many-to-one prediction if I am correct.
I have previously clustered my users and want to create one LSTM model per dataframe.
I've already filtered out users with less than 8 timestamps and I know how to create a target per row using the groupby and shift functions in pandas.
The Keras LSTM implementation requires data in the format of a 3D tensor and gives the following help in the documentation: [nSamples, nTimesteps, nFeatures]
I do not understand how I should achieve this, given my dataset and goal. I have tried searching for solutions or tutorials but have been unable to find any so far. Any help would be greatly appreciated!
If it matters, I am using Python 3.6.6, Keras 2.2.4, Tensorflow 1.11.0 and numpy 1.15.2
EDIT: Thanks to the suggestion from @ely I managed to figure it out. I should create a sample for every 7 timestamps as he explains in his comment. However, the most pythonic way of achieving this I still have not figured out.


Q: Java: How to retrieve a specific value from my arraylist? I'm trying to get a value, deep from an arraylist.
The attributes are in the following order:
arraylist > [0, 1, 2, 3 etc.] >
    (example from array[0]):
        [String name = "x"], [Private Time time] > (in time):
            [String beginTime="12:00", String endTime="12:30",
             long difference="1800000"].

I know how to get to the 0, 1, 2 of the array with help of .get(i) but how do I go deeper?
I have tried .get(i).get(time).get(difference), but, as expected, it did not work.
Basically what I need to do is to sniff through the array and only take the difference value, and add everything up.

A: I'm thinking that you are storing an array of class Time.
You could do something like
((Time)get(i)).difference

Assuming that difference is an accessible field in the Time class.


Q: How to push notifications from sql database to Flutter App My problem is that i have only found some tutorials about how to push notifications from firebase database using fcm to devices running an app made with flutter. In my case i have a server with mysql database with a lot of tables. User has the oppurtinity to choose from which table to get notifications from always when something is added to the table. I really dont know how to achieve this. I tried to learn about Fcm but it doesnt seem to be suitable for my purpose. I dont also know how to push notifications directly from sql. Im not using php by the way.
Please dont vote negatively im really sorry im new at this. So i would appreciate your help.
I would be very thankful for your answers.


Q: Visualize lowest nodes in hierarchical clustering with dendrogram I'm using linkage to generate an agglomerative hierarchical clustering for a dataset of around 5000 instances. I want to visualize the 'bottom' merges in the hierarchy, that is, the nodes close to the leaves with the smallest distance measures.
Unfortunately, the dendrogram visualization prefers to show the 'top' nodes from the last merges in the algorithm. By default it shows the top 30 nodes, collapsing the bottom of the tree. I can change the P value to show more nodes, but I would have to show all 5000+ to see the lowest levels of the clustering at which point the plot is no longer readable.
MCVE
For example, starting from the linkage documentation example
openExample('stats/CompareClusterAssignmentsToClustersExample')
run CompareClusterAssignmentsToClustersExample
dendrogram(Z, 'Orient', 'Left', 'Labels', species);

Produces a dendrogram with the top 30 nodes visible. The nodes with numerical labels are collapsing lower levels of the tree.

I can increase the number of visible nodes to include all leaves at expense of readability.
dendrogram(Z, size(Z,1), 'Orient', 'Left', 'Labels', species);

What I'd Like
What I'd really like is a zoomed in version of above, like the example below, but showing the first 30 closest clusters.

What I've Tried
I tried providing the function with the first 30 rows of Z,
dendrogram(Z(1:30), 'Orient', 'Left');

but that throws an "Index exceeds matrix dimensions." error when one of the rows references a cluster in a row > 30.
I also tried using the dendrogram Reorder property, but I am having difficulty finding a valid ordering that orders the clusters from closest to farthest.
%The Z matrix is in order from closest cluster to furthest,
% so I can use it to create an ordering
Y = reshape(Z(:, 1:2)', 1, [])
Y = Y(Y<151);
dendrogram(Z, 30, 'Orient', 'Left', 'Labels', species, 'Reorder', Y);

I get the error

In the requested ordering of the nodes, some data points belonging to
  the same leaf in the plot are separated by the points belonging to
  other leaves. Try to use a different ordering.

It may be the case that such an ordering is not possible if the entire tree is calculated because there would be branch crossings, but I'm hoping that there is a better ordering if I am only looking at a portion of the tree, and clusters at higher levels are not considered.
Question
How can I improve my visualization to show the lowest level clusters in the dendrogram?

A: Emmm...like ylim()?
dendrogram(Z, size(Z,1), 'Orient', 'Left', 'Labels', species);
ylim(max(ylim())-[30,0]);

yields


Q: How can I execute multiple NN training? I have two NVidia GPUs in the machine, but I am not using them.
I have three NN training running on my machine. When I am trying to run the fourth one, the script is giving me the following error:
my_user@my_machine:~/my_project/training_my_project$ python3 my_project.py
Traceback (most recent call last):
  File "my_project.py", line 211, in <module>
    load_data(
  File "my_project.py", line 132, in load_data
    tx = tf.convert_to_tensor(data_x, dtype=tf.float32)
  File "/home/my_user/.local/lib/python3.8/site-packages/tensorflow/python/util/traceback_utils.py", line 153, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "/home/my_user/.local/lib/python3.8/site-packages/tensorflow/python/framework/constant_op.py", line 106, in convert_to_eager_tensor
    return ops.EagerTensor(value, ctx.device_name, dtype)
tensorflow.python.framework.errors_impl.FailedPreconditionError: Failed to allocate scratch buffer for device 0
my_user@my_machine:~/my_project/training_my_project$

How can I resolve this issue?
The following is my RAM usage:
my_user@my_machine:~/my_project/training_my_project$ free -m
              total        used        free      shared  buff/cache   available
Mem:          15947        6651        3650          20        5645        8952
Swap:          2047         338        1709
my_user@my_machine:~/my_project/training_my_project$

The following is my CPU usage:
my_user@my_machine:~$ top -i
top - 12:46:12 up 79 days, 21:14,  2 users,  load average: 4,05, 3,82, 3,80
Tasks: 585 total,   2 running, 583 sleeping,   0 stopped,   0 zombie
%Cpu(s): 11,7 us,  1,6 sy,  0,0 ni, 86,6 id,  0,0 wa,  0,0 hi,  0,0 si,  0,0 st
MiB Mem :  15947,7 total,   3638,3 free,   6662,7 used,   5646,7 buff/cache
MiB Swap:   2048,0 total,   1709,4 free,    338,6 used.   8941,6 avail Mem

    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
2081821 my_user  20   0   48,9g   2,5g 471076 S 156,1  15,8   1832:54 python3
2082196 my_user  20   0   48,8g   2,6g 467708 S 148,5  16,8   1798:51 python3
2076942 my_user  20   0   47,8g   1,6g 466916 R 147,5  10,3   2797:51 python3
   1594 gdm       20   0 3989336  65816  31120 S   0,7   0,4  38:03.14 gnome-shell
     93 root      rt   0       0      0      0 S   0,3   0,0   0:38.42 migration/13
   1185 root     -51   0       0      0      0 S   0,3   0,0   3925:59 irq/54-nvidia
2075861 root      20   0       0      0      0 I   0,3   0,0   1:30.17 kworker/22:0-events
2076418 root      20   0       0      0      0 I   0,3   0,0   1:38.65 kworker/1:0-events
2085325 root      20   0       0      0      0 I   0,3   0,0   1:17.15 kworker/3:1-events
2093002 root      20   0       0      0      0 I   0,3   0,0   1:00.05 kworker/23:0-events
2100000 root      20   0       0      0      0 I   0,3   0,0   0:45.78 kworker/2:2-events
2104688 root      20   0       0      0      0 I   0,3   0,0   0:33.08 kworker/9:0-events
2106767 root      20   0       0      0      0 I   0,3   0,0   0:25.16 kworker/20:0-events
2115469 root      20   0       0      0      0 I   0,3   0,0   0:01.98 kworker/11:2-events
2115470 root      20   0       0      0      0 I   0,3   0,0   0:01.96 kworker/12:2-events
2115477 root      20   0       0      0      0 I   0,3   0,0   0:01.95 kworker/30:1-events
2116059 my_user  20   0   23560   4508   3420 R   0,3   0,0   0:00.80 top

The following is my TF configuration:
import os

os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
# os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
# os.environ["CUDA_VISIBLE_DEVICES"] = "99" # Use both gpus for training.

import sys, random
import time
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.callbacks import ModelCheckpoint
import numpy as np
from lxml import etree, objectify

# <editor-fold desc="GPU">
# resolve GPU related issues.
try:
    physical_devices = tf.config.list_physical_devices('GPU')
    for gpu_instance in physical_devices:
        tf.config.experimental.set_memory_growth(gpu_instance, True)
except Exception as e:
    pass
# END of try
# </editor-fold>

Please, take the commented lines as commented-out lines.
Relevant source code:
def load_data(fname: str, class_index: int, feature_start_index: int, **selection):
    i = 0
    file = open(fname)
    if "top_n_lines" in selection:
        lines = [next(file) for _ in range(int(selection["top_n_lines"]))]
    elif "random_n_lines" in selection:
        tmp_lines = file.readlines()
        lines = random.sample(tmp_lines, int(selection["random_n_lines"]))
    else:
        lines = file.readlines()

    data_x, data_y = [], []
    for l in lines:
        row = l.strip().split()
        x = [float(ix) for ix in row[feature_start_index:]]
        y = encode(row[class_index])
        data_x.append(x)
        data_y.append(y)
    # END for l in lines

    num_rows = len(data_x)
    given_fraction = selection.get("validation_part", 1.0)
    if given_fraction > 0.9999:
        valid_x, valid_y = data_x, data_y
    else:
        n = int(num_rows * given_fraction)
        data_x, data_y = data_x[n:], data_y[n:]
        valid_x, valid_y = data_x[:n], data_y[:n]
    # END of if-else block

    tx = tf.convert_to_tensor(data_x, np.float32)
    ty = tf.convert_to_tensor(data_y, np.float32)

    vx = tf.convert_to_tensor(valid_x, np.float32)
    vy = tf.convert_to_tensor(valid_y, np.float32)

    return tx, ty, vx, vy
# END of the function

A: Using multiple GPUs
If developing on a system with a single GPU, you can simulate multiple GPUs with virtual devices. This enables easy testing of multi-GPU setups without requiring additional resources.
gpus = tf.config.list_physical_devices('GPU')
if gpus:
  # Create 2 virtual GPUs with 1GB memory each
  try:
    tf.config.set_logical_device_configuration(
        gpus[0],
        [tf.config.LogicalDeviceConfiguration(memory_limit=1024),
         tf.config.LogicalDeviceConfiguration(memory_limit=1024)])
    logical_gpus = tf.config.list_logical_devices('GPU')
    print(len(gpus), "Physical GPU,", len(logical_gpus), "Logical GPUs")
  except RuntimeError as e:
    # Virtual devices must be set before GPUs have been initialized
    print(e)

NOTE: Virtual devices cannot be modified after being initialized
Once there are multiple logical GPUs available to the runtime, you can utilize the multiple GPUs with tf.distribute.Strategy or with manual placement.
With tf.distribute.Strategy best practice for using multiple GPUs, here is a simple example:
tf.debugging.set_log_device_placement(True)
gpus = tf.config.list_logical_devices('GPU')
strategy = tf.distribute.MirroredStrategy(gpus)
with strategy.scope():
  inputs = tf.keras.layers.Input(shape=(1,))
  predictions = tf.keras.layers.Dense(1)(inputs)
  model = tf.keras.models.Model(inputs=inputs, outputs=predictions)
  model.compile(loss='mse',
                optimizer=tf.keras.optimizers.SGD(learning_rate=0.2))

This program will run a copy of your model on each GPU, splitting the input data between them, also known as "data parallelism".
For more information about distribution strategies or manual placement, check out the guides on the links.

A: The RAM complaint isn't about your system ram (call it CPU RAM). It's about your GPU RAM.
The moment TF loads, it allocates all the GPU RAM for itself (some small fraction is left over due to page size stuff).
Your sample makes TF dynamically allocate GPU RAM, but it could still end up using up all the GPU RAM. Use the code below to provide a hard stop on GPU RAM per process. you'll likely want to change 1024 to 8096 or something like that.
and FYI, use nvidia-smi to monitor your GPU ram usage.
From the docs:
https://www.tensorflow.org/guide/gpu#limiting_gpu_memory_growth
gpus = tf.config.list_physical_devices('GPU')
if gpus:
  # Restrict TensorFlow to only allocate 1GB of memory on the first GPU
  try:
    tf.config.set_logical_device_configuration(
        gpus[0],
        [tf.config.LogicalDeviceConfiguration(memory_limit=1024)])
    logical_gpus = tf.config.list_logical_devices('GPU')
    print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
  except RuntimeError as e:
    # Virtual devices must be set before GPUs have been initialized
    print(e)


Q: Sort a cell array of strings alphabetically by last name In Matlab, I have a cell array like:
names = {
    'John Doe',
    'Jane Watkins',
    'Jeremy Jason Taylor',
    'Roger Adrian'
    }

I would like to sort these such that the last names appear in alphabetical order. In my example, it would come out being:
names_sorted = {
    'Roger Adrian',
    'John Doe',
    'Jeremy Jason Taylor',
    'Jane Watkins'
    }

I know of inelegant ways of doing this. For instance, I could tokenize at space, make a separate last_names cell array, sort that, and apply the indexing to my original array.
My question is, is there a better way?
Because someone is sure to come up with that list of assumptions you can't make with regards to people names in a database, let me assure you that all my names are either "FIRST MIDDLE LAST" or "FIRST LAST". I checked.

A: If all first names had the same length, then you would be able to use sortrows, but in your case, that would require padding and modifying your array, anyway, so that you're better off converting it into "LAST FIRST MIDDLE" before applying sort. Fortunately, there's a simple regular expression for that:
names = {'John Doe';'Roger Adrian';'John Fitzgerald Kennedy'};
names_rearranged = regexprep(names,'(.*) (\w*)$','$2 $1')
names_rearranged =
    'Doe John'
    'Adrian Roger'
    'Kennedy John Fitzgerald'

[names_rearranged_sorted, idx_sorted] = sort(names_rearranged);

names_sorted = names(idx_sorted)
names_sorted =
    'Roger Adrian'
    'John Doe'
    'John Fitzgerald Kennedy'


Q: AJAX URL requests in Drupal 7 on localhost Apache2 don't include base URL or base path I am currently stuck with a problem in my local Drupal 7 environment. As Drupal 7 site configurations can get very complex, I will try to explain my problem in as much details as possible.
The site sits in a sub folder in my local environment, I have more projects running on my localhost, so preferably I would like to keep the projects separated. In addition, for this site I have two separate folders, one for development and one for production that share the same database, so a solution by adding fake domains would not work here I think (correct me if I'm wrong).
So the main problem seems to be that AJAX requests don't include the base URL or base path and I can't login on http://localhost/mysite/devel/docroot/user because the AJAX request would go to http://localhost/system/ajax or http://localhost/ajax_register/login/ajax and therefore would not return the correct JSON response.
How can this be solved? Are configurations in Apache's httpd.conf or .htaccess enough to make this work?
Here's what I did so far, first in settings.php:
$base_url = 'http://localhost/mysite/devel/docroot';
$base_path = '/mysite/devel/docroot/';

Next, I've tried the following with rewrite rules in httpd.conf:
<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{HTTP_REFERER} .*devel.*$ [OR]
    RewriteRule ^/sites/(.*)$ /mysite/devel/docroot/sites/$1
    RewriteRule ^/system/(.*)$ /mysite/devel/docroot/system/$1
    RewriteRule ^/ajax_register/(.*)$ /mysite/devel/docroot/ajax_register/$1
</IfModule>

Here I got the following pop up with HTML (that seems to be from index.php) in the response text instead of the expected JSON response:
An AJAX HTTP error occurred.
HTTP Result Code: 404
Debugging information follows.
Path: http://localhost/ajax_register/login/ajax
StatusText: error
ResponseText: lots of HTML...

Then without rewrite rules but using proxies instead in httpd.conf:
<IfModule mod_proxy.c>

    ProxyRequests Off
    ProxyPreserveHost On

    <Proxy *>
        Order deny,allow
        Allow from all
    </Proxy>

    RewriteEngine on

    ProxyPass /system/ http://localhost/mysite/devel/docroot/system/
    ProxyPassReverse /system/ http://localhost/mysite/devel/docroot/system/
    <Location /system/>
        Order allow,deny
        Allow from all
    </Location>

    ProxyPass /ajax_register/ http://localhost/mysite/devel/docroot/ajax_register/
    ProxyPassReverse /ajax_register/ http://localhost/mysite/devel/docroot/ajax_register/
    <Location /ajax_register/>
        Order allow,deny
        Allow from all
    </Location>

</IfModule>

For the proxy directives, a similar 404 not found error was given for the POST AJAX request, except that now the response text is in JSON format.
An AJAX HTTP error occurred.
HTTP Result Code: 404
Debugging information follows.
Path: http://localhost/ajax_register/login/ajax
StatusText: error
ResponseText: some JSON code...

Without both the rewrite rules and the proxy directives I get the following error in the JavaScript pop up:
An AJAX HTTP error occurred.
HTTP Result Code: 404
Debugging information follows.
Path: http://localhost/ajax_register/login/ajax
StatusText: error
ResponseText:
404 Not Found
Not Found
The requested URL /ajax_register/login/ajax was not found on this server.

Finally in .htaccess I've tried to rewrite the base to the following:
RewriteBase /mysite/devel/docroot/

and here I get the same 404 error as was the case when both the rewrite rules and proxy directives are commented out in httpd.conf. I would also like to add that in the database, in the table languages I've set the domain for the English language to localhost.
I don't understand, why is the base not included in front of the AJAX URL requests? And how can I add it? When I query Drupal.settings.basePath in Firebug I do get the value that I've set in settings.php :S - Does someone have any ideas?

A: There are many solutions for your problem, but I'm gonna try to focus on the most mature one. I assume you are using windows as your environment.
You said you were running your projects on localhost, which is where your first mistake is.
Localhost is nothing but a form of weird domain name you specify. When you request a domain like "www.google.com" or "localhost" the following steps occur:

*

*The browser checks a specific file for the requested domain. This file is called hosts file

*If the domain name is found in the hosts file, the browser sends a request to the IP address specified in the hosts file

*If the domain name is not found in the hosts file, the browser queries domain name servers which return the corresponding IP adress.

Now localhost is nothing but a domain name specified in your hosts file, which points to the loopback address.(127.0.0.1).
So the magic trick here is to bind your custom hosts like "project1", "project2" etc.. to that loopback adress(127.0.0.1).
Than when you send a request to "project1" in your browser, the server running on port 80 will respond as if you typed "localhost".
The second part you need to take care of is called virtual hosts. When you send a request with a specific domain name, a special header is included in your http request called "Host".
Lets assume, that you redirect all this custom domains to the same IP (127.0.0.1). In order for apache to serve a different project, you should instruct apache to look at the "Host" header and resolve it for the corresponding project.
Again you do that by setting virtual hosts.
A lot of frameworks and content managing systems in PHP have some ugly ways to insert some magic "$BASE_PATH" variable, which is a bad practice as that could be achieved with relative paths in pure html and a properly configured server.


Q: Toggle a div in Angular How can I make a toggle in Angular.JS so a div will open and close when clicked on the same div again. For now it perfoms the action so it opens the div but whenever I click again on it, the div needs to close again.
 Zerg

and this opens:

  info

JS:
  $scope.activeRows = "";
  $scope.isAccordionOpen = function(row) {
    if ($scope.activeRows === row) {
      return true;
    } else {
      return false;
    }
  }

  $scope.openAccordionRow = function(row) {
    $scope.activeRows = row;
  }

Problem here is that the same clicked div doesn't close when pressing on it again.

A: Currently your code doesn't have anything that even attempts to collapse the row. You could change your code to this.
HTML:
 Zerg

JavaScript:
  $scope.activeRows = "";
  $scope.isAccordionOpen = function(row) {
    if ($scope.activeRows === row) {
      return true;
    } else {
      return false;
    }
  }

  $scope.toggleAccordionRow = function(row) {
    $scope.activeRows = $scope.isAccordionOpen(row) ? "" : row;
  }

A: If you want toggle. Just use these code.
$scope.activeRows = true // Am setting this for default to show
ng-click="$scope.activeRows = !$scope.activeRows" // change ng-click event
ng-show = "$scope.activeRows" // bind directly $scope.activeRows to show.

A: the easy way to do such a thing is the way bellow
 Zerg

  info


Q: Spark Structured Streaming with Azure EventHub In the context of Spark Streaming with Azure EventHub, technically i need some help in understanding the differrence b/w EventPosition.fromStartOfStream, EventPosition.fromEndOfStream. If i need to trigger the Streaming job only once a day with checkpointing enabled, what difference will the below code do.
Gone through couple of docs, couldn't find much information on this. Any help would be appreciated.
val ehConf = EventHubsConf(cs).setStartingPositions(positions).setStartingPosition(EventPosition.fromStartOfStream)

val ehConf = EventHubsConf(cs).setStartingPositions(positions).setStartingPosition(EventPosition.fromEndOfStream)

A: If you are checkpointing then position given by setStartingPosition won't have any use. it is only used if there is no checkpoint found.
Please see sample code and description here - https://github.com/Azure/azure-event-hubs-spark/blob/564267dd1287b0593f8914b1acf8ff7796b58e3b/docs/spark-streaming-eventhubs-integration.md#per-partition-configuration


Q: Docker different digest when push same images with different tags I built one docker image with one tag and then tag it with a new tag (both tags include registry URL).
I push the first tag, then the second tag, the push digest from 2 tags are different:
16:10:47 + docker build -t 10.88.102.47:8443/my-project/foo:jenkins-305 .
...
16:11:26 + docker tag 10.88.102.47:8443/my-project/foo:jenkins-305 10.88.102.47:8443/my-project/foo:latest

16:11:26 + docker push 10.88.102.47:8443/my-project/foo:jenkins-305
...
16:11:34 jenkins-280: digest: sha256:22a4cd54bf43f03530c475832ca4432adfcf02c796e9c1cdafea72cf07ce7bf4 size: 3654

16:11:35 + docker push 10.88.102.47:8443/my-project/foo:latest
...
16:11:36 latest: digest: sha256:ccb4e8c41339b1a5d780cc5d28064cabf839657617a9c1e1d14eaee507405b20 size: 3632

Pushing tag jenkins-305 - digest 22a4cd54bf43f03530c475832ca4432adfcf02c796e9c1cdafea72cf07ce7bf4
Pushing tag latest - digest ccb4e8c41339b1a5d780cc5d28064cabf839657617a9c1e1d14eaee507405b20
Shouldn't 2 digests of 2 tags from same image identical?
Update
I downloaded both tags on a different machines and see those tags have the same IMAGE ID (digest?)
10.88.102.47:8443/my-project/foo   jenkins-305      sha256:5537979d74ac00f75b7830c41c27be5f545ec55b0ab12622f9fad2eec8583a6e   21 minutes ago      689.2 MB
10.88.102.47:8443/my-project/foo   latest           sha256:5537979d74ac00f75b7830c41c27be5f545ec55b0ab12622f9fad2eec8583a6e   21 minutes ago      689.2 MB

But this digest is different from the digest provided by docker push, why?

A: The docs on the registry report that the digest contains the image manifest, and the manifest is made up of the tag amongst other things.


Q: Is there any function/implementation in python similar to peaks(N) in MATLAB? I can obtain a 2D matrix/3D plot using peaks(N) where N is any number in MATLAB. Is there any way to do this in python?
MATLAB example:
Create a 5-by-5 matrix of peaks and display the surface:
figure
peaks(5);

How to do this in python?

A: You can use SciPy
from scipy.signal import find_peaks
peaks, _ = find_peaks(x, height=0) # x is the signal

print("x-values: ", peaks," y-values: ",  x[peaks])

SciPy documentation for finding peaks
.. Or a quick solution if you signal is not too noisy then you can manually smooth the signal, differentiate the smoothed signal, find a threshold value and count the zeroes :)


Q: Fixing a git mess during a Pull Request I have a large series of git commits made during a pull request for a github project. I've been asked to squash all of the commits together, however since then I have made an incredible mess of merges, resets and accidentally merging over other commits that I've pulled to the repo whilst the PR has been underway.
What i'd like to be able to do, is simply copy the two files that are actually involved in the pull request to another directory, reset back to the very first commit I made for the PR, re-paste my new files with the latest changes and then commit them, so that the PR shows up with a single commit. Is this possible? Thanks!

A: If you want it to look like a single commit, you'll need to use git squash. Is there a reason why you can't use this?


Q: Pentaho Kettle/ETL integration with Subversion or Git We are using Pentaho ETL (aka Kettle). Pentaho has a built in enterprise repository for versioning. However, it is very poor. First, there's no way to go through an entire Pentaho project looking for changes. Each file is its own individual change. Second, there doesn't appear to be a way to tag an entire release.
We could use a file based system for storing our Pentaho objects. Jobs will end with a .kjb suffix and Transformations will end with a .ktr suffix. If that file system happened to be a Git or Subversion workspace, we could checkout/push/sync a revision of the Pentaho project, do the changes, and then commit/push those changes back to the repository.
However, there doesn't appear to be a way to check in and out of files from Pentaho itself like you can with Eclipse, or VisualStudio, or any other IDE environment.
Is there a way to integrate Subversion with Pentaho? Is it possible to use Eclipse (which not only integrates with Subversion and Git, but also integrates with Jira and Rally) with Pentaho ETL/Kettle?


Q: Debugging Paging in Sql Reporting Services I'm working on my first significant Sql Reporting Services project and am having problems with paging.  Most of the reports are already working.
What is happening is that I"m getting different numbers and locations of page breaks between Web Reportviewer, PDF and Word documents.  The word is the closest, but none of the three are really correct.
I've looked for the for the obvious like extra paging and making sure the report does not go outside of the left or right margins.  My problem is that I'm not sure how to go about troubleshooting reports that pages that do not break in the correct location.
Does anyone have a suggestion where to start?
I'm using VS2008, SQL2008 DE on Vista Dev box.

A: This isn't really a problem - the different renderers are rendering the report appropriately for their output. The web viewer is optimised for screen-based reading and generally allows more content per page than the PDF viewer does as the PDF viewer is constrained by the paper size that it formats to. Thus you get more pages when rendering for PDF than web; however, the content of the report is exactly the same.
The best illustration of this is the Excel renderer - the Excel renderer renders the entire report onto a single worksheet in most cases (for reports with grouping and page breaks set on the group footer it will render each group on its own worksheet). You wouldn't want the Excel renderer to artificially create worksheets to try to paginate your report. It does the appropriate thing which is to include all the data in one big worksheet even though that may be logically thought of as one big "page".
The web renderer page length is determined by the InteractiveHeight attribute of the report (in the InteractiveSize property in the Properties pane for the report) but the interactive height is an approximation rather than a fixed page break setting and your page breaks may still not conform to the PDF version even though the InteractiveHeight is set to the same length as your target page length.


Q: Posting rendered html page to a web service? Best way to transmit data? I am creating a web service that will send an email via Amazon SES. I want to separate the service(API) from the actual application that is going to take in data to be sent. So all I want to send the service is the to address, subject line, and rendered html body of the message. The service in this case is going to be an MVC action result method in C#, and I would like to post the information in JSON. Typically when I post data to a webservice, the data is pretty small and concise.
So my question is, is there a better way to submit html to a webservice as opposed to just sending JSON formatted like this? Would it be a good idea to base64 encode it? Or is there a better way to do this all together?
Post body.
{
   "to" : "asdasd@email.com",
   "subject":"hello",
   "body":"
asdasd
"
}

My model would look something like.
public class EmailMessage
{
    public string toAddress { get; set; }
    public string subject { get; set; }
    public string body { get; set; }
}

Then my action result would look something like...
 [HttpPost]
 public ActionResult SendEmail(EmailMessage msg)
 {

      //Send an email

 }

Is there a better way to do this? Thanks in advance for the help.

A: If you are worried about size of request an response, you can add GZip support.
public class CompressAttribute : System.Web.Mvc.ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpRequestBase request = filterContext.HttpContext.Request;

            string acceptEncoding = request.Headers["Accept-Encoding"];

            if (string.IsNullOrEmpty(acceptEncoding)) return;

            acceptEncoding = acceptEncoding.ToUpperInvariant();

            HttpResponseBase response = filterContext.HttpContext.Response;

            if (acceptEncoding.Contains("GZIP") && response.Filter != null)
            {
                response.AppendHeader("Content-encoding", "gzip");
                response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
            }
            else if (acceptEncoding.Contains("DEFLATE") && response.Filter != null)
            {
                response.AppendHeader("Content-encoding", "deflate");
                response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
            }
        }
    }

then in your controller add attribute to the action or the controller itself:
[Compress]
public class AccountController : Controller


Q: jquery eq selector loop for tumblr I have a question that I've been stuck with for awhile:
I'm using tumblr and trying to flip the img and the text of a "text post". So currently I'm doing it manually, selecting the 8th eq of .text img to insert before the 8th eq of .text p:first-child.
So in a photo/photoset post I could point to the captions and make them appear after the images, but in a text post everything is wrapped in the {body}, thus needing to select the particular post's image eq(8) to be matched and called up before that particular post's text eq(8)
$(".text img").eq(8).insertBefore($('.text p:first-child').eq(8));
$(".text img").eq(7).insertBefore($('.text p:first-child').eq(7));
$(".text img").eq(6).insertBefore($('.text p:first-child').eq(6));
$(".text img").eq(5).insertBefore($('.text p:first-child').eq(5));
$(".text img").eq(4).insertBefore($('.text p:first-child').eq(4));
$(".text img").eq(3).insertBefore($('.text p:first-child').eq(3));
$(".text img").eq(2).insertBefore($('.text p:first-child').eq(2));
$(".text img").eq(1).insertBefore($('.text p:first-child').eq(1));
$(".text img").eq(0).insertBefore($('.text p:first-child').eq(0));

The reason for using a text post to post images was to workaround the 10 imgs restriction on tumblr photoset posts.
Is there a way that I can code it such that every time a new text post is posted it will select that and insertbefore accordingly? The insertbefore is so that in my index-page, the first-child image and the first-child text would appear.
I know perhaps selecting eq is not the way to go...
(I've placed the relevant portion of the html and css code here, if I'm still lacking anything please let me know!!)
My Html code:

        {block:Posts inlineMediaWidth="1280"}

            {block:Text}

                {block:IndexPage}

                    {body}

                {/block:IndexPage}

            {block:PermalinkPage}

                    {body}

{body}

            {/block:PermalinkPage}

            {/block:Text}

         {block:Photo}
            {block:IndexPage}

                {block:Caption}

                    {Caption}

                {/block:Caption}

            {/block:IndexPage}

        {block:PermalinkPage}

                 {block:Caption}

{Caption}

                 {/block:Caption}

        {/block:PermalinkPage}
        {/block:Photo}

            {block:Panorama}

                    {LinkOpenTag}

                    {LinkCloseTag}
                    {block:Caption}

{Caption}

                    {/block:Caption}

            {/block:Panorama}

        {block:Photoset}
            {block:IndexPage}

                        {block:Photos}

                        {/block:Photos}

                    {block:Caption}

                        {Caption}

                     {/block:Caption}

            {/block:IndexPage}

            {block:PermalinkPage}

                        {block:Photos}

                        {/block:Photos}

                       {block:Caption}

{Caption}

                       {/block:Caption}

            {/block:PermalinkPage}
        {/block:Photoset}

            {block:Quote}

                    "{Quote}"

                    {block:Source}

{Source}

                    {/block:Source}

            {/block:Quote}{block:Link}

                    {Name}

                    {block:Description}

{Description}

                    {/block:Description}

            {/block:Link}{block:Chat}

                    {block:Title}

{Title}

                    {/block:Title}

                        {block:Lines}

                                {block:Label}
                                    {Label}
                                {/block:Label}{Line}

                        {/block:Lines}

            {/block:Chat}

            {block:Video}

                    {Video-500}{block:Caption}

{Caption}

                    {/block:Caption}

            {/block:Video}{block:Audio}

                    {AudioEmbed}{block:Caption}

{Caption}

                    {/block:Caption}

            {/block:Audio}

             {/block:Posts}

My CSS code:
.index-page .grid-item .caption p,
    .index-page .grid-item .text p {
        margin:auto;
    }
    .index-page .grid-item .caption p {
        display: none;
        padding-top:15px;
        line-height:125%;
        color:#fff;
        text-align:center;
    }
    .index-page .grid-item .caption p:first-child{
        display:block;
    }
    .index-page .photos img{
        display: none;
    }
    .index-page .photos img:first-child{
        display: block;
    }

    .index-page .text a {
        text-decoration:none;
    }

    .index-page .text p {
        display:none;
       padding-top:15px;
        line-height:125%;
        color:#fff;
        text-align:center;
       max-width:90%;
    }
    .index-page .text p:first-of-type{
        display: block;
    }

    .read_more {
        display: none;
    }


Q: How to generate different pages from a click in ng-repeat list? I have this code, and this is what it does:
It generates a list of topics from a json.
These topics will be used to determinate a page in the "CONTENT" area.
But, how can i make a "link" or "way" to call/create every page for every item in that list.
Exists a way to verify what item has been clicked? and call the respective page from that item ?

angular.module('duall')
.controller('documentationController', ['$scope', '$http', function($scope, $http){

 $scope.docs = [];

 $http.get('static/titles.json').success(function(doc){
  $scope.docs = doc;
 }).error(function(error){
  console.log(error);
 });

}]);

      <input id="search" type="search" ng-model="q" aria-label="filter docs"/>

                Pesquise Algo! :)

      search

          {{docs.title}}

        Nada encontrado :(

CONTENT


Q: Installing R under Program Files I installed R version 3.2.0 in my "C:\Program Files" folder, and then installed RStudio. When I tried to run an R markdown file, it prompted me to install the Rmarkdown package from source. However, I found that Installing RMarkdown packages in RStudio does not work on Windows 7.
Digging a little deeper I found that the R CMD --help command worked, but every R CMD <command> and R CMD <command> --help fails with
'C:\Program' is not recognized as an internal or external command, operable program or batch file

If I had tested my installation, I would have found the problem with
Sys.setenv(LC_COLLATE = "C", LANGUAGE = "en")
library("tools")
testInstalledBasic("both")

since that fails by calling R CMD BATCH during its execution.
The only solution I could find was to uninstall R and reinstall it a "C:" instead of "C:\Program Files."
It seems like installing R into the "Program Files" folder should be possible. Is there some configuration that would make that possible? Or is there some reason this basic scenario isn't supported?


Q: Netbeans + jquery = error I'm working in a php project and Netbeans insists on marking lines like
        $.get("/adminc/utilsAjax.php", { function: "orderIsOpenOrClosed", orderID: orderID, rand: randn }, function(data)

and the closings
        });

As errors
I tried using the non minifierd version of jquery and no change.
It's like Netbeans ignores the jquery syntax.
Any ideas?

A: The "function" is a reserved word, and in object notation may require quotes, Netbeans is expecting () after the Function key word.

A: As Bodman Said, function is a reserved word so you need to quote that. But you may also need to quote all the hash keys for netbeans to interpret them correctly for example:
    $.get("/adminc/utilsAjax.php", {
        "function": "orderIsOpenOrClosed",
        "orderID": orderID,
        "rand": randn
      },
      function(data){
        // fun body
    });

A: You have missed a { after function(data)


Q: Rails4 Form with remote - handling error message I have a simple remote form like this:
= form_for :question, :url => question_path, :remote => true, :html =>{:class => 'question-form'} do |form|
and in my controller I check if in the form the EULA is accepted:
  def create
    if (params[:question][:eula] != 1)
      puts "ERROR!"
      respond_to do |format|
          return format.json {render :json => {:error_message => "FOOOO", :success => false } }
      end
    end
    @question = Question.new(question_params)

    respond_to do |format|
      if @question.save
        format.html { redirect_to @question, notice: 'question was successfully created.' }
        format.json { render :show, status: :created, location: @question }
      else
        format.html { render :new }
        format.json { render json: @question.errors, status: :unprocessable_entity }
      end
    end
  end

How can I access :error_message or :success in my create.js.erb file?

A: You can do Ajax request
add id to form :id => "question-form"
= form_for :question, :url => question_path, :remote => true,
                  :html =>{:class => 'question-form', :id => "question-form"} do |form|

and anywhere in javascript file
$("#question-form").on("submit", function(e){
    e.preventDefault();
    var form = $(this);
    var request = $.ajax({
        method: "POST",
        beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
        url: "/questions",
        dataType: "json",
        data: form.serialize()
    })

    request.done(function(res){
        console.log(res.success);
    })

    request.catch(function(jqXHR){
        console.log(jqXHR.responseJSON)
    })

})


Q: How to reduce ipa size Xamarin.ios I am trying to reduce my ipa size, but cant succeed. I tried with linking SDK assemblies only but when the app is archived it shows 189 MB of the app store and 75mb for ipa. I tried different options but it never worked.
Then I looked into my bin folder and I found out that Xamarin.swift4 is taking about 80 MB of the size, When I removed that package my ipda was reduced to 34mb and playstore size was reduced to 89 MB, but because of this my app crashed instantly after opening. So it means that I can not remove Xamarin.swift 4 libraries.
I have attached my bin folder pic and packages.congifg file, let me know if there is any solution

    <?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Answers" version="1.4" targetFramework="xamarinios10" />
  <package id="Crashlytics" version="1.4" targetFramework="xamarinios10" />
  <package id="dannycabrera.GetiOSModel" version="1.4.0" targetFramework="xamarinios10" />
  <package id="Fabric" version="1.4" targetFramework="xamarinios10" />
  <package id="iOSCharts" version="3.1.1.2" targetFramework="xamarinios10" />
  <package id="Microsoft.CSharp" version="4.4.1" targetFramework="xamarinios10" />
  <package id="Microsoft.NETCore.Platforms" version="2.0.2" targetFramework="xamarinios10" />
  <package id="Microsoft.Win32.Primitives" version="4.3.0" targetFramework="xamarinios10" />
  <package id="NETStandard.Library" version="2.0.3" targetFramework="xamarinios10" />
  <package id="Newtonsoft.Json" version="11.0.2" targetFramework="xamarinios10" />
  <package id="System.AppContext" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Collections" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Collections.Concurrent" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.ComponentModel.TypeConverter" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Console" version="4.3.1" targetFramework="xamarinios10" />
  <package id="System.Diagnostics.Debug" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Diagnostics.Tools" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Diagnostics.Tracing" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Globalization" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Globalization.Calendars" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.IO" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.IO.Compression" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.IO.Compression.ZipFile" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.IO.FileSystem" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.IO.FileSystem.Primitives" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Linq" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Linq.Expressions" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Net.Http" version="4.3.3" targetFramework="xamarinios10" />
  <package id="System.Net.Primitives" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Net.Sockets" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.ObjectModel" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Reflection" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Reflection.Extensions" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Reflection.Primitives" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Resources.ResourceManager" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Runtime" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Runtime.Extensions" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Runtime.Handles" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Runtime.InteropServices" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Runtime.InteropServices.RuntimeInformation" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Runtime.Numerics" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Runtime.Serialization.Formatters" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Runtime.Serialization.Primitives" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Security.Cryptography.Algorithms" version="4.3.1" targetFramework="xamarinios10" />
  <package id="System.Security.Cryptography.Encoding" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Security.Cryptography.Primitives" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Security.Cryptography.X509Certificates" version="4.3.2" targetFramework="xamarinios10" />
  <package id="System.Text.Encoding" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Text.Encoding.Extensions" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Text.RegularExpressions" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Threading" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Threading.Tasks" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Threading.Timer" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Xml.ReaderWriter" version="4.3.1" targetFramework="xamarinios10" />
  <package id="System.Xml.XDocument" version="4.3.0" targetFramework="xamarinios10" />
  <package id="System.Xml.XmlDocument" version="4.3.0" targetFramework="xamarinios10" />
  <package id="UITextFieldShaker" version="2017.10.19" targetFramework="xamarinios10" />
  <package id="Xam.Plugin.Connectivity" version="3.1.1" targetFramework="xamarinios10" />
  <package id="Xamarin.Forms" version="3.0.0.446417" targetFramework="xamarinios10" />
  <package id="ZXing.Net.Mobile" version="2.3.2" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4" version="4.0.0.0" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4.Core" version="4.1.0" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4.CoreAudio" version="4.1.0" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4.CoreData" version="4.1.0" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4.CoreFoundation" version="4.1.0" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4.CoreGraphics" version="4.1.0" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4.CoreImage" version="4.1.0" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4.CoreMedia" version="4.1.0" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4.Darwin" version="4.1.0" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4.Dispatch" version="4.1.0" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4.Foundation" version="4.1.0" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4.Metal" version="4.1.0" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4.ObjectiveC" version="4.1.0" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4.OS" version="4.1.0" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4.QuartzCore" version="4.1.0" targetFramework="xamarinios10" />
  <package id="Xamarin.Swift4.UIKit" version="4.1.0" targetFramework="xamarinios10" />
</packages>

A: You should remove only the libraries you don't use in your project.
Two weeks ago my ipa file was at almost 200 MB, then I deleted all the Swift libraries that was unnecessary for the project, and now I create smaller ipa files than the previous one (80 MB).
So you need to check your application, see if you have unnecessary libraries and delete it, this way you will reduce the ipa size.

A: I would suggest looking into the 'Linker', which you will find in your iOS build options within Visual Studio
A brief overview:

*

*Don't Link - all assemblies left untouched (largest ipa size)

*Link SDK assemblies only - reduces size of SDK (Xamarin.iOS) assemblies by removing everything that your application doesn't use

*Link all assemblies - reduces size of all assemblies by removing everything that your application doesn't use (smallest ipasize)

Note that 'link all assemblies' can cause issues as the linker can't always determine what is used and can therefore remove code from an assembly that is actually required (think web services, reflection, serialisation). In such cases you can set a manual mtouch argument to prevent a specific assembly (or assemblies) from having being touched by the linker as below:
--linkskip=NameOfAssemblyToSkipWithoutFileExtension

or
--linkskip=NameOfFirstAssembly --linkskip=NameOfSecondAssembly

A real use case I've come across where the above is necessary is when using Entity Framework with Xamarin.iOS, as the linker removes code which is then called using reflection which causes the app to crash.
The full documentation for the Linker is available here: https://learn.microsoft.com/en-us/xamarin/ios/deploy-test/linker?tabs=vsmac


Q: SwiftUI - Changing parent @State doesn't update child View Specific question:
SwiftUI doesn't like us initializing @State using parameters from the parent, but what if the parent holding that @State causes major performance issues?
Example:
How do I make tapping on the top text change the slider to full/empty?

Dragging the slider correctly communicates upwards when the slider changes from full to empty, but tapping the [Overview] full: text doesn't communicate downwards that the slider should change to full/empty.
I could store the underlying Double in the parent view, but it causes major lag and seems unnecessary.
import SwiftUI

// Top level View. It doesn't know anything about specific slider percentages,
// it only knows if the slider got moved to full/empty
struct SliderOverviewView: View {

    // Try setting this to true and rerunning.. It DOES work here?!
    @State var overview = OverviewModel(state: .empty)

    var body: some View {
        VStack {
            Text("[Overview] full: \(overview.state.rawValue)")
                .onTapGesture { // BROKEN: should update child..
                    switch overview.state {
                    case .full, .between: overview.state = .empty
                    case .empty: overview.state = .full
                    }
                }
            SliderDetailView(overview: $overview)
        }
    }
}

// Bottom level View. It knows about specific slider percentages and only
// communicates upwards when percentage goes to 0% or 100%.
struct SliderDetailView: View {

    @State var details: DetailModel

    init(overview: Binding<OverviewModel>) {
        details = DetailModel(overview: overview)
    }

    var body: some View {
        VStack {
            Text("[Detail] percentFull: \(details.percentFull)")

            Slider(value: $details.percentFull)
                .padding(.horizontal, 48)
        }
    }
}

// Top level model that only knows if slider went to 0% or 100%
struct OverviewModel {
    var state: OverviewState

    enum OverviewState: String {
        case empty
        case between
        case full

    }
}

// Lower level model that knows full slider percentage
struct DetailModel {
    @Binding var overview: OverviewModel
    var percentFull: Double {
        didSet {
            if percentFull == 0 {
                overview.state = .empty
            } else if percentFull == 1 {
                overview.state = .full
            } else {
                overview.state = .between
            }
        }
    }

    init(overview: Binding<OverviewModel>) {
        _overview = overview

        // set inital percent
        switch overview.state.wrappedValue {
        case .empty:
            percentFull = 0.0
        case .between:
            percentFull = 0.5
        case .full:
            percentFull = 1.0
        }
    }
}

struct SliderOverviewView_Previews: PreviewProvider {
    static var previews: some View {
        SliderOverviewView()
    }
}

Why don't I just store percentFull in the OverviewModel?
I'm looking for a pattern so my top level @State struct doesn't need to know EVERY low level detail specific to certain Views.
Running the code example is the clearest way to see my problem.
This question uses a contrived example where an Overview only knows if the slider is full or empty, but the Detail knows what percentFull the slider actually is. The Detail has very detailed control and knowledge of the slider, and only communicates upwards to the Overview when the slider is 0% or 100%
What's my specific case for why I need to do this?
For those curious, my app is running into performance issues because I have several gestures that give the user control over progress. I want my top level ViewModel to store if the gesture is complete or not, but it doesn't need to know the specifics of how far the user has swiped. I'm trying to hide this specific progress Double from my higher level ViewModel to improve app performance.

A: Here is working, simplified and refactored answer for your issue:
struct ContentView: View {
    var body: some View {
        SliderOverviewView()
    }
}

struct SliderOverviewView: View {
    @State private var overview: OverviewModel = OverviewModel(full: false)
    var body: some View {
        VStack {
            Text("[Overview] full: \(overview.full.description)")
                .onTapGesture {
                    overview.full.toggle()
                }
            SliderDetailView(overview: $overview)
        }
    }
}

struct SliderDetailView: View {
    @Binding var overview: OverviewModel
    var body: some View {
        VStack {
            Text("[Detail] percentFull: \(tellValue(value: overview.full))")
            Slider(value: Binding(get: { () -> Double in
                return tellValue(value: overview.full)
            }, set: { newValue in
                if newValue == 1 { overview.full = true }
                else if newValue == 0 { overview.full = false }
            }))
        }
    }

    func tellValue(value: Bool) -> Double {
        if value { return 1 }
        else { return 0 }
    }
}

struct OverviewModel {
    var full: Bool
}

Update:
struct SliderDetailView: View {
    @Binding var overview: OverviewModel
    @State private var sliderValue: Double = Double()
    var body: some View {
        VStack {
            Text("[Detail] percentFull: \(sliderValue)")
            Slider(value: $sliderValue, in: 0.0...1.0)
        }
        .onAppear(perform: { sliderValue = tellValue(value: overview.full) })
        .onChange(of: overview.full, perform: { newValue in
            sliderValue = tellValue(value: newValue)
        })
        .onChange(of: sliderValue, perform: { newValue in
            if newValue == 1 { overview.full = true }
            else { overview.full = false }
        })
    }
    func tellValue(value: Bool) -> Double {
        value ? 1 : 0
    }
}

A: I present here a clean alternative using 2 ObservableObject, a hight level OverviewModel that
only deal with if slider went to 0% or 100%, and a DetailModel that deals only with the slider percentage.
Dragging the slider correctly communicates upwards when the slider changes from full to empty,  and
tapping the [Overview] full: text communicates downwards that the slider should change to full/empty.
import Foundation
import SwiftUI

@main
struct TestApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

struct ContentView: View {
    @StateObject var overview = OverviewModel()

    var body: some View {
        SliderOverviewView().environmentObject(overview)
    }
}

// Top level View. It doesn't know anything about specific slider percentages,
// it only cares if the slider got moved to full/empty
struct SliderOverviewView: View {
    @EnvironmentObject var overview: OverviewModel

    var body: some View {
        VStack {
            Text("[Overview] full: \(overview.state.rawValue)")
                .onTapGesture {
                    switch overview.state {
                    case .full, .between: overview.state = .empty
                    case .empty: overview.state = .full
                    }
                }
            SliderDetailView()
        }
    }
}

// Bottom level View. It knows about specific slider percentages and only
// communicates upwards when percentage goes to 0% or 100%.
struct SliderDetailView: View {
    @EnvironmentObject var overview: OverviewModel
    @StateObject var details = DetailModel()

    var body: some View {
        VStack {
            Text("[Detail] percentFull: \(details.percentFull)")
            Slider(value: $details.percentFull).padding(.horizontal, 48)
                .onChange(of: details.percentFull) { newVal in
                    switch newVal {
                    case 0: overview.state = .empty
                    case 1: overview.state = .full
                    default: break
                    }
                }
        }
        // listen for the high level OverviewModel changes
        .onReceive(overview.$state) { theState in
            details.percentFull = theState == .full ? 1.0 : 0.0
        }
    }
}

enum OverviewState: String {
    case empty
    case between
    case full
}

// Top level model that only knows if slider went to 0% or 100%
class OverviewModel: ObservableObject {
    @Published var state: OverviewState = .empty
}

// Lower level model that knows full slider percentage
class DetailModel: ObservableObject {
    @Published var percentFull = 0.0
}


Q: NgRx8 destruct values from action everyone, I would like to destruct action type and props in ngrx effect, I'm in a stuck with how I can do it
My actions:
export const addTab = createAction(
  '[SuperUserTabs] add tab',
  props<{ tab: SuperUserHeaderTab, tabType: TabType }>()
);

export const searchCompanyTab = createAction(
  '[SuperUserTabs] search company tab'
);

export const searchCardholderTab = createAction(
  '[SuperUserTabs] search cardholder tab'
);

Effect:
@Effect({ dispatch: false })
  addTab$ = this.actions$.pipe(
    ofType(
      TabsActions.addTab,
      TabsActions.searchCompanyTab,
      TabsActions.searchCardholderTab
    ),
    withLatestFrom(this.store.pipe(select(getTabs))),
    tap(([action, tabs]) => {
      // destruct here
      const {type, props} = action;
      // some logic
    })
  );

Any suggestions?

A: Updated: ofType accept action creator, so you can using it directly:
@Effect({ dispatch: false })
  addTab$ = this.actions$.pipe(
    ofType(
      TabsActions.addTab,
      TabsActions.searchCompanyTab,
      TabsActions.searchCardholderTab
    ),
    withLatestFrom(this.store.pipe(select(getTabs))),
    tap(([action, tabs]) => {
      // this object will contain `type` and action payload
      const {type, ...payload} = action;
      // some logic
      console.log(payload)
    })
  );

==============
Old answer also work:
because you're using action creator, which return a function, so you can access action type through type property like this:
@Effect({ dispatch: false })
  addTab$ = this.actions$.pipe(
    ofType(
      TabsActions.addTab.type,
      TabsActions.searchCompanyTab.type,
      TabsActions.searchCardholderTab.type
    ),
    withLatestFrom(this.store.pipe(select(getTabs))),
    tap(([action, tabs]) => {
      // this object will contain `type` and action payload
      const {type, ...payload} = action;
      // some logic
      console.log(payload)
    })
  );

demo: https://stackblitz.com/edit/angular-3t2fmx?file=src%2Fapp%2Fstore.ts


Q: onlongclick listner in android 2.0.3 In my java code i used onLongClickListener and opened 1 AlerDailogBox that shows delete or not!!but i want to show some options on my longclick and according to the choice i want to do further.i dont want to use context menu.plz suggest me in current code what changes should i make?
 OnLongClickListener myListener = new OnLongClickListener() {
                         public boolean onLongClick(final View v) {

                         // do something on long click
                         AlertDialog alertDialog = new AlertDialog.Builder(v.getContext()).create();
                         alertDialog.setTitle("Do you want to Delete?");
                         alertDialog.setMessage(" "+temp_name);
                         alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                EstimateTrackerActivity.this.dh.deleteexp(inc_id);
                                /*//Toast.makeText(EstimateTrackerActivity.this, "id"+id,Toast.LENGTH_LONG).show();
                                onclick_addcategory(v);*/
                                onclick_listexpense(v);
                                spinner.setSelection(temp3);
                            }
                         });
                         alertDialog.setButton2("CANCEL", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                onclick_listexpense(v);
                                spinner.setSelection(temp3);
                            }
                         });
                         alertDialog.show();
                       return false;
                     }
                 };  tr_inc.setOnLongClickListener(myListener);
                 }

A: Sound from your problem, I think you are new to Android.
Ok, look at code below.
To create an AlertDialog with a list of selectable items like the one shown to the right, use the setItems() method:
final CharSequence[] items = {"Red", "Green", "Blue"};

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a color");
builder.setItems(items, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int item) {
        Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
    }
});
AlertDialog alert = builder.create();

For more info look at Creating an AlertDialog.


Q: Add column in hive not allowed from scala/spark code I am trying to add a column in a Hive table if the source data has new columns. All the detection of new columns works well, however, when I try to add the column to the destination table, I receive this error:
for (f <- df.schema.fields) {
  if ("[" + f.name + "]"==chk) {
    spark.sqlContext.sql("alter table dbo_nwd_orders add columns (" + f.name + " " + f.dataType.typeName.replace("integer", "int") + ")")
  }
}

Error:
WARN HiveExternalCatalog: Could not alter schema of table  `default`.`dbo_nwd_orders` in a Hive compatible way. Updating Hive metastore in Spark SQL specific format
InvalidOperationException(message:partition keys can not be changed.)

However, if I catch the alter sentence generated and execute it from hive GUI (HUE), I can add it without issues.
alter table dbo_nwd_orders add columns (newCol int)

Why that sentence is valid from the GUI and not from spark code?
Thank you very much.

A: It has been said multiple times here, but just to reiterate - Spark is not Hive interface and is not designed for full Hive compatibility in terms of language (Spark targets SQL standard, Hive uses custom SQL-like query language) or capabilities (Spark is ETL solution, Hive is a Data Warehousing solution).
Even data layouts are not fully compatible between these two.
Spark with Hive support is Spark with access to Hive metastore, not Spark that behaves like Hive.
If you need to access full set of Hive's features connect to Hive directly with native client or native (not Spark) JDBC connection, and use interact with it from there.