text:
Q: in python, write a function called wordendwithS() , to count the number of words ending with 's' from the TEXT FILE "file.txt" I have already tried
def wordendwithS():

    f=open("file.txt",'r')

    a=f.readlines()
    c=0
    for i in a:

        if i.endswith('s'):
            c=c+1

I dont know what to do please help
What is wrong in this?

A: You have a few problems with your code. The first is that you're not returning the count c which means that your function is doing nothing. Additionally, you are checking if a line ends with 's' instead of if a word ends with 's'. Third, you are not closing your file. You can do this to fix all three of these problems
def wordendwithS():
    c = 0
    with open('file.txt', 'r') as f:
        for l in f:
            for i in l.split():
                if i.endswith('s'):
                    c += 1
    return c

with is a content manager which autocloses the file after you're done using it.


text:
Q: Implementing your own MVVM vs. using an MVVM framework? I have just started learning .net, wpf, wcf, and mvvm, and my question is:
Is it better to implement own MVVM or use an MVVM framework like MVVM Light toolkit, Prism(it is too advanced and has unity framework(not sure how it helps in development))?

A: If you really want to understand the inner workings of MVVM, then try implementing your own.
If you already understand the concepts and don't feel the need to re-invent the wheel, use a Framework. Prism is a solid choice...go for it.

A: I wouldn't reinvent the wheel, evaluate the frameworks and only if those don't satisfy your requirements should you consider writing your own framework.

A: I'd suggest to look at this talk: Build Your Own MVVM Framework
(if you still haven't)
I decided to read some resources of various frameworks first, then I've downloaded some sample project based on Caliburn Micro to understand how the things worked
Caliburn is a great framework and provide with all you need to get started and take a deep ride into MVVM
I'd suggest you to start using it, and maybe, when you feel comfortable enough, you could try to customize it or simplify it to suits your needs/style, then, if you'll have time, you will build your own one =)
EDIT
MediaOwl is the best open source project I've found to see a good implementation of Caliburn Micro in action, be sure to check it out if you'll end up chosing this framework

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can we use JMX for Alerts/Notification Here are the specs that I'm trying to implement in a nutshell:
1) Some Alerts have to be sent on certain events in the application.
2) These Alerts have Users subscribe to them.
3) And the Users have set their own Notification preferences (e.g. Email and/or SMS).
I have not been able to find an open source solution in Java so far.
Is JMX Notifications an option? The more I read about JMX, the more I feel that it is trying to achieve something different that my problem.
Any help would be useful.

A: JMX can be a mechanism to solve this problem, but it's not the complete solution.
JMX provides facilities and services to your programs to allow clients to access monitoring data as well as allowing clients to make control calls to the application.
As you mentioned, one aspect of JMX is the notification system. What this system provides is infrastructure to make it easy for your program to make alerts and notifications available to clients, and modern JVMs also provide a free JMX server to allow client to connect to your application remotely and subscribe to those events.
But its one thing to make a JMX alert, and it's another thing completely to act on it.
What you would need to do is have some JMX client, somewhere, "subscribe" to the JMX notifications of your programs, and then THAT client can act upon those notification by sending emails, or whatever.
The JMX client can be a remote client talking to your application via TCP, or it can be an internal JMX client within the program, running in a thread, say, and it can act on the notifications.
So, basically, JMX provides the plumbing and infrastructure for what you want to do, but doesn't take it "the last mile" to converting alerts in to emails.
As @fawce mentioned, there are some "generic" JMX clients of various sophistication that can act upon JMX data and may do what you want (I'm not familiar with them, so I can not say first hand), or you can code your own system to monitor the JMX data.

A: There is an article with sample code for using JMX in your app to raise alerts: Delivering notification with JMX.
Once you have that working with local monitoring, you need to set these properties when executing your program:
-Dcom.sun.management.jmxremote.port=9999
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false

.. so that you can connect from a remote machine using jconsole or other tool with JMX capabilities.
JManage is one of many programs to monitor JMX-enabled Java processes capable of:

*

*plotting webpages of moving graphs

*emitting e-mails when thresholds change

*remote control

You can easily upgrade to something more complex, such as Nagios or another commercial tool. Those tools have workflows, roles and other features suitable for big teams - which might be a distraction if you just starting out with getting the Java side of JMX working.

A: If you mean JMX, there is a JBoss/Nagios bridge called monju that has a generlized JMX hook.

A: I would suggest using JMX notifications and SNMP which should support your scenario, 2) and 3) being covered by the SNMP software.
You could also code it in Java yourself as long as you have access to a SMS gateway with some API. Using javax.mail is straightforward as long as you have access to a SMTP host allowing anonymous access. A flexible publish-subscribe mechanism for 2) can be used to connect 1) and 3).

A: Solarwinds is a commercial enterprise monitoring tool that has the ability to hook into JMX  for monitoring.  It has the ability to generate SMS and Email alerts.

A: Do you mean JMS (instead of JMX)? JMS is an messaging API while JMX is a monitoring/administration API.
Using JMS as the back end is a good way to implement the back-end messages, it will take care of decoupaging, load balancing, and persistency. But you still have to have a component that receives the messages and send them on to the user.


text:
Q: How to obtain this formula for 2+1 dimensional boosts In this paper on anyons, a formula for boost transformations in 2+1 dimensional spacetime is given (equations 2.7--2.10).
The boost transformation here is defined as:
$$\displaystyle B(p) \hat{p} = p$$
where $\hat{p}$ is the rest frame momentum = $(m,0,0)$.
The formula for $B(p)$ is then given to be:
$$\displaystyle B(p) = e^{i \Omega_a(p)J^a} $$
where $J^a$ are representations of the generators of so(2,1), given by ${(J^b)}_{ac}= i{{\epsilon_a}^b}_c$. (The so(2,1) algebra is $[J^a,J^b]=i\epsilon^{abc}J_c$.)
$\Omega_a(p)$ is given by:
$$\displaystyle \Omega_a(p) = \epsilon_{abc} \frac{p^b}{|p|}\eta^c\ln \frac{E+|p|}{m} $$
where $\eta^a = (1,0,0)$ and $E= \sqrt{|p|^2 +m^2}$.
I want to understand how to derive or understand this formula for the boost generator.

A: To boost a vector $(m,0,0)$ to a general vector, $p$, one must do a Lorentz transformation in the direction of $p$. To determine the magnitude, check this Wikipedia article, https://en.wikipedia.org/wiki/Lorentz_transformation, which gives the formula for a general Lorentz transformation:
$$L=\begin{bmatrix}\gamma&-\gamma\beta n_x&-\gamma\beta n_y\\\gamma\beta n_x&1+(\gamma-1)n^2_x&(\gamma-1)n_xn_y\\\gamma\beta n_y&1+(\gamma-1)n_xn_y&(\gamma-1)n_y^2\end{bmatrix}$$
I have suppressed the z index because it is a three dimensional problem. $\gamma$ turns out to be $(1+\dfrac{p^2}{m^2})^{1/2}$ and $\beta$ is $\frac{p}{(p^2+m^2)^{1/2}}$.
Now, it remains to be shown that $L=exp(i\Omega_a(p)J^a)$. Expanding out the argument of the exponential it becomes, $$exp(i\Omega_a(p)J^a)=exp[ln(\frac{E+p}{m})\begin{bmatrix}0&-p_x/p&-p_y/p\\p_x/p&0&0\\p_y/p&0&0\end{bmatrix}]$$. This matrix is equivalent to a rotation matrix corresponding to a rotation by an angle $\theta=ln(\frac{E+P}{m})$ about an axis $\hat{n}=(0,-p_y/p,p_x/p)$ which you can verify by checking page 5 of this article.
Then using the form of the rotation matrix given there and substituting for
$\theta$ we get the answer.


text:
Q: Integrate website template in eclipse maven project I was wondering if it's possible to integrate a free website template downloaded into an eclipse maven project developed using spring. (I talk about html, javascript, css files). And how to do it ? just copy all files in folders of the projects ?

A: Yes!
You can copy the folders. but you have to include in the build.xml to create the deployment file.
should be in under WEB-INF/xyz..
dependent on your request url

A: This is an example of directory structure:
webapp
     |
     resources
     |       |
     |       css (CSS files go here)
     |       |
     |       js (JavaScript files go here)
     |
     |
     WEB-INF
           |
           views (JSP, html... files go here)

However a big note! As I mentioned, you have to be careful about loading them.
I.e. in JSP you load JS and CSS files like this:
<link href="<c:url value="/resources/css/style.css" />"
    rel="stylesheet">
<script src="<c:url value="/resources/js/functions.js" />"></script>

In something like Thymeleaf you will do it like this:
<link th:href="@{/resources/css/style.css}" rel="stylesheet" />

<script th:src="@{/resources/js/functions.js}"></script>

Basically, it depends which template engine you use.


text:
Q: What does libvips VIPS_DISC_THRESHOLD default=100 mean? Does it mean that it will take 100MB (Open via Disk)?
Or it mean that it will take 100MB (Open via Memory)?

A: That's the threshold at which libvips will flip from open-via-memory to open-via-disc.
For small images (100mb when decompressed in this case), libvips will decompress to memory then process from there. This is obviously not a good idea for large images, so for these libvips will decompress to a temporary disc file, then map that area of disc into virtual memory and use that as the pixel source.
tldr: set VIPS_DISC_THRESHOLD to a small number to prefer the use of disc, set it to a large number to prefer RAM.
There's a chapter in the libvips docs which goes into a lot more detail:
https://www.libvips.org/API/current/How-it-opens-files.md.html
To very quickly summarize:

*

*libvips has at least four ways of opening images and tries hard to pick the best one for you automatically.

*Sometimes it'll need a bit of help to hit the best path for your use case and you have three main ways of influencing this.

*You can hint the access pattern you expect for this image with the access= parameter, you can set the threshold at which it'll flip between preferring memory and preferring disc, and you can say where you'd like disc temporaries to be held.


text:
Q: How do I get the source of an exception in my Application.OnException event handler? In Delphi 7, if I catch an exception in my Application.OnException event handler, then how can we find out which function or procedure of the application threw this unhandled exception?
I have created an application and am getting the exception correctly, but how I can print the method name that caused this exception?

A: That's not something that can easily be done. You need to hook into the low-level exception handling routines to obtain reliable stack traces. This is a very advanced topic. It requires reverse engineering of the runtime library. Not something that can reasonably be explained in detail in a Stack Overflow question.
There are a number of existing third party tools that offer such capabilities: madExcept, EurekaLog and JclDebug. I only have experience of madExcept which I endorse enthusiastically. However, the other toils are, by all accounts very good too.
If you want to learn how to do this, then look at JclDebug which is open source. If you don't require learning and just wish to add the capabilities to your program, evaluate and pick one of the tools. JclDebug is perhaps a little harder to integrate into your program so if you are looking for a quick and easy route forward, one of the other two may be more rewarding.


