text:
Q: Excel function to VBA I have a column (E) of items that are filled with codes that resemble the following format: 5301-500-300-000
with an adjacent column (F) of 'amounts paid' that look like the following: 53.20
My goal is to multiply the appropriate amounts in column F with the right tax rebates by using a nested if formula in vba. I've managed to do this using excel functions as follows:
a left(E2,4) formula
& a mid(E2,10,2) formula followed by a
=IF(OR(F282=1151,F282=1153),IF(OR(G282=131,G282=200,G282=210,G282=300,G282=310,G282=320,G282=800,G282=821,G282=831,G282=841,,G282=700,G282=721),H282*0.5,IF(OR(G282=341,G282=351,G282=400,G282=410,G282=421,G282=431,G282=441,G282=500,G282=511,G282=521,G282=531,G282=600,G282=611,G282=900,G282=700,G282=721),H282*0.3031,0))) formula
My question is how could I convert this series of excel formulas into a vba format so that I wouldn't have to constantly use the LEFT & MID excel functions.
So far, I've tried creating variables for left' &mid `
Private Sub CommandButton2_Click()

Dim taxcode As Range, location As Range

Set taxcode = Left(Range("E2:E10000"), 4)
Set location = Mid(Range("E2:E10000"), 10, 2)

End Sub

But have already seen problems with my code. Any help would be most appreciated.

A: I would use a regular expression for this sort of thing; that way you can avoid having those awfull nested LEFT() and MID() stuff.
So, let's get to it.
First, in the VBA editor, clic on the Tools menu and select References; enable Microsoft VBScript Regular Expressions 5.5.
Then, let's use a RegEx to split each entry from your string:
Function splitCode(code As String) As String()
    Dim ans(1 To 4) As String
    Dim re As RegExp

    Set re = New RegExp

    With re
        .IgnoreCase = True
        .MultiLine = False
        .Pattern = "([0-9]*)-([0-9]*)-([0-9]*)-([0-9]*)"
        ' Here's the magic:
        '       [0-9]* will match any sequence of digits
        '       The parenthesis will help you retreive each piece of the pattern
    End With

    If re.Test(code) Then
        ans(1) = re.Replace(code, "$1") ' You can use the Replace method to get
        ans(2) = re.Replace(code, "$2") ' each piece of the pattern.
        ans(3) = re.Replace(code, "$3") ' Simply use $n (where n is an integer)
        ans(4) = re.Replace(code, "$4") ' to get the n-th piece of the pattern enclosed in parenthesis
    End If
    Set re = Nothing
    splitCode = ans
End Function

Now that you have this array with each piece of your code, you can use it in other sub or function to get what you need:
sub doMyStuff()
    dim taxCodeRange as Range, taxCode as String()
    dim i as integer
    taxCodeRange = Range("E2:E1000")
    for i = 1 to taxCodeRange.Rows.count
        taxCode = splitCode(taxCodeRange.Cells(i,1))
        ' Now you can make whatever comparissons you need with each entry
        ' of the taxCode array.
        ' WARNING: Each entry in the array is a String, so you may want
        ' to convert it to integer before doing any comparissons
        if CInt(taxCode(1)) = 5301 then
        ' Do some stuff
        elseIf cInt(taxCode(1)) = 5302 then
        ' Do some other stuff
        ' ...
        ' ...
        ' end if
    next i
end sub

Hope this helps you.
Take a look to this post for more information about Regular Expressions in Excel


text:
Q: (JavaFX) How do I initialize my TreeView? Im not able to initialize my treeview,my fx:id is right but the output just gives me a blank treeview.
I am using scene builder with fxml controllers.
This is my Fxml Controller.
///////////////////////////////////////////////////////////////////
import java.net.URL;
import static java.time.Clock.system;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;

/**
 *
 * @author Man Eesh
 */
public class FXMLDocumentController implements Initializable {

    @FXML
    private TreeView<String> treeView;
    @FXML
    private Label label;

    @FXML
    private void handleButtonAction(ActionEvent event){

    }
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // System.out.print("here");
        label.setText("Hello World!");
        TreeItem<String> root = new TreeItem<>("Root Node");
        root.setExpanded(true);
        System.out.print("here");
        root.getChildren().addAll(
            new TreeItem<>("Item 1"),
            new TreeItem<>("Item 2"),
            new TreeItem<>("Item 3")
        );

        treeView.setRoot(root);

    }

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular JS Error - $injector:modulerr I am trying to view an angular app on a local server using npm, bower and grunt. I am using the exact code (from a cloned repository) that my colleague is using. He is able to view the full app correctly on a local server whereas I get the following error:
Failed to instantiate module [appName] due to:
Error: [$injector:modulerr] http://errors.angularjs.org/1.3.15/$injector/modulerr?p0=...)
    at Error (native)
    at http://localhost:9000/bower_components/angular/angular.min.js:6:417...
He is using a PC and I am on Mac. Does anyone have any suggestions for why he can see the app properly and I cannot?
Thanks

A: This looks to be an issue with your server setup.
He likely has a port setup on his server (http://localhost:9000/bower_components/angular/angular.min.js:6:417...) - where :9000 is the port.
I'm going to guess that you do not have the same port setup in your bindings. So your version isn't loading the angular.min.js where his is.
You could try removing the :9000 part of the url. This will then make the site look at your localhost for the js file.
This is assuming that you're even running a server on your machine? you mention a mac, so guessing perhaps not.
In that case, use the CDN https://code.angularjs.org/1.3.15/angular.min.js
So change:
http://localhost:9000/bower_components/angular/angular.min.js
To
https://code.angularjs.org/1.3.15/angular.min.js


text:
Q: Javascript hard-coded object works as parameter, but not reference to global object I'm running into an odd issue with JQuery Flot.
I had been running
var plot = null;

function initPlot () {
    plot = $.plot("#graph", myData, { /* my options here */ });
}

and everything worked fine.
I moved my options data into a variable within the scope of the function
var plot = null;

function initPlot () {
    var myOptions = { /* my options here */ };
    plot = $.plot("#graph", myData, myOptions);
}

and again, everything works fine.
Then I moved the variable to a broader scope (so I could reference it in other functions).
var plot = null;
var myOptions = { /* my options here */ };

function initPlot () {
    plot = $.plot("#graph", myData, myOptions);
}

Suddenly it won't plot correctly.  What's even more confusing to me is that it gets the values of most of the options--the graph appears, just not the data.
Using Chrome's debugger, I can see that myOptions has the correct value at the time I call $.plot().  I also tried setting a local variable o = myOptions and calling $.plot() with o instead of myOptions, but this, too, fails to plot the data.
What's causing this and how do I fix it?
I should note that I'm using Flot.Grow and Flot.Stack, but disabling these does not change the result.
EDIT (again)
Per the comments, here is literally the state of my code:

A: Turns out I'm a bit of an idiot.
The issue was that I was calculating myOptions.yaxis.max before idMap was populated.  Then, while I was waiting for an answer here, I did some refactoring on the database side, which resulted in an empty dataset.
When I fixed the db and set myOptions to only static values, it worked fine.


text:
Q: Initializing SCORM using APIWrapper.js always returns false I am new to SCORM and I found a library at http://pipwerks.com/downloads/
I tried using the sample code in SCORM Cloud, and it worked.
//Using pipwerks namespace, SCORM 1.2

var success = pipwerks.SCORM.init();

if(success){
  var status = pipwerks.SCORM.get("cmi.core.lesson_status");
  if(status != "completed"){
    success = pipwerks.SCORM.get("cmi.core.lesson_status", "completed");
    if(success){
       pipwerks.SCORM.quit();
    }
  }
}

The problem is pipwerks.SCORM.init() always returns false.
How can I resolve this problem?

A: Sounds like the wrapper can't find the API object that is provided by the LMS.
Make sure you are running this code within the context of an LMS, and that the LMS is providing the API object as required.
That wrapper also logs a trace, but only if pipwerks.debug.isActive is true.  Set that to true, run it in Firefox, and open the Console in Firebug.
It may be that the API object is fine, and that something else is going wrong.  Check that trace, it'll help.


text:
Q: Determinant of a matrix of monomial elements I'm using a $n\times m$ matrix $A$ defined over $\mathbb{N}^0$ to construct a $n\times m$ matrix $B$ such that $b_{ij} = x^{a_{ij}}$, for an indeterminate $x$. My questions are:

*

*Are these $B$ matrices known or studied in any field of mathematics. If so, can anyone point me to where I can learn more about it?

*In specific, I'm looking to see if we can say anything in general about $det(B)$ that we cannot say about $det(A)$?


text:
Q: How can a .png file have a Query String? I'm working on a site saved as php pages.
An image tag has the following src value:
<img src="xxxxx.png?src=http://xxxx.com/xxx/xxx.png&h=192&w=334&zc=1">

I've searched everywhere to try and decipher this. The first section src="xxxx.png is the location of the image in the local files. I am guessing the ?src=xxx is a call to the server to resend an alternate image? This second image is the same image as the first, only slightly larger. Any guess as to what the developer is accomplishing?
On the same note, I'm not sure I understand the height and width in the same call...h=192&w=334&zc=1.
Appreciate any insight.


text:
Q: Run-time error '91' VBA when trying to find a match in Worksheet I am trying to Find a specific string in a Range. Run-time error '91'keeps showing up. I understand this happens because the Find function does not find any coincidence. Nevertheless I am unsure why this is happening.
Currently I have a Listbox in a Userform. When I select an option in the Listbox, the string of such selection will be shown on a Userform Textbox (txt_selected). On a worksheet I have exactly the same list as displayed on the Listbox. I want to find the row in the worksheet where there is a coincidence with the selected element.
I have an if statement which is triggered when there is a match found (countif>0), displaying a MessageBox with the message "Match found". However, when I try to find the row number of the match I get the error.
My code is the following:
Private Sub lstbx_diarias_Click()

For n = 0 To (UserForm1.lstbx_diarias.ListCount - 1)
    UserForm1.txt_selected.Value = UserForm1.lstbx_diarias.Text
Next n

End Sub

Sub llenar_checklist()

Dim result_row As Long
Dim actividad As String
Dim look_range as Range

''' Actividades Diarias
If UserForm1.chbx_diarias.Value = True Then

    Set look_range = Sheets("Checklist").Range("C9:C23")

    actividad = UserForm1.txt_selected.Value

    If Application.WorksheetFunction.CountIf(look_range, actividad) > 0 Then

        MsgBox "Match found"
        result = look_range.Find(what:=actividad, LookIn:=xlValues, LookAt:=xlWhole)
        result_row = result.Row

    End If
    MsgBox "The row is " & result_row

End If

End Sub

According to VBA, the error comes from line where result if defined. Any ideas why this may be happening?
Thanks a lot in advance.


text:
Q: jdk -version shows the old one different than the recent installed I have upgraded my java to jdk 1.7 (1.7.0_71-b14 <- System Configuration shows). But, in terminal, 'java -version' shows 1.6.0_65. I wonder what I should do to fix this.
Some say JAVA_HOME must be /library/java/JavaVirtualMachines/jdk1.7.0...., but I don't have anything in that folder. Some other solutions from the internet do not fix my problem.
I am using Mac, OSX 10.9.5. Can anyone help me please ?

A: Try this command:
export JAVA_HOME=$(/usr/libexec/java_home -v 1.7)

Then issue the java -version command and if that doesn't work, try rebooting your computer like @RC mentioned in the comments.


text:
Q: uiview width is zero I added a uigesture to my uiview using the following code
UIPinchGestureRecognizer *pinchRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(scale:)];
[pinchRecognizer setDelegate:self];
[holderView addGestureRecognizer:pinchRecognizer];
[pinchRecognizer release];

and the code of scalling is
    if([(UIPinchGestureRecognizer*)sender state] == UIGestureRecognizerStateEnded) {

        lastScale = 1.0;
        return;
    }

    CGFloat scale = 1.0 - (lastScale - [(UIPinchGestureRecognizer*)sender scale]);

    CGAffineTransform currentTransform = [(UIPinchGestureRecognizer*)sender view].transform;
    CGAffineTransform newTransform = CGAffineTransformScale(currentTransform, scale, scale);

    [[(UIPinchGestureRecognizer*)sender view] setTransform:newTransform];

    lastScale = [(UIPinchGestureRecognizer*)sender scale];

    OldTransform = newTransform;

    OldCenter = [(UIPinchGestureRecognizer*)sender view].center;

the problem before the zooming I can get the width and height of holdview but after scaling it return zero
I use the following code to display
NSLog(@" the rectangle %f , %f ,%f, %f ", holderView.frame.origin.x, holderView.frame.origin.y, holderView.bounds.size.width , holderView.bounds.size.height ) ;
another problem is that when I add subview above it all the values return from the holderview the size the origin ,.. become zero
any suggestion to solve that

A: Setting the transform of a view does not change the values of its frame property. So even if the frame reports back that the width is 100, it might visually be 50, or whatever, due to the transform.
The reason you get 0 for the width of your frame is probably because you either set it to 0 at some point, or haven't set it yet. You need to provide a default size to make your view visible.


text:
Q: Node.js process.exit() does not exit cleanly, and the dangers of async fs.writeFile tl;dr:
Calling the asynchronous fs.writeFile from asynchronous events (and perhaps even from just a plain old loop) and then calling process.exit() successfully opens the files but fails to flush the data into the files. The callbacks given to writeFile do not get a chance to run before the process exits. Is this expected behavior?
Regardless of whether process.exit() is failing to perform this cleanup, I call into question whether it should be node's duty to at least attempt to work the file writes into the schedule, because it may very well be the case that the deallocation of huge buffers depends on writing them out to disk.
details
I have a conceptually basic piece of node.js code which performs a transformation on a large data file. This happens to be a LiDAR sensor's data file, which should not be relevant. It is simply a dataset that is quite large owing to the nature of its existence. It is structurally simple. The sensor sends its data over the network. My task for this script is to produce a separate file for each rotating scan. The details of this logic is irrelevant as well.
The basic idea is I use node_pcap to read a huge .pcap file using the method given to do this task by node_pcap, which is "offline mode".
What this means is that instead of asynchronously catching the network packets as they appear, what appears to be a rather dense stream of asynchronous events representing the packets are "generated".
So, the main structure of the program consists of a few global state variables, and a single callback to the pcap session. I initialize globals, then assign the callback function to the pcap session. This callback to the packet event does all the work.
Part of this work is writing out a large array of data files. Once in a while a packet will indicate some condition that means I should move on to writing into the next data file. I increment the data filename index, and call fs.writeFile() again to begin writing the new file. Since I am writing only, it seems natural to let node decide when a good time is to begin writing.
Basically, both fs.writeFileSync and fs.writeFile should end up calling the OS's write() system call on their respective files in an asynchronous fashion. This does not bother me because I am only writing, so the asynchronous nature of the write which can affect certain access patterns does not matter to me since I do not do any access. The only difference is in that writeFileSync forces the node event loop to block until such time as the write() syscall completes.
As the program progresses, when I use writeFile (the js-asynchronous version), hundreds of my output files are created, but no data is written to them. Not one. The very first data file is still open when the hundredth data file is created.
This is conceptually fine. The reason is that node is busy crunching new data, and is happily holding on to the increasing number of file descriptors that it will eventually get to in order to write the files' data in. Meanwhile it also has to keep inside of memory all the eventual contents of the files. This will eventually run out, but let's ignore the RAM size limitation for a moment. Obviously a bad thing to happen here would be running out of RAM and crashing the program. Hopefully node will be smart and realize it just needs to schedule some file writes and then it can free a bunch of buffers...
If I stick a statement in the middle of all this to call process.exit(), I would expect that node will clean up and flush the pending writeFile writes before exiting.
But node does not do this.
Changing to writeFileSync fixes the problem obviously.
Changing and truncating my input data such that process.exit() is not explicitly called also results in the files eventually getting written (and the completion callback given to writeFile to run) at the very end when the input events are done pumping.
This seems to indicate for me that the cleanup is being improperly performed by process.exit().
Question: Is there some alternative to exiting the event loop cleanly in the middle? Note I had to manually truncate my large input file, because terminating with process.exit() caused all the file writes to not complete.
This is node v0.10.26 installed a while ago on OS X with Homebrew.
Continuing with my thought process, the behavior that I am seeing here calls into question the fundamental purpose of using writeFile. It's supposed to improve things to be able to flexibly write my file whenever node deems it fit. However, apparently if node's event loop is pumped hard enough, then it will basically "get behind" on its workload.
It is like the event loop has an inbox and an outbox. In this analogy, the outbox represents the temp variables containing the data I am writing to the files. The assumption that a lazy productive programmer like me wants to make is that the inbox and outbox are interfaces that I can use and that they are flexible and that the system will manage for me. However if I feed the inbox at too high a rate, then node actually can't keep up, and it will just start piling the data into the outbox without having any time to flush it because for one reason or another, the scheduling is such that all the incoming events have to get processed first. This in turn defers all garbage collection of the outbox's contents, and quite quickly we deplete the system's RAM. This is quite easily a hard-to-find bug when this pattern is used in a complex system. I am glad I took a modular approach to this project.
I mean, yes, clearly, obviously, beyond all doubt the answer is to use writeFileSync as I do almost every single time that I write files with node.
What, then, is the value in even having writeFile? At this point I am trading a potential small increase in parallel processing for the increased possibility that if (for some reason) the machine's processing capability drops (whether it's thermal throttling or OS level scheduling or I don't pay my IaaS bills on time, or any other reason), that it can potentially lead to a snowballing memory explosion?
Perhaps this is getting at the core of solving the truly rather complex problems inherent in streaming data processing systems, and that I cannot realistically expect this event-based processing model to step up and elegantly solve these problems automatically. Maybe I should be satisfied that it only gets me about half of the way to something robust. Maybe I am just projecting my wishes onto it and that it is unreasonable for me to assume that node needs to less deterministically "improve" the scheduling of its event loop.

A: I'm not a node expert but it seems like your problem can be simplified using streams. Streams let you pause and resume and also provide other neat functionality. I suggest you take at look at Chapter 9 of Professional NodeJS by Pedro Teixeira. You can find an online copy easily for reading purposes. It provides very detailed and well explained examples on how to use streams to read and write data and also prevent potential memory leaks and loss of data.


text:
Q: Nested if statements declaring return false for each one Say I have the following code:
function a() {
    if ($a) {
        if ($b) {
            if ($c) {
                // do something
            }
            return FALSE
        }
        return FALSE;
    }
    return FALSE;
}

In this instance do I need all the return falses or will it sort of cascade to the last one if I remove both the inner ones?
Thanks

A: if ($a && $b && $c) {
    //do something
    return TRUE;
} else {
    return FALSE;
}

A: It will cascade down the list. You don't need each return false call.

A: It will fall/cascade through to the last one.
But you may also need a return true; in your //do something part as the return false; will be called otherwise.
The function will continoue to run until one of the three things happen:

*

*a return statement is executed

*the closing } of the function is reached

*an uncatched Exception or (Fatal) error occurs

A: It will continue on through, however, this may not be what you want, as such a return will end the function altogether and might skip something you want done.

A: Use something like this for a straightforward and easily understood representation:
function a() {
    if ($a) {
        if ($b) {
            if ($c) {
                // do something
                return TRUE; // or something other than TRUE
            }
        }
    }
    return FALSE;
}

A: Short answer; you can safely remove all "return false;" except the last one and it will still work the same.
Once it reaches the end of an if-statement it will jump out of it and continue in the previous block of code ( a block is defined by a { and }). For example, if $a is true but $b is not, it will enter the $a-block and then skip the $b-block, continuing right after it. When the $a-block has ended it will return to the previous block. See the following illustration:
function a() {
    if ($a) { // $a is true, enters block
        if($b) { // $b is false, skip block
            return true;
        }
        // end of $a-block reached, leave $a-block
    }
    return false; // return false and stop further execution
}

A cleaner way to write the above if-statements could be:
If ($a && $b)
    return true;
return false;


text:
Q: TypeError: Cannot read properties of undefined (reading 'length') I am following a youtube tutorial and we returned conditional HTML elements if post.length is 0 or not but I get "TypeError: Cannot read properties of undefined (reading 'length')"
const Posts = () => {
const posts = useSelector((state) => state.posts)

return (
!posts.length ? <CircularProgress /> : (
  <Grid className={classes.container} container alignItems="stretch" spacing={3}>
    {posts.map((post) => (
      <Grid key={post._id} item xs={12} sm={6}>
        <Post post={post}/>
      </Grid>
    ))}
  </Grid>
 )
);
};

So I tried to use the following traditional if statement to see if I made a syntax error but seems like it wasn't the case
if (!posts.length) {
return <CircularProgress />
} else {
<Grid className={classes.container} container alignItems="stretch" spacing={3}>
    {posts.map((post) => (
      <Grid key={post._id} item xs={12} sm={6}>
        <Post post={post}/>
      </Grid>
    ))}
  </Grid>
}

A: First of all make sure you have posts already defined in the component with a console log :
console.log(posts);

If it is defined then you need to change the posts.length code to this code :
if (posts && !posts.length) {
return <CircularProgress />
} else {
<Grid className={classes.container} container alignItems="stretch" spacing={3}>
    {posts && posts.map((post) => (
      <Grid key={post._id} item xs={12} sm={6}>
        <Post post={post}/>
      </Grid>
    ))}
  </Grid>
}

This way we are saying that get the length of the posts only when it gets available in the component .


text:
Q: I've killed the guy (Cale) who has the key open the door to the locked house in Mejula, is there a way to get it? I accidentally killed him and now i have no way of getting the house key of the building Mejula. Anyone know of another way to get it?

A: After a little time has passed, a tombstone will appear where you killed Cale. If you interact with the tombstone, you can pay souls to speak with Cale's spirit, which will allow you to obtain the key.
This same technique works for all (or almost all?) NPCs in the game. If the NPC in question had items for sale, you're also able to browse their wares this way.


text:
Q: Use ESC Key to leave html5 video fullscreen So I have been embeding html5 videos into my website as of late using the mediaelement.js script.  It works really great and seems like be the least buggy.  However, I am simply trying to add the function that when pressing the ESC key, it takes you out of full screen mode, I have done a lot of searching and it doesnt seem like anybody has asked this question, which makes me think it is a simple oversight.  But nontheless I need to figure it out to satisfy my client.  Thanks
Media Element Website: http://mediaelementjs.com/
Update: It is only Chrome from what I can tell that it doesn't work in

A: http://api.jquery.com/keyup/
maybe something like that, media element should have a function you can call to reduce the window size. ESC has keycode 27 if I'm not wrong


text:
Q: Tools, recommendations to understand NTFS permissions? I'm trying to troubleshoot some issues with our IIS7 FTP site--namely, why some users have access to the site when it doesn't look like they should. The basic problem is that I do not understand NTFS / Active Directory permissions very well.
Does anyone know if any tools exist that allow you to view where permissions are coming from? For example, if I have read access to a particular folder, what is the source of that permission? I know the basics such as group membership and inherited permissions, but I'm running into situations where a user does not appear to be part of any group that has permissions to a resource, and yet is able to access that resource nonetheless. Clearly I lack an understanding of how/what permissions are inherited, what overrides what, etc.
In addition to tools that might help analyze/learn about permissions, I would welcome suggestions on the best way to get a thorough understanding of permissions. Favorite books, articles, etc. Thanks!

A: NTFS permissions are hierarchical by nature.  Any file/folder inherits permissions from the parent folder.  You can append permissions to & from, or start a new "root" by blocking inheritance.  Finding where permissions come from... is as simple as looking where the file is at... and what is above it.
Similarly user permissions are also hierarchical... If I'm in a group... who is in another group... who is in a group who has sufficient privileges to access the folder... that means I do too.  By default, every user must be in at least 1 group, and 99% of the time they're in the "Users" group, or "Domain Users" (if you're in a domain).

A: One tool that I find useful to see the state of permissions for a heircarchy is the sysinernals tool AccessEnum.  It does not show you the permissions, instead it scans a folder and shows you who has read, write, or been denied access.
Past that, go to a command line and use the icacls command to examine a folder or files.


text:
Q: ASP.NET-C#: Inserting const into TextBox in Gridview I have some problems inserting a const "1" into a textbox which is gridview.
The gridview code:
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" EnableViewState="False">
        <Columns>
        <asp:BoundField DataField="Price" HeaderText="Price" ItemStyle-CssClass="price" >

<ItemStyle CssClass="price"></ItemStyle>
            </asp:BoundField>

                         <asp:TemplateField HeaderText="ProductID">
                <ItemTemplate>
                    <asp:Label ID="lblID" runat="server" Text='<%# Eval("ProductID") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
             <asp:TemplateField HeaderText="ProductName">
                <ItemTemplate>
                    <asp:Label ID="lblName" runat="server" Text='<%# Eval("ProductName") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>

             <asp:TemplateField HeaderText="Summary">
                <ItemTemplate>
                    <asp:Label ID="lblSum" runat="server" Text='<%# Eval("Summary") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
             <asp:TemplateField HeaderText="picPath">
                <ItemTemplate>
                    <asp:Label ID="lblPic" runat="server" Text='<%# Eval("picPath") %>' ></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>

            <asp:TemplateField HeaderText = "quantity">
            <ItemTemplate>
                <asp:TextBox ID="lblquantity" runat="server" ></asp:TextBox>

            </ItemTemplate>
        </asp:TemplateField>

        <asp:TemplateField HeaderText = "Total">
            <ItemTemplate>
                <asp:Label ID="lblTotal" runat="server" ></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

All the information is populated from the session of the previous page, beside this textbox which doesn't comes from anywhere, it's a quantity textbox which the user should enter. And I want it to have a default value of "1".
I don't actually know how to insert into a textbox which is in the gridview.
Please help me.
Thanks

A: This may be because code is also checking for Header and footer template..
just put a null check before settings value...
TextBox tb = (TextBox)e.Row.FindControl("lblquantity");
if(tb!=null)
    tb.Text = Convert.ToString(123);

This will surely work...

A: <asp:TemplateField HeaderText = "quantity">
        <ItemTemplate>
            <asp:TextBox ID="lblquantity" runat="server" Text='<%# Eval("quantity") == DBNull.Value ? "1" : Eval("quantity").ToString()' ></asp:TextBox>
        </ItemTemplate>
</asp:TemplateField>

if quantity value is null in the table, then Text property will be default 1. Otherwise it will be quantity column in the table.

A: You can put chis code in your GridView's RowDataBound event...
TextBox tb = (TextBox)e.Row.FindControl("lblquantity");
tb.Text = Convert.ToString(123);

I hope this helps...


text:
Q: create CvMat from a C++ vector of CvPoint2D32f I am trying to create a CvMat data structure using cvMat() in OpenCV.
The last parameter of cvMat() expects a void* to the data.
My data is stored in the following data structure
vector<vector<CvPoint2D32f>> data;

I expected
data.at(0)

to work as the last parameter, but the compiler says that it can not convert to void*.
What path should I be taking now ?
Create an array from vectors ? That would waste a lot of time/memory.

A: data.at(0) has vector<CvPoint2D32f> type, but you need pointer to the first element of that vector. Try:
 &(data.at(0).at(0))

Also keep in mind, that vector<vector<CvPoint2D32f>> is not a two dimensional array of CvPoint2D32f. It is more like "vector of references" to one dimensional arrays.


text:
Q: Would it be possible in Access to show the name of the user who has made changes in the report or the data in the access database Would it be possible in Access to show the name of the user who has logged in to the application and made changes in the report or the data in the access database.
For e.g.
I have a table with more than 1 users in the access application used for storing and editing data.
-User ABC logs in to the application edits the data / records in the table
-User DEF and other users should be able to see the name of the user who has changed the table records .viz. user abc's name in the table record column name "modified by" and "modified date"

A: You can receive OS user name using function
Environ("username")

Create a table with real user names and their OS user names and show to others real name instead of OS.
If you use custom login form with internal application users, just use application user name/ID
Store OS or application user name in ModifiedBy field of your data tables in AfterUpdate form event.
You can update this field automatically if you create a Data Macro for table with data. Data Macro was introduced in Access 2010, this is not regular macro, use table designer for editing data macroses. Create Before Change data macro:
SetField
    Name  ModifiedDate
    Value Now()
SetField
    Name  ModifiedBy
    Value GetFullUserInfo()

Here GetFullUserInfo is a public function, which returns anything you want - OS user name, application user name, application version etc.


text:
Q: I'm trying to avoid calling dispatch inside a state reducer, and I'm not sure if redux-thunk is the solution I need I'm still new to using Redux, but basically I'm creating a javascript scientific calculator for a learning project, and I'm not quite sure if I'm on the right track. basically, the calculator is going to use a stack in the form of an array with parenthetical groupings within an expression being represented as a reference to another element in the stack which contains the expression contained in the parentheses.
for example, 3 * (4 + 1)/5 + ln(6+8) would be represented by
[
  [4, '*', 'ref:1', '/', 5, '+', 'ln', 'ref:2'],
  [4, '+', 1],
  [6, '+', 8]
]

I'm creating various reducers to handle different pieces. For example, one reducer will handle adding operators to the stack, while another will handle adding numbers to the stack. (after adding their respective elements, each reducer will call two functions that are not a part of the Redux store to handle rendering the input and evaluating/rendering the output into strings, which are also parts of the state object).
Now obviously if the user hits, for example, the number 2, and the last element is the number 3, then the result would be to transform the element into the number 32. However, if the last element is 2, and the user hits the pi key, then I would want to add a '*' operator and THEN 3.14159.
Now it wouldn't make sense for the number reducer to handle adding the '*' operator, and I understand from this question that calling dispatch from the reducer is considered to be an "anti-pattern". Is this where Redux-Thunk would step in, or is there some other solution that I should be looking at?
Also, I was reading this article and I'm not quite sure what they mean when they say that two reducers can't share state slices. What exactly is a single slice, and how is one slice differentiated from another within the combineReducers function?

A: So after taking what seemed like forever to learn Middleware and redux-thunk, I came up with a solution. I realize now that the entire stack needs to be handled by a single reducer, but to get around the problem of using recursion mention above within the reducer, I created an action creator that returns a function:
Function addElement(element)
{
  return (dispatch, getState) => {
    dispatch(addToStack(element));
    while (getState().stack.hasOwnProperty('elementsToBeDispatched'))
    {
      dispatch(addToStack(elementsToBeDispatched[0]));
    }
}

Sorry for any typos, I'm writing this out on my phone.


text:
Q: Listener for Google Events This other question suggested using webhooks to listen for an event. Google Calendars API - Listener for new calendar events or updates to existing events?
As the admin, I need to listen for new, updated or deleted events in all my users calendars. Once alerted then I will take the event information and then do something with it in another business software application.
How can I use the webhook to not just listen for a events in a single user's calendar but in all calendars?

A: You have to create a resource for each Calendar. You can do it using the Directory API to fetch all the users and their respective Calendars:

*

*List all the users in your domain.

*Get the primary email of each user, which is also their Calendar Id.

*Use a for loop to iterate over the emails and make a POST request:
POST https://www.googleapis.com/calendar/v3/calendars/my_calendar@gmail.com/events/watch
If this is not feasible, you can request this feature on Google's Issue Tracker.


text:
Q: Model an information system which communicates with other information systems in a UML-diagram? I have to develop an integration concept to integrate my software as a subsystem into an enterprise information system which communicates with other information systems in other institutions.
I want to show a diagram which explains how the several subsystems are connected and which data is communicated between the subsystems. My problem is that I'm not sure if there is in the UML language a diagram-type that supports modeling of complete information systems.
I thought about the deployment diagram, but I am not sure if it is the right. I don't want to start an then recognize that it is the wrong way.
Is there any advice which diagram should be used,  or if there is an alternative modeling language for complex information systems?

A:
I want to show a diagram which explains how the several subsystems work together and which data is communicated between the subsystems.

I'd probably start with a conceptual sequence diagram.
So, for example, you could have your lifelines represent the various components that you're integrating with, and your interactions could be any of the messages that need to transfer to and from those components.

A: A component diagram is what you want - see chapter 25 of "The Unified Modeling Language User Guide".


text:
Q: How to write a python string to a C struct's (char *) member in python? I have a C struct passed from C to python, and I want to change the content of a (char *)member in python.
little.c
#include <Python.h>
typedef struct little littleStruct;
struct little{

        char *memberStr;
        PyObject *(*callFunc)(littleStruct *s, char *funcName, PyObject *paraList);
};

littleStruct *createLittle();
void init_little(littleStruct *s);
PyObject *little_callFunc(littleStruct *s, char *funcName, PyObject *paraList);

littleStruct *createLittle(){
    littleStruct *little = malloc(sizeof(littleStruct));
    init_little(little);
    return little;
}
void init_little(littleStruct *s){
    s->memberStr = malloc(sizeof(char)*128);
    memset(s->memberStr, 0, 128);

    s->callFunc = little_callFunc;
}

PyObject *little_callFunc(littleStruct *s, char *funcName, PyObject *paraList){
    PyGILState_STATE st = PyGILState_Ensure();

    PyObject *module, *moduleDict, *moduleFunc, *moduleFuncArgs, *moduleFuncRet;

    // skipped error checking in this little example

    module = PyImport_ImportModule(funcName);
    moduleDict = PyModule_GetDict(module);
    moduleFunc = PyDict_GetItemString(moduleDict, funcName);

    // set arguments for littleOperation.littleOperation
    moduleFuncArgs = PyTuple_New(2);
    PyTuple_SetItem(moduleFuncArgs, 0, PyLong_FromVoidPtr(s));
    PyTuple_SetItem(moduleFuncArgs, 1, paraList);

    printf("==== In C, before call func: %s, address(memberStr): %p, memberStr: %s\n", funcName, s->memberStr, s->memberStr);
    moduleFuncRet = PyObject_CallObject(moduleFunc, moduleFuncArgs);
    printf("==== In C, after call func: %s, address(memberStr): %p, memberStr: %s\n", funcName, s->memberStr, s->memberStr);

    PyGILState_Release(st);
    return moduleFuncRet;
}

compile to .so file
gcc -g -fPIC -c little.c -I/usr/include/python2.7 -L/usr/lib/python2.7 -lpython2.7
gcc -shared little.o -o little.so
mv little.so /usr/lib

create the struct and call the struct member function callFunc in little.py
little.py
from ctypes import *

class littleStruct(Structure):
        pass
littleStruct._fields_ = [
            ("memberStr", c_char_p),
            ("callFunc", CFUNCTYPE(py_object, POINTER(littleStruct), c_char_p, py_object))
        ]

def main():
    try:
        littleDll = PyDLL("little.so")
        littleDll.createLittle.restype = POINTER(littleStruct)
        little = littleDll.createLittle()

        paraList = {"para0": 0, "para1": "test"}
        ret = little.contents.callFunc(little, "littleOperation", paraList)
    except Exception, e:
        print("%s"%str(e))

if __name__ == "__main__":
    main()

littleOperation.py
from little import littleStruct
from ctypes import memset
def littleOperation(little_pointer, paraList):
    try:
        little = littleStruct.from_address(little_pointer)

        # set little.memberStr
        # little.memberStr = paraList["para1"]
        for i in range(0, len(paraList["para1"])):
            memset(id(little.memberStr)+i, ord(paraList["para1"][i]), 1)
        print("After set little.memberStr in littleOperation.py")
        return {"status": 0}
    except Exception, e:
        print("%s"%str(e))
        return {"status": -1}

If I deirectly assign python string to C struct (char*) member, little.memberStr = paraList["para1"], the address will be changed.
==== In C, before call func: littleOperation, address(memberStr): 0x226a200, memberStr:
After set little.memberStr in littleOperation.py
==== In C, after call func: littleOperation, address(memberStr): 0x7fb9db196ec4, memberStr: test

I tried ctypes.memset, the address remains the same, but the (char *) member not changed at all.
==== In C, before call func: littleOperation, address(memberStr): 0x1d97200, memberStr:
After set little.memberStr in littleOperation.py
==== In C, after call func: littleOperation, address(memberStr): 0x1d97200, memberStr:

Why is ctypes.memset not working ?

A: Due to ctypes special handling of c_char_p types, it returns a Python
byte string object when accessed.  Your memset/id code is modifying the first few bytes of the PyObject structure representing that immutable byte string object.
Instead, change the memberStr type in littleStruct._fields_ to POINTER(c_char) to preserve access to the C pointer.
Then, in littleOperation.py, you may cast the POINTER(c_char) to a POINTER(c_char * <size> where <size> is the required write size or known size of the buffer.  Then you can dereference the pointer via .contents to access a fixed size array that can be assigned a byte string directly through .value:
p = cast(little.memberStr,POINTER(c_char * 128))
p.contents.value = paraList['para1']

See another answer of mine that has a smaller, standalone example.


text:
Q: Set base64 image filename on upload on TinyMCE I'm pasting images from Google Docs.
Those contain an src with a Google Docs URL and then I replace with a base64 blob URL data.
Now the image gets uploaded correctly on submit.
The problem that I find is that I can not choose the filename for the image.
The image always looks like blobid1, blobid2.
How can I customize those names?


text:
Q: Run-time error '-2147221241 (80040107) returning Item.ReceivedTime I have a VBA script in Outlook to move incoming emails with a specific subject to a subfolder within Outlook, and then export those emails to TXT files.
After several emails are exported a message pops up.

"Run-time error '-2147221241 (80040107)': The Operation failed."

It is highlighting:
RevdDate = Item.ReceivedTime

I can restart Outlook and it will usually export the remainder of the emails.
Option Explicit

Private WithEvents Items As Outlook.Items

Private Sub Application_Startup()
    Dim olNs As Outlook.NameSpace
    Dim Inbox  As Outlook.MAPIFolder

    Set olNs = Application.GetNamespace("MAPI")
    Set Inbox = olNs.GetDefaultFolder(olFolderInbox)
    Set Items = Inbox.Items
End Sub

Private Sub Items_ItemAdd(ByVal Item As Object)
    If TypeOf Item Is Outlook.MailItem Then
        SaveMailAsFile Item ' call sub
    End If
End Sub

Public Sub SaveMailAsFile(ByVal Item As Object)
    Dim olNs As Outlook.NameSpace
    Dim Inbox As Outlook.MAPIFolder
    Dim SubFolder As Outlook.MAPIFolder
    Dim Items As Outlook.Items
    Dim ItemSubject As String
    Dim NewName As String
    Dim RevdDate As Date
    Dim Path As String
    Dim Ext As String
    Dim i As Long

    Set olNs = Application.GetNamespace("MAPI")
    Set Inbox = olNs.GetDefaultFolder(olFolderInbox)
    Set Items = Inbox.Items.Restrict("[Subject] = 'VVAnalyze Results'")

    Path = Environ("ltvstatus") & "C:\Users\ltvstatus\Desktop\Backup Reports\"
    ItemSubject = Item.Subject
    RevdDate = Item.ReceivedTime
    Ext = "txt"

    For i = Items.Count To 1 Step -1
        Set Item = Items.Item(i)

        DoEvents

        If Item.Class = olMail Then
            Debug.Print Item.Subject ' Immediate Window
            Set SubFolder = Inbox.Folders("Reports") ' <--- Update Fldr Name

            ItemSubject = Format(RevdDate, "YYYYMMDD-HHNNSS") _
                                                    & " - " & _
                                            Item.Subject & Ext

            ItemSubject = FileNameUnique(Path, ItemSubject, Ext)

            Item.SaveAs Path & ItemSubject, olTXT
            Item.Move SubFolder
        End If
    Next

    Set olNs = Nothing
    Set Inbox = Nothing
    Set SubFolder = Nothing
    Set Items = Nothing

End Sub

'// Check if the file exists
Private Function FileExists(FullName As String) As Boolean
Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")

    If fso.FileExists(FullName) Then
        FileExists = True
    Else
        FileExists = False
    End If

    Exit Function
End Function

'// If the same file name exist then add (1)
Private Function FileNameUnique(Path As String, _
                               FileName As String, _
                               Ext As String) As String
Dim lngF As Long
Dim lngName As Long
    lngF = 1
    lngName = Len(FileName) - (Len(Ext) + 1)
    FileName = Left(FileName, lngName)

    Do While FileExists(Path & FileName & Chr(46) & Ext) = True
        FileName = Left(FileName, lngName) & " (" & lngF & ")"
        lngF = lngF + 1
    Loop

    FileNameUnique = FileName & Chr(46) & Ext

    Exit Function
End Function

A: This line accepts Item passed to it by the ItemAdd code.
Public Sub SaveMailAsFile(ByVal Item As Object)

You have intermixed code to handle one item and code to handle many items.
You could first process the one Item then look for mail that might have been missed previously and is now unprocessed in the Inbox.
Private Sub SaveMailAsFile(ByVal Item As Object)

    Dim olNs As Outlook.NameSpace
    Dim Inbox As Outlook.MAPIFolder
    Dim SubFolder As Outlook.MAPIFolder

    Dim Items As Outlook.Items
    Dim ItemSubject As String

    Dim RevdDate As Date
    Dim Path As String
    Dim Ext As String

    Set olNs = Application.GetNamespace("MAPI")
    Set Inbox = olNs.GetDefaultFolder(olFolderInbox)

    If Item.Subject = "VVAnalyze Results" Then

        Path = Environ("ltvstatus") & "C:\Users\ltvstatus\Desktop\Backup Reports\"
        ItemSubject = Item.Subject
        RevdDate = Item.ReceivedTime
        Ext = "txt"

        Debug.Print Item.Subject ' Immediate Window

        Set SubFolder = Inbox.Folders("Reports") ' <--- Update Fldr Name

        ItemSubject = Format(RevdDate, "YYYYMMDD-HHNNSS") _
                                                & " - " & _
                                        Item.Subject & Ext

        ItemSubject = FileNameUnique(Path, ItemSubject, Ext)

        Item.SaveAs Path & ItemSubject, olTXT
        Item.Move SubFolder

    End If

    SaveMailAsFile_Standalone ' Comment out to run separately if needed

ExitRoutine:
    Set olNs = Nothing
    Set SubFolder = Nothing
    Set Inbox = Nothing
    Set Items = Nothing

End Sub

Public Sub SaveMailAsFile_Standalone()

    Dim olNs As NameSpace
    Dim Inbox As Folder
    Dim SubFolder As Folder

    Dim resItems As Items
    Dim unprocessedItem As Object

    Dim ItemSubject As String
    Dim RevdDate As Date
    Dim Path As String
    Dim Ext As String

    Dim i As Long

    Set olNs = Application.GetNamespace("MAPI")
    Set Inbox = olNs.GetDefaultFolder(olFolderInbox)

    Set resItems = Inbox.Items.Restrict("[Subject] = 'VVAnalyze Results'")

    Path = Environ("ltvstatus") & "C:\Users\ltvstatus\Desktop\Backup Reports\"
    'ItemSubject = Item.Subject
    'RevdDate = Item.ReceivedTime
    Ext = "txt"

    For i = resItems.count To 1 Step -1

        Set unprocessedItem = resItems.Item(i)

        DoEvents

        If unprocessedItem.Class = olMail Then

            ItemSubject = unprocessedItem.Subject
            RevdDate = unprocessedItem.ReceivedTime

            Debug.Print unprocessedItem.Subject ' Immediate Window

            Set SubFolder = Inbox.Folders("Reports") ' <--- Update Fldr Name

            ItemSubject = Format(RevdDate, "YYYYMMDD-HHNNSS") _
                                                    & " - " & _
                                    unprocessedItem.Subject & Ext

            ItemSubject = FileNameUnique(Path, ItemSubject, Ext)

            unprocessedItem.SaveAs Path & ItemSubject, olTXT
            unprocessedItem.Move SubFolder

        End If
    Next

ExitRoutine:
    Set olNs = Nothing
    Set Inbox = Nothing
    Set SubFolder = Nothing
    Set resItems = Nothing
    Set unprocessedItem = Nothing

End Sub

A: The error is MAPI_E_INVALID_ENTRYID, which usually means an entry id passed to Namespace.GetItemfromID cannot be recognized.
Are you sure you have the error location right? How is it possible for your script to successfully retrieve the Subject property and then fail on ReceivedTime?


text:
Q: navbar-nav gets pushed below navbar-brand? When the width of my screen reaches 767px, the navigation collapses as excepted.  When I go to 768px, the navbar-nav goes below the navbar-brand.  It is not until I reach 795px, that the navbar-brand and navbar-nav line up again.  These values change depending on how large your navigation is.  Here is a jsbin

A: Your navbar is too wide so there is not enough space for it to stay on the same line. You could reduce the padding of ".nav > li > a" to
padding: 10px 13px;

to avoid the problem

A: Not sure if this is the cause or not, but try taking some of the padding off of your list items. I believe it's just too wide to fit into that spot on the page at that window size.

A: The total width of .navbar-header and .navbar-nav is 794px and there is no space for them in the same row. You can change padding for .nav>.li>a  to 10px 13px


text:
Q: How to capture arguments passed to a Groovy script? I am just starting out with Groovy.   I couldn't find any examples anywhere of how to handle arguments to a Groovy script and so I hacked this method myself.   There must be a better way of doing this?  If so, I am looking for this better way, since I am probably overlooking the obvious.
import groovy.lang.Binding;
Binding binding = new Binding();
int x = 1
for (a in this.args) {
  println("arg$x: " + a)
  binding.setProperty("arg$x", a);
  x=x+1
}
println binding.getProperty("arg1")
println binding.getProperty("arg2")
println binding.getProperty("arg3")

A: try this:
args.each{println it}

A: If you want more advanced parsing than just getting the arguments you can use the Groovy CliBuilder to help you. It helps you with commandline flags, optional arguments and printing the usage instruction.
Checkout CliBuilder's Javadoc or MrHakis post about it.

A: The simplest is just to use this.args as an array e.g.:
test.groovy
println this.args[0]

Call:
C:>groovy test this

Output:
this

A: It is very much similar to Java and you can use the same java syntax. For eg.
class TestExecutor {

    public static void main(def args) {
        println("Printing arguments");
        for(String arguments : args) {
            println (arguments);
        }
    }

}

Run it and you should see the arguments printed
C:\Users\athakur\Desktop>groovy TestExecutor.groovy test1 test2 test3
Aug 16, 2014 11:47:56 AM org.codehaus.groovy.runtime.m12n.MetaInfExtensionModule
 newModule
WARNING: Module [groovy-nio] - Unable to load extension class [org.codehaus.groo
vy.runtime.NioGroovyMethods]
Printing arguments
test1
test2
test3

Also note if you do not provide main method or provide one like in above example then you can get arguments as args[i] but you can change the name of the array (again same as java). So you can  have something like -
public static void main(def argsNew) {
    println("Printing arguments");
    for(String arguments : argsNew) {
        //using args in above for loop will throw error
        println (arguments);
    }
}

Point being it's not something that is hard-coded. Finally as suggested in other answer you can always use CliBuilder for smart parsing. But again in that too it internally used def options = cli.parse(args).

A: Sorry about asking the question.  I just figured it out:
println args[0]
println args[1]
println args[2]

A: If you run your script with --compile-static or --type-checked option, the args variable won't be visible and therefore the compile throws an error:

[Static type checking] - The variable [args] is undeclared.

I like to do the following at the top of the script:
import groovy.transform.Field

@Field String[] args = binding.getVariable('args') as String[]

This will expose args as a global variable which can be used anywhere in the script.

References:
https://stackoverflow.com/a/53783178/2089675
https://groovy-lang.org/structure.html#_variables


text:
Q: Remove Duplicate URLs from Elements list in jSoup? When using jSoup to scrape a page, all of the links on the page can be gathered using;
Elements allLinksOnPage = doc.select("a");

Which is great. Now how would one go about removing duplicate URLs from this list? I.e. imagine a /contact-us.html that is linked in both the main navigation.
Once all the duplicate URLs have been removed, then the next step is to crawl those unique URLs and continue the loop.
A question on the practicalities of this though. For the code;
for (Element e : allLinksOnPage) {
    String absUrl = e.absUrl("href");

    //Asbolute URL Starts with HTTP or HTTPS to make sure it isn't a mailto: link
    if (absUrl.startsWith("http") || absUrl.startsWith("https")) {
        //Check that the URL starts with the original domain name
        if (absUrl.startsWith(getURL)) {
            //Remove Duplicate URLs
            //Not sure how to do this bit yet?
            //Add New URLs found on Page to 'allLinksOnPage' to allow this
            //For Loop to continue until the entire website has been scraped
        }
    }
}

So the question being, the final part of the loop, imagine when page-2.html is crawled, more URLs are identified on here and added to the allLinksOnPage variable.
Will the for loop continue for the length of the full list, i.e. 10 links found on page-1.html and 10 links on page-2.html, so 20 pages will be crawled in total - OR - Will the loop only continue for the length of the first 10 links identified, i.e. the links before the code 'for (Element e : allLinksOnPage)' is triggered?
This will all inevitably end up in a database once the logic is finalised, but looking to keep the logic purely Java based initially to prevent lots of reads/writes to the DB which will slow everything down.

A: allLinksOnPage is iterated only once. You never retrieve any information about pages you found links to.
You can use a Set and a List for this, however. Furthermore you can use the URL class to extract the protocol for you.
URL startUrl = ...;
Set<String> addedPages = new HashSet<>();
List<URL> urls = new ArrayList<>();
addedPages.add(startUrl.toExternalForm());
urls.add(startUrl);
while (!urls.isEmpty()) {
     // retrieve url not yet crawled
     URL url = urls.remove(urls.size()-1);

     Document doc = JSoup.parse(url, TIMEOUT);
     Elements allLinksOnPage = doc.select("a");
     for (Element e : allLinksOnPage) {
        // add hrefs
        URL absUrl = new URL(e.absUrl("href"));

        switch (absUrl.getProtocol()) {
            case "https":
            case "http":
                if (absUrl.toExternalForm().startsWith(getURL) && addedPages.add(absUrl.toExternalForm())) {
                    // add url, if not already added
                    urls.add(absUrl);
                }
        }
    }
}


text:
Q: What do the Pokéball upgrades do? At the top of each table in Pokémon Pinball: Ruby & Sapphire, there are three lights which can temporarily upgrade your Pokéball to a higher tier. (Poké Ball, Great Ball, Ultra Ball, and Master Ball)
In the main series higher tier Poké Balls make Pokémon easier to catch, but in Pokémon Pinball they always take 3 hits to catch regardless of the ball type.
What do the Pokeball upgrades do in Pokémon Pinball?

A: According to Bulbapedia, it multiplies the points you score:

Fittingly with the other Pokémon-inspired tweaks to the basic pinball formula, the ball is a Poké Ball. Each table has three lights near the top of the upper half that, when lit simultaneously, will upgrade the Poké Ball temporarily to the next better basic Poké Ball; the upgrades are the Great Ball, the Ultra Ball, and the Master Ball. Each upgrade multiplies the points gained on the table by a different multiplier: 2×, 3×, and 4×, respectively.


text:
Q: How to go to searched word in TextView - Android Can somebody help me? I have the following problem:
I have a TextView and I can search some words, so that they're marked.
The TextView is named textView and it shows the text, I have an EditText Etxt to get the searched word and a Button to start the search. The code above is the code of the search. The app marks all found words big and italic. And I have a TextView text_total which shows the number of found words.
The problem: But if there is a searched word in the text below the shown screen, you must scroll and find the marked word:
int total = 0;
String word_search = Etxt.getText().toString().trim().toLowerCase();
String fullTxt = textView.getText().toString();
String[] array = fullTxt.split("\n");
String word;
StringBuilder st = new StringBuilder();
for (int i = 0; i < array.length; i++) {
    word = array[i];
    if (word.toLowerCase().contains(word_search)) {
        String markiert = word.trim();
        st.append("" + markiert + "");
        total++;
    } else {
        st.append(word);
    }
    st.append("
");
}
textView.setText(Html.fromHtml("" + st));
text_total.setText("Ergebnisse: " + total);

Now, I have a problem because the text is too long to see all search results. I want that I have a 'back' and a 'next' button and the view goes to the next result if I click the next button and that the the found word goes automatically to the shown screen.
Does anyone know how to code this?
That's very important. Thanks for help!

A: The Next & Back function is important. Paste it. but you can save founded text array and then call i+1 for next and i-1 for back
int total = 0;
String word_search = Etxt.getText().toString().trim().toLowerCase();
String fullTxt = textView.getText().toString();
String[] array = fullTxt.split("\n");
String[] markiert = new String[array.length]
String word;
StringBuilder st = new StringBuilder();
for (int i = 0; i < array.length; i++) {
    word = array[i];
    if (word.toLowerCase().contains(word_search)) {
        markiert[i] = word.trim();//this is result in array do whatever you want with it
        st.append("" + markiert[i] + "");
        total++;
    } else {
        st.append(word);
    }
    st.append("
");
}
textView.setText(Html.fromHtml("" + st));
text_total.setText("Ergebnisse: " + total);

at First Show markiert[0] and for Next call markiert[0+1] then markiert[N+1]


text:
Q: unable to install postgresql on SLES 10 i am trying to install postgresql-server on a Suse 10 (SLES10 SP2) 64 bit machine with no luck.
I followed the link on the postgres website to the place where they maintain the build for SUSE:
http://software.opensuse.org/package/postgresql-server?search_term=postgresql-server
When i try to install the rpm package i downloaded it complains about missing dependant libs:
# rpm -Uvh postgresql-server-9.0.7-12.1.x86_64.rpm
warning: postgresql-server-9.0.7-12.1.x86_64.rpm: Header V3 RSA/SHA256 signature: NOKEY, key ID 3dbdc284
error: Failed dependencies:
    postgresql = 9.0 is needed by postgresql-server-9.0.7-12.1.x86_64
    libc.so.6(GLIBC_2.11)(64bit) is needed by postgresql-server-9.0.7-12.1.x86_64
    libcrypto.so.1.0.0()(64bit) is needed by postgresql-server-9.0.7-12.1.x86_64
    libldap-2.4.so.2()(64bit) is needed by postgresql-server-9.0.7-12.1.x86_64
    libpq.so.5()(64bit) is needed by postgresql-server-9.0.7-12.1.x86_64
    libssl.so.1.0.0()(64bit) is needed by postgresql-server-9.0.7-12.1.x86_64
    rpmlib(PayloadIsLzma) <= 4.4.6-1 is needed by postgresql-server-9.0.7-12.1.x86_64

Now when i try to install on of the dependant libs: libc.so.6 by trying to install glibc-32bit-2.15-21.1.x86_64.rpm, it complains about a missing lib  rpmlib(PayloadIsLzma) which i can't find on the internet.
The 32 bit version gives the same problem.
Alternately when i try installing using zypper, it complains about a transaction in progress:
zypper in postgresql-server-9.0.7-12.1.x86_64.rpm
A ZYpp transaction is already in progress.

Also tried:  yast2 --install postgresql-server
but it says:
Following packages haven't been found on the medium: postgresql-server

Can anyone please help me out? I feel I am hitting dead ends each way I go.

A: I'd go with zypper since it should take care of installing the dependencies as needed.  Per your statement:

Alternately when i try installing using zypper, it complains about a
  transaction in progress:
zypper in postgresql-server-9.0.7-12.1.x86_64.rpm A ZYpp transaction
  is already in progress.

Try killing any zypper process(es) you see.  List zypper processes with
ps aux | grep -i zypp

Then kill each one with
kill -9 pid

where pid is the process ID.  Then try your zypper install again.  The following simpler command should work:
zypper install postgresql-server

A: The following link can be followed. It worked for me.
https://www.osradar.com/postgresql-opensuse-15/


text:
Q: What comparator does Vuetify use to sort data table String columns If I take the standard Vuetify example and change Calories to contain Strings, and now the data are not all numeric:
https://codepen.io/hobbeschild/pen/WNQWmrJ
then what comparator is Vuetify using internally to order these Strings?
Say I have another page with a v-select on it, and I want to give the user all the Calorie options that were on the other page in the table, and I want to show in the same order that they were in the table when Calories were sorted in ascending order.  How could I replicate that?
I think I need to do something like this before populating the v-select (this doesn't sort them quite right but I think it will be something similar):
calories.sort((a, b) => a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' }))

I am imagining that internally the v-data-table code does a localeCompare or something similar and I just need the arguments it uses.

A: I think it might be this
https://github.com/vuetifyjs/vuetify/blob/268434aa851dded8b67c0e67bfa39b3cbe791584/packages/vuetify/src/util/helpers.ts#L285
Though I am not sure how to reference the sortItems method directly.  When I add
import { sortItems } from "vuetify/src/util/helpers";

I get an error "Can't resolve 'vuetify/src/util/helpers'".

A: @hobbes_child  comment
I change to import from lib is resolved
import { sortItems } from "vuetify/lib/util/helpers";


text:
Q: XPath select the next tab/col I'm trying to scrap certain elements like "East to West" from "Label:" in html.

Label:

      East to West

Subtitles:

      ----

Here's what I tested in shell:

response.xpath('//dl[dt =
  "Label:"]/following-sibling::text()').extract_first()

it only returns
'\r\n\t'

I've explored a little deeper into the code, but it seems "East to West" is neither "sibling/child/descendant", it doesn't even show up in "following".
What should I use to pick out the right text?
More detailed html code:
http://www.xpathtester.com/xpath/0a8c8acce7197b50c03b8f2c3bc3939d

A: This XPath,
normalize-space((//dt[.="Label:"])[1]/following-sibling::dd[1])

will select the space-normalized string value of first immediately following dd element of the first dt element whose string value is "Label:",
East to West

as requested.


text:
Q: Calculate Moving Average in Excel I want to calculate a moving average of the last, say 20, numbers of a column. A problem is that some of the cells of the column may be empty, they should be ignored. Example:
 A
175
154

188
145
155

167
201

A moving average of the last three would be (155+167+201)/3. I've tried to implement this using average, offset, index, but I simply don't know how. I'm a little bit familiar with macros, so such a solution would work fine: =MovingAverage(A1;3)
Thanks for any tips or solutions!

A: {=SUM(($A$1:A9)*(ROW($A$1:A9)>LARGE((ROW($A$1:A9))*(NOT(ISBLANK($A$1:A9))),3+1)))/3}

Enter this with control+shift+enter to make it an array formula.  This will find the latest three values.  If you want more or less, change the two instances of '3' in the formula to whatever you want.
LARGE((ROW($A$1:A9))*(NOT(ISBLANK($A$1:A9))),3+1)

This part returns the 4th highest row number of all the cells that have a value, or 5 in your example because rows 6, 8, and 9 are the 1st through 3rd highest rows with a value.
(ROW($A$1:A9)>LARGE((ROW($A$1:A9))*(NOT(ISBLANK($A$1:A9))),3+1))

This part returns 9 TRUEs or FALSEs based on whether the row number is larger than the 4th largest.
($A$1:A9)*(ROW($A$1:A9)>LARGE((ROW($A$1:A9))*(NOT(ISBLANK($A$1:A9))),3+1))

This multiplies the values in A1:A9 by those 9 TRUEs or FALSEs.  TRUEs are converted to 1 and FALSEs to zero.  This leaves a SUM function like this
=SUM({0;0;0;0;0;155;0;167;201})/3

Because all the values above 155 don't satisfy the row number criterion, the get multiplied by zero.

A: If you are going to use a UDF it will only recalculate correctly when you change the data if the parameters include all the range of data you want to handle.
Here is a moving average UDF that handles entire columns and contains some error handling. You can call it using by entering the formula =MovingAverage(A:A,3) into a cell.
Function MovingAverage(theRange As Range, LastN As Long) As Variant
    Dim vArr As Variant

    Dim j As Long
    Dim nFound As Long
    Dim dSum As Double

    On Error GoTo Fail
    MovingAverage = CVErr(xlErrNA)
    '
    ' handle entire column reference
    '
    vArr = Intersect(Application.Caller.Parent.UsedRange, theRange).Value2

    If IsArray(vArr) And LastN > 0 Then
        For j = UBound(vArr) To 1 Step -1
            ' skip empty/uncalculated
            If Not IsEmpty(vArr(j, 1)) Then
                ' look for valid numbers
                If IsNumeric(vArr(j, 1)) Then
                    If Len(Trim(CStr(vArr(j, 1)))) > 0 Then
                        nFound = nFound + 1
                        If nFound <= LastN Then
                            dSum = dSum + CDbl(vArr(j, 1))
                        Else
                            Exit For
                        End If
                    End If
                End If
            End If
        Next j

        If nFound >= LastN Then MovingAverage = dSum / LastN

    End If
    Exit Function
Fail:
    MovingAverage = CVErr(xlErrNA)
End Function

A: Just a quick solution:
Supposing your numbers are on the cells A2:A10, put in B10 the following formula:
=IF(COUNT(A8:A10)=3,AVERAGE(A8:A10),IF(COUNT(A7:A10)=3,AVERAGE(A7:A10),"too many blanks"))

Dragging up the formula you get the moving average
If there is the possibility of two consecutive blank you could nest another if, more than that and this solution became too complicated

A: I have written a short script in VBA. Hopefull it does what you want. Here you are:
Function MovingAverage(ByVal r As String, ByVal i As Integer) As Double
Dim rng As Range, counter As Long, j As Integer, tmp As Double
    Set rng = Range(r)
    counter = 360
    j = 0
    tmp = 0
    While j < i + 1 And counter > 0
        If Len(rng.Offset(j, 0)) > 0 Then
            tmp = tmp + rng.Offset(j, 0).Value
        End If
        j = j + 1
        counter = counter - 1
    Wend
    MovingAverage = CDbl(tmp / i)
End Function

1) I have set limit to 360 cells. It means that the script will not look for more than 360 cells. If you want to change it then change the initial value of counter.
2) The script returns not rounded average. Change the last row to
     MovingAverage = Round(CDbl(tmp / i),2)
3) The use is just like you wanted, so just type =MovingAverage("a1";3) into the cell.
Any comments are welcome.


text:
Q: Ansible: read csv file line by line and render it to template with loop I am using a csv file to get data and render it to template and copy to remote servers. I am facing issue that CSV file read twice for same server and this results in loop to copy last line in each server instead of 1st line in first server and second on second servers and so on...
test.csv file:
Application,env,Datacenter,Hostname
Microsoft,Test,DC1,testserver1
Apple,Test,DC2,testserver2

main.yml:
- name: read csv
  read_csv:
    path: /u00/app/monitor/test.csv
    key: Hostname
  register: newrelic

- name: Print newrelic var
  ansible.builtin.debug:
    var: newrelic.dict[inventory_hostname]

- name: copy template
  template:
    src: /u00/ansible/Playbooks/files/infra-config.yml_template
    dest: /u00/app/monitor/infra-config.yml
  loop: "{{ newrelic.list }}"

- name: Start the New Relic Service
  ansible.builtin.systemd:
    name: newrelic-infra.service
    state: started
  become: yes
  become_user: root

Template:
custom_attributes:
    application : {{ item.Application }}
    env : {{ item.env }}
    datacenter : {{ item.Datacenter }}
log:
 file: /u00/app/monitor/infra.log

Expected result is to get first entry in csv in testserver1 and second line in testserver2
**ssh admin@testserver1 - **

cat infra-config.yml

custom_attributes:
    application : Microsoft
    env : Test
    datacenter : DC1
log:
 file: /u00/app/monitor/infra.log

**ssh admin@testserver2- **

custom_attributes:
    application : Apple
    env : Test
    datacenter : DC2
log:
 file: /u00/app/monitor/infra.log

but I am getting
**ssh admin@testserver1 -**

cat infra-config.yml

custom_attributes:
    application : Apple
    env : Test
    datacenter : DC2
log:
 file: /u00/app/monitor/infra.log
**
ssh admin@testserver2- **

custom_attributes:
    application : Apple
    env : Test
    datacenter : DC2
log:
 file: /u00/app/monitor/infra.log

A: Given the CSV file on the controller
shell> cat /tmp/test.csv
Application,env,Datacenter,Hostname
Microsoft,Test,DC1,testserver1
Apple,Test,DC2,testserver2

The project below
shell> tree .
.
├── ansible.cfg
├── hosts
├── infra-config.yml.j2
└── pb.yml

0 directories, 4 files

shell> cat ansible.cfg
[defaults]
gathering = explicit
collections_path = $HOME/.local/lib/python3.9/site-packages/
inventory = $PWD/hosts
roles_path = $PWD/roles
remote_tmp = ~/.ansible/tmp
retry_files_enabled = false
stdout_callback = yaml

shell> cat hosts
[test]
testserver1 ansible_host=10.1.0.61
testserver2 ansible_host=10.1.0.63

[test:vars]
ansible_connection=ssh
ansible_user=admin
ansible_become=yes
ansible_become_user=root
ansible_become_method=sudo
ansible_python_interpreter=/usr/local/bin/python3.8
ansible_perl_interpreter=/usr/local/bin/perl

The playbook
shell> cat pb.yml
- hosts: all

  tasks:

    - block:
        - read_csv:
            path: /tmp/test.csv
            key: Hostname
          register: newrelic
        - debug:
            var: newrelic
      delegate_to: localhost
      run_once: true

    - template:
        src: infra-config.yml.j2
        dest: /tmp/infra-config.yml
      vars:
        _data: "{{ newrelic.dict[inventory_hostname] }}"

shell> cat infra-config.yml.j2
custom_attributes:
  application : {{ _data.Application }}
  env : {{ _data.env }}
  datacenter : {{ _data.Datacenter }}
log:
  file: /u00/app/monitor/infra.log

creates the configuration files at the remote hosts

shell> ansible-playbook pb.yml

PLAY [all] ***********************************************************************************

TASK [read_csv] ******************************************************************************
ok: [testserver1 -> localhost]

TASK [debug] *********************************************************************************
ok: [testserver1 -> localhost] =>
  newrelic:
    changed: false
    dict:
      testserver1:
        Application: Microsoft
        Datacenter: DC1
        Hostname: testserver1
        env: Test
      testserver2:
        Application: Apple
        Datacenter: DC2
        Hostname: testserver2
        env: Test
    failed: false
    list: []

TASK [template] ******************************************************************************
changed: [testserver1]
changed: [testserver2]

PLAY RECAP ***********************************************************************************
testserver1: ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
testserver2: ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

shell> ssh admin@10.1.0.61 cat /tmp/infra-config.yml
custom_attributes:
  application : Microsoft
  env : Test
  datacenter : DC1
log:
  file: /u00/app/monitor/infra.log

shell> ssh admin@10.1.0.63 cat /tmp/infra-config.yml
custom_attributes:
  application : Apple
  env : Test
  datacenter : DC2
log:
  file: /u00/app/monitor/infra.log


text:
Q: How to Zip files using JavaScript? Is there a way to zip files using JavaScript?? For an example, like in Yahoo mail, when you chose to download all the attachments from an email, it gets zipped and downloaded in a single zip file. Is JavaScript capable of doing that? If so, please provide a coding example.
I found this library called jszip to do the task but it has known and unresolved issues.
How do I solve the problem?

A: JSZip has been updated over the years. Now you can find it on its GitHub repo
It can be used together with FileSaver.js
You can install them using npm:
npm install jszip --save
npm install file-saver --save

And then import and use them:
import JSZip from 'jszip';
import FileSaver from 'file-saver';

const zip = new JSZip();
zip.file('idlist.txt', 'PMID:29651880\r\nPMID:29303721');
zip.generateAsync({ type: 'blob' }).then(function (content) {
    FileSaver.saveAs(content, 'download.zip');
});

Then you will download a zip file called download.zip, once you've extracted it, and you can find inside a file called idlist.txt, which has got two lines:
PMID:29651880
PMID:29303721

And for your reference, I tested with the following browsers, and all passed:

*

*Firefox 59.0.2 (Windows 10)

*Chrome 65.0.3325.181 (Windows 10)

*Microsoft Edge 41.16299.371.0 (Windows 10)

*Internet Explorer 11.0.60 (Windows 10)

*Opera 52 (Mac OSX 10.13)

*Safari 11 (Mac OSX 10.13)

A: I developed a new solution to generate zip files using JavaScript. The solution is in the public domain.
The Zip class.
Zip {

    constructor(name) {
        this.name = name;
        this.zip = new Array();
        this.file = new Array();
    }

    dec2bin=(dec,size)=>dec.toString(2).padStart(size,'0');
    str2dec=str=>Array.from(new TextEncoder().encode(str));
    str2hex=str=>[...new TextEncoder().encode(str)].map(x=>x.toString(16).padStart(2,'0'));
    hex2buf=hex=>new Uint8Array(hex.split(' ').map(x=>parseInt(x,16)));
    bin2hex=bin=>(parseInt(bin.slice(8),2).toString(16).padStart(2,'0')+' '+parseInt(bin.slice(0,8),2).toString(16).padStart(2,'0'));

    reverse=hex=>{
        let hexArray=new Array();
        for(let i=0;i<hex.length;i=i+2)hexArray[i]=hex[i]+''+hex[i+1];
        return hexArray.filter((a)=>a).reverse().join(' ');
    }

    crc32=r=>{
        for(var a,o=[],c=0;c<256;c++){
            a=c;
            for(var f=0;f<8;f++)a=1&a?3988292384^a>>>1:a>>>1;
            o[c]=a;
        }
        for(var n=-1,t=0;t<r.length;t++)n=n>>>8^o[255&(n^r[t])];
        return this.reverse(((-1^n)>>>0).toString(16).padStart(8,'0'));
    }

    fecth2zip(filesArray,folder=''){
        filesArray.forEach(fileUrl=>{
            let resp;
            fetch(fileUrl).then(response=>{
                resp=response;
                return response.arrayBuffer();
            }).then(blob=>{
                new Response(blob).arrayBuffer().then(buffer=>{
                    console.log(`File: ${fileUrl} load`);
                    let uint=[...new Uint8Array(buffer)];
                    uint.modTime=resp.headers.get('Last-Modified');
                    uint.fileUrl=`${this.name}/${folder}${fileUrl}`;
                    this.zip[fileUrl]=uint;
                });
            });
        });
    }

    str2zip(name,str,folder){
        let uint=[...new Uint8Array(this.str2dec(str))];
        uint.name=name;
        uint.modTime=new Date();
        uint.fileUrl=`${this.name}/${folder}${name}`;
        this.zip[uint.fileUrl]=uint;
    }

    files2zip(files,folder){
        for(let i=0;i<files.length;i++){
            files[i].arrayBuffer().then(data=>{
                let uint=[...new Uint8Array(data)];
                uint.name=files[i].name;
                uint.modTime=files[i].lastModifiedDate;
                uint.fileUrl=`${this.name}/${folder}${files[i].name}`;
                this.zip[uint.fileUrl]=uint;
            });
        }
    }

    makeZip(){
        let count=0;
        let fileHeader='';
        let centralDirectoryFileHeader='';
        let directoryInit=0;
        let offSetLocalHeader='00 00 00 00';
        let zip=this.zip;
        for(const name in zip){
            let modTime=()=>{
                lastMod=new Date(zip[name].modTime);
                hour=this.dec2bin(lastMod.getHours(),5);
                minutes=this.dec2bin(lastMod.getMinutes(),6);
                seconds=this.dec2bin(Math.round(lastMod.getSeconds()/2),5);
                year=this.dec2bin(lastMod.getFullYear()-1980,7);
                month=this.dec2bin(lastMod.getMonth()+1,4);
                day=this.dec2bin(lastMod.getDate(),5);
                return this.bin2hex(`${hour}${minutes}${seconds}`)+' '+this.bin2hex(`${year}${month}${day}`);
            }
            let crc=this.crc32(zip[name]);
            let size=this.reverse(parseInt(zip[name].length).toString(16).padStart(8,'0'));
            let nameFile=this.str2hex(zip[name].fileUrl).join(' ');
            let nameSize=this.reverse(zip[name].fileUrl.length.toString(16).padStart(4,'0'));
            let fileHeader=`50 4B 03 04 14 00 00 00 00 00 ${modTime} ${crc} ${size} ${size} ${nameSize} 00 00 ${nameFile}`;
            let fileHeaderBuffer=this.hex2buf(fileHeader);
            directoryInit=directoryInit+fileHeaderBuffer.length+zip[name].length;
            centralDirectoryFileHeader=`${centralDirectoryFileHeader}50 4B 01 02 14 00 14 00 00 00 00 00 ${modTime} ${crc} ${size} ${size} ${nameSize} 00 00 00 00 00 00 01 00 20 00 00 00 ${offSetLocalHeader} ${nameFile} `;
            offSetLocalHeader=this.reverse(directoryInit.toString(16).padStart(8,'0'));
            this.file.push(fileHeaderBuffer,new Uint8Array(zip[name]));
            count++;
        }
        centralDirectoryFileHeader=centralDirectoryFileHeader.trim();
        let entries=this.reverse(count.toString(16).padStart(4,'0'));
        let dirSize=this.reverse(centralDirectoryFileHeader.split(' ').length.toString(16).padStart(8,'0'));
        let dirInit=this.reverse(directoryInit.toString(16).padStart(8,'0'));
        let centralDirectory=`50 4b 05 06 00 00 00 00 ${entries} ${entries} ${dirSize} ${dirInit} 00 00`;
        this.file.push(this.hex2buf(centralDirectoryFileHeader),this.hex2buf(centralDirectory));
        let a = document.createElement('a');
        a.href = URL.createObjectURL(new Blob([...this.file],{type:'application/octet-stream'}));
        a.download = `${this.name}.zip`;
        a.click();
    }
}

Then, create a new object Zip.
  z=new Zip('myZipFileName');

You you can:

*

*Load files of your directory to zip object with fecth2zip(filesArray,folder).

  filesArray=[
    'file01.ext',
    'file02.ext',
    'file...'
  ];
  z.fecth2zip(filesArray,'public/');

*

*Create a new file from a string  with str2zip(nameFile,content,directory).

  z.str2zip('test.txt','content','public/teste/');

*

*Or upload to zip.
Put onchange event into the input file and send the files to function files2zip(this.files).
  <input type="file" onchange="z.files2zip(this.files)" value='files' multiple>

After placing all the objects inside your Zip object file, just download it.
  <input type="button" onclick="z.makeZip()" value='Zip'>

The class can also be found here: https://github.com/pwasystem/zip/

A: I'd recommend going straight to using Node's built-in library Zlib for this, which includes images; encode in base 64 using "buffers". Rather than using npm packages. Reasons being:

*

*Zlib is a Node native library - has been kept up-to-date for nearly 10 years now - so the proofs there for long-term supports

*Node allows you work with Buffers - i.e. you can convert your text string/images to the raw binary data and compress it that way with Zlib

*Easily compress and decompress large files - leverage node streams to compress files in MBs or GBs

The fact you are using jszip, would allow me to guess that you are using npm as well as node; assumes you have set up your environment correctly, i.e. node installed globally.

Example: input.txt compressed to become input.txt.gz

const zlib = require('zlib');
const fs = require('fs');
const gzip = zlib.createGzip();
const input = fs.createReadStream('input.txt');
const output = fs.createWriteStream('input.txt.gz');

input.pipe(gzip).pipe(output);

Step 1: So you require each of the native modules from node - require is part of ES5. Zlib as previously mentioned, and fs module, the File System module.
const zlib = require('zlib');
const fs = require('fs');

Step 2: The fs module, this allows you to create a readstream, are specifically called to read chunks of data. This will return a readstream object; readable stream
const input = fs.createReadStream(FILE PATH HERE);

__Note: This readstream object then gets piped again; this chaining of pipes on readsteam objects can occur endlessly, making pipes very flexible.

ReadStream.pipe(DoesSomething).pipe(SomethingElse).pipe(ConvertToWriteStream)

Step 3: The readstream object, that has been piped and compressed is then converted to writestream object.
const output = fs.createWriteStream('input.txt.gz');

input.pipe(gzip).pipe(output); // returned filename input.txt.gz, within local directory

So this library allows you easily enter a file path and decide where you want your compressed file to be. You can also choose to do the reverse, if need be.

A: If you don't care about IE, client-zip is much faster and smaller than JSZip and is meant to solve exactly this problem (yes, this is a shameless but completely relevant plug for my library ).
You would do something like this (where files could be an array of fetch Responses for example, though there are many supported inputs):
import { downloadZip } from "client-zip/index.js"
import FileSaver from "file-saver"

const content = await downloadZip(files).blob()
FileSaver.saveAs(content, "download.zip");

Essentially the same usage as in Yuci's answer but updated for 2020.

A: By using JSZIP we can generate and download zip file in JavaScript. For that you have to follow the steps below

*

*Download jszip zip file from http://github.com/Stuk/jszip/zipball/master

*Extract the zip and find jszip.js file inside dist folder

*Import jszip.js file in your html file like below
<script type="text/javascript" src="jszip.js"></script>

*Add below function in your code and call it
onClickDownload: function () {
    var zip = new JSZip();
    for (var i = 0; i < 5; i++) {
        var txt = 'hello';
        zip.file("file" + i + ".txt", txt);
    }
    zip.generateAsync({
        type: "base64"
    }).then(function(content) {
        window.location.href = "data:application/zip;base64," + content;
    });
}

*You can download sample code from my git repository here (GIT link)

A: With the new HTML5 file APIs and the typed arrays, you can pretty much do anything you want in JavaScript. However, the browser support isn't going to be great. I'm guessing that's what you meant by "unresolved issues". I would recommend, for the time being, to do it on the server. For example, in PHP, you could use this extension.

A: This is an older question but I ran across it searching for a solution to creating a zip archive.
For my use case, I'm creating several thousand zip archives in node.js from a very large logger source every minute consisting of up to 200 files in each archive.
I had tried JSZip with very poor results due to performance issues and a memory leak not worth the time to track down. Since my use case is fairly extreme, it's quite the stress test.
I came across another pure javascript zip library worth mentioning here for others to check out.
I ended up using fflate.
https://github.com/101arrowz/fflate
This library has been extremely performant. I'm only using the zip archive feature with level 9 compression, but fflate is a full featured library which works server side and complete browser support (2011+).  I'm not including any examples here as fflate documentation is very complete. I'd highly recommend it as an alternative.


text:
Q: Issue with Dynamic Sender Profile I'm trying to create a dynamic sender profile in Salesforce Marketing Cloud. I have a fields first_Name in data extension which I want to use as from name.
How can I do this?
I created a dynamic sender profile and used %%first_Name%% as from Name and %%ReplyEmailAddress%% as the from email.
what should I do to populate the Sender profile dynamically from the first_Name field?


text:
Q: Get the word right before the coma with javascript and regex? Hi im trying to get the word right before the coma in a sentence.
For example if the string is:
"Cloudy, and 51 ° F "

I want the output CLOUDY.
How is this done in regex and javascript? I know you have to use the .match command in javascript. Thanks, any help is appricated.

A: I wanted to add an alternative to the split solution in the comments.
Here's the simplest regex you can use:
\S+(?=,)

Demo. In regex syntax, it literally means sequence of non-whitespace characters followed by a comma.
Here's how to use this from JS:
var str = "Mostly cloudy, and 51 ° F";
var matches = str.match(/\S+(?=,)/g); // matches = ["cloudy"]

matches will contain an array with all the words followed by a comma in str. If you only need the first match, remove the g.


text:
Q: ArgumentException when using USB to connect to Android phone with C# I want to have an Android app communicate with a UWP C# program via USB. I have my phone showing up in Device Manager as an ADB interface with the winusb.sys driver. To communicate with it, I want to put the phone into Accessory mode, for which I need to send a USB control packet (https://source.android.com/docs/core/interaction/accessories/aoa?hl=en#attempt-to-start-in-accessory-mode). But whenever I try to send it, I get an ArgumentException.
I wrote the following code in C#:
//vendor id and product id of phone
uint vid = 0x1004;
uint pid = 0x633E;
string aqs = UsbDevice.GetDeviceSelector(vid, pid);

DeviceInformationCollection devices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(aqs);

UsbDevice usbDevice = await UsbDevice.FromIdAsync(devices[0].Id); // get UsbDevice

if (usbDevice != null)
{

    byte[] bytes = new byte[2];
    IBuffer buf = bytes.AsBuffer();

    UsbSetupPacket initSetupPacket = new UsbSetupPacket()
    {
        RequestType = new UsbControlRequestType()
        {
            Direction = UsbTransferDirection.In,
            Recipient = UsbControlRecipient.Device,
            ControlTransferType = UsbControlTransferType.Vendor,
        },
        Request = 51,
        Value = 0,
        Index = 0,
        Length = 2
    };

    IBuffer result = await usbDevice.SendControlInTransferAsync(initSetupPacket, buf);
}

My problem is that an ArgumentException ('Value does not fall within the expected range.') is thrown when calling usbDevice.SendControlInTransferAsync and I don't know why.


text:
Q: systemVerilog - define a function which return vector/array with unknown size? Can I define a function which return vector/array with unknown size?
Return values can be:
bit [15:0] , bit [10:0], bit [2:0]....
I want be able to define something like:
   function bit [] foo (int size, int mem, string mem_name);
   endfunction: foo

A: You can use a dynamic array/queue if you define a type for that. Other than that you can use ref and pass the array as a parameter.


text:
Q: How to update selected records in one transaction with Entity Framework? I am using SQL Server. My case looks like this:

*

*I have a table Messages. The table has a column MessageStatusId

*I have a couple of services which have access this database

*Periodically each service selects messages with status New and handles these messages somehow

*The services select messages like:
await DbContext.Set<Message>()
               .Where(m => m.MessageStatusId == MessageStatusEnum.New)
              .ToListAsync();

*After processing, the service updates message status

I don't want the services to select the same set of records. So I need to update message status to InProcess. How to implement this in one transaction with Entity Framework?

A: You can implement pessimistic locking to ensure only one worker is accessing the table at a time, however it is very important to keep the table access as short as absolutely possible to avoid deadlocks between clients. I would suggest fetching a limited number of rows per request:
var options = new TransactionOptions
{
   IsolationLevel = System.Transactions.IsolationLevel.Serializable,
   Timeout = new TimeSpan(0, 0, 0, 10)
};

var messageIds = new List<int>();

using(var scope = new TransactionScope(TransactionScopeOption.RequiresNew, options))
{
    using (var context = new MessageDbContext())
    {
        var messages = context.Messages
            .Where(x => x.MessageStatusId == MessageStatusEnum.New)
            .OrderBy(x => x.MessageDate)
            .Take(100)
            .ToList();

       foreach(var message in messages)
           message.MessageStatusId = MessageStatusEnum.InProgress;

       context.SaveChanges();
       messageIds = messages.Select(x => x.MessageId).ToList();
    }
    scope.Commit();
}

My recommendations here would be:

*

*Separate this Message entity off into a bounded DbContext that serves just message checking/status updating, nothing else. This message entity could just be MessageId and MessageStatusId for this operation and others to check on a message status /w pessimistic locking.

*Use a synchronous call, faster than async.

*Fetch the rows, mark them off as in-progress and grab their IDs then commit the status change. You can read them with optimistic locking afterwards to process at your leisure and avoid deadlocking.

*Limit the # of rows queried to avoid surprises if there happen to be a significant backlog. (10, 100, whatever is reasonable)


text:
Q: Sum each element across a structure containing oddly sized arrays [MATLAB] I've spent some time researching this, but am likely missing something simple. I have intermediate Matlab knowledge.
I have a structure of data saved from an experiment;
1x30 struct array with fields:
pixelStats: [118.6892 3.1370e+003 -0.1418 2.1195 -25.9308 259.3778]
  pixelLPStats: [5x2 double]
  autoCorrReal: [9x9x5 double]
   autoCorrMag: [4-D double]
      magMeans: [18x1 double]
 cousinMagCorr: [4x4x5 double]
 parentMagCorr: [4x4x4 double]
cousinRealCorr: [8x8x5 double]
parentRealCorr: [8x8x4 double]
   varianceHPR: 21.5116

Where each sub-field ('arrays'? terminology is likely incorrect I'm sorry) is a different size. There are 30 entries (trials) that I need to average across so that the shape of the above is retained, but the values for each cell within each field are averaged across the 30 trials. I also need the variance (I am trying to calculate Z scores to see if other trials are significantly different from this population).
First I tried to do this in a for loop, where I get the fieldnames, then for each field I break in and try to add the values for each element across the 30 trials, though this strategy doesn't work for fields with differently sized dimensions (e.g. I'd need to variably create differently sized for loops according to dimensions of current field).
Then I tried to convert the data structure to a cell array, which works;
cell_in = struct2cell(s_params_in)

cell_in = 10x1x30  607440  cell

...and then I tried something I found in my searching that uses cellfun, though to be honest I am not entirely sure of how it works. I had to add the UniformOutput to deal with unequal sized fields.
cellfun( @(cell_in) sum(cell_in(:)), cell_in,'UniformOutput',false)

This summed all values within each 'field' (first dimension), collapsing across elements within them, for all 30 trials. e.g.
ans(:,:,30) =

[3.4911e+003]
[    10.9414]
[2.0854e+009]
[2.6877e+007]
[1.3612e+004]
[2.3328e+006]
[8.4917e+004]
[7.3826e+008]
[8.2038e+003]
[    22.4030]

I tried playing around with how I called the cell_in(:) part, but could not get the result I was looking for i.e. an array summed across the dimension for trials, whilst retaining the other dimensionality.
I have also tried to convert that to a matrix and then I could use something like
sum([data(:)])

And play around with reshaping to get the original size back, though that also seems difficult and I'd probably have to do it per fields and manually input the dimensions. The cell2mat doesn't work anyhow on account of the inconsistent dimensions.
So now I'm at the limit of my knowledge and am reaching out for help, can anyone  solve this?
Cheers,
Alex

A: A working code.
clear;clc

% create an example struct array
field1 = 'f1';  value1 = rand(1,10);
field2 = 'f2';  value2 = {rand(3,4,2), rand(3,4,2)};
field3 = 'f3';  value3 = {pi, pi.^2};
field4 = 'f4';  value4 = {magic(3), magic(3).^2};
S = struct(field1,value1,field2,value2,field3,value3,field4,value4);
clearvars field* value*

N = length(S);
T = struct();
U = T;

% enumerate over all fields (all should be numbers)
FN = fieldnames(S);
for ii=1:length(FN)
    fn = FN{ii};
    ss = {S.(fn)};
%     convert cell array of N-dim matrices into one (N+1)-dim matrix
    ssdim = ndims(ss{1});
    TT = cell2mat( reshape(ss, [ones(1,ssdim),N]) );
%     here you can do what you want
    T.(fn) = mean(TT,ndims(TT));
    U.(fn) = var(TT,0,ndims(TT));
end
clearvars ii ssdim ss fn TT

for ii=1:length(FN)
    disp(FN{ii})
    disp(T.(FN{ii}))
    disp(U.(FN{ii}))
end
clearvars ii N

The basic steps are addressed in code comments. TT is 30 trials of one particular type of experimental data. Say you are in the iteration for field pixelLPStats. Each trial has a matrix assigned by this name, which is a 5x2 double array. So, TT will be a 5x2x30 array. You can do what you want with it. Then let the loop bring you to the next field.

I think this time I got the right answer?
>> ( S(1).f2 + S(2).f2 )/2 == T.f2

ans(:,:,1) =

     1     1     1     1
     1     1     1     1
     1     1     1     1

ans(:,:,2) =

     1     1     1     1
     1     1     1     1
     1     1     1     1

>>

One more way to convert a cell array of N-dimension matrices into one (N+1)-dimension matrix - How to average over a cell-array of arrays?

A: @Yvon
Thanks for your reply, the code looks great and i have taken the time to go through it. I will be keeping this one on file as it has a few shortcuts I wasn't aware of. unfortunatelyit doesn't seem to have solved my problem, likely due to my inexperience and inability to manipulate your generous contribution to make it work for me. Grovelling aside, my results are as below
pixelStats: [1x6x30 double]
  pixelLPStats: [1x2x30 double]
  autoCorrReal: [1x9x150 double]
   autoCorrMag: [4-D double]
      magMeans: [1x1x30 double]
 cousinMagCorr: [1x4x150 double]
 parentMagCorr: [1x4x120 double]
cousinRealCorr: [1x8x150 double]
parentRealCorr: [1x8x120 double]
   varianceHPR: [1x1x30 double]

To begin with, the mean/variance parts don't seem to work when I run through the code step by step, it just populates that field with an mxmx30 array instead of an mxnx1 array of each element's mean. Also concerning is the dimensions of the above output. Notice that the dimension representing the 30 trials has been added within each field, and some it seems to have multiplied 30 by the last dimension. For example, comapre these fields, the top one is the original, the bottom is from your output:
cousinMagCorr: [4x4x5 double]

vs.
cousinMagCorr: [1x4x150 double]

notice the final dimension is multiplied by 30? I ran into this problem trying to loop through the fields and convert the cells to matrices; they worked for 2d, but not higher configurations, which came out like your output where the last dimension is multiplied by n trials.
it is likely I wasn't clear; I hope to get something like the very first entry in the structure, where all values within each field correspond to the mean for that values across al 30 trials. I am interested in each individual value, rather than collapsing across dimensions within a field.
Thanks again,
Alex