text:
Q: How to check if a undirected cycle is formed given a set of edges and what is its complexity? I have been given only a set of edges and asked if there is a cycle in the graph (graph may not be connected). I know it can be easily solved using a simple DFS. But I would like to know if there is any other method with reduced complexity as I may receive multiple such queries to check for cycles and running dfs every time would give O(nq) complexity, n number of edges and q number of queries.

A: You can use Disjoint sets, It can find all cycles in O(E) (E is number of edges)
What it does:

*

*Keeps track of which nodes are connected, directly or indirectly
(Meaning the two nodes are in the same set).

*Put two nodes in the same set. (Meaning they are
connected). Actually, it does a union of the two sets these nodes are from.
Disjoint set does both of these operations in O(1).
Here's how I implement Disjoint set with path compression:
#include <iostream>
#include <cstdio>

using namespace std;

// This array is used to represent a backward tree (Forest actually)
// all nodes part of a tree are in the same set
int disjointset[1000];

// at first all nodes are separated
// that is they are part of a 1 element set
void initialize(int n){
    for(int i= 0; i<=n; i++){
        disjointset[i]= i;
    }
}

// get the root parent of node a in disjoint tree structure
int getParent(int a){
    if(disjointset[a] == a)
        return a;

    // we do this assignment to shorten the path from this node to it's top ancestor in tree
    // this is called path compression
    disjointset[a] = getParent(disjointset[a]);

    return disjointset[a];
}

// check if two nodes are directly/indirectly connected
bool connected(int a, int b){
    return getParent(a) == getParent(b);
}

// join two nodes a and b, after this they will be connected
void join(int a, int b){
    disjointset[getParent(a)] = getParent(b);
}

int main(){
    //freopen("F:/input.txt", "r", stdin);

    // n nodes, e edges
    int n, e, u, v;

    cin>>n>>e;   // e number of edges

    //initialize the backward tree of disjoint set
    initialize(n);

    for(int i= 0; i<e; i++){
        cin>>u>>v;

        if(connected(u, v)){
            cout<< "Cycle found"<<endl;
        }

        join(u,v);
    }

}

/*

//sample input
//6 nodes 6 edges
6 6
1 2
2 3
1 3
3 4
3 5
4 6

*/

Note: Inserting the same edge multiple times will be counted as a cycle.


text:
Q: footer ignores content in the middle I want to add a footer to the bottom of the page, but it stays in middle, after like header content, and like ignores content below, so it stays in the middle.

Custom clearance

Our employee proceeds the necessary customs documentation for exports, imports and transit of cargo. Our knowledge of the Latvian customs and tax legislation and our familiarity with.
Learn more

Cargo Inspections

                        Наш сотрудник переходит необходимой документации для таможенного экспорта, импорта и транзита грузов. Наши знания латышского таможенного и налоговогои.
Learn more

Our Location

                        Mūsu darbinieks ieņēmumi nepieciešamo muitas dokumentāciju, eksporta, importa un tranzīta kravas. Mūsu zināšanas par Latvijas muitas un nodokļu tiību aktus un mūsu.
Learn more

content class style
#content {
    width: 100%;
    height:100%;
    display: block;
}
 #content ul li {
    display: block;
    list-style: none;
    float: left;
    min-width:15%;
}

#content  ul li > h3 {
    text-decoration: none;
    display:block;
    float:left;
    font-size: 24px;
    margin: 0 0 0 20px;
    font-family: gothamlight;
    padding: 10px 20px 10px 20px;
 }
 #content  ul li > img {
    display: block;
    float:left;
    margin: 0 0 0 10px;
    padding: 0px 25px 0px 25px;
 }

  #content  ul li > p {
    text-decoration: none;
    line-height: 1.3;
    display:block;
    color: #404041;
    float:left;
    font-size: 14px;
    margin: 0 0 0 20px;
    padding: 5px 20px 5px 20px;
    display: block;
 }

And here is the footers style, which is ok.
 #footer {
    position:absolute;
    bottom:0;
    width:100%;
    height:60px;   /* Height of the footer */
    background:#6cf;
 }

A: Change position to fixed
#footer {
  position:fixed;
  bottom:0;
  width:100%;
  height:60px;   /* Height of the footer */
 background:#6cf;
 }

A: #footer{position:absolute;bottom:0; clear:both;}

redpajama_set_name: RedPajamaStackExchange


text:
Q: UWP : How to avoid style name(x:Name) in Templete Control Development? With UWP ( or WPF ), I add x:Name on my XAML-style.
and Style does not work at all with x:name. Why ?
Now, I am developing a Template control. To change style property with "SetValue", I have to add name on my Style. then I added name x:Name="MyStyleName" but It make problem.
Here is a simple example code with Style x:Name.
    <Grid Background="Black" Width="200" Height="200" >

        <Grid.Resources>
            <Style x:Name="MyStyleName"  TargetType="Ellipse">
                <Setter Property="Height" Value="100" />
                <Setter Property="Width" Value="100" />
                <Setter Property="Stroke" Value="Red"/>
            </Style>
        </Grid.Resources>

        <Ellipse x:Name="Circle1" />
        <Ellipse x:Name="Circle2" />

    </Grid>

Main reason that I add x:Name on style, During Template control development, I want to access STYLE by name.
        var _grid = this.GetTemplateChild(GRID_NAME) as Grid;
        if (_grid != null)
        {
            // change grid margin.
            _grid.Margin = new Thickness(0, 5, 0, 0);

            // get Style of Grid
            var _gridStyle = _grid .Resources[GRID_STYLE_NAME] as Style;
            if(_gridStyle != null)
            {
                // Change Gird Height as STYLE !
                _gridStyle.SetValue(FrameworkElement.HeightProperty, 10);

            }
        }

Is there any good way to avoid Style x:Name ??

A: You need to use x:Key instead for resources. It's mainly the identifier inside a ResourceDictionary.
But can we improve this? As I don't recommend hard-coded string like this. What if a developer that's using your control doesn't know that he needs to specify that style?
The solution to this is to create a GridStyle of type Style dependency property in your control, and bind it to your existing style in your XAML file (e.g. your Generic.xaml inside Themes folder where you put the default style of your control). This way, other developers can freely apply their own Grid style too.


text:
Q: Gender Neutral Salutation /Honorific In the context of addressing an unknown individual in an email/letter, how does one include persons belonging to the broad gender spectrum?
For instance, in binary terms Dear Mam/Sir was the norm for a while. What would be the appropriate/ widely accepted way to address an audience which could be non-binary, to ensure that any receiver is not offended?
As a specific scenario, assume that I am writing to a non-academic committee, therefore, the usage of First Name is ruled out ( being too personal), also I cannot use words such as Dear Professor (since the occupation is not Professor).
Note that I am aware of previous (old) questions on gender neutral words in a letter and this. Do we have any new words in current usage?
While I agree that "To whomsoever it may concern" may be used, as mentioned in one of the questions:

addressing the person by his/her title is a little more specific and evidence that you've put some thought into it.

A: As you've ruled out 'to whom it may concern' I would probably go for

Dear Committee Member(s)

As that it what they all are, and is relevant to the letter you are writing.
(s) depending on if it's a letter to each of them, or a singular letter to the goup.

A: As suggested in the comments "Dear members of the search committee" would be an excellent suggestion, or use "Dear head official of the search committee" for an "individual".
You might also use "Dear honorable search committee" to emphasize the "honorific" aspect of your question. You can decide.


text:
Q: Rijndael differences between C# and Java I need to write Java code for encrypting a string using AES (Rijndael).
There is an already working C# code that does this same encryption for the same purpose.
The C# code:
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.KeySize = 256;
rijndaelCipher.BlockSize = 256;
rijndaelCipher.Mode = CipherMode.CBC;
rijndaelCipher.Padding = PaddingMode.PKCS7;
byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(password); // password is 32 bytes long
byte[] keyBytes = new byte[32];
System.Array.Copy(pwdBytes, keyBytes, 32);
rijndaelCipher.Key = keyBytes;
rijndaelCipher.IV = keyBytes;
ICryptoTransform transform = rijndaelCipher.CreateEncryptor();

The Java code I came up with:
byte[] sessionKey = SENDER_KEY.getBytes(StandardCharsets.UTF_8);
byte[] iv = SENDER_KEY.getBytes(StandardCharsets.UTF_8) ;
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
SecretKeySpec secretKeySpec = new SecretKeySpec(sessionKey, "AES");

cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] cipheredText = cipher.doFinal(stringedXmlForSending.getBytes());

When I execute the Java code I get the exception:
java.security.InvalidAlgorithmParameterException: Wrong IV length: must be 16 bytes long
Is it true that I cannot write in Java Rijndael encryption which is using 32 bytes keys?
Another difference is that padding in the C# is PKCS7 while in Java there is PKCS5. Will it still work?

A: The basic Java Cryptographic Extensions only provide AES implementations which is compatible with Rijndael at 128-bit block size. You should use 128-bit BlockSize so that you are compatible with most implementations which implement AES. If you do then the padding is no problem, since PKCS#5 is the same as PKCS#7 padding in AES.
It's important to note that AES is standardized which Rijndael isn't.

A: I struggled significantly to get this working due to the padding issue. By theory PKCS#5 from java should match PKCS#7 padding from .Net . When I looked deeper into the issue I found that there is an issue with Base64  encoder. Java has different library to encode byte into base64. By default java uses Base64 from java.util and it gives padding issue. When I used the different library to achieve this purpose I could get the desired library.
org.apache.commons.codec.binary.Base64.encodeBase64String (byte[] encryptedtext)


text:
Q: Android spinner give a NullPointException Any ideas why this code throws a NullPointException?
    Spinner spinnerLoadLayouts = (Spinner)this.findViewById(R.id.spnLoadLay);

    ArrayAdapter<CharSequence> adapter =
    new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, new ArrayList<CharSequence>());

    adapter.add("aaa"); adapter.add("bbb");
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinnerLoadLayouts.setAdapter(adapter);

Thanks! :)

A: I guess that the View or Activity cannot find R.id.spnLoadLay
Quote:

findViewById: Returns: The View that has the given tag in the hierarchy or null

A: If the error is on the last line, then spinnerLoadLayouts is NULL.
This could be because you can only do this
(Spinner)this.findViewById(R.id.spnLoadLay);

If the spnLoadLay view is actually in the current view (is available in an XML you have allready called setContentView on for instance). If you haven't put that on the screen, you can't find it using findViewById. You need to use an Inflater for that


text:
Q: How can I success to download(with "fetch") the real world datasets of scikit-learn? I'm a beginner of Scikit-learn. If I run the code for download "the 20 newsgroups text dataset" of sklearn.datasets (The code is shown at https://scikit-learn.org/stable/datasets/real_world.html)
from sklearn.datasets import fetch_20newsgroups
newsgroups_train = fetch_20newsgroups(subset='train')

the following error is returned.
OSError                                   Traceback (most recent call last)
<ipython-input-17-ade32d7dd81b> in <module>
      1 from sklearn.datasets import fetch_20newsgroups
----> 2 newsgroups_train = fetch_20newsgroups(subset='train')

~\anaconda3\lib\site-packages\sklearn\utils\validation.py in inner_f(*args, **kwargs)
     61             extra_args = len(args) - len(all_args)
     62             if extra_args <= 0:
---> 63                 return f(*args, **kwargs)
     64
     65             # extra_args > 0

~\anaconda3\lib\site-packages\sklearn\datasets\_twenty_newsgroups.py in fetch_20newsgroups(data_home, subset, categories, shuffle, random_state, remove, download_if_missing, return_X_y)
    257             logger.info("Downloading 20news dataset. "
    258                         "This may take a few minutes.")
--> 259             cache = _download_20newsgroups(target_dir=twenty_home,
    260                                            cache_path=cache_path)
    261         else:

~\anaconda3\lib\site-packages\sklearn\datasets\_twenty_newsgroups.py in _download_20newsgroups(target_dir, cache_path)
     73
     74     logger.info("Downloading dataset from %s (14 MB)", ARCHIVE.url)
---> 75     archive_path = _fetch_remote(ARCHIVE, dirname=target_dir)
     76
     77     logger.debug("Decompressing %s", archive_path)

~\anaconda3\lib\site-packages\sklearn\datasets\_base.py in _fetch_remote(remote, dirname)
   1195     checksum = _sha256(file_path)
   1196