text:
Q: How to create effect of divs floating over image with css and js/jQuery? How do I create the effect of divs or sections of pages floating (for lack of a better description) over images?
The effects I'm interested in are showcased here:
http://www.thedailybeast.com/newsweek/2013/08/30/on-syria-go-big-or-stay-home.html
http://www.kitkat.com/
Links to libraries, jsfiddle examples, or tutorials would be very appreciated. Thanks

A: Put background on div like this, here's a Fiddle

HTML

CSS
.wrapper {
  position: relative;
  background: url(../images/myimage.png) center no-repeat;
  z-index: 1;
}
.innerdiv {
  position: absolute;
  top: 300px;
  left: 300px;
  z-index: 100;
}

A: Actually you can see what they did by doing inspection on the page, but to directly answer your question, they are using a framework for the most part, however they did some extra stuff.
They are using Twitter Bootstrap for their layout.  Below is a very rough copy of what they did.
http://jsbin.com/EjeDiPI/1/


text:
Q: What are Parent-Child relationships? What is the parent and what is the child in a sql relationship?
In my case, I have a part (Say screw), and product material. For argument's sake, a product material (eg steel) can only belong to one part (but not in the real world). So this is 1:n. The part will have its pk as a fk in the ProductMaterial table.
Which is parent and which is child in this case?

A: You can interpret a 1:n relationship in database this way: A child is always that model which holds the foreign key as this indicates where it belongs to.
Of course if you have self referencing models/tables you have to look at it in a different way.

A: Relational databases such as SQL actually have no concept of parent/child relationships - that is an interpretation that you as  a programmer put on the data. There are architectures that explicitly state and use such relationships, such as heirarchical (and to a certain extent OO) databases.

A: In this case, Part is parent and ProductMaterial is child.
A parent can have unlimited numbers of children (scary thought - 2 is enough for me!), whereas a child can have only a limited number of parents - and in DB terms, only 1!

A: Usually in a one-to-many relationship, it's the "one" record that is the parent, and the "many" records that are the children.
Of course, in some cases it doesn't make any sense to talk about a parent-child relationship. In your example it makes some kind of sense at least. In other examples you may even find the opposite, where a child has many parents, but then it's not very useful to describe it that way.

A: Another way to look at this, in addition to what David M. said, is in terms of an ORM implementation (such as Linq to SQL). You have two entities, Part and ProductMaterial. Each part entity has a set of ProductMaterial entities (children entities or an EntitySet). Each ProductMaterial entity has zero or one Part entity (parent entity or an EntityRef).
Randy

A: I would say that any table which has a one to many relationship with one or more other tables can be considered a parent to those other tables. Self joining? An ambiguous term which I don't think anyone understands.

A: 'Product' is parent and 'Product material' is child in Product_ProductMaterial relationship or association.
If you delete a child, parent can live and continue life. If you delete parent, child become orphan or identityless which is not good. If A can not not be deleted before B is deleted, then A is parent and B is child.
If I guess right, in your case in Product_ProductMaterial relationship, if you delete Product, ProductMaterial will be assigned to no one, become orphan, identity crisis. But if you delete ProductMaterial, Product can still be there, no need identity support.
Sorry if my wordings are not good.


text:
Q: Ignore NerdTree buffer when manipulating splits When dealing with multiple splits, the split management commands are very useful: <C-W> R/r or <C-w><S-h>, for instance.
The issue I have is that when I have a NedTree buffer opened as a split, a command like <C-W>R or <C-W><S-h> will also move the NerdTree split which is obviously not the desired result.
I tried re-mapping these commands by including :NERTreeToggle<CR>:NERDTreeToggle<CR> but that doesn't work and is pretty clunky anyway.
Is there a way to "lock" the NerdTree split either on the left or the right side and have it be ignored by split manipulation commands ?

A: What if you just closed Nerdtree before moving your splits thereby avoiding any of the ensuing issues:
nnoremap <C-W> :NERDTreeClose<CR><C-W>

Once you're done juggling your split screens, reopen Nerdtree. If you need to be fancy, combine closing, rotating splits and reopening Nerdtree in one mapping, something like:
nnoremap <C-W>r :NERDTreeClose<CR><C-W>r<bar>:NERDTreeToggle<CR>


text:
Q: Display Magic Mouse Battery in Touch bar using BetterTouchTool I'm using this BetterTouchToll for make my touch bar more interesting, what is very cool.
He accept some Apple Scripts for more dynamic, so I start to study this scripts.
Now I wanna to display my Magic Mouse Battery on my touch bar, for this I was trying this code, but is not working.
if application "Mouse" is running then
    tell application "Mouse"
        return (get Battery)
    end tell
end if
return "no mouse"

My guess is that Mouse is not a application, but don't know what to put in the place

A: The traditional means of getting the battery level is to use ioreg on the command line. However, the traditional means of doing this no longer seem to work as of at least macOS High Sierra/10.13.4; that is, they no longer allow choosing to display just the battery percentage of a single bluetooth device.
So this is a hack that assumes that the Magic Mouse is always the last device displayed by ioreg. This is likely to fail, if not across different installations of macOS, then across different versions.
ioreg -c AppleDeviceManagementHIDEventService | grep BatteryPercent | tail -1 | sed 's/[^[:digit:]]//g'

In an AppleScript, this would be:
do shell script "ioreg -c AppleDeviceManagementHIDEventService | grep BatteryPercent | tail -1 | sed 's/[^[:digit:]]//g'"

You have your code setup to also detect when the Magic Mouse is not connected. The product name is in the property "Product" in ioreg. For example:
ioreg -c AppleDeviceManagementHIDEventService | grep '"Product" ='

So to make sure that this final device is the Mouse, you could do:
set finalDevice to do shell script "ioreg -c AppleDeviceManagementHIDEventService | grep '\"Product\" =' | tail -1"
if finalDevice contains "Magic Mouse" then
    set remaining to do shell script "ioreg -c AppleDeviceManagementHIDEventService | grep BatteryPercent | tail -1 | sed 's/[^[:digit:]]//g'"
    remaining & "%"
else
    "no mouse"
end if

The basic logic:

*

*Grab the list of all products using ioreg.

*Use tail to get only the final product in the list.

*If the final product is a Magic Mouse, then:

*

*Grab the list of all battery percentages using ioreg.

*Use tail to get only the final battery percentage in the list.

*Use sed to get only the actual number from that line.

*Append a percentage symbol to the number.

*Otherwise, there is no mouse. (Or the mouse is not the final item in the list.)

For the older means of using ioreg, see, for example:

*

*Reporting on Bluetooth Mouse/Keyboard battery status

*Read Magic Mouse and Apple Wireless Keyboard Battery percentage

A: Thanks so much for the solution. Very inspiring. As I have multiple devices I made my own script based on your solutions. I want to share it here in case it could be useful to others.
As I have more than one bluetooth device, the order of them in ioreg is based on the order they were connected. Which means I cannot assume that the mouse is the last device.
I made most of it in shell, not in applescript, since I am more experienced in shell and therefore it was quicker that way. Using Applescript for filtering the output from ioreg would properly have been a 'cleaner' solution :p
WARNING: I know this code is pretty crappy, but it was quick to write and it does the job, don't assume this to be a way of doing things properly.
My solution
From BTT the following script calls the shell script
set devicename to "Magic Mouse 2" -- The name of the device in ioreg
set displayname to "Mouse" -- The name to display on the touchbar

set remaining to do shell script "~/.dotfiles/shell/device_battery_level.sh" & " " & quoted form of devicename

if remaining is "" then

    "" --No device present = no output to touchbar

else

    displayname & " " & remaining & "%" -- Show output on touchbar

end if

As seen the code pretty much just calls the shell script. The name provided in the variable "devicename" is used as a argument to the script and is the name that the script will look for in ioreg. If the shell script outputs an empty script no widget will be displayed. For me this was preferred over displaying "No device".
The script in "~/.dotfiles/shell/device_battery_level.sh" then looks like this:
#!/bin/sh
DEVICES=$(ioreg -r -l -n AppleHSBluetoothDevice | egrep '"BatteryPercent" = |^  \|   "Bluetooth Product Name" = ') #Lets get a list of all bluetooth devices

DEVICELINE=$(grep -n "$1" <<< "$DEVICES") #$1 is the device that this script was called with. Lets extract only the line with that device
if [$DEVICELINE = ""] #If DEVICELINE is empty the name of the device was not in the output and it is properly not connected.
then

    echo "" #Device not present, lets give BTT an empty string

else

    LINENR="${DEVICELINE:0:1}" #Then we find out where the line of the device is located

    NEXTLINE=$(expr $LINENR + "1") #The battery level is at the next line therefore we increment the line number
    SEDCOMMAND="p"

    BATTERYLINE=$(echo "$DEVICES" | sed -n  $NEXTLINE$SEDCOMMAND) # Now we can extract the line with the battery percent

    echo $BATTERYLINE | sed 's/[^[:digit:]]//g' #Finally we just need to get the digit and echo that to BTT

fi

The basic logic is the same as the above answer. Except instead of grabbing the last line from ioreg with tail egrep is used to only output relevant lines. The egrep code is based on another post here: https://apple.stackexchange.com/questions/293502/how-can-i-determine-the-battery-level-of-my-magic-mouse-from-the-command-line/293505#293505
Based on this the line which mentions the devicename is found. The logic is that since the battery level information is always below the devicename in ioreg the next line in the extracted list must be the battery level.


text:
Q: Laravel pretty URL I'm going crazy here! I'm trying to learn Laravel and pretty URLs just don't work.
I have enabled mod_rewrite from my apache config file, I have set AllowOverride to All in my user config file and I have the following in my .htaccess file in public folder of Laravel installation:
Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1 [L]

I enter http://localhost/~user/lara/public/index.php/users it works, but with http://localhost/~user/lara/public/users I get 404 Not Found error
The requested URL /Users/user/Sites/lara/public/index.php/users was not found on this server.

You can see that the redirection works fine, as public/users have turned into public/index.php/users but it says not found, even though when I manually enter public/index.php/users it show me the output.
I have read all the related questions on SO, none of the worked for me!