-> 1197     if remote.checksum != checksum:
   1198         raise IOError("{} has an SHA256 checksum ({}) "
   1199                       "differing from expected ({}), "

OSError: C:\Users\owner\scikit_learn_data\20news_home\20news-bydate.tar.gz has an SHA256 checksum (cb5c6e663e59b628d9016d3cb2a3992ad38811d846c04561c3fbfa58badcb1f7) differing from expected (8f1b2514ca22a5ade8fbb9cfa5727df95fa587f4c87b786e15c759fa66d95610), file may be corrupted.

The downloaded file size (C:\Users\owner\scikit_learn_data\20news_home\20news-bydate.tar.gz) is 1KB. However the real size of the file is about 14MB (http://qwone.com/~jason/20Newsgroups/).
Why fetch(downloading) does failed and how can I success downloading the file with 'fetch_20newsgroups'?
My OS is Windows10
Many thanks.

A: I found the reason. The reason is that our company blocked amazon website for the reason of security. so the downloading is failed. The 20 newsgroups text dataset maybe saved in amazon and scikit-learn module takes the data from it. Message from our company shows that 's3-eu-west-1.amazonaws.com/pfigshare-u-files' and 's3-eu-west-1.amazonaws.com/' are blocked.
Thanks to Kota Mori. Your answer gives me some hint. The URL is 'https://ndownloader.figshare.com/files/5975967' and if I copy it to web-browser, the address is changed to 'https://s3-eu-west-1.amazonaws.com/pfigshare-u-files/5975967/20newsbydate.tar.gz?...' and blocked image shows up.


text:
Q: add class to li when a tag inside is clicked i want to add a class to the li when the  tag is clicked i am using jQuery addclass but not sure how to get it to the LI

   Home

link 1

link 2

link 3

News

Contact

About

I hope this makes sense
Thanks in advance

A: You can achieve by adding following click function
$("ul.nav > li > a").click(function(){
     $(this).parent().addClass("your_class");
});

A: For efficiency, you should use a single delegated event handler attached to your .nav element:
If you want all the sibling element to remove that class use not.
e.g.
    $('.nav').on('click', 'li > a', function(){
          var $li = $(this).parent();
          $li.siblings().not($li.addClass('smclass')).removeClass('smclass');
    });

Note: Answers with .nav > li (emphasis on >) will only work for the top level links. You need to clarify if you want the same behaviour on all links (which this example currently does).
If you only wanted it to work on the top-level links it would be
    $('.nav').on('click', '> li > a', function(){
          var $li = $(this).parent();
          $li.siblings().not($li.addClass('smclass')).removeClass('smclass');
    });

A: You can use immediate child selector to target all direct child elements:
$('.nav > li > a').click(function(){
  $(this).parent().addClass('smclass')
});


text:
Q: In SwiftUI, how can I avoid redrawing a parent view while updating shared state data from a child view to avoid Navigation issues? Since Xcode 12.5, I am seeing a lot of "Unable to present. Please file a bug." console logs in the Xcode console which I remember not seeing prior to 12.5.
This message is shown when I am using NavigationLink from a parent view to navigate to a child view, and if logic in the child view updates one of the states that parent view depends on.
Below is a sample pseudo code where a list of messages are shown in the parent view, message detail is shown in the child view from a list, and lastly, independent settings child view.
struct MessageListView: View {
    ...
    @StateObject var messageList = MessageList()

    var body: some View {
        debugPrint("!!MessageListView has been redrawn!!")
        return VStack {
            NavigationLink(destination:SettingsView()){
                Text("Go to settings")
            }
            ForEach(messageList.data.sorted(by: {$0.key < $1.key}), id:\.key) { k, m in
                NavigationLink(destination:MessageView(message:...){
                    Text(m.text)
                }
            }
        }
    }
}

struct MessageView: View {
    ...
    @ObservedObject var messageList : MessageList
    @ObservedObject var message : Message
    ...
    var body: some View {
        Text(...)
        .onAppear {
            messageList.readAndIncrement(message.id) //<- This updates both this view & parent view.
        }
    }
}

class MessageList : ObservableObject {
    @Published var data : [String:Message] = [:]

    func readAndIncrement(id: String){
        //Modify one of the message in dictionary.
    }
}

So when user clicks on message and traverses the navigation like below,
MessageListView -> MessageView

As soon as MessageView appears on screen, it will increment message's "read count" due to at the logic in onAppear, which will update data in MessageListView at the same time.
As soon as that happens, it appears that the parent view, MessageListView which is observing MessageList objects gets updated, the two following things happen.

*

*debugPrint will print message !!MessageListView has been redrawn!! (from source code above) on console, which proves that the parent view has been updated while Navigation is currently showing child view.

*'Unable to present. Please file a bug.' console log gets shown on screen, probably because the update in the parent view "cannot" be presented on screen?

So SwiftUI seems to be throwing "Unable to present" error log when I am updating parent view's observed data while viewing & interacting in the child view, but I am unsure how I can properly fix to get rid of this error.
The reason that I am thinking this is not a bug, but my error is because of the following.
When user traverses into a completely different view, something like
MessageListView -> SettingsView

and if the following two conditions are met,

*

*The child view (SettingsView) does not use or rely on any of the parent view's state objects.

*Parent view's data model is updated by other means, such as from network updates/sync, periodic refresh, etc.

then the parent view (MessageListView) gets redrawn for its dependent model's every single update and the child view starts stacking itself like below.

At least, in the above case, Unable to present. Please file a bug. doesn't get shown in the console.
In the iOS 14.5 & Xcode 12.5 patch notes, the only comments related to NavigationLink is as follows, but that does not seem to be relevant to my case.

The destination of NavigationLink that only differs by local state now resets that state when switching between links as expected. (72117345)

So my question is... how can I properly manage states (or decouple them) in this case that won't cause funkiness in SwiftUI Navigation?
Is it against SwiftUI's paradigm to update parent view's state data while presenting child view on screen or is this simply a NavigationLink bug in Xcode 12.5?

A: I am answering my own question about the workaround that I found. The solution that worked for me is to use Class instead of Struct and update properties of the Class. This prevented the View, which is watching the @Published array/list, from getting updated.
Previously, I was using Struct for the Message type. What ended up happening is that any change to one of the properties of the struct/Message will trigger UI updates (which is expected), even if View is not directly watching the struct itself, but watching the list of structs (MessageList class's data property in my case.).
I converted Message from Struct to Class that implements ObservableObject and updates its properties. That prevented parent View, which dependent on the list of Messages from getting redrawn, when one of the list elements had to be updated.
In summary, when you assign @Published annotation to an array of Struct, list item addition/removal as well as any change to one of the properties of the struct item in the list will trigger dependent View updates in SwiftUI.
On the other hand, if you assign @Published annotation to an array of Class, only list item addition/removal will trigger SwiftUI update. Any change to one of the properties of the Class won't trigger dependent View updates in SwiftUI.


text:
Q: Cassandra long queries (33s for dropping empty table) Currently trying a setup for a large project.
The project will utilize tens of thousands of tables to chunk the big data into separate pieces that are faster to search. So to test this I'm creating these tables but notice that these are created very slowly.
Adjusting the schema for these tables requires me to (of course) delete the existing tables. But with it taking 10-30 seconds per table results in days of waiting time.
Command to delete table:
echo "use keyspace;TRACING ON;drop table table28;exit;" | cqlsh --request-timeout=60000 > trace
The data will exceed 1,000,000,000,000 rows which is why they are being split up per time frame. We always know what the timeframe is so we split the tables up by timeframe. <5 columns though.
I was hoping someone could help me with debugging this to see how performance can be increased. Trace is linked below:
https://ufile.io/gz9mz

A: More than several hundreds tables in Cassandra is a clear sign of the bad data model - if you have thousands of tables, then you need to think about how you're trying to solve your task. You need to take into account that for every table, a memory allocated on heap and off-heap to contain different metadata, etc.
Why you need to separate data into chunks - why it doesn't work inside one table? Are you using queries with ALLOW FILTERING? Can you describe the use case?
P.S. This question is more for StackOverflow or DBA StackExchange...


text:
Q: STS / Eclipse JVM max heap lower than free memory on machine I'm trying to increase my max heap in eclipse / STS.  I find that the ceiling seems much lower than my free memory.  Windows reports 2G available memory in the Task Manager.  It appears that the JVM in Eclipse is only able to allocate around 1.2G of that.  In the config below found in the eclipse.ini if I change the -Xmx to above 1200m I get an error that the JVM failed to start.  Why won't it allow me to allocate more?
-startup
plugins/org.eclipse.equinox.launcher_1.1.0.v20100507.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.1.R36x_v20100810
-product
com.springsource.sts.ide
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
256M
-vm
C:/bea/jdk160_05/bin/javaw.exe
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Dsun.lang.ClassLoader.allowArraySyntax=true
-Xms1200m
-Xmx1200m

A: This is typically the Windows 2Gb/DLL process limit for 32-bit systems. Java usually (and therefore Eclipse) allocates a contiguous block of memory for its heap. Windows only allows a maximum (normally) of 2Gb for a process on a 32-bit system. (There are some tricks to raise that to 3Gb.) The annoying issue is that Windows DLLs are likely to be mapped to places in memory that eat into that 2Gb -- although they can be moved by a technique called rebasing. On typical Windows 32-bit systems, depending on what is installed, you can get between 1.2Gb and 1.4Gb in a contiguous chunk, and this, therefore, is the most you can get as a Java heap.
The only real way to raise this significantly is by switching to a 64-bit system. There are techniques for moving DLLs and switching to 3Gb for the process limit that can make a modest improvement. See http://msdn.microsoft.com/en-us/windows/hardware/gg487508 for a little more information.


text:
Q: Declaring variable from third party library in header file I have a game class as follows:
// game.h
class Game {
 public:
  void Run();
  void CleanUp();
}

I want to create a texture pointer which is declared here, but initiated at construction. This pointer is to a type that exists in a third party header file:
private:
 std::unique_ptr<Texture> sprite_sheet; // Texture is in game_engine.h which is third party.

The problem is, if I #include "game_engine.h" in this header, then every file that includes this header will include everything from game_engine as well which I want to avoid. Ideally, I would only like to include game_engine in the source file (.cpp).
Is there a standard design pattern to help me avoid this?
One way is to create my own Texture class which only exposes the relevant parts I want. But this will slowly blow out of proportion as I will have to re-do my own classes for everything.

A: Posting an answer because there's a bit more for completeness. Here is what worked for me.
The source file is as follows:
// game_engine.h - C library.
typedef struct Texture {
  ...
} Texture;

If I want to use a unique_ptr, the approach is as follows:
// game.h
// Forward declare the typedef.
// https://stackoverflow.com/q/804894/1287554
typedef struct Texture Texture_;

class Game {
 public:
  void Run();
  void CleanUp();

  // Destructor is required for unique_ptr and forward declarations.
  // https://stackoverflow.com/q/13414652/1287554
  ~Game();
 protected:
  std::unique_ptr<Texture_> sprite_sheet;

};

// game.cpp
#include "game.h" // This is first.
#include "game_engine.h"

void Game::Run() {
  sprite_sheet = std::make_unique<Texture_>(LoadTexture(...));
}

// This has to be explicit.
Game::~Game() = default;


text:
Q: Truncate a Duration in Java When capturing elapsed time as a Duration, I only care about whole seconds resolution.
How do I drop the fractional second from a Duration object?
Other classes in the java.time framework offer a truncatedTo method. But I do not see one on Duration.

A: Java 9 and later
Java 9 brought some minor features and bug fixes to the java.time classes that debuted in Java 8.
One of those features is adding a Duration::truncatedTo method, similar to such methods seen on other classes. Pass a ChronoUnit (an implementation of TemporalUnit interface) to specify the granularity of what to truncate.
Duration d = myDuration.truncatedTo( ChronoUnit.SECONDS ) ;

Java 8
If you are using Java 8 and cannot yet move to Java 9, 10, 11, or later, then calculate the truncation yourself.
Call the minusNanos method found on the Java 8 version of Duration. Get the number of nanoseconds on the Duration object, then subtract that number of nanoseconds.
Duration d = myDuration.minusNanos( myDuration.getNano() ) ;

The java.time classes use the immutable objects pattern. So you get back a fresh new object without altering ("mutating") the original.

A: I like your own answer. I know this was not what you asked, yet I'd like to present one or two options for Java 8 for the cases where we want to truncate to a unit other than seconds.
If we know the unit at the time we are writing the code, we may combine the toXx and the ofXx methods to form the truncated duration:
    Duration d = Duration.ofMillis(myDuration.toMillis());
    Duration d = Duration.ofSeconds(myDuration.toSeconds());
    Duration d = Duration.ofMinutes(myDuration.toMinutes());
    Duration d = Duration.ofHours(myDuration.toHours());
    Duration d = Duration.ofDays(myDuration.toDays());

If the unit is variable, we may adapt the code from the implementation of the Java 9 method you mentioned, truncatedTo:
    Duration d;
    if (unit.equals(ChronoUnit.SECONDS)
            && (myDuration.getSeconds() >= 0 || myDuration.getNano() == 0)) {
        d = Duration.ofSeconds(myDuration.getSeconds());
    } else if (unit == ChronoUnit.NANOS) {
        d = myDuration;
    }
    Duration unitDur = unit.getDuration();
    if (unitDur.getSeconds() > TimeUnit.DAYS.toSeconds(1)) {
        throw new UnsupportedTemporalTypeException("Unit is too large to be used for truncation");
    }
    long dur = unitDur.toNanos();
    if ((TimeUnit.DAYS.toNanos(1) % dur) != 0) {
        throw new UnsupportedTemporalTypeException("Unit must divide into a standard day without remainder");
    }
    long nod = (myDuration.getSeconds() % TimeUnit.DAYS.toSeconds(1)) * TimeUnit.SECONDS.toNanos(1)
            + myDuration.getNano();
    long result = (nod / dur) * dur;
    d = myDuration.plusNanos(result - nod);

The original method used some private stuff from the Duration class, so a number of changes were necessary. The code only accepts ChronoUnit units, not other TemporalUnits. I haven't considered how hard it would be to generalize it.


text:
Q: how can i rename a empty column in excel sheet using pandas I am trying to rename empty column with a column name  can you please help me
    CaseNumber  QueueName
0   3510926     AudioSW_India
1   3510937     ModemSW_LTEAS_RJIL_India
2   3510940     ModemSW_RILQMI_AndroidRIL_Taiwan_VT
3   3510944     ModemSW_Data_India_All_LTE
4   3510956     QIPL_IMS
5   3510980     MODEMSW_LC_INDIA_LTE_Protocol_VT
6   3511017     QIPL_IMS

I am using
df2=df.rename(columns = {" " : "Signal"}, inplace = True)

but i am getting error

'NoneType' object has no attribute 'to_excel'

A: First column is index, so possible rename is by:
df.index.name = 'val'

Or:
df = df.rename_axis('val')

But if want avoid write first column (index) to excel, use:
df.to_excel('file.xlsx', index=False)

EDIT:
There is problem if use inplace=True it return None, so df2 is None, not DataFrame.


text:
Q: Convergence of maximum points on compact sets Suppose $f$ and $f_n$ ($n=1,2,\dots$) are continuous functions $[0,1]\rightarrow\mathbb{R}$, achieving their maxima at unique points $x^*$ and $x^*_n$ respectively. If $f_n(x)\rightarrow f(x)$ for all $x\in [0,1]$, do we also have $x^*_n\rightarrow x^*$?
Here are a few thoughts on the problem:

*

*One can ask a similar question when $[0,1]$ is replaced by $[0,\infty).$ In that case the answer is negative, as the maximum may escape to infinity. This behaviour is prohibited on $[0,1]$ due to compactness, but of course something else might go wrong.

*If $f_n\rightarrow f$ uniformly, then the answer is positive; indeed, say (after selecting a subsequence) $x_n^*\rightarrow y \neq x^*$. Then $\vert f_n(x_n^*) - f(y) \vert \le \vert f_n(x_n^*)-f(x_n^*)\vert + \vert f(x_n^*) - f(y) \vert \le \Vert f - f_n \Vert_{L^\infty[0,1]} + \vert f(x_n^*) - f(y) \vert \rightarrow 0$ and thus taking limits in the inequality $f_n(x^*) \le f_n(x_n^*)$ yields $f(x^*) \le f(y)$. This is a contradiction, as $f$ is assumed to achieve its maximum at a unique point.

A: Hint
What about $f(x) = x$ and $f_n = \sup(f, 2g_n)$ where
$$g_n(x)=
\begin{cases}
nx & 0 \le x \le 1/n\\
2-nx & 1/n \le x \le 2/n\\
0 & x \ge 2/n
\end{cases}$$


text:
Q: How change the scale and labels in scatterPlot of the openair package of R How to change the labels of the values on the x-axis of a scatterPlot of the openair package?
And how to change the scale on this x-axis?

A: I am not aware of how this can be done in openair's scatterPlot function, as the typical way of doing so (outlined below) does not work on testing. However, if you are after a scatter plot for simple linear regression, for example, you can always use the plot() function, and apply the following modifications -
With the plot() function in R, this can be done using the xaxt= "n" argument and axis() function to create your own x-axis labels. The range can be changed with the xlim=c(min, max) argument. For example -
plot(x_vector, y_vector, xaxt = "n", xlim=c(0.02, 0.09))
axis(1, at = c(0.02, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09),
        lab = expression (1, 2, 3, 4, 5, 6, 7, 8, 9))

The at = c(values) is the list of the default x-label values, The lab=expression(values) is where you give your value for each of the default values listed under at =c(values).


text:
Q: How to list YII namespaces in default? In Yii framework, I find the \Yii namespaces.
how to list all kinds namespace of yii framework?

A: Hi i am not sure which kind of list you want but you can find all namespace on API documentation,
Hope below link will be useful to you.
https://www.yiiframework.com/doc/api/2.0


text:
Q: AVPlayer - Benny Hill style speeded up video issue I'm using AVPlayer to show a live stream. Works fine. Part of my app requires a modal view to appear over the video. Actually, it flips the video view to show the modal view. I want the video's audio to keep playing, which it does fine.
However, the problem is when I return to the video. The video's visuals speed up for a few seconds, Benny Hill style, to compensate for the period they were off the screen. Then the video starts playing normally. Is there a way to stop this speed up? If not, can I remove the visual element until the speeded up bit stops.


text:
Q: Aggregate root and large amount of data I have a problem when I need to change a status of a parent model when there are > 100 of child related models.
class AggregateRoot {
    constuctor(private parentModel, private childModels) {}

    public function updateStatus()
    {
        if (count(this->childModels) > 100) {
            this->parentModel->status = 'some status';
        }
    }
}

As far as I understand, aggregate root contains only models, not services, so I can't inject a repository into the aggregate root. From the other hand, retrieving all the child models just to see if there are 100 of them seems like overhead, while I can make a simple request to DB.
How do you solve such a problem with aggregate roots?


text:
Q: TeamCity results don't match JMeter's I'm currently using JMeter to load test some application, I used the duration assertion and I set it to, let's say 200, when the load time exceeds 200, the Request in the Result Tree becomes Red for it is an error.
Problem is, when i run the same test with TeamCity, it is always marked as success, even if all the Requests have failed.

A: What you are looking at is the summary.
You need to add a listener to your project, that saves results to a file.
Then you need to have Teamcity read that file and assert the result.
Teamcity is just telling you "Ehhhhh the script you wanted me to run worked".
Here's a small guide of how:
https://devblog.xero.com/run-jmeter-performance-tests-on-teamcity-8315f7ccffc1#.8ga4jso7k

A: Take a look at the Performance Metrics Calculation under Build Features in Team City's project. You need to make sure that assertions is checked in order to make the build fail on assertions.
In addition to that, the newer versions of JMeter and Team City add more columns to the .jtl file that is output, so you need to make sure your "success" column is in the 5th spot in the file. I found this out after coming across this post in the TeamCity JMeter Plugin git repo: https://github.com/jtorgan/jmeter_plugin/issues/24#issuecomment-421016226
Instead of creating a script, I just made sure to remove some columns in the JMeter user.properties settings on the TeamCity server to make sure the success column was in the 5th spot.
Here were the columns I had to turn off under user.properties for JMeter:
jmeter.save.saveservice.response_message=false
jmeter.save.saveservice.thread_name=false
jmeter.save.saveservice.data_type=false

A: You don't really specify a lot of information. How do you run the application? Do you have the TeamCity JMeter plugin available?
I run a maven project with the jmeter-maven-plugin and teamcity with the JMeter-plugin. Now you can specify in the pom.xml if you want the test to fail on test failures:
<ignoreResultFailures>false</ignoreResultFailures>

Please also read info on the TeamCity plugin as it uses a specific (non-standard) jtl format:
    <propertiesJMeter>
      <jmeter.save.saveservice.default_delimiter>\t</jmeter.save.saveservice.default_delimiter>
      <jmeter.save.saveservice.print_field_names>true</jmeter.save.saveservice.print_field_names>
    </propertiesJMeter>

For more info, see this page, which explains the configuration of the TeamCity JMeter plugin: https://www.blazemeter.com/blog/how-run-jmeter-tests-teamcity-continuous-integration
As a bonus: I invested some time to see how to pass parameters to the JMeter script from the maven build. I came to the conclusion that the maven plugin does not support the normal -J JMeter parameters and you should use -D instead:
    <jMeterProcessJVMSettings>
      <arguments>
        <argument>-Dimage_path=${teamcity.build.workingDir}/src/test/resources/images</argument>
        <argument>-Denvironment=TEST</argument>
      </arguments>
    </jMeterProcessJVMSettings>

Now in JMeter you can use the following variable value to get the value specified in the pom.xml:
${__groovy(System.getProperty("image_path"\,"/some/default/dir"))}


text:
Q: Extract raw data from Tables in Word? using Perl I'm trying to extract data from multiple Tables in a Word document. When trying to convert the data in the tables to text I get an error. The ConvertToText method has two optional parameters(how to seperate the data, and a boolean).Here is my current code:
#usr/bin/perl
#OLEWord.pl

#Use string and print warnings
use strict;use warnings;
#Using OLE + OLE constants for Variants and OLE enumeration for Enumerations
use Win32::OLE qw(in);
use Win32::OLE::Const 'Microsoft Word';
use Win32::OLE::Variant;

my $var1 = Win32::OLE::Variant->new(VT_BOOL, 'true');

$Win32::OLE::Warn = 3;

#set the file to be opened
my $file = 'C:\work\SCL_International Financial New Fund Setup Questionnaire V1.6.docx';

#Create a new instance of Win32::OLE for the Word application, die if could not open the application
my $MSWord = Win32::OLE->GetActiveObject('Excel.Application') or Win32::OLE->new('Word.Application','Quit');

#Set the screen to Visible, so that you can see what is going on
$MSWord->{'Visible'} = 1;
 $MSWord->{'DisplayAlerts'} = 0; #Supress Alerts, such as 'Save As....'

#open the request file or die and print warning message
my $Doc = $MSWord->{'Documents'}->Open($file) or die "Could not open ", $file, " Error:", Win32::OLE->LastError();

#$MSWord->ActiveDocument->SaveAs({Filename => 'AlteredTest.docx',
                            #FileFormat => wdFormatDocument});

my $tables = $MSWord->ActiveDocument->{'Tables'};

for my $table (in $tables){
   my $tableText = $table->ConverToText(wdSeparateByParagraphs,$var1);
   print "Table: ", $tableText, "\n";
}

$MSWord->ActiveDocument->Close;
$MSWord->Quit;

and I'm getting this error:

Bareword "VT_BOOL" not allowed while "strict subs" in use at OLEWord.pl line 31
  Bareword "true" not allowed while "strict subs" in use at OLEWord.pl line 31
  Execution of OLEWord.pl aborted due to compilation errors.

A: When things like VT_BOOL are not defined as constant, perl will consider them bareword. Others already provided info on them.
The root cause of your problem are missing constants that are exported by Win32::OLE::Variant module. Add:
use Win32::OLE::Variant;

to your script to remove first error. The second one is similar problem, true is not defined as well. Replace it with 1 or define constant yourself with:
use constant true => 1;

Edit: Here is example of extracting table text:
my $tables = $MSWord->ActiveDocument->{'Tables'};
for my $table (in $tables){
   my $tableText = $table->ConvertToText({ Separator => wdSeparateByTabs });
   print "Table: ", $tableText->Text(), "\n";
}

In your code you had typo in method name ConverToText. Also the method returns Range object, so you have to use Text method to get actual text.

A:
A 'Bareword' error is caused by a syntax error in your code. A
  'runaway multi-line' usually pinpoints where the start of the error
  is, and usually means that a line has not been completed, often
  because of mismatched brackets or quote marks.
As has been pointed out by several SO-ers, that doesn't look like
  Perl! The Perl interpreter is balking on a syntax error because it
  doesn't speak that particular language! Source

Not using strict will not give you the warning. (But you should use it for a good code)
Read about Bareword so that you will know what are they and you will know by your own that how can you correct this error.
Here are some links for study about Bareword:
1. perl.com
2. alumnus

A: removing "use strict"  will remove the "Bareword" errors

A: extract all the doc tables into a single xls file
     sub doParseDoc {

           my $msg     = '' ;
           my $ret     = 1 ; # assume failure at the beginning ...

           $msg        = 'START --- doParseDoc' ;
           $objLogger->LogDebugMsg( $msg );
           $msg        = 'using the following DocFile: "' . $DocFile . '"' ;
           $objLogger->LogInfoMsg( $msg );
           #-----------------------------------------------------------------------
           #Using OLE + OLE constants for Variants and OLE enumeration for Enumerations

           # Create a new Excel workbook
           my $objWorkBook = Spreadsheet::WriteExcel->new("$DocFile" . '.xls');

           # Add a worksheet
           my $objWorkSheet = $objWorkBook->add_worksheet();

           my $var1 = Win32::OLE::Variant->new(VT_BOOL, 'true');

           Win32::OLE->Option(Warn => \&Carp::croak);
           use constant true => 0;

           # at this point you should have the Word application opened in UI with t
           # the DocFile
           # build the MS Word object during run-time
           my $objMSWord = Win32::OLE->GetActiveObject('Word.Application')
                             or Win32::OLE->new('Word.Application', 'Quit');

           # build the doc object during run-time
           my $objDoc   = $objMSWord->Documents->Open($DocFile)
                 or die "Could not open ", $DocFile, " Error:", Win32::OLE->LastError();

           #Set the screen to Visible, so that you can see what is going on
           $objMSWord->{'Visible'} = 1;
           # try NOT printing directly to the file

            #$objMSWord->ActiveDocument->SaveAs({Filename => 'AlteredTest.docx',
                                        #FileFormat => wdFormatDocument});

           my $tables        = $objMSWord->ActiveDocument->Tables();
           my $tableText     = '' ;
           my $xlsRow        = 1 ;

           for my $table (in $tables){
              # extract the table text as a single string
              #$tableText = $table->ConvertToText({ Separator => 'wdSeparateByTabs' });
              # cheated those properties from here:
              # https://msdn.microsoft.com/en-us/library/aa537149(v=office.11).aspx#officewordautomatingtablesdata_populateatablewithdata
              my $RowsCount = $table->{'Rows'}->{'Count'} ;
              my $ColsCount = $table->{'Columns'}->{'Count'} ;

              # disgard the tables having different than 5 columns count
              next unless ( $ColsCount == 5 ) ;

              $msg           = "Rows Count: $RowsCount " ;
              $msg           .= "Cols Count: $ColsCount " ;
              $objLogger->LogDebugMsg ( $msg ) ;

              #my $tableRange = $table->ConvertToText({ Separator => '##' });
              # OBS !!! simple print WILL print to your doc file use Select ?!
              #$objLogger->LogDebugMsg ( $tableRange . "\n" );
              # skip the header row
              foreach my $row ( 0..$RowsCount ) {
                 foreach my $col (0..$ColsCount) {

                    # nope ... $table->cell($row,$col)->->{'WrapText'} = 1 ;
                    # nope $table->cell($row,$col)->{'WordWrap'} = 1  ;
                    # so so $table->cell($row,$col)->WordWrap() ;

                    my $txt = '';
                    # well some 1% of the values are so nasty that we really give up on them ...
                    eval {
                       $txt = $table->cell($row,$col)->range->{'Text'};
                       #replace all the ctrl chars by space
                       $txt =~ s/\r/ /g   ;
                       $txt =~ s/[^\040-\176]/ /g  ;
                       # perform some cleansing - ColName<primary key>=> ColName
                       #$txt =~ s#^(.[a-zA-Z_0-9]*)(\<.*)#$1#g ;

                       # this will most probably brake your cmd ...
                       # $objLogger->LogDebugMsg ( "row: $row , col: $col with txt: $txt \n" ) ;
                    } or $txt = 'N/A' ;

                    # Write a formatted and unformatted string, row and column notation.
                    $objWorkSheet->write($xlsRow, $col, $txt);

                 } #eof foreach col

                 # we just want to dump all the tables into the one sheet
                 $xlsRow++ ;
               } #eof foreach row
               sleep 1 ;
           }  #eof foreach table

           # close the opened in the UI document
           $objMSWord->ActiveDocument->Close;

           # OBS !!! now we are able to print
           $objLogger->LogDebugMsg ( $tableText . "\n" );

           # exit the whole Word application
           $objMSWord->Quit;

           return ( $ret , $msg ) ;
     }
     #eof sub doParseDoc


text:
Q: Rules on hyphenating phrases I see a ton of questions on hyphenated words, specifically, but nothing on the more general question how/when they're supposed to be used vs omitted. Another great answer gives some general rules on hyphens:

A hyphen is used to join words in a compound construction, or separate syllables of a word, like during a line break, or (self-evidently) a hyphenated name.

..but this leaves the greater question of when this "compound construction" should be used, open.
Consider this a "canonical" usage question, then.
A common usage I see is "day-of-the-week" vs. "day of the week". Both of these seem correct, and are read out loud identically from what I can tell.
Some other common examples I've seen:

*

*"Video-of-the-month club"

*"Give-and-take arrangement"

*"State-of-the-art technology"

*"Friendly-looking person"

I see very little difference in meaning in the above phrases, both with and without the hyphens.
When should hyphens or dashes in multi-word (or is it multi word? or multiword?) phrases be used?

A: Compound constructions are oftend used/created when there is chance of ambiguity, in a way similar to how 'Let's eat grandpa' is put into its proper context by adding a comma between 'eat' and 'grandpa'.
For example, 'That is a friendly looking person' doesn't say much about how the person looks, only that he is friendly (for sake of the example assuming that 'looking person' is a thing).
'That is a friendly-looking person' says something about how the person looks, but it doesn't mean that person actually is friendly.
Use 'Can you get me the video-of-the-month', and everybody knows what you mean, at least conceptually speaking, but omit the hyphens, and the sentence just looks incomplete 'Can you get me the video of the month' (january, last august?).
'State of art technology' refers to the technology in (the making of) art, and the state that technology is in. 'State-of-the-art' means that something is the most modern, most advanced, etc, so a different meaning altogether.
Just like any other punctuation mark, hyphens have their uses, and the rules and guidelines you already found can help determine when they are best used in a text.
PS: Concerning 'multi-word'; some words are prefixed, while others are not. I can't promise that this site explains it all (if you haven't visted it already), but it does give some good background information on hyphenation.

A: Hyphens are used in compound adjectives to avoid confusion. You would use a hyphen where it is not possible to remove one of the words and still make sense (or make the same sense).
In your first three examples, removing any of the words would leave a nonsensical phrase:
"Video of the club"
"Give and arrangement"
"of the art technology"

In the 4th one "Friendly-looking person" you could remove 'looking' but you couldn't remove 'friendly'. The importance of 'looking' is that the person appears to be friendly (but may not be).
Here is a helpful site:

How do we know when to put a hyphen?
If you can use the word "and" between the two adjectives or words,
  then a hyphen isn't necessary.
She has a big blue book.

(Big and Blue are adjectives) Can we say: She has a big and blue book.
  (Yes, it is possible)
He is a world famous singer

Can we say: He is a world and famous singer. No, it doesn't sound
  correct so we need a hyphen to join the words world and famous.
Also, look at the following:
It's an old coal-mining town

Notice how we didn't put a hyphen between the word old and coal. If we
  had have done that, we would have been referring to old coal, as in
  coal that is old. We want to emphasis that the town in old and not the
  coal.
Here we can say it is old and a coal-mining one.


text:
Q: Is it ok to use Qt metatype system before QApplication is created? I use following code whenever I need to register a type in Qt metaobject system:
*.h file
class MyClass
{

    //.....

    class MyType {.....};
    static const int metaType_MyType;

    class MetaClerk
    {
    public:
        MetaClerk(void);
    };
    static const MetaClerk metaClerk;

    //.....

};
Q_DECLARE_METATYPE(MyClass::MyType)
QDataStream &operator<<(QDataStream &stream, const MyClass::MyType &a);
QDataStream &operator>>(QDataStream &stream, MyClass::MyType &a);

*.cpp file
//.....
const int MyClass::metaType_MyType = qRegisterMetaType<MyClass::MyType>("MyClass::MyType");
MyClass::MetaClerk::MetaClerk()
{
    qRegisterMetaTypeStreamOperators<MyClass::MyType>("MyClass::MyType");
}
const MyClass::MetaClerk MyClass::metaClerk;
//.....

This way I have MyType registered in all possible ways before the main() function even starts. So, the question is
1) Does the whole Qt MetaObject system need an instance of QCoreApplication? Maybe my code works by happy coincidence?
2) Is there any nice solution NOT involving my ugly crutch (namely the Clerk class)?

A: QCoreApplication is responsible for providing an event loop for Qt applications, handling the application's initialization and finalization and managing the application and system settings.
When creating items like QWidget you definitely should have an instance of QApplication. But there would be no trouble using the QMetaType class or using qRegisterMetaType before creating an instance of QCoreApplication or QApplication.


text:
Q: AngularJs - Window prompt appears as scroll down I am facing a weird issue. I have applied anchor scroll in my html, which loads data on scroll. It works fine unless i reach offset to 180. When i reach it, a call like this url/x appears in network and a prompt box appears and ask for input, it comes two times. see the screen shot for more clarification.
I have a simple code.Here is my controller.
    var aosListing = this;
        aosListing.page = 0;
        aosListing.limit = 20;
        aosListing.aosUsers = [];
        aosListing.changeAOSPermission = changeAOSPermission;
        aosListing.loadMoreData = loadMoreData;
        aosListing.paused = paused;
        aosListing.loadingData = true;

        function getAOSUserListing() {
            aosListing.loadingData = true;
            var offset = aosListing.page * aosListing.limit;
            aosListing.page++;
            TSSServices.getAOSListing(offset, aosListing.limit).then(function (res) {
                if (res.msgCode === "405") {
                    angular.forEach(res.data, function (aosUser) {
                        if (aosUser.website === "null") {
                            aosUser.website = "Not Available";
                        }
                        aosUser.showhistoryPopover = false;
                        aosListing.aosUsers.push(aosUser);
                    });
                    if (res.data.length > 0) {
                        aosListing.loadingData = false;
                    }
                }
            });
        }

        getAOSUserListing();

        function paused() {
            return aosListing.loadingData;
        }

        function loadMoreData() {
            getAOSUserListing();
        }

My html

        Full Name
        Email
        Website
        Institution
        Access?

{{aos.userEmail}}

{{aos.website}}

                        Revoke Access

                        Grant Access

A: In function getAOSUserListing you push to aosListing.aosUser only if (msgCode === "405"), otherwise the res.data is not used at all.


text:
Q: When a button is clicked, how do I show an element if another element contains a specific text? When I click on the button, I want the #test2 element to show if span.test1 contains the keyword 'TEST'. I'm new with jquery so I'm not sure what I need to change here.

$(document).ready(function(){
  $("#button").click(function()
   if ($("span.test1:contains(TEST)") {
              $("#test2").show()
  };
  };
#test2 {
display: none;
}
<input id="button" type="button" value="Button"></input>
TEST

TEST2

A: You can do it as shown below. I used the is() method so that we can cache reference to the element and test :contains selector against it.
Otherwise the selectors inside click handler will be looked up on each click.

const $test1 = $("span.test1");
const $test2 = $("#test2");
$("#button").click(function() {
  if ($test1.is(':contains("TEST")')) {
    $test2.show()
  };
});
#test2 {
  display: none;
}

<input id="button" type="button" value="Button"></input>
TEST

TEST2

A: Use RegExp to check if the string contains a specific word or not.

$("#button").click(function() {
  var txt = $("span.test1").text();
  if (/test/i.test(txt)) // "i" is for case case-insensitive
    $("#test2").show()
});
#test2 {
  display: none;
}

<input id="button" type="button" value="Button"></input>
this is a sample TEST

TEST2

A: You can use following code

$('#button').click(function(){
      if(document.getElementById("test1").innerText.includes("TEST")){
      $('#test2').html("yes it includes")
      console.log("yes")
    }
    })
<input id="button" type="button" value="Button"></input>
  TEST


text:
Q: Is there a name for a bijection that is bi-measurable? So there is already a name for a bijection $f$ between a topological space $(X, \tau_{1})$ and a topological space $(Y, \tau_{2})$ such that $f$ is continuous-$(\tau_{1}, \tau_{2})$ and $f^{-1}$ is continuous-$(\tau_{2}, \tau_{1})$. I wonder, if we replace "topological" with "measurable", $\tau_{1}, \tau_{2}$ with sigma algebras, and "continuous" with "measurable", then how do people call $f$?
Such a map, if I am not mistaken, is used in probability theory for defining the concept of a Borel space. (If a measurable space is identified as the Borel space $\mathbb{R}$ under such a map, then it is called a Borel space.) But of interest now is the "canonical" name of the map itself.


text:
Q: Several stationary points of the action functional In QFT the principle of stationary action states that we choose fields that will make the action stationary but what if the action has many stationary points (for a fixed choice of boundary conditions)? What's the significance of these other solutions?

A: As an example, consider the real scalar field with action,
$$S=\int \mathrm{d}^4 x \, \left( \partial_\mu \phi \partial^\mu \phi - \frac{1}{2}m^2\phi^2\right)$$
The principle of stationary action insists $\delta S = 0$, and the fields which allow this are those which satisfy the associated Euler-Lagrange equations, which are simply,
$$(\square+m^2)\phi=0$$
As the OP noted, there are many solutions to the equations of motion; this is not an issue. For the purposes of canonical quantization, we usually expand the field as a plane wave, and promote the Fourier coefficients to operators, etc. A theory may have other solutions, and in many cases it is interesting to study these, c.f. solitons.

A: There can be more than one stationary classical solution to an action principle with pertinent boundary conditions. E.g. because of instantons or gauge symmetry.
Example: A rotating rigid body with moment of inertia $I$. The action is  $$\tag{1} S~=~\int_{t_i}^{t_f}\! dt ~L , \qquad L ~:=~\frac{I}{2}\dot{\theta}^2, $$
with Dirichlet boundary conditions (BC)
$$\tag{2} \theta(t_i)-\theta_i~\in~2\pi\mathbb{Z} \qquad\text{and}\qquad\theta(t_f)~-\theta_f\in~2\pi\mathbb{Z} . $$
It is possible to satisfy the EOM $\ddot{\theta}\approx 0$ and BC (2) in infinitely many ways corresponding to different number of windings.
Instanton solutions are an important feature of a quantum field theory. On the other hand, gauge ambiguities are typically removed by gauge-fixing.


text:
Q: progressDialog and wait for a signal I want look for my GPS signal, while it's looking for it I have a ProgressDialog, but, it showed when the task is finished:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);

    DialogInterface.OnCancelListener dialogCancel = new DialogInterface.OnCancelListener() {

        public void onCancel(DialogInterface dialog) {
            Toast.makeText(getBaseContext(),
                    "no encotnrada",
                    Toast.LENGTH_LONG).show();
           // handler.sendEmptyMessage(0);
        }

    };

    pd = ProgressDialog.show(this, "buscando", "gps", true, true, dialogCancel);

    while(currentLocation == null){

    }

    Thread thread = new Thread(this);
thread.start();
}

in run() I look for my currentLocation value.
How can I wait for this signal in order to show the dialog?
Thank you in advance

A: It's shown at the end, because you're looping in the main thread. Instead you should do the waiting in the asynctask or another thread - then the dialog will be shown. In the onPostExecute of the asynctask you can start your other thread.
Try something like this:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);

    final WaitForIt waiter = new WaitForIt();

    DialogInterface.OnCancelListener dialogCancel = new DialogInterface.OnCancelListener() {

        public void onCancel(DialogInterface dialog) {
            Toast.makeText(getBaseContext(),
                    "no encotnrada",
                    Toast.LENGTH_LONG).show();
            waiter.cancelWait();
        }

    };

    pd = ProgressDialog.show(this, "buscando", "gps", true, true, dialogCancel);

    waiter.execute();
}

private class WaitForIt extends AsyncTask<Void, Void, Void> {
     private synchronized boolean cancelled = false;
     public void cancelWait() { cancelled = true; }

     protected Void doInBackground() {
         while(!cancelled) {
             if (gps signal available)
                 break;
         }
     }

     protected void onPostExecute() {
         pd.dismiss();
         Thread thread = new Thread(MyActivity.this);
         thread.start();
     }
}

A: I've used GPS, and the GPS process is not running on the same process that running your app.
so there must be something wrong with your code, the GPS listener fires a location object if signal is found, so you can dismiss your ProgressDialog.