A: This is most likely caused by the fact that you are changing the document root during a request. From the looks of your URL (with the ~user segment) you are using mod_userdir or something similar, and what these types of plugins do it allow you to map a given URL prefix to a document root that is not the normal one for the server.
As such, you sometimes run into issues like this where the right .htaccess file is found, but its rewritten URL is against the original document root rather than the modified one and so your index.php file cannot be found (maybe, to be honest I don't really know, this is all conjecture). This is also why going directly to index.php/users works - the problem isn't the setup per se, but the mixing of rewrite rules and the change of the document root.
As such, the fix is to use a RewriteBase line, ad the following to the .htccess file:
RewriteBase /~user/lara/public/


text:
Q: Get raw parameter data in Ruby on Rails I have a ruby on rails api where I want to sign my request data by appending a hashed version of all passed in parameters to the request and rebuild this one at the server side as well to validate the integrity of the requests.
When I simply use the params method in the controller I have different parameters (e.g. for an update-method which is specified by this:
put 'login' => 'login#update'

I get as parameters on the server:
{"timestamp"=>"1399562324118", "secured"=>"xxx",
 "login"=>{"timestamp"=>"1399562324118", "secured"=>"xxx"}}

although I only send the request from the client with
{"timestamp"=>"1399562324118", "secured"=>"xxx"}

Does any one have an idea how to get rid of this "login" parameter in the params list in a generic way? I do not want to exclude this for every single request of my api.
Thanks a lot!

A: Per the Rails Edge guide on ActionController:
"If you've turned on config.wrap_parameters in your initializer or calling wrap_parameters in your controller, you can safely omit the root element in the JSON parameter"
See http://guides.rubyonrails.org/action_controller_overview.html#json-parameters


text:
Q: "Local variable referenced before assignment" error while declaring variable same as the imported class local variable 'Document' referenced before assignment

I keep on getting this variable unbound error but i do not seem to understand why.
Importing it seems fine. I am using django 1-10
from django.shortcuts import render

# Create your views here.
from forms import DocumentForm
from models import Document

def SaveDocument(request):
    saved = False
    if request.method == "POST":
        #Get the posted form
        MyDocumentForm = DocumentForm(request.POST, request.FILES)

        if MyDocumentForm.is_valid():
            print 'It enters here'
            Document = Document()
            Document.name = MyDocumentForm.cleaned_data["name"]
            Document.document = MyDocumentForm.cleaned_data["document"]
            Document.save()
            saved = True
        else:
            print 'Fails'
    else:
        MyDocumentForm = DocumentForm()

    return render(request, 'saved.html', locals())

A: The problem is that you just redefine Document inside SaveDocument() function.
Just rename local variable to document instead of Document:
document = Document()

A: When Python parses the body of a function definition and encounters an assignment such as
foo = ...

Python interprets foo as a local variable by default.
Hence, when you mentioned:
Document = Document()

The Document you imported was no longer accessible within your SaveDocument() function. In order to make this work, change it to:
document = Document()

and use the referrence of document in rest of your code.
You may verify this via telling Python to use the global reference of Document (which will let you execute your current code) as:
global Document
Document = Document()
# NOTE: Do not use this in actual code. It is bad practice to
# override the imported modules, class, function with the variable names

As per the Python's The global statement document:

The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without global, although free variables may refer to globals without being declared global.


text:
Q: Android.mk try access .so file I want to include *.so in Android.mk. Here is my code save in app/jni/Android.mk
The .so file is same in app/jni/libdpfr6.so
My code is
LOCAL_PATH:=$(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := libdpfr6
LOCAL_SRC_FILES := libdpfr6.so
include $(PREBUILT_STATIC_LIBRARY)
but after running the app I got a error.
LOCAL_SRC_FILES should point to a file ending with ".a"
Android NDK: The following file is unsupported: libdpfr6.so
I need help.


text:
Q: Cannot access hidden folder in flutter like .Statuses in Android 11? I tried solutions given for similar questions, which the solution is adding ManageExternalStorage permission to AndroidManifest.xml. But Playstore rejected my app to have permission which is sensitive like this.
But Other developers in GooglePlay manages to access  /.Statuses (hiddenfolder) without any sensitive permission. How do they able to achieve that without the solution given above??


text:
Q: Multiple Java versions running concurrently under Windows We have a couple of applications running on Java 5 and would like now to bring in an application based on Java 6. Can both java versions live together under Windows?
Is there any control panel to set the appropriate Java version for different applications, or any other way to set up, what version of Java will be used to run that particular application?

A: Of course you can use multiple versions of Java under Windows. And different applications can use different Java versions. How is your application started? Usually you will have a batch file where there is something like
java ...

This will search the Java executable using the PATH variable. So if Java 5 is first on the PATH, you will have problems running a Java 6 application. You should then modify the batch file to use a certain Java version e.g. by defining a environment variable JAVA6HOME with the value C:\java\java6 (if Java 6 is installed in this directory) and change the batch file calling
%JAVA6HOME%\bin\java ...

A: We can install multiple versions of Java Development kits on the same machine using SDKMan.
Some points about SDKMan are as following:

*

*SDKMan is free to use and it is developed by the open source community.

*SDKMan is written in bash and it only requires curl and zip/unzip programs to be present on your system.

*SDKMan can install around 29 Software Development Kits for the JVM such as Java, Groovy, Scala, Kotlin and Ceylon. Ant, Gradle, Grails, Maven, SBT, Spark, Spring Boot, Vert.x.

*We do not need to worry about setting the _HOME and PATH environment variables because SDKMan handles it automatically.

SDKMan can run on any UNIX based platforms such as Mac OSX, Linux, Cygwin, Solaris and FreeBSD and we can install it using following commands:
$ curl -s "https://get.sdkman.io" | bash
$ source "$HOME/.sdkman/bin/sdkman-init.sh"

Because SDKMan is written in bash and only requires curl and zip/unzip to be present on your system. You can install SDKMan on windows as well either by first installing Cygwin or Git Bash for Windows environment and then running above commands.

Command sdk list java will give us a list of java versions which we can install using SDKMan.
Installing Java 8
$ sdk install java 8.0.201-oracle

Installing Java 9
$ sdk install java 9.0.4-open

Installing Java 11
$ sdk install java 11.0.2-open

Uninstalling a Java version
In case you want to uninstall any JDK version e.g., 11.0.2-open you can do that as follows:
$ sdk uninstall java 11.0.2-open

Switching current Java version
If you want to activate one version of JDK for all terminals and applications, you can use the command
sdk default java <your-java_version>

Above commands will also update the PATH and JAVA_HOME variables automatically. You can read more on my article How to Install Multiple Versions of Java on the Same Machine.

A: It should be possible changing setting the JAVA_HOME environment variable differently for specific applications.
When starting from the command line or from a batch script you can use set JAVA_HOME=C:\...\j2dskXXX to change the JAVA_HOME environment.
It is possible that you also need to change the PATH environment variable to use the correct java binary. To do this you can use set PATH=%JAVA_HOME%\bin;%PATH%.

A: I use a simple script when starting JMeter with my own java version
setlocal
set JAVA_HOME="c:\java8"
set PATH=%JAVA_HOME%\bin;%PATH%;
java -version

To have a java "portable"
you can use this method here:
https://www.whitebyte.info/programming/java/how-to-install-a-portable-jdk-in-windows-without-admin-rights

A: Or use links. While it is rather unpleasant to update the PATH in a running environment, it's easy to recreate a link to a new version of JRE/JDK. So:

*

*install different versions of JDK you want to use

*create a link to that folder either by junction or by built-in mklink command

*set the PATH to the link

*If other version of java is to be used, delete the link, create a new one, PATH/JAVA_HOME/hardcoded scripts remain untouched

A: I was appalled at the clumsiness of the CLASSPATH, JAVA_HOME, and PATH ideas, in Windows, to keep track of Java files.  I got here, because of multiple JREs, and how to content with it.  Without regurgitating information, from a guy much more clever than me, I would rather point to to his article on this issue, which for me, resolves it perfectly.
Article by: Ted Neward: Multiple Java Homes: Giving Java Apps Their Own JRE

With the exponential growth of Java as a server-side development language has come an equivablent
  exponential growth in Java development tools, environments, frameworks, and extensions.
  Unfortunately, not all of these tools play nicely together under the same Java VM installation. Some
  require a Servlet 2.1-compliant environment, some require 2.2. Some only run under JDK 1.2 or above,
  some under JDK 1.1 (and no higher). Some require the "com.sun.swing" packages from pre-Swing 1.0
  days, others require the "javax.swing" package names.
Worse yet, this problem can be found even within the corporate enterprise, as systems developed using
  Java from just six months ago may suddenly "not work" due to the installation of some Java Extension
  required by a new (seemingly unrelated) application release. This can complicate deployment of Java
  applications across the corporation, and lead customers to wonder precisely why, five years after the
  start of the infamous "Installing-this-app-breaks-my-system" woes began with Microsoft's DLL schemes,
  we still haven't progressed much beyond that. (In fact, the new .NET initiative actually seeks to solve the
  infamous "DLL-Hell" problem just described.)
This paper describes how to configure a Java installation such that a given application receives its own,
  private, JRE, allowing multiple Java environments to coexist without driving customers (or system
  administrators) insane...

A: It is absolutely possible to install side-by-side several JRE/JDK versions. Moreover, you don't have to do anything special for that to happen, as Sun is creating a different folder for each (under Program Files).
There is no control panel to check which JRE works for each application. Basically, the JRE that will work would be the first in your PATH environment variable. You can change that, or the JAVA_HOME variable, or create specific cmd/bat files to launch the applications you desire, each with a different JRE in path.

A: Invoking Java with "java -version:1.5", etc. should run with the correct version of Java. (Obviously replace 1.5 with the version you want.)
If Java is properly installed on Windows there are paths to the vm for each version stored in the registry which it uses so you don't need to mess about with environment versions on Windows.

A: If you use Java Web Start (you can start applications from any URL, even the local file system) it will take care of finding the right version for your application.

A: Using Java Web Start, you can install multiple JRE, then call what you need.
On win, you can make a .bat file:
1- online version:
<your_JRE_version\bin\javaws.exe> -localfile -J-Djnlp.application.href=<the url of .jnlp file.jnlp> -localfile -J "<path_temp_jnlp_file_.jnlp>"
2- launch from cache:
<your_JRE_version\bin\javaws.exe> -localfile -J "<path_of_your_local_jnlp_file.jnlp>"


text:
Q: Slide Left animated transition in ng-hide, ng-Animate I have created jsfiddle http://jsfiddle.net/99vtukjk/
On clicking left or right text, currently the animation for hide is upwards, how can we change it to slide left animation e.g slide & fade to left menubar?.

LEFT

RIGHT

               this is just a sample div

         {{myValue}}

CSS:
.animate-hide {
 -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 2s;
    -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 2s;
    -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 2s;
    transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 2s;
  line-height:20px;
  opacity:1;
  padding:10px;
  border:1px solid black;
  background:white;
}

.animate-hide.ng-hide {
  line-height:0;
  opacity:0;
  padding:0 10px;
}

Angular Module
  var app = angular.module("myApp1", ["ngAnimate"]);
    app.controller("MyCtrl", function ($scope) {
    $scope.myValue=false;
    });

A: you can set left: 0 on .animate-hide
and left: -100% on .animate-hide.ng-hide
here's a working fiddle
One thing that can help you make beautiful animations is using
Animate.css

animate.css is a bunch of cool, fun, and cross-browser animations for you to use in your projects.

A: Check out ngAnimate. Amazing.
DEMO


text:
Q: Booleans in shell script I am using a optional variable BUILD_X flag to decide whether to build X based on user input.
BUILD_X=true
while getopts "B:" option; do
  case "$option" in
    B) BUILD_X=$OPTARG;;
  esac
done

if (( $BUILD_X == true )); then
    body
fi

I am observing that even if I give BUILD_X false from the terminal as an input to script, it still executes the body. Where am I going wrong ?


text:
Q: Cannot find libHalide.so to build I'd like to build the Halide tutorials on mac.
The instruction says:
// On os x:
// g++ lesson_02*.cpp -g -I <path/to/Halide.h> -I <path/to/tools/halide_image_io.h> -L <path/to/libHalide.so> -lHalide `libpng-config --cflags --ldflags` -ljpeg -o lesson_02 -std=c++17
// DYLD_LIBRARY_PATH=<path/to/libHalide.dylib> ./lesson_02

From the release of Halide, I can locate Halide.h and libHalide.dylib but not libHalide.so.
Where do I find it?
Example:
find . -name 'Halide.h'
./include/Halide.h

but looking for the .so file returns nothing.

A: The instructions were originally written for Linux systems. On macOS, shared libraries use the .dylib extension, not .so, so this amounts to a typo in the tutorial.

That said, I would recommend using CMake instead...
cmake_minimum_required(VERSION 3.16)
project(tutorial)

find_package(Halide REQUIRED)

add_executable(lesson02 lesson02.cpp)
target_link_libraries(lesson02 PRIVATE Halide::Halide)

This build is portable across Windows, macOS, and Linux.


text:
Q: Rails 3: Delete association duplicates from the database I've got these models:
class Relationship < ActiveRecord::Base
  belongs_to :student
  belongs_to :guardian
end

class Student < ActiveRecord::Base
  has_many :relationships
  has_many :guardians, through: :relationships
end

class Guardian < ActiveRecord::Base
  has_many :relationships
  has_many :students, through: :relationships
end

I don't want any guardian to be related many times with one student. This can be prevented with a validation, but let's say it's too late and there are case where this is happening. For example, where g is a guardian:
g.relationships

[
    [0] #<Relationship:0x0000000bc33650> {
                          :id => 40321,
        :relationship_type_id => 2,
                  :student_id => 41700,
                 :guardian_id => 45820,
                  :created_at => Tue, 23 Apr 2013 17:44:29 UTC +00:00,
                  :updated_at => Tue, 23 Apr 2013 17:44:29 UTC +00:00,
    },
    [1] #<Relationship:0x0000000bc32e80> {
                          :id => 40923,
        :relationship_type_id => 2,
                  :student_id => 41700,
                 :guardian_id => 45820,
                  :created_at => Tue, 23 Apr 2013 18:58:46 UTC +00:00,
                  :updated_at => Tue, 23 Apr 2013 18:58:46 UTC +00:00,
    }
]