text:
Q: Spring integration : Not able to send the message to channel I am using spring-framework and spring-integration latest versions and just making POC application with spring integration but can't run this.
I have spring integration confing something like this.
    <bean id="initUrlQ" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg value="initUrl.Q" />
    </bean>
   <int:channel id="initChannelProducerId" />

    <jms:outbound-channel-adapter id="initOutboundId" channel="initChannelProducerId" connection-factory="padtoys.jms.cachedConnectionFactory"
        destination="initUrlQ"  />
    <int:channel id="initChannelConsumerId" />
    <jms:message-driven-channel-adapter id="initQListenerId" channel="initChannelConsumerId"
        connection-factory="padtoys.jms.cachedConnectionFactory" destination="initUrlQ"
        acknowledge="auto" concurrent-consumers="1" max-concurrent-consumers="1" />

    <int:service-activator method="testSA" ref="testBean" input-channel="initChannelConsumerId" output-channel="nullChannel"/>

And my testBean java file looks like this.
public class TestBean implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @PostConstruct
    public void afterInit(){
        System.err.println("after init..!");
        DirectChannel inChannel = applicationContext.getBean("initChannelProducerId", DirectChannel.class);
        System.err.println("channel::" + inChannel);
        inChannel.send(createMessage("This is test url!!", 0));
    }

    @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @ServiceActivator
    public String testSA(){
        System.err.println("inside service activator!!!");
        return "this is test";
    }

    private Message<String> createMessage(final String url, final int depth) {
        return MessageBuilder.withPayload(StringUtils.EMPTY)
                .setHeader(MESSAGE_HEADERS.URL, url)
                .setHeader(MESSAGE_HEADERS.DEPTH, depth).build();
    }
}