As you can see, these two relationships share the same student_id. I want to find out if there's a way I can delete from the database the duplicated relationships. I've tried the following lines of code to no avail:
g.relationships.uniq!(&:student_id)
g.update_attributes(relatioships: g.relationships.uniq!(&:student_id))

How can I solve this problem. Thanks!

A: subquery = Relationship.select("student_id, guardian_id").
             group(:student_id, :guardian_id).
             having("count(*) > 1").to_sql
groups = Relationship.joins("JOIN (#{subquery}) sub ON relationships.student_id = sub.student_id AND relationships.guardian_id = sub.guardian_id").
                      group_by{|r| [r.student_id, r.guardian_id] }

groups.values.each do |duplicates|
  duplicates.drop(1).each(&:destroy)
end


text:
Q: MS Access Query - Incompatible Types (Dates) I am trying to get a range of records within the last 5 years. Unfortunately, the data type on my column is a string with a slightly odd formatting. For example, December 2018 would be represented as : 2018/012.
I have tried making the following query :
SELECT tbl.StrDate
FROM tbl
WHERE DateValue(StrDate) > DateAdd("yyyy", -5, Date());

The query works for a fraction of a second (as in I see the results)... However, it pops up a display saying that there are "incompatible types within the query criterias" and the entire column changes to #Name ?.
I am not quite sure what is causing this issue. Thanks for the help.
Note: I am using a French version of Access 2010 the wording might be slightly different here.

A: Try ignoring the invalid "dates":
SELECT tbl.StrDate
FROM tbl
WHERE DateValue(IIf(IsDate(StrDate), strDate, Date()) > DateAdd("yyyy", -5, Date())

or list - and correct - those "dates":
SELECT tbl.StrDate
FROM tbl
WHERE NOT IsDate(StrDate);

A: If you are willing to ignore the day portion, then use left() and val():
WHERE VAL(LEFT(StrDate, 4)) > DateAdd("yyyy", -5, Date());

Actually, LEFT() isn't needed, but I prefer to keep it for clarity.


text:
Q: PHPDocumentor. Can I add link to property from it's getter description? /**
* @property $Property
*/
class SomeClass {

    public function __get($name){
       return $this->{'get'.$name};
    }

    /**
     * Some description
     * @return bool
     */
    public function getProperty(){
       return true;
    }

}

So the question is - how can I see description from getProperty() by viewing documentation of $Property? Or just see link to getProperty() documentation...

A: The question seems to be the reverse of the title.  Do you want to look at the property and see the getter's description, or do you want to look at the getter and see the property's description?
I'll assume you want both.  However, you can't actually get either.  At most, one's description could contain a link to the other, but not actually contain the other's description in its own description.
Here, the property's description will contain a link to the getter's doc.
/**
 * @property $Property is controlled by {@link getProperty()}.
 */
class SomeClass {

    public function __get($name){
       return $this->{'get'.$name};
    }

    /**
     * Gets the value of {@link $Property}.
     * @return bool
     */
    public function getProperty(){
       return true;
    }

}

There are two complications here:  with regard to how magic things appear in the actual docs (and how IDEs display them); and with whether or not the {@link} inline tags actually do anything.
In phpDocumentor 1.x, magic stuff only appears as extra information listed on the class itself.  In phpDocumentor 2.x, both magic properties and magic methods will appear as if they were true properties and methods.  The 2.x behavior is a strong improvement.  For IDEs, and I can only speak for Eclipse PDT, I see that it matches the 1.x behavior.
In phpDocumentor 1.x, the inline {@link} tag does function, and normally becomes a hyperlink to the document for the element (property, method) that it points to.  However, since 1.x does not actually create a dedicated doc for magic things identified by @property and @method, then "{@link $Property}" cannot actually point to anything.  It's possible that the text in the class docblock where the "@property $Property" description is shown might correctly show a link to getProperty(), but only because getProperty() is a true method, and as such it has its own doc.  Had getProperty() been a magic method denoted by "@method getProperty()", then "{@link getProperty()}" would not have anywhere to point to.
In phpDocumentor 2.x, the inline {@link} tag is not implemented, and therefore it will end up just a visible text as if it had no tag purpose.  Once 2.x implements this inline tag, then my solution above should be able to solve both of your potential questions.

A: I think the best you can manage is
@property $Property
@see getProperty

A: Use a class-level PHPDoc comment
/**
 * @method string getMyFirstProperty()  Return value of the property called first
 * @method float  getMySecondProperty() Return value of the property called second
 */

And yes, magic getters will appear in the IDE, which is really what makes it useful


text:
Q: 'Daily vote limit reached' only for comments
Possible Duplicate:
What is the daily comment vote limit?

I'm not completely sure but when I want to vote a comment I get the message:
Daily vote limit reached; vote again in 10 hours

but for answers I can still vote.
Does this mean there is a separate limit for comment votes and answer votes? If so, from my point of view it would be a nice idea if the message was written more precisely.

A: There are two different limits: There is a daily limit for votes on posts, and there is a daily limit for votes on comments.
The limit on comment votes is reported on Comments: Now with Flags and Votes.

Each user gets 5 comment flag votes, and 30 comment upvotes, per day.

The error message could be misunderstood, and interpreted as saying that you cannot vote anymore on comments and posts.
Probably the message should report which daily limit has been reached. In that way, users would not take the assumption it means they cannot vote anymore for that day. The problem is when you have also reached the daily limit for post votes, and you think there is a daily limit for votes that includes both the votes on posts, and on comments. (It actually happened to me, and I thought I could vote for comments as long as I still had votes for posts to cast.)


text:
Q: Recorded videos from Iphone is playing in upper left corner in jwplayer I have integrated jwplayer in my website to play videos. All videos working fine instead of those videos that recorded by I-phone. If videos recorded by iphone then it is playing in upper left corner. I have searched alot but didn't got any clue why it happening. Please help..!!

A: Run the video through Handbrake with its default options, plus check "Web optimized." That will cure this issue.
http://handbrake.fr/
(Edit: BTW, this problem occurs when the phone is held in portrait mode instead of landscape mode. The orientation flags in the video are screwed up.)


text:
Q: Protobuf "Unresolved reference" with generated classes in Android Studio using Kotlin it's my first time diving in with protobuf and jetpack's DataStore but I've encountered an issue which is quite confusing.
I've created my .proto file in src/main/java/proto, it's really simple:
syntax = "proto3";

option java_package = "com.test.appname.proto";
option java_multiple_files = true;

message WalkInfo {
  float distance = 1;
  bool run = 2;
}

Then I've written in kotlin a serializer class for some data in my app.
object WalkInfoSerializer : Serializer<Walker.WalkInfo>{
        override val defaultValue: Walker.WalkInfo
            get() = WalkInfo.getDefaultInstance()

        override fun readFrom(input: InputStream): Walker.WalkInfo {
            try {
                return WalkInfo.parseFrom(input)
            } catch (exception: InvalidProtocolBufferException) {
                throw CorruptionException("Cannot read proto.", exception)
            }

        }

        override fun writeTo(t: Walker.WalkInfo, output: OutputStream) {
            t.writeTo(output)
        }

    }

I've also set up my build.gradle file like this:
plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id "com.google.protobuf" version "0.8.14"

}
...
dependencies {
    ...
    //DataStore
    implementation "androidx.datastore:datastore:1.0.0-alpha05"
    implementation 'com.google.protobuf:protobuf-javalite:3.14.0'
}

protobuf {
    protoc {
        artifact = "com.google.protobuf:protoc:3.10.0"
    }

    generateProtoTasks {
        all().each { task ->
            task.builtins {
                java {
                    option 'lite'
                }
            }
        }
    }
}