And I am starting my application something like this.
@SuppressWarnings("resource") public static void main(String[] args) {
        LOG.info("Trigerring process!");
        new ClassPathXmlApplicationContext("/application-context.xml");
    }

Please consider that I have declared testBean and padtoys.jms.cachedConnectionFactory in spring context xml.
PROBLEM :
When I start the application, getting below error
Caused by: org.springframework.messaging.MessageDeliveryException: Dispatcher has no subscribers for channel 'org.springframework.context.support.ClassPathXmlApplicationContext@5a1198c7.initChannelProducerId'.; nested exception is org.springframework.integration.MessageDispatchingException: Dispatcher has no subscribers
        at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:77)
        at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:423)
        at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:373)
        at com.dodax.pad.ext.toys.crawler.scanner.TestBean.afterInit(TestBean.java:25)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:366)
        at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:311)
        at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:134)
        ... 30 more
Caused by: org.springframework.integration.MessageDispatchingException: Dispatcher has no subscribers
        at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:138)
        at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:105)
        at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:73)

NOTE :
I am getting right channel name at this line,
System.err.println("channel::" + inChannel);, but problem starts when I try to send the message to channel.

A: You must not perform messaging (send()) in a @PostConstruct method - it is too early in the application context lifecycle; the context is not yet ready to perform messaging.
See this answer for the proper place to perform messaging during startup.


text:
Q: How do i debug database related error in Agiletookit ? ATK4 I know about the $m->debug(); as mentioned here
But i am not sure how i should start debugging the following issue. My approach will be doing a var_dump inside dsql.php and compare fields and then go step by step upwards in the OOP layers. I was wondering if there was some easy way to do the same thing.
Actual Error:
/Users/Qambar/Work/VERYCOOLAWESOMEPROJECT/atk4/lib/DB/dsql.php  :1518   bozims_db_db_dsql_mysql DB_dsql_mysql-  >exception("Database Query Failed")

Full Log
/Users/Qambar/Work/VERYCOOLAWESOMEPROJECT/atk4/lib/BaseException.php    :63     Exception_DB    Exception_DB->collectBasicData(Null)
/Users/Qambar/Work/VERYCOOLAWESOMEPROJECT/atk4/lib/AbstractObject.php   :545    Exception_DB    Exception_DB->__construct("Database Query Failed", Null)
/Users/Qambar/Work/VERYCOOLAWESOMEPROJECT/atk4/lib/DB/dsql.php  :1518   bozims_db_db_dsql_mysql DB_dsql_mysql->exception("Database Query Failed")
/Users/Qambar/Work/VERYCOOLAWESOMEPROJECT/atk4/lib/DB/dsql.php  :1545   bozims_db_db_dsql_mysql DB_dsql_mysql->execute()
/Users/Qambar/Work/VERYCOOLAWESOMEPROJECT/atk4/lib/SQL/Model.php    :635    bozims_db_db_dsql_mysql DB_dsql_mysql->insert()
/Users/Qambar/Work/VERYCOOLAWESOMEPROJECT/atk4/lib/SQL/Model.php    :610    bozims_fileadmin_form_Upload_test_filestore_model_file  filestore\Model_File->insert()
/Users/Qambar/Work/VERYCOOLAWESOMEPROJECT/atk4/lib/Form/Field/Upload.php    :143    bozims_fileadmin_form_Upload_test_filestore_model_file  filestore\Model_File->save()
/   :   bozims_fileadmin_form_Upload_test   Form_Field_Upload->loadPOST(Object(Form))
/Users/Qambar/Work/VERYCOOLAWESOMEPROJECT/atk4/lib/AbstractObject.php   :786        Loggercall_user_func_array(Array(2), Array(1))
/Users/Qambar/Work/VERYCOOLAWESOMEPROJECT/atk4/lib/Form/Basic.php   :348    bozims_fileadmin_form   Form->hook("loadPOST")
/   :   bozims_fileadmin_form   Form->submitted(Object(Frontend))
/Users/Qambar/Work/VERYCOOLAWESOMEPROJECT/atk4/lib/AbstractObject.php   :786        Loggercall_user_func_array(Array(2), Array(1))
/Users/Qambar/Work/VERYCOOLAWESOMEPROJECT/atk4/lib/ApiWeb.php   :290    bozims  Frontend->hook("submitted")
/Users/Qambar/Work/VERYCOOLAWESOMEPROJECT/index.php :5  bozims  Frontend->main()

A: Usually - do a debug() which will give you a query itself. Copy-paste query into SQL console. If you get error there, then try to understand why.
You can also use setActualFields to narrow down list of fields queried, which will make your query simpler.
That should help you narrow down the problem.


text:
Q: Connect iPhone to ITunes on Ubuntu 22.04 I was able to install iTunes version 12.9.03 (64bit) and it's up and running with no problem. All my music and other downloads from iTunes appear and it is apparently working flawlessly on Ubuntu 22.04, but it cannot recognize my iPhone. This  making the software pointless.
Is there any way to fix this? I believe it is a software compatibility issue because my iPhone is being recognize by Ubuntu and the iPhone folders and media are accessible in Ubuntu.
I already installed/updated the libraries, as well as iFuse.
Thanks, and cheers!


text:
Q: How can I plan an experiment to change magnetic field of a coil rapidly while keeping the magnitude of oscillations constant? Note: I might be completely wrong in my calculations, the important question is the one in the title.$$$$
For an experiment, I want to have an alternating current a conducting coil, and have the frequency of the change in the current accelerate with time but the current remain the same. So I want to find a function that describes the current I need to supply in order to achieve that. By faraday's Law:
$$\epsilon =- \frac{\partial \Phi}{\partial t}$$
But I am a bit confused about what I need the current I supply to be. I control V so:
$$I_{tot}=\frac{V}{R}+I_{in}+I_{faraday}=I_{in}+\frac{\epsilon}{R}=(I_{in}-\frac{1}{R}\frac{\partial \Phi}{\partial t})$$
Since it is a coil, we have approximately:
$$I_{tot}=I_{in}-\frac{BA}{R}$$
Where B is the magnitude of the field of a because the field lines are parallel to the surface $A$. $B$ is linear with respect to the total current so:
$$I_{tot}=I_{in}-\frac{\alpha A}{R}I_{tot}$$
And this is a solvable equation. Now I am not sure how to proceed to find a function of $I_{in}(t)$ that will result in a total current of the form: $$I_{tot}(t)=Asin(\omega t)\Longrightarrow B=Bsin(\omega t)$$

A: One way to do this is to drive your coil with a signal generator which automatically maintains constant drive current with changes in load impedance, as would occur as the drive frequency changes. This is called a constant-current source and a search will turn up a variety of circuits which will accomplish this.
A constant-current supply contains a current sensor (in simplest form, a series resistor across which a voltage is measured) that generates a voltage signal proportional to the current flow. That voltage is then used as a control signal in a feedback loop inside the power supply to automatically increase or decrease the source voltage so as to maintain constant current.
The current can be adjusted at any time with a knob that adjusts the setpoint of the variable voltage supply at its summing junction.
Since an open circuit would require ~infinite voltage to maintain constant current, constant-current supplies have protection circuits inside them which limit how high the source voltage is allowed to go, and shut the supply down if the load resistance is too high.


text:
Q: Find all primes $p$ such that $p+1$ is a perfect square. Find all primes $p$ such that $p+1$ is a perfect square.
All primes except for 2 (3 is not a perfect square, so we can exclude that case) are odd, so we can express them as $2n+1$ for some $n\in\mathbb{Z}_{+}$. Let's express the perfect square as $a^2$, where $a\in\mathbb{Z}_{+}$. Since we are interested in a number that is one more than $2n+1$, we know that our perfect square can also be expressed as $2n+1+1=2(n+1)$.
$2n+2=a^2$
$2(n+1)=a^2$
So we know that our perfect square must be even, as it has a factor of 2 in it (in fact $2\cdot2$).
It is my strong intuition that we get a perfect square only if $n=1$, and therefore $p=3$ and $p+1=a^2=2\cdot2=4$, but how should I continue with this proof? It seems to me that whatever factor we have on the LHS we need to have it twice on the RHS (since $a$ must be an integer), but how do I continue from there?

A: If a prime $p$ is of the form of $n^2-1$, then
$$p=(n+1)(n-1)$$
and so $n-1$ must be 1.

A: I believe that if we have $p+1=k^2$ we can see $p=(k-1)(k+1)$ and hence $3$ is the only such prime.

A: If our prime $p$ is in form of $n^2-1,\quad n\in\mathbb{Z}$ then it could also be written as $p=(n-1)(n+1)$ If $p$ is a prime than it cannot be written as the product of two other primes (or the productof any integer other than $1$ and itself) (states the fundamental theorem of arithmetic) If $n-1=1$ then $n=2$ and the other multiplier $n+1=3=p$. Another possibility is that $n+1=1$ however that doesn't give us a prime for $p$..
So there is only one prime $p$ that makes $p+1$ a perfect square and it is $3$.


text:
Q: Serving an IIS website through nginx (proxy_pass) doesn't display CSS, images or js (404 not found) I have an nginx reverse proxy running on Ubuntu 14.04 LTS. When requests are made to the nginx proxy, it passes it to an IIS server containing one (default) website. It seems to render the HTML fine, but unfortunately the server responds with a 404 error for all of the other assets.
Here is the /etc/nginx/nginx.conf file:
user www-data;
worker_processes 4;
pid /run/nginx.pid;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile off;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;
    gzip_disable "msie6";

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

Here is my default nginx server config:
server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    index index.php index.html index.htm;

    server_name example.com www.example.com;

    location / {
        try_files $uri $uri/ =404;
        proxy_pass http://104.46.52.226/;
    }

    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

Here's the result of the request to example.com or www.example.com (the hosts file has been changed):

I figured perhaps it was an issue with the fact there's no root directive in my server config - but then I didn't really know where to start with that issue. At the very least I know it isn't an issue with the IIS server itself, because I can browse the localhost perfectly.
Any thoughts? Thanks very much in advance.
Edit: Here are my error logs, too:
2015/10/13 09:41:10 [emerg] 3069#0: invalid number of arguments in "proxy_pass" directive in /etc/nginx/sites-enabled/armari.com:31
2015/10/13 10:12:33 [emerg] 3606#0: "listen" directive is not allowed here in /etc/nginx/sites-enabled/armari.com:2
2015/10/13 13:39:18 [error] 3911#0: *1 open() "/usr/share/nginx/html/css/new-web.css" failed (2: No such file or directory), client: 188.39.188.214, server: armari.com, request: "GET /css/new-web.css HTTP/1.1", host: "www.armari.com", referrer: "http://www.armari.com/"
2015/10/13 13:39:18 [error] 3911#0: *3 open() "/usr/share/nginx/html/css/nivo/themes/default/default.css" failed (2: No such file or directory), client: 188.39.188.214, server: armari.com, request: "GET /css/nivo/themes/default/default.css HTTP/1.1", host: "www.armari.com", referrer: "http://www.armari.com/"
2015/10/13 13:39:18 [error] 3911#0: *4 open() "/usr/share/nginx/html/css/nivo/nivo-slider.css" failed (2: No such file or directory), client: 188.39.188.214, server: armari.com, request: "GET /css/nivo/nivo-slider.css HTTP/1.1", host: "www.armari.com", referrer: "http://www.armari.com/"
2015/10/13 13:39:21 [error] 3911#0: *8 open() "/usr/share/nginx/html/css/new-web.css" failed (2: No such file or directory), client: 188.39.188.214, server: armari.com, request: "GET /css/new-web.css HTTP/1.1", host: "armari.com", referrer: "http://armari.com/"
2015/10/13 13:39:21 [error] 3909#0: *10 open() "/usr/share/nginx/html/css/nivo/themes/default/default.css" failed (2: No such file or directory), client: 188.39.188.214, server: armari.com, request: "GET /css/nivo/themes/default/default.css HTTP/1.1", host: "armari.com", referrer: "http://armari.com/"
2015/10/13 13:39:21 [error] 3909#0: *11 open() "/usr/share/nginx/html/css/nivo/nivo-slider.css" failed (2: No such file or directory), client: 188.39.188.214, server: armari.com, request: "GET /css/nivo/nivo-slider.css HTTP/1.1", host: "armari.com", referrer: "http://armari.com/"

A: Found a solution in the end - I was forcing the nginx server to attempt serving files locally using the try_files $uri $uri/ =404;. All I had to do was remove this line and it works perfectly :)
location / {
    proxy_pass http://104.46.52.226/;
}

A: Starting with the least likely problem, is 80 the correct port for proxy_pass http://104.46.52.226/? If not, which port is this listening on? If it's, say, 5000, you need proxy_pass http://104.46.52.226:5000; This probably isn't your issue.
You need to set some headers in the location block so that IIS can use them:
    proxy_set_header  x-real-IP        $remote_addr;
    proxy_set_header  x-forwarded-for  $proxy_add_x_forwarded_for;
    proxy_set_header  host             $http_host;

To quote Karl Seguin:

Since Nginx is actually issueing the request to our web server, we are
  adding headers to the request so that the web server has all necessary
  informaton.