Everything works fine, the classes seem to be generated correctly and they even pop up in android studio's autocomplete.
The problem is that I can't get the project to compile as I can't seem to find a way to resolve the "Unresolved Reference" for the methods generated (like getDefaultInstance(), parseFrom(), writeTo()
Even by writing the full class path it won't work.

Am I missing something? I've tried to play around with build.gradle and the proto file with some settings I found in their documentation but I still couldn't get it to work
Thank you!

A: Went to sleep, woke up, and knew the answer to my problems.
Dumb brain managed to do 1 + 1 during the night.
I realized that if the proto classes are being generated, I should not be defining them myself in kotlin code.
I had a WalkInfo message that generated a WalkInfo class, but I also had a WalkInfo class already with some methods in it. This is what was confusing the compiler.
After further research I realized that classes generated by proto are not even meant to be extended, they are supposed to be just data containers.
What I ended up doing is renaming my message to WalkInfoStorage while also keeping my WalkInfo kotlin class, I'll then be handling generating WalkInfo instances from the serialized data


text:
Q: Html tags inserted to MySQL changed I have a form with POST method, one of element is a text input, which can contain html code as a value. I need to save this value to mysql database.
This is without troubles on my local server, but on our hosting server (with different versions of php and MySQL) the code from input was changed after the insert.
E. g. for value

a

b

 in DB is saved "- a - b"
How to solve that correctly?
Edit - more info: project is on wordpress, using wpdb for communication with database.
Form field:
<textarea name="description" value=""></textarea>

getting value and inserting to db:
$description = $_POST ["description"];

      $wpdb->insert(
                'attribute',
                array(
                    'name' => $name,
                    'description' => $description,
                    'attribute_order' => $order,
                    'section_id' => $section_id
                )
              );

A: You need to escape it if you want to save unformatted value
Check the Entity name of each characters


text:
Q: Making and appending into new lists with loops I've been trying to make  a program to look at the first x numbers of a list, sort them in ascending order, then look at the next x-1 numbers and sort them in descending order, all the way until x = 1
I've tried this program but I am very stuck and unsure of how the logic of this problem should be.

n = [3, 14, 1, 59, 26, 535, 8, 97, 932, 38, 462, 64, 3, 3, 83, 279, 50, 288, 4, 19, 716, 939, 9, 37510]

l = []
count = 0
for i in n:
  count += 1
print(count)

length = 6
for i in range(1, count):
        l = (n[::length])
        length = length - 1
print(l)

It only returned the first and last of the list.

A: Consider using a while loop:
def split_list(nums: list[int], size: int) -> list[list[int]]:
    """
    Splits list into sorted sublists of decreasing sizes
    alternating between ascending and descending until size < 1.
    """
    result = []
    i = 0
    ascending = True
    while i + size < len(nums) and size >= 1:
        result.append(
            sorted(nums[i:i + size])
            if ascending
            else sorted(nums[i:i + size], reverse=True)
        )
        i += size
        size -= 1
        ascending = not ascending
    if i < len(nums):
        result.append(
            sorted(nums[i:])
            if ascending
            else sorted(nums[i:], reverse=True)
        )
    return result

nums = [
    3, 14, 1, 59, 26, 535, 8, 97, 932, 38, 462, 64, 3, 3, 83, 279, 50, 288, 4,
    19, 716, 939, 9, 37510
]
print(f'{nums = }')
print(f'{split_list(nums, size=4) = }')
print(f'{split_list(nums, size=10) = }')
print(f'{split_list(nums, size=7) = }')

Output:
nums = [3, 14, 1, 59, 26, 535, 8, 97, 932, 38, 462, 64, 3, 3, 83, 279, 50, 288, 4, 19, 716, 939, 9, 37510]
split_list(nums, size=4) = [[1, 3, 14, 59], [535, 26, 8], [97, 932], [38], [3, 3, 4, 9, 19, 50, 64, 83, 279, 288, 462, 716, 939, 37510]]
split_list(nums, size=10) = [[1, 3, 8, 14, 26, 38, 59, 97, 535, 932], [462, 288, 279, 83, 64, 50, 4, 3, 3], [9, 19, 716, 939, 37510]]
split_list(nums, size=7) = [[1, 3, 8, 14, 26, 59, 535], [932, 462, 97, 64, 38, 3], [3, 50, 83, 279, 288], [939, 716, 19, 4], [9, 37510]]


text:
Q: Increase the Duration of a Toast Currently there only exist two duration for a Toast: Toast.LENGTH_SHORT and Toast.LENGTH_LONG...
But what if you want to increase the duration of a Toast in Android?
Here is a hack I came up with and wanted to share:
public void createToast(Context context, String s) {
    int duration = Toast.LENGTH_LONG;
    final Toast toast = Toast.makeText(context, s, duration);

    toast.show();

    new CountDownTimer(5000, 1000)
    {
        public void onTick(long millisUntilFinished) {
            if (toast.getView().getWindowToken() != null)
                toast.show();
            else
                cancel();
        }
        public void onFinish() {
            if (toast.getView().getWindowToken() !=null)
                toast.show();
            else
                cancel();
        }

    }.start();
}

If you want a longer toast, just increase the duration of the CountDownTimer.
Please make note of the lines
if (toast.getView().getWindowToken !=null)

If the windowToken of the toast is null, that is pretty much saying the Toast has already left the view, (i.e. the toast was canceled).
I found a few solutions online for increasing the duration of a toast, but I couldn't find one to preserve dismissal if the toast has been dismissed by the user.  So I pieced the above together to preserve normal Toast functionality.
Let me know what you think!

A: First of all, I don't see your question. If the question is "what do you think?", I doubt about the cases where you would need a Toast longer than Toast.LENGTH_LONG. If Toast.LENGTH_LONG if short, probably is better to use an AlertDialog.
Anyway, your solution seems a little heavy... you can stack the Toast messages, so you could make two or more Toasts with the same message and instantiate one after the other. The effect of this should be what you are looking for.

A: I posted this question a little wonky, what I was really looking to do was to share this following hack with everyone on how to make a Toast duration Longer in Android:
public void createToast(Context context, String s) {
     int duration = Toast.LENGTH_LONG;
     final Toast toast = Toast.makeText(context, s, duration);

     toast.show();

     new CountDownTimer(5000, 1000)
     {
         public void onTick(long millisUntilFinished) {
             if (toast.getView().getWindowToken() != null)
                 toast.show();
             else
                 cancel();
         }
         public void onFinish() {
             if (toast.getView().getWindowToken() !=null)
                 toast.show();
             else
                 cancel();
         }
     }.start();
}


text:
Q: Running multiple similar job files (sbatch) I am trying to run multiple (several hundred) very similar job-files with slurm using sbatch.
My .job file look like:
#SBATCH ...
...
...
srun ./someProg -a A -b B -c C -d D

Is there any convenient way to submit the job file using sbatch with multiple options for A/B/C and D and generating a new job for every combination of A/B/C/D, without just generating hundreds of .job files? (I have already seen a lot of arrays in slurm files, but I do not think it will help me here anyway.)

A:
without just generating hundreds of .job files?

You can use bash's Process Subsitution for replacing the creation of files:
#!/bin/bash

genjob() {
    local content
    IFS='' read -d '' -r content <<-EOF
        #!/bin/bash
        #SBATCH ...
        ...
        ...
        srun ./someProg $(printf '%q ' "$@")
    EOF
    printf '%s\n' "$content"
}

sbatch <(genjob -a A -b B -c C -d D)

important: The dash in <<-EOF means that the TAB characters at the beginning of each line of the Heredoc will be stripped; so the indentation must be done with TABs.

A: You say you have several hundred jobs like that. That may be more than your available core count, so you want to be careful how you submit it. You want to submit as many as possible, but not all of them at once.
Here are two utilities that accept an arbitrary long list of commandlines, and then spread them over the available nodes/cores:
https://github.com/TACC/launcher
https://github.com/TACC/pylauncher

A: I often pass the necessary information as arguments to the job file: The contents of the submit file (let's call it submit.sh) may look like this:
#SBATCH ...
...
...
srun ./someProg -a $1 -b $2 -c $3

In a second bash script i loop over all options that I need. The bash script could look like this:
#!/bin/bash

for aa in a1 a2 a3
do
  for bb in b1 b2 b3
  do
    for cc in c1 c2 c3
    do
      scommand="sbatch -J A=${aa},B=${bb},C=${cc} submit.sh $aa $bb $cc"
      echo "submit command: $scommand"
      $scommand
    done
  done
done

The -J option sets the name of the slurm job.


text:
Q: How to combine binary (PDF-) file chunks retrieved via a get function from an API Ive written a function which uses xmlhttprequest-ts and should help with asynchronously getting a pdf from an api.
That PDF gets then send to a frontend afterwards, where its unfortunately displayed empty.
I would guess that I somehow need to merge the single data chunks I receive, but I have no clue what to do after trying out a multitude of ways.
For Example Buffer.from() + Buffer.concat() results in an empty buffer Printed out after the promise was resolved. The seemingly closest solution I had, is the following, where i just add up a binary string:
export async function getFile(resourceUrl: string, apiPath: string, responseType:string, token?: string, basicId?:string, apiKey?:string,  ): Promise<any>{
  try {
  return new Promise((resolve, reject) => {
    var xhr = new XMLHttpRequest();

    xhr.open("GET", resourceUrl + apiPath, true);
    if(!isNullOrUndefined(apiKey)){
      xhr.setRequestHeader("api-key", apiKey);
    } else if(!isNullOrUndefined( token) && isNullOrUndefined(basicId)){
      xhr.setRequestHeader("Authorization", "Bearer " + token);
    } else if(!isNullOrUndefined( token) && !isNullOrUndefined(basicId)){
      xhr.setRequestHeader("Authorization", "Basic " + Buffer.from(basicId + ":" + token).toString('base64'));
    }

    xhr.setRequestHeader("Accept", responseType);

    let binaryString = ""; // initial binary string

    xhr.onload =  function (){
        try{
            if (xhr.readyState == 4 && xhr.status == 200 ) {
              console.log("Code: " + xhr.status + ": " + xhr.statusText +  "; Request success"  );

              binaryString = binaryString + xhr.responseText; //adding up binary string
            } else {
              console.log("Code: " + xhr.status + ": " +  xhr.statusText + "; "  + xhr.responseText);
              reject(new ErrorModule.xmlHttpServiceError(xhr.responseText, xhr.status , xhr.statusText, xhr.responseText ));
            }
        } catch(err){
          reject(err);
        }
    }

    xhr.onloadend = function (){
        try {
          if (xhr.readyState == 4 && xhr.status == 200 ) {

              resolve(binaryString); // returning binary string
            } else {
              console.log("Code: " + xhr.status + ": " +  xhr.statusText + "; "  + xhr.responseText);
              reject(new ErrorModule.xmlHttpServiceError(xhr.responseText, xhr.status , xhr.statusText, xhr.responseText ));
            }
          } catch(err){
            reject(err);
          }
      }

    xhr.send();

    });
} catch(err){
throw new Error(err);
}

}
When I print out the binary string after resolving, you can clearly see that there are multiple of chunks after each other in the following pattern (taken from the end of the string):
C}O�����D.��w�#n]:ީ��qqUX��N+��;�RD����]��}�_ܝ�%�/
                                             �
                                              ˢ)�"�r���L��U�Y�TI(@fu����Y���Z���x�Y+�Үµ-

    .8d�P�+e�����4��N�    [�
                                                                                ������+��b�Z]�6����D�/�(q�2��0Ӣ�Z�HeA�� ��Y
endstream
endobj
16 0 obj
<</Type /FontDescriptor
/FontName /Arial-BoldMT
/Flags 4
/Ascent 905.27344
/Descent -211.91406
/StemV 76.171875
/CapHeight 715.82031
/ItalicAngle 0
/FontBBox [-627.92969 -376.46484 2033.6914 1047.85156]
/FontFile2 15 0 R>>
endobj
17 0 obj
<</Type /Font
/FontDescriptor 16 0 R
/BaseFont /Arial-BoldMT
/Subtype /CIDFontType2
/CIDToGIDMap /Identity
/CIDSystemInfo <</Registry (Adobe)
/Ordering (Identity)
/Supplement 0>>
/W [0 [750] 3 17 277.83203 21 23 556.15234 40 [666.99219 0 777.83203] 51 [666.99219] 68 [556.15234 610.83984 0 0 556.15234 0 610.83984 0 277.83203 0 0 277.83203 889.16016 610.83984 610.83984 0 0 389.16016 556.15234 333.00781] 93 [500] 188 [556.15234]]
/DW 0>>
endobj
18 0 obj
<</Filter /FlateDecode
/Length 320>> stream
x�]��n�0
        ��<E�ݡ��P6     !1�J�G�{ ��.QH���M;i� ���3v��n�ў�n�-x�k�L��I`g�hq���~%|ˡ�Q��<yӏQQ0�����6�����N����6_u�Z�ϒ�,��>dz��[7 �ѶmT�k?o��Oq�-0�̩9*�l'�u�Q��U��V�Q��|��{��9
��<IDR"�j$Ή^��#R�UD9Ҏ�d�%%垔))��Lk�'�쀔WH�KL$U���5�����
                                                       M<��NP��V��I�d�6���$�s����/G���>yu.��3XN__;�ŵ<�����
endstream
endobj
7 0 obj
<</Type /Font
/Subtype /Type0
/BaseFont /Arial-BoldMT
/Encoding /Identity-H
/DescendantFonts [17 0 R]
/ToUnicode 18 0 R>>
endobj
xref
0 19
0000000000 65535 f
0000000015 00000 n
0000071700 00000 n
0000000154 00000 n
0000000191 00000 n
0000048619 00000 n
0000094566 00000 n
0000109180 00000 n
0000069862 00000 n
0000071953 00000 n
0000072008 00000 n
0000072056 00000 n
0000093141 00000 n
0000093375 00000 n
0000094148 00000 n
0000094698 00000 n
0000108095 00000 n
0000108334 00000 n
0000108789 00000 n
trailer
<</Size 19
/Root 10 0 R
/Info 1 0 R>>
startxref
109317
%%EOF


text:
Q: How to make delay and delete a text? First post!
I'm beginner in java.
My code use switch/case for display an CardLayout in relation with text in "codeCD".
I want to display CardLayout[1-7] just for 5 seconds and delete text in "codeCD" for return to cardLayout[0] 'menu'.
I test method "sleep and wait" but didn't work. I don't know how use sleep method with try and catch.
//++zone JTextField++

        ZoneText.setPreferredSize(new Dimension(300,25));

        ZoneText.setBackground(Color.decode("#0d141e"));
        ZoneText.add(codeCD);

        codeCD.requestFocus(true);
        codeCD.setColumns(7);
        codeCD.setOpaque(false);

        //**check input on textfield**
        codeCD.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {

                super.keyTyped(e);

                if (codeCD.getText().length() >= 7 ) // limit textfield to 7 characters
                    e.consume();

                switch (codeCD.getText()) {
                    //---CARDLAYOUT 1---
                    case "6524875":
                        pile.show(pileCard, listContent[1]);
                        break;

                    //---CARDLAYOUT 2---
                    case "7854862":
                        pile.show(pileCard, listContent[2]);
                        break;

                    //---CARDLAYOUT 3---
                    case "8632547":
                        pile.show(pileCard, listContent[3]);
                        break;

                    //---CARDLAYOUT 4---
                    case "1447559":
                        pile.show(pileCard, listContent[4]);
                        break;

                    //---CARDLAYOUT 5---
                    case "3567487":
                        pile.show(pileCard, listContent[5]);
                        break;

                    //---CARDLAYOUT 6---
                    case "5556897":
                        pile.show(pileCard, listContent[6]);
                        break;

                    //---CARDLAYOUT 7---
                    case "3558774":
                        pile.show(pileCard, listContent[7]);
                        break;

                    //---MENU DEFAULT---
                    default:
                        pile.show(pileCard, listContent[0]);
                        break;
                }
            }
        });
        //--zone JTextField--


text:
Q: Sample Browser Visual Studio (2012) Extension does not show samples After downloading, when i click "open" button, i get this message:
This command needs a single parameter that contains 9 pipe-separated parts. Only 10 part(s) detected in the given parameter.
Does anybody know how to fix it?


text:
Q: Spring WS SOAP Response Header modification in EndPoint class I am new to Spring WS and in the midst of implementing a service.
For this, I am using EndPoint class and can successfully receive a request and send response.
The SOAP Request message contains vital information in SOAP header which I successfully extract. Some information must be sent in SOAP response header also but I am unable to edit or modify the SOAP response header.
I will need help in understanding on what is the best way and best practice to create SOAP Response header together with SOAP Response message.
You can find my EndPoint class below:
 @Endpoint
public class EndpointAccountInformationInquiry {

    private static final String TARGET_NAMESPACE = "http://www.sample.com/inquiry/GetAccountInformation";

    @Autowired
    private ServiceAccountInformation service;

    @PayloadRoot(localPart = "GetAccountInformationRq", namespace = TARGET_NAMESPACE)
    public @ResponsePayload GetAccountInformationRs handleRequest(@RequestPayload GetAccountInformationRq request, MessageContext messageContext) throws JAXBException, TransformerException {

        /*****************************************************************
         * Parse the request header and body
         * Also create response body and header
         *****************************************************************/
        SaajSoapMessage soapRequest = (SaajSoapMessage) messageContext.getRequest();
        SoapHeader soapRequestHeader = soapRequest.getSoapHeader();

        SaajSoapMessage soapResponse = (SaajSoapMessage) messageContext.getResponse();
        SoapHeader soapResponseHeader = soapResponse.getSoapHeader();

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();

        MyHeaderClassRq myHeaderClassRq = null;
        JAXBContext jaxbContext = JAXBContext.newInstance(MyHeaderClassRq.class);
        Iterator<SoapHeaderElement> itr = soapRequestHeader.examineAllHeaderElements();
        while (itr.hasNext()) {
            SoapHeaderElement ele = itr.next();

            myHeaderClassRq = (MyHeaderClassRq)jaxbContext.createUnmarshaller().unmarshal(ele.getSource());
            transformer.transform(ele.getSource(), soapResponseHeader.getResult());
        }

        /*****************************************************************
         * Call the handler function
         * This handler function is asynchronous
         *****************************************************************/
        service.handleRequest(request, msgHdrRq);

        /*****************************************************************
         * Set the response body and header over here
         *****************************************************************/
         //TODO: I want to modify my response header over here....

        GetAccountInformationRs response = new GetAccountInformationRs();
        return response;
    }
}

A: I have solved it myself.
You can see the below code in section:
/*****************************************************************
*Create response body and header
*And send back
*****************************************************************/
 @Endpoint
public class EndpointAccountInformationInquiry {

//  private Logger logger = Logger.getLogger(EndpointAccountInformationInquiry.class);

    private static final String TARGET_NAMESPACE = "http://www.sample.com/inquiry/GetAccountInformation";

    @Autowired
    private ServiceAccountInformation service;

    @PayloadRoot(localPart = "GetAccountInformationRq", namespace = TARGET_NAMESPACE)
    public @ResponsePayload GetAccountInformationRs handleRequest(@RequestPayload GetAccountInformationRq request, MessageContext messageContext) throws JAXBException, TransformerException {

        /*****************************************************************
         * Parse the request header and body
         * Also create response body and header
         *****************************************************************/
        SaajSoapMessage soapRequest = (SaajSoapMessage) messageContext.getRequest();
        SoapHeader soapRequestHeader = soapRequest.getSoapHeader();

        SaajSoapMessage soapResponse = (SaajSoapMessage) messageContext.getResponse();
        SoapHeader soapResponseHeader = soapResponse.getSoapHeader();

        MyHeaderClassRq myHeaderClassRq = null;
        JAXBContext jaxbContext = JAXBContext.newInstance(MyHeaderClassRq.class);
        Iterator<SoapHeaderElement> itr = reqheader.examineAllHeaderElements();
        while (itr.hasNext()) {
            SoapHeaderElement ele = itr.next();
            myHeaderClassRq = (MyHeaderClassRq)jaxbContext.createUnmarshaller().unmarshal(ele.getSource());
        }

        /*****************************************************************
         * Call the handler function
         * This handler function is asynchronous
         *****************************************************************/
        service.handleRequest(request, myHeaderClassRq);

        /*****************************************************************
         * Create response body and header
         * And send back
         *****************************************************************/
        //Response header
        MyHeaderClassRs myHeaderClassRs = new MsgHdrRs();
        //Set header values here

        //Response body
        GetAccountInformationRs response = new GetAccountInformationRs();

        /*****************************************************************
         * Send response back
         *****************************************************************/
        jaxbContext = JAXBContext.newInstance(MyHeaderClassRs.class);
        jaxbContext.createMarshaller().marshal(myHeaderClassRs, soapResponseHeader.getResult());

        return response;
    }
}


text:
Q: find the periodicity of a modular function I created my own version of the fractal (which in fact takes the same principle as the Pythagorean tree).
If you want to know what this gives you can do a little tour here.
    var myCanvas = document.getElementById('cnv');
    var ctx =  myCanvas.getContext('2d');
    myCanvas.style.backgroundColor =  "rgba(0, 0, 0, 0.1)";

My draw function like this.
  function draw(x, y, len, angle) {
    ctx.beginPath();
    ctx.save();
    ctx.translate(x, y);
    ctx.rotate((angle * Math.sin(len)) );
    ctx.moveTo(0, 0);
    ctx.lineTo(0, -len);
    ctx.stroke();
    ctx.strokeStyle = "grey";

    if(len < 1) {
      ctx.restore();
      return;
    }
    var slider = document.getElementById("myRangeAngle");
    slider.oninput =  function() {
      var  p = document.getElementById('p');
      p.innerHTML = "L'angle : " + slider.value;
      ctx.clearRect(0, 0, 1366, 900);
      draw(550,578,120,0);
    }
   draw(0, -len, len*0.7, - slider.value);
   draw(0, -len, len*0.7, slider.value);
   ctx.restore();
  }

  draw(550,578,200,0);

https://codepen.io/m-metore/pen/Mxvqdq
Here is my problem I have an iterative function, U0 = 200; A + 1 = A * 0.7
or Un = U0 * 0.7 ^ n.
Then I multiply my angle x in (rad) by this formula:
f (x) = x * sin (Un).
My question is is there an integer x for which (fx) gives an integer.
In other words, we must solve x * sin (U0 * 0.7 ^ n) = 2 * PI; (where x and n are integers) and we look for x (which is an integer)
I specify that U0 = 200;
I do not think there is an x such that this equation is true. Do you have any idea of how to prove it?
thank you

A: according to the Lindemann-Weierstrass theorem sin (200 * O.7 ^ n) is a transcendent number https://planetmath.org/proofoflindemannweierstrasstheoremandthateandpiaretranscendental
so I have to show that arcsin (2 * PI / x) is an irrational number.

The best way to do this is to try some k (anyway, you do not want big
  k).

in fact I want to demonstrate for all numbers k that's why.
Thank you for your help !


text:
Q: ASP.NET C# - Unable to upload image I'm trying to upload an image by form in ASP.NET
This is my model
    public class ItemTypeModels
{
    [Key]
    [Required]
    public int ItemTypeID { get; set; }

    [Required]
    public int CategoryID { get; set; }
    public CategoryModels models { get; set; }

    [Required]
    public string ItemTypeName { get; set; }

    [Required]
    public string ItemTypeImageName { get; set; }

    [NotMapped]
    public HttpPostedFileBase UploadedFile { get; set; }
}

This is my Create Page
@using (Html.BeginForm("Create","ItemTypeModels",FormMethod.Post, new { enctype = "multipart/form-data" }))
  {
      @Html.AntiForgeryToken()

ItemTypeModels

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.CategoryID, "CategoryID", htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.DropDownList("CategoryID", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.CategoryID, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.ItemTypeName, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.ItemTypeName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.ItemTypeName, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.ItemTypeImageName, htmlAttributes: new { @class = "control-label col-md-2" })

            <input type="file" name="UploadedFile" required />

            <input type="submit" value="Create" class="btn btn-default" />

}
And finally, this is my POST Method
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ItemTypeID,CategoryID,ItemTypeName,ItemTypeImageName")] ItemTypeModels itemTypeModels)
    {
        if (ModelState.IsValid)
        {
            string fileName = Path.GetFileNameWithoutExtension(itemTypeModels.UploadedFile.FileName);
            string extension = Path.GetExtension(itemTypeModels.UploadedFile.FileName);
            fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension;
            itemTypeModels.ItemTypeImageName = "~/Image/" + fileName;
            fileName = Path.Combine(Server.MapPath("~/Image/"), fileName);
            itemTypeModels.UploadedFile.SaveAs(fileName);
            db.ItemTypeModels.Add(itemTypeModels);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.CategoryID = new SelectList(db.Categorymodels, "CategoryID", "CategoryName", itemTypeModels.CategoryID);
        return View(itemTypeModels);
    }

Whenever I press the Create button on the Create page, the fields (Category + Name) stay filled, however the image uploader gets reset and states no file chosen. I did follow the tutorial that I used properly, so i'm not sure as to why the issue is having, I have also created the folder that the image is meant to be saved in. When I check the database, the data isn't being saved either.

A: Refer This link How to Upload Files in ASP.NET MVC
your action method must accept HttpPostedFileBase:
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
  // your code
}


text:
Q: Test (rspec) a module inside a class (Ruby, Rails) I have this to work with...
class LegoFactory # file_num_one.rb

  include Butter # this is where the module is included that I want to test.
  include SomthingElse
  include Jelly

  def initialize(for_nothing)
    @something = for_nothing
  end
end

class LegoFactory # file_num_2.rb
  module Butter

    def find_me
      # test me!
    end
  end
end

So, when LegoFactory.new("hello") we get the find_me method as an instance method of the instantiated LegoFactory.
However, there are quite a few modules includes in the class and I just want to separate the Butter module without instantiating the LegoFactory class.
I want to test ONLY the Butter module inside of the LegoFactory. Names are made up for this example.
Can this be done?
Note: I cannot restructure the code base, I have to work with what I have. I want to just test the individual module without the complexity of the rest of the LegoFactory class and its other included modules.

A: A way to do it is to create a fake class that includes your module in order to test it:
describe LegoFactory::Butter do
  let(:fake_lego_factory) do
    Class.new do
      include LegoFactory::Butter
    end
  end
  subject { fake_lego_factory.new }

  describe '#find_me' do
    it 'finds me' do
      expect(subject.find_me).to eq :me
    end
  end
end

You can also implement in the fake class a mocked version of any method required by find_me.


text:
Q: VBA/macro to move rows to various other sheets automatically Getting familiar with VBA/Macro's but still new and struggling. I've been able to piece together stuff by looking up examples on youtube videos and playing around with other codes posted online but I'm stuck and need major help
I've got four sheets on my workbook. All of them have the same layout, the first column is my header and has a filter. All the columns after L are hidden/deleted.
I copy/paste information into the first sheet (Feb – Monitor), from an application, "an example is on the text to column sheet). I have a macro to move everything to the correct columns which is run on the first sheet.
I'd like a macro for the first sheet so that when it's run, it'll do the following;
Look at information in column G and move them to the appropriate sheets in the next empty row.
Pending – Move anything that is "DA" or "I" to this sheet
Accepted - Move anything that is "AC" to this sheet
Released – Move anything that is "RL" to this sheet.
One thing to point out, there are blank spaces that appear in some of the cells in column G next to the characters ie "T " (two blank spaces after T) or "RT " (one blank space after RT)
For the other sheets, I'd like to know how to modify the code I have in "Module1" to automatically move rows for just the Pending, Accepted, and Released sheets to other sheets once you key in the specific status. I've played around with the code and can get it to work but it overwrites the first row instead of moving it an empty row.
Feb - Monitor - Anything keyed in as RT, T, RE, RJ is moved to the first sheet
Pending - Anything keyed in as DA or I moves to this sheet
Accepted - Anything keyed in as AC moves to this sheet.
Released - Anything keyed in as RL moves to this sheet.
Link to the spreadsheet on google drive.
https://drive.google.com/open?id=0B6fek87_mXuEMnVCRUtobVVqQU0
Much appreciated

A: There is a lot of if's in that answer.  Mostly in the "set ws" section.  To the right of each "set" command I put the strings that should be sent to those pages.  Are all of those correct?  And if so, when you import your data is it imported to  Worksheets("Feb - Monitor")?  And that is the main page you are searching for strings in column G?  If all of that is correct then this should work for you.  Make a copy of your workbook and try it in the copy first.  Create a plain module in the VBA editor and paste this into it.  It will copy rows based on strings found in column G and paste them into the appropriate pages.  If you want to remove those rows from  Worksheets("Feb - Monitor") after they have been copied to other pages then uncomment (remove the ') from nextRow = 2 on down.
Sub Macro1()
'Feb - Monitor - Anything keyed in as RT, T, RE, RJ
'is moved to the first sheet Pending -
'Anything keyed in as DA or I moves to this sheet Accepted -
'Anything keyed in as AC moves to this sheet. Released -
'Anything keyed in as RL moves to this sheet.

Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim ws3 As Worksheet
Dim ws4 As Worksheet
Dim lastRow As Long
Dim nextRow As Long
Dim myArray() As Variant

Set ws1 = Worksheets("Feb - Monitor") '  RT, T, RE, RJ
Set ws2 = Worksheets("Pending") '   DA, I
Set ws3 = Worksheets("Accepted") '  AC
Set ws4 = Worksheets("Released") '  RL

lastRow = ws1.Range("G65536").End(xlUp).Row

myArray = ws1.Range("G2:G" & lastRow)

 For i = LBound(myArray) To UBound(myArray)
    If InStr(1, myArray(i, 1), "T") > 0 And InStr(1, myArray(i, 1), "RT") = 0 Or _
        InStr(1, myArray(i, 1), "RT") > 0 Or InStr(1, myArray(i, 1), "RE") > 0 Or _
        InStr(1, myArray(i, 1), "RJ") > 0 Then
        ' These need to stay on Worksheets("Feb - Monitor") so we do nothing
        ' The reason I added this loop is in case I misunderstood your need
        ' This loop is not necessary if we are'nt moving them
    End If
    If InStr(1, myArray(i, 1), "DA") > 0 Or InStr(1, myArray(i, 1), "I") > 0 Then ' send to "Pending"
        nextRow = ws2.Range("G65536").End(xlUp).Row + 1

        ws1.Rows(i + 1).Copy Destination:=ws2.Range("A" & nextRow)
    End If
    If InStr(1, myArray(i, 1), "AC") > 0 Then ' send to "Accepted"
        nextRow = ws3.Range("G65536").End(xlUp).Row + 1
        ws1.Rows(i + 1).Copy Destination:=ws3.Range("A" & nextRow)
    End If
    If InStr(1, myArray(i, 1), "RL") > 0 Then ' send to "Released"
        nextRow = ws4.Range("G65536").End(xlUp).Row + 1
        ws1.Rows(i + 1).Copy Destination:=ws4.Range("A" & nextRow)
    End If

Next i

'*********************************************
'   The following code deletes all rows on worksheets("Feb - Monotor)
'   that are not RT, T, RE, RJ
'   You can uncomment it if you want to do that

'nextRow = 2
'For i = LBound(myArray) To UBound(myArray)
'    nextRow = nextRow + 1
'    If InStr(1, myArray(i, 1), "DA") > 0 Or InStr(1, myArray(i, 1), "I") > 0 _
'        Or InStr(1, myArray(i, 1), "AC") Or InStr(1, myArray(i, 1), "RL") > 0 Then
'        nextRow = nextRow - 1
'        Debug.Print i, myArray(i, 1), nextRow
'        ws1.Rows(nextRow).Delete Shift:=xlUp
'    End If
'Next i

Set ws1 = Nothing
Set ws2 = Nothing
Set ws3 = Nothing
Set ws4 = Nothing

End Sub


text:
Q: Which is the physical insight behind the widely approved 'space vector' notation used in the analysis of the dynamic model of electric machines? When approaching the study of electric machines in transient condition, it is customary to discard the real physical vector quantities like magnetic field and magnetic induction and to define fake vectors like flux linkages, currents and voltages (among which there also induced electromotive forces) which are directed along the magnetic axis of a certain coil (for instance in a three phase winding system) and have the magnitude equal to the actual scalar value.
I have read that they are not intended exactly as physical vectors, rather as complex numbers, lying on a complex plane which is the shadow of the actual plane defined by a cross section of the machine: for instance the real axis is aligned with the phase 'A' magnetic axis and the other two phases 'B' and 'C' windings correspond to a couple of complex conjugate points; then, such quantities are used, without any particular derivation, as actual vector lying in the cartesian space (for instance the flux has component along two orthogonal axes, usually called \$\alpha, \beta\$ or \$d,q\$).
I perfecly understand, that, in order to simplify the analysis and improve the understanding of a complex system like an electromagnetic device, a certain abstraction, which requires to define also artificial entities, is needed, but I cannot see the reason why such 'abuse of notation' is physically legitimized, in fact I am not sure if it is still an abuse of notation or directly a misuse of notation.
The most confusing situation is the anisotropic (salient pole) rotor used inside synchronous machines, where, for instance, the flux produced by a sinusoidally distributed winding in the stator, linked with another distributed winding (which can be the same phase or another) is simply computed using direct flux and quadrature flux as fluxes produced when the rotor is aligned or in quadrature with that winding.
I think that, when dealing with physical phenomena, before using powerful mathematical tools like these, one should prove that they produce the same result of a strict physical approach (just like when Maxwell equations are replaced by other theoretical tools, like circuit theory or transmission lines, after showing that this is actually possible, not only sought). I hope someone can help me understand this formalism.
EDIT:
In order to better explain the problem, if a winding of a certain phase, no matter what, is distributed along the stator inner periphery, it is accustomed to consider the field it produces as sinusoidal (considering just the first angular harmonic) and the coil distribution can be approximated as sinusoidal as well, centred about the winding magnetic axis. Now to compute the mutual inductance between two stator phases, one should compute the flux linkage of a differential coil (in the angular span between \$\theta\$ and \$\theta +\mathrm{d} \theta\$) produced by the sinusoidal field produced by another winding, then integrate this infinitesimal contribution along all the flat angle, whereas often the problem is roughly solved drawing a flux vector (which is not a vector) and decomposing it along the axes of the other windings, like there were just single loop coil for each phase (non distributed windings).

A: Perhaps your difficulty is that the frame of reference or the "space" containing the magnetic flux and force vectors is rotating rather than fixed to points on the structure of the machine. In induction motors, the frame of reference rotates with respect to both the stator and the rotor, moving at the synchronous speed with respect to the stator and at the slip speed with respect to the rotor. In synchronous motors, the frame of reference is fixed with respect to the rotor, but rotates at the synchronous speed with respect to the stator. Thus the vector representations of the fluxes and forces have fixed positions with respect to the phase-vector representations of the AC voltages and currents.
I believe that this representation is developed by first examining the vectors with respect to the windings in the machine without considering the motion of the rotor and then examining the machine operating at a steady-state speed.
Equivalent Circuits
The analysis and control of electric machines makes use of equivalent electric circuits that are mathematically analogous to electromagnetic machines. They have a basis in physics, but that basis may not be as firm and direct as you might like. Engineers generally use the tools that will provide answers with a level of accuracy that is suitable for the ultimate purpose. Scientists strive to explain the laws of nature as thoroughly and accurately as humanly possible. Engineers strive to design products that are useful to human endeavors and economically affordable.
Terminology
Not all engineering terminology is carefully thought out. Even terminology that is carefully created is often simplified in everyday use. As a result, some terminology can have more than one meaning depending on context.  I suspect that engineers are more tolerant of imprecise terminology than scientists may be.


text:
Q: Display Angular drop down list from Java HashMap I want to display HashMap in Angular app using GET request from Spring Application. I tried this:
Spring code:
@GetMapping("gateways")
public ResponseEntity<?> getGateways() {
    Map<Integer, String> list = new HashMap<>();
    list.put(1, "Bogus");
    return ok(list.put);
}

Angular Service:
getContractGatewaysList(): Observable<Array<ContractGatewaysList>> {
    return this.http.get<Array<ContractGatewaysList>>(environment.api.urls.contracts.getContractGateways);
  }

Angular component:
gateways: ContractGatewaysList[];

this.contractService.getContractGatewaysList()
      .subscribe(value => {
        if (value != null) {
          this.gateways = value;
        }
      });

Interface:
export interface ContractGatewaysList {
  id: number;
  name: string;
}

HTML code:

      Gateway

    <select class="custom-select" name="gateway" [(ngModel)]="contract.gateway" id="gateway" required>
      <option selected>Please Select...</option>
      <option [value]="gateway.id" *ngFor="let gateway of gateways">{{ gateway.name }}</option>
    </select>

But I get empty list. What is the proper way to convert the Java Hashmap and display the values in Angular drop down menu? Can you show me working code example, please because I'm stuck with this problem?
I get this error:
ERROR Error: Cannot find a differ supporting object '3873648042962238500' of type 'number'. NgFor only supports binding to Iterables such as Arrays.
    at NgForOf.push../node_modules/@angular/common/fesm5/common.js.NgForOf.ngDoCheck (common.js:3152)
    at checkAndUpdateDirectiveInline (core.js:9246)
    at checkAndUpdateNodeInline (core.js:10507)
    at checkAndUpdateNode (core.js:10469)
    at debugCheckAndUpdateNode (core.js:11102)
    at debugCheckDirectivesFn (core.js:11062)
    at Object.eval [as updateDirectives] (ContractNewComponent.html:50)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:11054)
    at checkAndUpdateView (core.js:10451)
    at callViewAction (core.js:10692)

A: The Java/Spring code looks incorrect. I wonder if the statement return ok(list.put) even compiles as put is a method.
The Error: Cannot find a differ supporting object... error you provided is a client side error and would not be very useful if the root cause is at the server (i.e. REST API call).
Instead of looking at this as an 'Angular' related issue, I suggest confirming that the server is actually returning a proper JSON object with key value pairs.

*

*Make sure server side is returning data as expected BEFORE you even look at Angular/client side codes. Directly access the spring boot REST API using Chrome or REST API clients like Postman.

*If you see errors, check server side (Java/Spring) log/exceptions.

*Here is an example on how to convert a Java map object to JSON data that can be consumed by clients. As with Spring framework, there are multiple ways, so do check the official documentation for details.

*Once confirmed that server side code works as expected, then integrating Angular code should be easier.
Hope this helps. Good luck!

A: Your response will be something like:
{1:"Bogus"}

It's not possible to map this flat JSON to gateways as it's of array type.
Solution:
1.
You need to iterate response JSON and by key fetch it's value and push data to gateways.
for (var key in responseObject) {
  console.log(key, responseObject[key]);
  // here push data `gateways`, you will find lots of tutorial to push data in array
}

You can even have var keys = Object.keys(yourobject); and then you can iterate this keys and get value of specific key from your response object.
Choice is yours, what you need to implement.

*You can send angular compatible response from Java/Spring so it will bind to gateways directly if all the structure and keys are valid.


text:
Q: How to flip index of jquery's each?
Possible Duplicate:
JQuery .each() backwards

I am using this code to show each div -> this with a delay an an animation:
$.fn.slideDelay = function(){
    var delay = 0;
    return this.each(function(){
        $(this).delay(delay).animate({
            opacity: 1,
            top: 0
        }, 2000);
        delay += 1000;
    });
};

Works well so far... the only Problem i got is that i need to start with the last index not the first one. Which means the last div gets animated first then the beforelast and so on until the first one.

A: Theoretically the following should work:
$.fn.slideDelay = function() {
    var len = this.length,
        delay = (len - 1) * 1000;

    return this.each(function() {
        $(this).delay(delay).animate({
            opacity: 1,
            top: 0
        }, 2000);
        delay -= 1000;
    });
};

DEMO: http://jsfiddle.net/q4cGP/

A: You could reverse the collection...
collection = Array.prototype.reverse.call(collection);

jsFiddle.

A: Just retrieve the array from your jQuery object and reverse it:
var items = jQuery(this).get();
items.reverse();
jQuery.each(items, function() {.....

A: Map the delay with a function like this:
$.fn.slideDelay = function(){
    var max = this.length - 1;
    return this.each(function(i){
        $(this).delay((max - i) * 1000).animate({
            opacity: 1,
            top: 0
        }, 2000);
    });
};


text:
Q: loop enumerate objects in radioButton Hello i want to loop this object in checkbox value and index
 data: [
        {
        key1: 'last 6 months'
      },
      {
        key2: 'last 30 days'
      }
    ]

i want to create a radioButton like this
° last 6 months
° last 30 days
i'm do that in my code

                    <radio-button
                      v-model="date"
                      :value="index"
                      :label="index"
                    />

my results is
° key1
° key2
i wan't to recover value in label not key because the key is send to api
Please help thank you

A: Iterate an object
When iterating an object with v-for, the object value is the first argument, then the object key. And since the object key is unique, you can use that as the key binding:

The label prop of <radio-button> should be bound to the object value, which is descriptive text; and the value prop could be bound to either the object value or object key, depending on what you want the v-model to reflect:
<radio-button v-model="date" :value="key" :label="value" />

The final result should be similiar to:

  <radio-button name="my-date" v-model="date" :value="key" :label="value" />

demo 1
Iterate an array of objects
Nest the solution above in another v-for. The outer v-for iterates the array, while the inner one iterates the the object:
<template v-for="item in data">

    <radio-button name="my-date" v-model="date" :value="key" :label="value" />

</template>

demo 2


text:
Q: Size of the HTML page for all screens I am new to web designing. I had just build a web page but now it is not looking accurate as it was built.
Right Now i have just built a container with:
#container {
    width:auto;
    height:auto;
    border:4px solid green;
}

Question: How do I fix the height & width of the page for all screens & sizes.

A: Here you go
html,body{
    height:100%;
    margin:0
}
.container
{
    width:auto; /*Since div is block element, it takes automatic full width*/
    height:100%;
    background:grey;
    border:4px solid green;
}

DEMO

A: Having height:100%; plus a 4px border will always exceed the height of the page, and will cause scroll bars to appear at all times


text:
Q: Error adding service reference So I'm trying to add a service reference in WebForms 4.5 project.
I keep getting a same error message:

The configuration for the service reference could not be added due to
  the following error: An error occurred creating the configuration
  section handler for system.ServiceModel/bindings: AssemblyResolveEvent
  handlers cannot return Assemblies loaded for reflexion only.

You can test this service to add : http://beeyepoll.azurewebsites.net/apis/PollsService.asmx
It works in every project, except this one :(

A: Ended up creating separate DLL project and importing service reference there. Still don`t know why it did not work directly in the main project.


text:
Q: Javascript Regex parsing a string to numbers and doing some calucations I am scraping some data and trying to parse some strings into numbers
So for example, I have an object like "(7 years 1 month)" and I want to parse it to count total months.
This code works, but it's a bit messy. Is there an easier way to simplify it?
var str = "(7 years 1 month)"

function calculateMonths(str){
        var parseTime = /\d*/;
        var findMonths = /\d*\s\month/;
        var monthsTime = str.match(findMonths)
        if (monthsTime == null) {
            var months = 0
        } else {
            r = monthsTime[0];
            var y = r.match(parseTime)
            var months = y[0]
            return months
        }
    }

    function calculateYears(str){
        var parseTime = /\d*/;
        var findYears = /\d*\s\year/;
        var yearsTime = str.match(findYears);
        if (yearsTime == null) {
            var years = 0
        } else {
            r = yearsTime[0];
            var x = r.match(parseTime);
            var years = x[0];
        }
        return years
    }

A: you can just split the string using split(" ") which will return you an array, then loop over the array and add months based on years and month. something like this:

var str = "(7 years 1 month)";
var arr = str.replace(/[()]/g, "").split(/\s/), totalMonths = 0;
arr.forEach((x,index) => {
   switch(x){
   case 'years':
       totalMonths += +arr[index-1]*12;
       break;
   case 'month':
       totalMonths += +arr[index-1];
       break;
   }

})
console.log(totalMonths);