He also talks about caching.
File /etc/nginx/sites-enabled/armari.com looks like it has a commented out server { line. That's one of the errors. ALL the files in /etc/nginx/sites-enabled/ need to be working for Nginx to feel good. If that's this file, you probably just didn't paste the # (comment start code). Or perhaps you changed it since the error happened.


text:
Q: Want to read sequential lines in a file and do some mathematical calculation I have a file(Data.txt), which contains data like (two column data)
0.105785959943        9.75133617601e+15
0.111906693211        9.03309900398e+15
0.118381569654        9.10020956844e+15
0.125231079854        9.92284743442e+15
0.132476899971        8.90313525209e+15
0.140141960337        8.94055824107e+15
0.148250518026        9.26206609674e+15
0.156828233614        8.91802025262e+15

The file may contain 100 lines. Let me call the values in first column as r_i and second column as d_i (i may change from 0 to 100). My problem is to write a code to compute
C*(r_(i+1)-r_i)^3 * d_i, where C is a constant.
And also I want to write these data into a new file containing 3 columns, in which the third column should be our new computed data.
How can I achieve this? Does any body know how to solve this problem?

A: For reading the files in Python, take a look at here. For writing output to file, take a look here.

A: #include <iostream>

int main(int, char*[]) {
  const double C = 1;
  double rp, dp;
  double r, d;

  std::cin >> rp >> dp;
  while (std::cin.good()) {
    std::cin >> r >> d;
    if (std::cin.good()) {
      double t = r - rp;
      double v = C * t * t * t * dp;
      std::cout << rp << " " << dp << " " << v << std::endl;
      rp = r; dp = d;
    }
  }
  std::cout << rp << " " << dp << " " << 0 << std::endl;

  return 0;
}

A: awk is ideal for this type of calculations:
awk -v c="$c" '{if (s) print o, c*($1-r)^3*d;o=$0;r=$1;d=$2;s=1}' file

where c is a shell variable

A: Even though 5 persons down voted my question, I found my on way to solve the problem.
Here is the code which I used. It is written in Python.
enter codefrom numpy import *
from math import *
import operator

f = open('Data_Genergy_26.txt', 'r')
lines = f.readlines()
# initialize some variable to be lists:
r = []
ro = []
E =[]

# scan the rows of the file stored in lines, and put the values into some variables:
for line in lines:
    p = line.split()
    r.append(float(p[0]))
    ro.append(float(p[1]))
#Subtracting the current and previous item in a list
def foo(it):
    it = iter(it)
    t = it.next()
    for s in it:
        yield t, s
        t = s
list(foo(r))
E=[x[1] - x[0] for x in foo(r)]
#print E
#Cubing all elements in a list
def cube(E):
    return [i ** 3 for i in E]
#print cube(E)
#computing total energy
z =[a*b for a,b in zip(cube(E),ro)]
z[:] = [x*4/3*pi for x in z]
z.append(0.0) #for making r, ro, and z of same dimension
#print z

DataOut = column_stack((r,ro,z))
savetxt('output.dat', DataOut)

If there is any better way to implement this please inform me.
Thanks


text:
Q: Equation paramétrique du second degré C'est un exercice du concours d'admission en économie de L'Université Protestante au Congo.
Voici la question: déterminer la valeur de m pour que la fonction f(x)=(x-7)/(mx²+ mx+m+1) admette deux asymptotes verticales.

[Edited English translation]:

This is an exercise from the economics entrance examination of L'Université Protestante au Congo. The question is: determine the value of $m$ such that the function:
  $$
f(x) = \frac{x - 7}{mx^2 + mx + m + 1}
$$
  has two vertical asymptotes.

A: Hint: If $m \neq 0$, then $mx^2 +mx+m+1 = m(x^2 + x + 1 + 1/m)$. Using the quadratic equation, the roots of $x^2+x+1+1/m$ are $$ -\frac{1}{2}\pm \frac{\sqrt{1-4(1+1/m)}}{2}.$$ You will get two real roots whenever the discriminant $1-4(1+1/m)$ is positive. That is, when $1-4(1+1/m) > 0$.
Can you take it from there?

A: In order that function $$f(x) = \frac{x - 7}{mx^2 + mx + m + 1}$$ shows two vertical asymptotes, the denominator must cancel twice. This first implies that $m \neq 0$ (otherwise, the quadratic would not be anymore a quadratic).
Now, the roots of $${mx^2 + mx + m + 1}=0$$ are given by $$x_{\pm}=-\frac{m \pm \sqrt{-3 m^2-4 m}}{2 m}$$ and so the requirement is $$3m^2+4m=m(3m+4)\lt 0$$ which then implies $$-\frac{4}{3} <m<0$$


text:
Q: How to add 4 decimal places as precision while defining Schema in mongoose I am designing a wallet rest api where I am taking wallet balance as request body. I can enter balance as 10.123456 but i want to keep the decimal precision upto 4 places. that is my response gets saved with 10.1234.
What can my approach be?

A: You can use the following code:
const input = 10.123456;
const rounded = Math.floor(input * 10000) / 10000;

console.log(rounded);

You can, of course, add this code to your schema directly like:
myValue: {
    type: Number,
    set: v => Math.floor(v * 10000) / 10000
  }


text:
Q: Count distinct by multiple columns takes a long time I'm trying to perform count distinct in SQL server, by two fields.
I've tried two different ways. the first one is concatenation:
select count (distinct CONCAT ([UCID],[CALLSEGMENT]))
 from IVR_LINES
where UCID in (select UCID
from [EPMTest].[dbo].[IVR_LINES]
where MODULE = 'hozlap' and EVENT_NAME = 'A3' and EVENT_VALUE in ('1','2','3') and DATE> 20160911)
and EVENT_NAME = 'A6' or  EVENT_NAME = 'A7'

While the second one is by using a sub-query:
select COUNT(*) from(
select distinct UCID,CALLSEGMENT
 from IVR_LINES
where UCID in (select UCID
from [EPMTest].[dbo].[IVR_LINES]
where MODULE = 'hozlap' and EVENT_NAME = 'A3' and EVENT_VALUE in ('1','2','3') and DATE> 20160911)
and EVENT_NAME = 'A6' or  EVENT_NAME = 'A7'
)a

They take about the same running time (more than 10 seconds, probably due to the inner query itself).
 However, I would like to know - which one is more efficient? which method should I choose?
Thanks

A: Please post your execution plan to find where exactly it takes time. Meanwhile you can rewrite your query with exists clause like this.
SELECT COUNT(*)
FROM (
    SELECT DISTINCT UCID
        ,CALLSEGMENT
    FROM IVR_LINES IL
    WHERE EXISTS (
            SELECT 1
            FROM [EPMTest].[dbo].[IVR_LINES]
            WHERE MODULE = 'hozlap'
                AND EVENT_NAME = 'A3'
                AND EVENT_VALUE IN (
                    '1'
                    ,'2'
                    ,'3'
                    )
                AND UCID = IL.UCID
                AND DATE > 20160911
            )
        AND EVENT_NAME IN (
            'A6'
            ,'A7'
            )
    ) A

A: I think something is wrong with your queries
first DATE > 20160911 should give an error,
try to replace it with DATE > '20160911'
second and EVENT_NAME = 'A6' or  EVENT_NAME = 'A7'
is VERY different from and (EVENT_NAME = 'A6' or  EVENT_NAME = 'A7')
with your syntax the queries will count many more records than (I think) expected and this could be the problem of slow execution time
talking about which is the best... they are almost the same for the optimizer
you should add some info about primary key, indexes, number of records and some example of data.


text:
Q: Show button in the actionbar when a fragment is displayed I have a navigation drawer and I want to show a button in the actionbar only when a precise Fragment is show. How I can do this?

A: Try:
if(YourFragment.this.isVisible) { //Fragment is shown
    myBtn.setVisible(true);  //show button
    invalidateOptionsMenu();  //refresh actionbar
}
else{
    // Fragment is not shown
}

A: It's basically as in an activity. In your fragment:

*

*In OnCreate call setHasOptionsMenu(true);

*Inflate your menu in OnCreateOptionsMenu

*The system calls onOptionsItemSelected when an item is selected

See the note on the Fragment Guide for more information.

A: Just follow this Simple steps and make a try.

*

*Create a function in activity that makes that particular button
visible or hidden.

*Goto that child fragment from where you want to show menu button on
actionbar and call function created in step 1 statically.

*This step is not important but if your desired fragment is in
viewPager or is created but not on screen. Because in viewPager it
loads 3 Fragments at a time current one ,previous and next fragment.
So in this case , override onMenuVisible() or onUserVisible() and
call function on visibility true using if condition.

A: In your desired Fragment just override the following method,
@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
}

inflate the menu using MenuInflater and get the menu item as follows,
MenuItem yourMenuItem = menu.findItem(R.id.your_menu_name);
yourMenuItem.setVisible(true);

by default in your menu and in your menu item xml make that menuitem visiblity as false


text:
Q: Неправильно отображается navbar (boostrap) Неправильно отображается navbar. Этот пример скопировал из оф. документации bootsrap.
Код:

  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

  </button>
  Navbar

        Home (current)

        Features

        Pricing

        Disabled

Результат:

Должно быть так:

A: Добавьте класс .navbar-extend-* в зависимости от того, с какой ширины экрана вы хотите, чтобы появлялась кнопка:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

  </button>
  Navbar

        Home (current)

        Features

        Pricing

        Disabled


text:
Q: Terraform: Map Set of Complex Objects to List of a specific property I'm having a complex set of complex objects, e.g. DynamoDB tables received via data
data "aws_dynamodb_table" "table" {
  for_each = toset([
    "table-1",
    "table-2",
    "table-3",
  ])
  name     = each.value
}

I want to use some of the table properties in different places, e.g. creating event source mappings to lambda functions, which is quite easy:
resource "aws_lambda_event_source_mapping" "mapping" {
  for_each          = data.aws_dynamodb_table.table
  batch_size        = 100
  event_source_arn  = each.value.stream_arn
  function_name     = // some function ARN
  starting_position = "LATEST"
}

Now where I'm stuck: how do it just get a list of some specific field like the table ARN, so that I can use that directly in a IAM policy for the resources?
statement {
  actions = [
    "dynamodb:PutItem",
    "dynamodb:UpdateItem",
    "dynamodb:Query",
    "dynamodb:Scan"
  ]
  # that's not how it works
  resources = tolist(data.aws_dynamodb_table.table.*.arn)
  effect = "Allow"
}

I'm sure the terraform documentation gives me an answer on that, but I'm not able to find it.

A: Since your data.aws_dynamodb_table.table is a map due to the use of for_each, you have to use values to get all the values for the arn:
 resources = values(data.aws_dynamodb_table.table)[*].arn


text:
Q: Extraction of UDP data stream from pcap file how can i get udp data stream (in ascii format) of all packets captured in pcap file into a text file using tshark.
I tried this
tshark -V -r /tmp/file_src.pcap > file_dst.txt

but how can i get only udp data stream?
Thanks

A: You can tshark's -Y flag to specify a filter
tshark -V -r /tmp/file_src.pcap -Y udp > file_dst.txt