NetworkStream AccessViolationException on thread

Question: I have a little program that gets a stream from TCPclient, but I am getting an error message that says: "".
The code as follows:
<code>  AutoResetEvent _waitEvent = new AutoResetEvent(false);
    bool _isConnected = false;
    private TcpClient tcpClient;
    public void Connect()
    {
        Thread t = new Thread(new ThreadStart(() =>
        {

            try
            {
                while (true)
                {

                     tcpClient = new TcpClient();
                    tcpClient.Client.NoDelay = true;
                    tcpClient.Client.Blocking = true;
                    tcpClient.Client.DontFragment = false;
                    tcpClient.Client.LingerState.Enabled = false;
                    tcpClient.Client.LingerState.LingerTime = 0;
                    tcpClient.Client.UseOnlyOverlappedIO = true;
                    try
                    {
                        tcpClient.Connect("myhost", 8001);
                        NetworkStream networkStream = tcpClient.GetStream();
                        byte[] buffer = new byte[tcpClient.ReceiveBufferSize];
                        networkStream.BeginRead(buffer, 0, buffer.Length, ReadCallback, buffer);
                        var wasSet = _waitEvent.WaitOne(TimeSpan.FromSeconds(30));
                        if (wasSet)
                        {
                            if (_isConnected)
                            {
                                return;
                            }
                            else
                            {
                                Thread.Sleep(TimeSpan.FromSeconds(10));
                                continue;
                            }
                        }
                        else
                        {
                            Thread.Sleep(TimeSpan.FromSeconds(10));
                            continue;
                        }
                    }
                    catch (Exception ex)
                    {
                        Thread.Sleep(TimeSpan.FromSeconds(10));
                        continue;
                    }
                }
            }
            catch (ThreadAbortException)
            {
                return;
            }
        }));
        t.Start();
    }

    private void ReadCallback(IAsyncResult result)
    {
        try
        {
            int read;
            NetworkStream networkStream;
            try
            {
                networkStream = tcpClient.GetStream();
                read = networkStream.EndRead(result);
            }
            catch (Exception ex)
            {
                Close();
                return;
            }

            if (read == 0)
            {
                Close();
                return;
            }
            if (!_isConnected)
            {
                _isConnected = true;
                _waitEvent.Set();
            }
            byte[] buffer = result.AsyncState as byte[];
            networkStream.BeginRead(buffer, 0, buffer.Length, ReadCallback, buffer);
        }
        catch { };
    }

    public void Close()
    {
        try
        {
            _isConnected = false;
            if (tcpClient != null)
                tcpClient.Close();
        }
        catch
        {

        }
    }
</code>
In row:
<code>networkStream.BeginRead(buffer, 0, buffer.Length, ReadCallback, buffer);
</code>
I getting an error that says: "AccessViolationException was unhandled - Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
How to can I fix it? Thanks!
Comment: We need to see some code to help you out
Comment: What is code? What is message? Something, anything would help
Comment: Well he is editing. I think he tabed, and published it. And your error Message s missing
Comment: i getting a error when i trying to enter a code here, and i could not, so i paste at pastebin site:) sorry for the delay! and thanks for your patient!
Comment: Could you put the code in the post? Not everybody can open pastebin :P
Comment: I have the same problem. Is there anybody to help or did you solve it?
Answer: for  user2191454, try this:
<code>    private void ReadCallback(IAsyncResult result)
{
    try
    {
        int read;
        NetworkStream networkStream;
        try
        {
            networkStream = tcpClient.GetStream();
            read = networkStream.EndRead(result);
        }
        catch (Exception ex)
        {
            Close();
            return;
        }

        if (read == 0)
        {
            Close();
            return;
        }
        if (!_isConnected)
        {
            _isConnected = true;
            _waitEvent.Set();
        }
        try
        {
            byte[] buffer = result.AsyncState as byte[];
            try
            {
                ParseData(buffer, read);
            }
            catch (Exception e1)
            {
            }
            //Then start reading from the network again.
            networkStream.BeginRead(buffer, 0, buffer.Length, ReadCallback, buffer);
        }
        catch (Exception ex)
        {
            Close();
            return;
        }
    }
    catch (Exception ex)
    {
    }
}
</code>


Android custom Seekbar from drawable

Question: Could you please help me to draw custom Seekbar like shown in this picture -

Here is my code:
<android.support.v7.widget.AppCompatSeekBar
            android:id="@+id/volume_seekbar"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:progressDrawable="@drawable/seekbar_drawable"/>

seekbar_drawable.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@android:id/background"
        android:drawable="@drawable/seekbar_background" />
    <item
        android:id="@android:id/progress"
        android:drawable="@drawable/seekbar_progress" />
</layer-list>

seekbar_background.xml:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape xmlns:android="http://schemas.android.com/apk/res/android">
            <gradient
                android:layout_height="20dp"
                android:centerY="0.5"/>
        </shape>
    </item>
    <item>
        <clip>
            <bitmap
                android:layout_height="10dp"
                android:src="@drawable/volume_empty"
                android:tileMode="repeat" />
        </clip>
    </item>
</layer-list>

seekbar_progress.xml:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <clip>
            <shape>
                <gradient
                    android:centerY="0.5"
                    android:endColor="@color/colorWhite"
                    android:startColor="@color/colorWhite" />
            </shape>
        </clip>
    </item>
    <item>
        <bitmap
            android:src="@drawable/volume_empty"
            android:tileMode="repeat" />
    </item>
</layer-list>

where @drawable/volume_empty is volume_empty.png
Answer: I have found solution.
seekbar_background.xml:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape xmlns:android="http://schemas.android.com/apk/res/android">
            <gradient
                android:centerY="0.5"/>
        </shape>
    </item>
    <item>
        <clip>
            <bitmap
                android:src="@drawable/ic_volume_empty"
                android:tileMode="repeat" />
        </clip>
    </item>
</layer-list>

seekbar_progress.xml:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <clip>
            <bitmap
                android:src="@drawable/ic_volume_full"
                android:tileMode="repeat" />
        </clip>
    </item>
    <item>
        <bitmap
            android:src="@drawable/ic_volume_empty"
            android:tileMode="repeat" />
    </item>
</layer-list>

I've added similar transparent padding in both images, like ic_volume_empty - ic_volume_empty and ic_volume_full - ic_volume_full

Android custom Seekbar from drawable


How to use the repaint method in Java Swing

Question: I am very new to the Graphics portion of Java. I have created a frame and on it I have added a panel whose color has been set to Green. Now on clicking that panel I want to draw a circle using a test class's object called Mypanel. But it does not happen. Please guide !
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;

class Mypanel extends JPanel
{
    @Override
    public void paintComponent(Graphics g)
    {
        g.drawOval(15, 15, 5, 5);
    }
}
public class algo extends javax.swing.JFrame {

    public algo() {
        initComponents();
        jPanel1.setBackground(Color.GREEN);
    }
    Mypanel p = new Mypanel() ;

    private void jPanel1MouseClicked(java.awt.event.MouseEvent evt) {
        p.repaint();
    }

    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new algo().setVisible(true);
            }
        });
    }

}

If I were to guess I would say that I am not supposed to use the repaint method, but I was told that this was to be used.
Comment: It's impossible to be sure, since you haven't included your `initComponents()` method in your question, but a likely reason is that your `Mypanel` instance has a width of zero and height of zero.  You can fix this by overriding [getPreferredSize()](http://docs.oracle.com/javase/8/docs/api/java/awt/Component.html#getPreferredSize--) in your Mypanel class.  Also, the first line in an overridden paintComponent method should always be `super.paintComponent(g);`.  If you don't do this, you will see strange behavior.
Comment: In my opinion you will need repaint when you are changing structure, i.e Oval to square or similarly. In swing most of the time component changes gets reflected automatically. when you make call to setter method of the specific attribute.
Comment: Based on your code, I believe you are a C# Programmer, right?
In Java, only creating a Method with name of your object and the sufix `MouseClicked` doesn't add an event to your object at all. I sugest you to study more about Java, Events, Naming convetions before and then rewrite your code =)
Answer: That code as supplied would not compile.  For better help sooner, post a Minimal, Complete, and Verifiable example or Short, Self Contained, Correct Example.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Mypanel extends JPanel {

    boolean clicked = false;

    Mypanel() {
        setBackground(Color.GREEN);
        MouseListener mouseListener = new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                clicked = true;
                repaint();
            }
        };
        this.addMouseListener(mouseListener);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(400, 100);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (clicked) {
            g.drawOval(15, 15, 50, 50);
        }
    }
}

public class algo extends JFrame {

    public algo() {
        initComponents();
        pack();
        //jPanel1.setBackground(Color.GREEN); ?!?
    }

    protected final void initComponents() {
        add(new Mypanel());
    }

    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new algo().setVisible(true);
            }
        });
    }
}

Answer: There are a few things to correct in your example...
When you create the frame (i.e. in the constructor) you'll want to call super(). This is the first thing the constructor has to do. Then, you'll probably want to set an initial width/height, and set the background color of the frame green.
You need to add a mouse listener so that the mouseClicked method is actually called. Then have it add the 'MyPanel' object to the frame, and call repaint.
I think that's roughly what you're going for.
Comment: *"I think that's roughly what you're going for."*  I think you should test ideas before writing them in public.  *"you'll probably want to set an initial width/height"*  No, the components (including custom components like `Mypanel` should override `getPreferredSize` to return a sensible value, then the frame should be packed to that size.  *"Then have it add the 'MyPanel' object to the frame, and call repaint."*  Better to add the panel to the frame at start-up, then simply change its state (and call `repaint()` when the button is clicked.
Comment: There is no reason to write `super()`.  It is always called automatically, if no call to a different constructor is present.


How to catch key presses in editable QTableWidgetItem?

Question: Now I can process all key presses in my QTableWidget in a function eventFilter() (after calling of myTable->viewport()->installEventFilter(this); in the constructor).
The only place where this doesn't work is editable cell while editing (because it grabs all key presses). To fix it I can't call installEventFilter() for each item in the table, because these items are not QObjects (and also I can't use connect for putting of my processing of key presses).
The only solution I have is to put QLineEdits in these cells and to use event filter to catch key presses while editing. But is it possible to solve it using only standard items? (i.e. only QTableWidgetItem with a flag Qt::ItemIsEditable)
Also I can call grabKeyboard() for my QTableWidget. In this case I'll have all key presses (even while editing of cells by user), but it blocks edit box (i.e. user can't input anything). May be it is possible to fix broken edit boxes after calling of grabKeyboard() for the table?
Comment: Can you implement another class, subclassing `QTableWidgetItem`, in order to have all the functions of `QTableWidgetItem` and your own functions to get the behavior you want?
Comment: Yes, I can implement another class, but I don't understand how to override processing of key presses in this case.
Comment: "because it grabs all key presses". You do get key releases though.  Wonder what is doing the grabbing. Maybe there is a good reason?
Comment: @S.Pinkus The dream was to catch key presses silently (i.e. without breaking of existent processes in editabal cell). And those words about `grabKeyboard()` were only to explain why I expect that it is possible to solve this problem.
Answer: This so quite ease to achieve. Just subclass QStyledItemDelegate override createEditor method like this:
QWidget *AlterEditorDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const {
    QWidget *result = QStyledItemDelegate::createEditor(parent, option, index);
    result->installEventFilter(new YourEventFilter(result));
    return result;
}

Than replace delegate for your QTableWidget.
Or even better instead subclassing create proxy class which accepts original QAbstractItemDelegate (more writing but much more universal and can be composed with other modifications).
AlterEditorProxyDelegate::AlterEditorProxyDelegate(QAbstractItemDelegate *original, QObject *parent)
    : QAbstractItemDelegate(parent)
    , original(original)
{}

QWidget *AlterEditorProxyDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const {
    QWidget *result = original->createEditor(parent, option, index);
    result->installEventFilter(new YourEventFilter(result));
    return result;
}

// other methods which invokes respective methods for `original` style.

Answer: Since QTableWidgetItem has no function keyEvent() that you can overload this is not possible.
What you have to do is set a delegate with custom editor factory that produces widgets where keyEvent is overloaded.
Comment: Thank you for your answer! I am not completely sure that there are no  simplier solution. For instance, I can call `grabKeyboard()` for my `QTableWidget`. After it I'll have all key presses (even while editing of cells by user), but also that edit box will not work as it is expected.
Answer:
But is it possible to solve it using only standard items? (i.e. only QTableWidgetItem with a flag Qt::ItemIsEditable)

Not really. In Qt4 QTableWidget leaks KeyRelease events from the cell editor, but exploiting that would be an ugly hack.

May be it is possible to fix broken edit boxes after calling of grabKeyboard() for the table?

I once tried doing that and then posting the events to QTableWidget but ran into trouble as well.
The proper thing to do is to create your own delegate and install event filter in createEditor function. You can do something like this:
class FilterDelegate : public QStyledItemDelegate
{
public:
    FilterDelegate(QObject *filter, QObject *parent = 0) :
        QStyledItemDelegate(parent), filter(filter)
    { }

    virtual QWidget *createEditor(QWidget *parent,
                                  const QStyleOptionViewItem &option,
                                  const QModelIndex &index) const
    {
        QWidget *editor = QStyledItemDelegate::createEditor(parent, option, index);
        editor->installEventFilter(filter);
        return editor;
    }

private:
    QObject *filter;
};

Then your MainWindow constructor would look something like this:
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    setupUi(this);

    tableWidget->setItemDelegate(new FilterDelegate(this));
    tableWidget->installEventFilter(this);
}

And your event filter:
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
    if(event->type() == QEvent::KeyPress)
    {
        // do something
    }
    return QMainWindow::eventFilter(obj, event);
}

Comment: Thank you. As far as I understand the line `tableWidget->installEventFilter(this);` is not necessary. Do you agree?
Comment: @Ilya, if you only want to capture presses from the cell editors widgets, then yes, you are right.
Comment: As far as I understand we need to do `tableWidget->viewport()->installEventFilter(this);` to capture any other key presses in this table (not `tableWidget->installEventFilter(this);`)
Comment: It worked for me when I installed it on the `tableWidget`. You can try it both ways and see which one works.
Answer: ANOTHER ALTERNATIVE:
You can install event filter on the QApplication object and capture all events. This is a bit of an overkill if you ask me, but it would work for a small application and requires minimal code.
All you have to do is:
qApp->installEventFilter(this);

And:
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
    if(event->type() == QEvent::KeyPress)
    {
        // do something
    }
    return QMainWindow::eventFilter(obj, event);
}


Simplest way to check "is app running for the first time"

Question: I am writing an app for the Ubuntu Phone and I want to store a boolean which represents if the App is running for the first time or has it run before. Personally I don't really want to create a full fledged database but if it comes to that, then sure.
Are there any simple helpers that I could call and get done ?
Comment: What I simply do sometimes is have the application create a hidden (empty?) file *if it does not exist yet*.  Depending on if it existed already, you know if the applications runs for the first time or not.
Comment: What about adding --first-run option to your app ? You could check process of that app and whether or not it runs with that flag. Helps avoid having a file
Answer: A common way is to create a dotfile in the user's home directory: if the file does not exist, then the program is run for the first time (or the user has requested that the program behave as if it were run for the first time, by manually deleting the file). If its sole purpose is to perform this check, the file can be empty, but usually dotfiles also serve as configuration files. For example, the Zsh shell prints this if the configuration file ~/.zshrc does not exist when it starts:
This is the Z Shell configuration function for new users,
zsh-newuser-install.
You are seeing this message because you have no zsh startup files
(the files .zshenv, .zprofile, .zshrc, .zlogin in the directory
~).  This function can help you with a few settings that should
make your use of the shell easier.

You can:

(q)  Quit and do nothing.  The function will be run again next time.

(0)  Exit, creating the file ~/.zshrc containing just a comment.
     That will prevent this function being run again.

(1)  Continue to the main menu.

(2)  Populate your ~/.zshrc with the configuration recommended
     by the system administrator and exit (you will need to edit
     the file by hand, if so desired).

--- Type one of the keys in parentheses ---


Mass Effect 3 - Best ending after missing some time sensitive missions

Question: I just missed some time sensitive missions, but I guess I'm doing well with the other assets:

Collector's base intact
Rachni Queen saved
Genophage cured
Council saved

The missions that I didn't complete are the ones I should've done before the Priority: Tuchanka part of the game.
Should I go back (lose around 5 hours of game) or can I keep on moving forward and compensate these lost points through Galaxy readiness on the multiplayer mode?
Thanks!
Answer: Provided you haven't messed up/missed out on many other assets, you should be able to get the "best" ending with sufficiently high galactic readiness. You need 5000 effective war assets, how much total war assets do you have now?
Comment: If you have the Extended Cut DLC installed, I think you only need somewhere around 3000 for the best ending.
Comment: I think I was around 2400 when I finished the mission the Citadel. I might have to double check on that.
Answer: Got around 4000 now, just by doing side missions after Priority: Citadel (2), so I guess it's not a problem.


where to put log4j.properties file for tomcat6 java apps?

Question: I'm trying to configure logging for a RESTful / jax-rs java app. The app functions correctly, but I can't get logging configured. in my code I have:
private static Logger logger = Logger.getLogger(Foo.class);
        static
        {
                PropertyConfigurator.configure("log4j.properties");
        }
and i have put the usual log4j.properties in WebContent/WEB-INF/,
but when I start tomcat with this app, I get in catalina.out:
log4j:ERROR Could not read configuration file [log4j.properties].
java.io.FileNotFoundException: log4j.properties (No such file or directory)
where else can i possibly put the file? sorry if this is a n00b question, but this has been stumping me for a while.
Answer: Put it with your application code under /WEB-INF/classes, log4j expects to find it in the classpath. And you don't need to call the configurator, that happens automatically.
Comment: And don't manually call `PropertyConfigurator.configure()` It happens by itself.


Why Pro Junglers often buy SightStone?

Question: I know that sightstone is good on Lee Sin. It provides some good mobility for him and extra vision control.
But when watching Pro Jungler streamers or youtubers I sometimes see cases of them buying SightStone on Vi, Nunu, Elise even Jarvan.
I know that "Wards Win Games" and I believe in that, but is it worth it at all?
Comment: well you are talking about pro players right ? At their level vision and map awareness is a greater resource than a few more stats from a different item. +X AD or AP has no worth if you don't have vision to be able to track the enemy's team members. Vision isn't "nothing" or "useless" as you say, it's a valuable resource, getting even more value when you reach higher levels of play.
Comment: "I know that "Wards Win Games" and I believe in that, but is it worth it at all?" is winning the game not worth it enough for you ? ^^
Comment: It's not granted that good warding is gonna win you the game. It helps but my point is junglers can delay their build and the wards ending up not doing nothing. and becoming useless.
Comment: `It provides some good mobility` doubt that. it provides sustain
Comment: for lee it provides mobility for his W
Comment: Wards help laners potentially win their lane more then any jungler can gank. Knowing whether or not the enemy jungler/midlaner is comming for your top lane lets you play more agressive or passive.
Answer: The jungler has the ability to place wards all over the map. While warding the map is the job of every player, the jungler and supporter usually do more warding than the other roles.
High elo games usually have a lot more wards than mid-low elo ones. Everyone buys wards but the jungler has the advantage of not having to farm in lane which allows for offensive and defensive vision control without losing too much farm. Also the sightstone provides some extra HP which is useful on every jungler.
Answer: Sightstone gives you free wards every time you go back, but also precious stats, especialy early in the game. An early sightstone on the jungler gives your team a huge vision advantage, and makes him tankier for a cheap cost.
The jungler also has more option for placing wards, since early on your support will probably be limited to botlane and the surounding jungle: if his team is winning, your jungler will place aggressive wards in the enemy jungle to be able to counter gank and snowball even further ahead.
when your team is losing, he will ward his own jungle to allow his team to come and help him when the enemy jungler is invading, thus allowing the team to get back into the game.
You'll notice that in pro games and most high elo games, it's usual for the junglers, and even most laners, to buy 2-3 wards on each back, to assure vision for their team. Buying a sightstone on the jungler allows him to keep doing so, while not delaying his items too much, since junglers are usually starved on farm later in the game.
Answer: So sightstone is obviously used to grant vision and junglers can place deep wards without giving up much farm etc. The jungler typical uses his/her wards to track the enemy jungle. Junglers with weaker early games typically try to farm as much as possible and counter gank when necessary. The vision from sightstone allows you to react to ganks and counter gank them much sooner. Thats my theory on why pro junglers rush sightstone. That being said I'm a relatively low elo so I really can't say for sure.

Why Pro Junglers often buy SightStone?


Conditionally decoding JSON based on a field in the JSON

Question: I am receiving JSON from an API and the response can be one of 30 types. Each type has a unique set of fields, but all responses have a field type which states which type it is.
My approach is to use serde. I create a struct for each response type and make them decodable. Once I have that how do I choose which struct should be used for a freshly received message?
At the moment, I've created another struct TypeStruct with only a single field for type. I decode the JSON into a TypeStruct, then choose the appropriate struct for received message, based on type value, and decode the message again.
I would like to get rid of this decoding duplication.
Comment: Your current solution is what I would do. What do you think would be better or more efficient about avoiding the "decoding duplication"?
Comment: I'm comming from python, so I don't feel comfortable with stacilly typed languages. But if you say, that my approach is ok, I'll stick with it.
Comment: Just my opinion, but this sounds like a good example of premature worrying about optimization. Get your code to run and see if you deem it fast enough. If not, profile your code before changing it – perhaps the JSON decoding isn't even the problem.
Answer: You can use the existing enum deserialization. I'll give a step by step example to deserialize your format to the following enum:
#[derive(Debug, PartialEq, Eq, Deserialize)]
enum MyType {
    A {gar: ()},
    B {test: i32},
    C {blub: String},
}

Start with an example json string:
let json = r#"{"type": "B", "test": 42}"#;

Turn it into a Value enum
let mut json: serde_json::Value = serde_json::from_str(json).unwrap();

Rip out the type field
let type_ = {
    let obj = json.as_object_mut().expect("object");
    let type_ = obj.remove("type").expect("`type` field");
    if let serde_json::Value::String(s) = type_ {
        s
    } else {
        panic!("type field not a string");
    }
};

Create the "proper" enum json. A struct with a single field where the name of the field is the enum variant and the value of the field is the variant value
let mut enum_obj = std::collections::BTreeMap::new();
enum_obj.insert(type_, json);
let json = serde_json::Value::Object(enum_obj);

Use the generated json deserializer to turn the json into a value of your enum
let obj: MyType = serde_json::from_value(json).unwrap();

Comment: it's more of a DRY solution. This way you don't need to handle any type in two locations. You just need to declare the enum. Never to match over all the possible types or anything. Speedwise this is probably worse than the solution offered in the Question (except if there are a lot of `String` fields and no struct/enum fields, then it's probably faster than the solution in the Question). It's hard to know without seeing the exact code. General solutions that are faster require precise knowledge about the field order in the json string and/or hacks on serde
Comment: Any numbers or gut feelings on the efficiency of this compared to the "decode it twice" solution outlined in the question?
Comment: Thank you, I suspected that, something like you suggested is possible. Can I use the same technique with rust-serialize?
Comment: I'm sure that works, too, yes. It also has a `Json` enum for raw json and it has a special format for enums (most likely the same as serde?). So the conversion of my above code to `rustc-serialize` should be straight forward
Comment: unfortuenatly, rustc-serialize can't do that. http://stackoverflow.com/questions/25604339/parse-json-value-as-enum-in-rust

so this example (http://is.gd/XB1TiG) produces

{"variant":"Message","fields":["123","superuser","some text","beginning of epoch"]}


requestImageForAsset always returns nil - even after checking for nil

Question: So, I'm having a weird (and frustrating) issue.
I'm looping through an array of assets returned by an image picker:
let manager = PHImageManager.defaultManager()
let options = PHImageRequestOptions()
for asset in assets {
    var image = UIImageView?
    manager.requestImageForAsset(asset, targetSize: CGSize(width: asset.pixelWidth, height: asset.pixelHeight), contentMode: .AspectFit, options: option, resultHandler: { (result, info) -> Void in
        if result == nil {
            print("Nil alert!")
            return
        }
        print("not nil")
        image!.image = result

    }
}

In the console I get the expected messages:
not nil

immediately followed by this message:
fatal error: unexpectedly found nil while unwrapping an Optional value

I've been messing around with this for hours and I can't seem to figure out what exactly the problem is. If I try to print the result directly it says something like <UIImage: 0x12f780a20>, {45, 60}
Any help would be welcome :)
Comment: There are two optional values on that line, image and result.
Answer: You aren't setting anything to image after defining it, so it's going to be nil here:
 var image = UIImageView?

When you force-unwrap it with ! here, you're hitting the runtime error:
 image!.image = result

Comment: That is so obvious it hurts. That's whats happen when you stare at something for too long. I'll accept this as the answer as soon as I can. Thank you!


(impala) AnalysisException: Subqueries are not supported in the select list

Question: I have a query like this, and appearantly Impala doesn't support subqueries in SELECT statement. How can I neatly rewrite it in Impala?
SELECT
  col1,
  col2,
  ...
  CASE
    WHEN (SELECT 1
          FROM
            table1 x,
            table2 y
          WHERE
            x.id = y.id
          LIMIT 1) = 1
    THEN
      'A'
    ELSE
      'B'
  END
    coln

FROM
...

Your query has the following error(s):
AnalysisException: Subqueries are not supported in the select list.
Answer: You could try
SELECT col1, col2, ... 'A' coln
  FROM ...
  WHERE EXISTS (SELECT 1 FROM table1 x, table2 y WHERE x.id = y.id LIMIT 1)
UNION ALL
SELECT col1, col2, ... 'B' coln
  FROM ...
  WHERE NOT EXISTS (SELECT 1 FROM table1 x, table2 y WHERE x.id = y.id LIMIT 1)

No guarantees, haven't tried it myself.
Comment: Thanks, this works. Though, mine is actually a very large query, has multiple subqueries and it's intimidating to rephrase like this :) And it costs lots of  extra processor time if I'm not wrong.
Comment: I haven't checked the query plan myself, but the subquery in your example is independent from the main query, thus I guess it will be evaluated only once. If you have a dependent subquery, you may use a join instead, but the best way to do that depends on the actual query.
Answer: In general, a cleaner solution is placing the subqueries into the FROM clause, thereby linking the subqueries to the main table through inner or left joins. I usually do this when dealing with complex types in Impala.
However, in your specific example you are trying to do a left join, defining a field for each row which indicates whether the join was successful ('A') or not ('B'). In this case you could do the following:
SELECT
  x.id, x.col2, x.col3, ...
  CASE
    WHEN y.id IS NOT NULL THEN 'A'
    ELSE 'B'
    END
  coln
FROM table1 x LEFT JOIN
     table2 y USING (id)
...


Why does Titan execution not trigger when meleeing a doomed Titan

Question: This question was already asked and answered for Titanfall 1, but I wonder if there are any differences for Titanfall 2.
I just had this situation where I (in Ronin) meleed another Titan who was doomed at least three times. We were hitting each other and then I was doomed to and he performed an execution on me, which was very frustrating.
(My Sword Core was NOT activated at that moment.)
I felt like this was happening before, so I wanted to ask:
Is there more to Titan executions than meleeing a doomed Titan?
Answer: For starters, I have seen this behavior before too and have not found an easily reproducible scenario for it. 9 times out of 10 the execution works as expected.
There are several points to make, although a recording would have really helped to get to the exact reason for the execution not to happen.

The other linked question states that "you cannot trigger an execution from behind" which is false in Titanfall 2.
If another titan is doomed but is ejecting (or going nuclear) they cannot be executed, although this doesn't sound like what you described.
If a titan is doomed, but has picked up battery and has a shield, the shield will prevent that titan from being executed.
It is possible to stun lock another titan with melee when the other titan is moving forward, if due to timing the other titan punches just prior to you punching, then you will be hit back, miss your punch, and then move into another punch. If you are hit into a wall and knocked back into the second punch, this is essentially a stun lock.
There is also a slightly buggy issue with titan executions. If you are on something and the other titan is below you, for instance if you happen to be standing on a car while the other titan is not, it is possible that the execution does not trigger for some reason. It is also the same if you happen to have the high ground during the melee encounter. I am not sure if this is a visual bug where the attack visually takes place but does not actually register as a hit towards damage, or what, but I have observed this in several instances. It is certainly not consistent though.
Comment: Thanks, those points sound reasonable. I think "lag" doesn't have to be listed here, because almost every weird behavior can also be caused by lag.
Comment: "If a titan is doomed, but has picked up battery and has a shield, the shield will prevent that titan from being executed." This just isn't true.
Comment: Perhaps it has since been patched, I don't play TF2 right now. Can you show a clip where you get executed while doomed with a battery shield?


How different are the elf and human sides?

Question: I've just finished the Goth Kids quest, and my next quest is to pick a side. I'm curious how different the game plays for the two sides? In particular, my brother and I are both playing the game independently, and I'd like to know if we pick different sides, we'll be confused when talking to each other.
With as few spoilers as possible, please.
Answer: They're basically identical.
Aside from the buddies available to you during the school invasion, events play out essentially identically.
Comment: Yep this is correct, an extra tip I could give is save right before you pick so you can reload and get both the achievements.
Answer: The only thing that will be different is a brief buddy selection, one fight, and one or 2 cut scenes. Nothing major, no effect on the game play at all, just depends on who you want to make mad for a few minutes.
Answer: In addition to what has already been said, you get a different weapon as reward:
Elves: Butters' Hammer of Storms

122-170 (3x)
Shock dmg +50

Humans: Stan's Slashing Blade of the Ranger

180-250 (x2)
Target starts bleeding on Perfect Attack
A Perfect Attack targets everyone in a column.


setUndecorated(true) to a JDialog created from an instance of JOptionPane

Question: I currently have a JDialog created by calling the createDialog() method from my instance of JOptionPane:
JOptionPane pane = new JOptionPane(myPanel, JOptionPane.PLAIN_MESSAGE,JOptionPane.DEFAULT_OPTION, null, new Object[]{}, null);
dialog = pane.createDialog(null, "");

I wanted to be able to remove the title bar from the JDialog by calling setUndecorated(true) onto the JDialog, but I get an IllegalComponentStateException: The dialog is displayable exception when I attempt to run my program.
As far as I know, the dialog is not being displayed before I call dialog.show(), which leads me to believe that the dialog is indeed "displayable" upon instantiating the dialog through pane.createDialog() far beyond my understanding of the JDialog API.
I have attempted to call setVisible(false) prior to using setUndecorated(true), but to no avail.
Any help would be appreciated as to how or of it is possible at all to remove the title bar of a JDialog of this type. Removing the title bar from a normal JDialog is easy enough, as seen from numerous other answers to questions of this type, but I cannot seem to get it to work for a JDialog created through createDialog().
Relevant code:
            input= new JTextField(50);

        input.addKeyListener(new ConsoleKeyListener());

        input.addAncestorListener( new RequestFocusListener() );
        field = new JTextArea();
        field.setEditable(false);
        field.setLineWrap(true);
        JScrollPane area = new JScrollPane(field, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        field.setRows(10);
        field.setText(consoleText);
        JPanel myPanel = new JPanel();

        myPanel.setLayout(new BorderLayout(0,0));
        myPanel.add(input, BorderLayout.PAGE_END);
        myPanel.add(area, BorderLayout.PAGE_START);
        input.setFocusable(true);
        input.requestFocus();
        int result = 101;
        //int result = JOptionPane.showOptionDialog(null, myPanel,"", JOptionPane.DEFAULT_OPTION,JOptionPane.PLAIN_MESSAGE, null, new Object[]{}, null);
        JOptionPane pane = new JOptionPane(myPanel, JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION, null, new Object[]{}, null);

        dialog = pane.createDialog(null, "");
        dialog.setVisible(false);
        dialog.setUndecorated(true);
        //dialog.undecorated = true;

        //dialog.setOpacity(0.55f);
        removeMinMaxClose(dialog);
        removeMinMaxClose(pane);
        removeMinMaxClose(myPanel);
        dialog.getRootPane().setOpaque(false);

        //JDialog dialog = new JDialog();
        //dialog.setVisible(false);
        //dialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        //myPanel.setUndecorated(true);
        //dialog.setUndecorated(true);
        //dialog.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
        //dialog.setBounds( 100, 100, 300, 200 );
        dialog.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                System.out.println("yo");
            }
        });
        dialog.setVisible(true);
        dialog.show();

Answer: You need to read the JavaDoc entry on Component#isDisplayable, then have a look at the source code for create dialog

"A component is made displayable either when it is added to a displayable containment hierarchy or when its containment hierarchy is
  made displayable. A containment hierarchy is made displayable when its
  ancestor window is either packed or made visible."

Basically the dialog is packed as part of the createDialog method
Possible solution
A possible solution is to create your own dialog...

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Frame;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestOptionPane11 {

    public static void main(String[] args) {
        new TestOptionPane11();
    }

    public TestOptionPane11() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                final JDialog dialog = new JDialog((Frame)null, "Boo");

                JOptionPane op = new JOptionPane("Look ma, no hands", JOptionPane.INFORMATION_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
                op.addPropertyChangeListener(new PropertyChangeListener() {
                    @Override
                    public void propertyChange(PropertyChangeEvent evt) {
                        String name = evt.getPropertyName();
                        if ("value".equals(name)) {

                            dialog.dispose();

                        }
                    }
                });

                dialog.setUndecorated(true);
                dialog.setLayout(new BorderLayout());
                dialog.add(op);
                dialog.pack();
                dialog.setLocationRelativeTo(null);
                dialog.setVisible(true);
            }
        });
    }

}

Comment: Thank you for the JavaDoc reference and excellent explanation. Your solution helped me create a very believable console.


Get ACF post meta value in query

Question: I would like to add the value of an ACF custom field into a plugin in order to narrow the query with it.
Here the function I've create in order to retrieve the value :
function vayvo_elements_post_difficulty(){
$post_meta = the_field( array(
    'meta_key'=> 'difficulty',
    'hide_empty' => false,
));

if ( ! empty( $post_meta ) && ! is_wp_error( $post_meta ) ){
    foreach ( $post_meta as $meta_value ) {
        $options[ $meta_value->string ] = $post->meta_value;
    }
    return $options;
}

And here the code to display it :
enter       $this->add_control(
        'progression_post_difficulty',
        [
            'label' => esc_html__( 'Narrow by difficulty', 'progression-elements-vayvo' ),
            'description' => esc_html__( 'Choose a difficulty to display posts', 'progression-elements-vayvo' ),
            'label_block' => true,
            'multiple' => true,
            'type' => Controls_Manager::SELECT2,
            'options' => vayvo_elements_post_difficulty(),
        ]
    );

Unfortunetly, I can see the new args into the query but is totally empty even if I have posts with this meta_key fielded.
Someone have an idea?
best regards,
Clément
Comment: The function `the_field` doesn't return, it echos. Instead, try using `get_field`
Answer: I'm not entirely sure if I follow. But from my understanding, you are using the function the_field incorrectly, see the documentation here.
You should be able to simply get the field value from get_field and disabling value formatting.
$this->add_control( 'progression_post_difficulty', [
    'label' => esc_html__( 'Narrow by difficulty', 'progression-elements-vayvo' ),
    'description' => esc_html__( 'Choose a difficulty to display posts', 'progression-elements-vayvo' ),
    'label_block' => true,
    'multiple' => true,
    'type' => Controls_Manager::SELECT2,
    'options' => get_field( 'difficulty', false, false ) ?: [],
] );

Comment: Hi, thnaks for your answer !! I didn't saw it. I'll come back as soon as I can with the solution. Thanks for getting me on the way :)

Get ACF post meta value in query


Java Extract key values from nested json

Question: i do have following JSON and i am trying to extract objects inside result
{
   "status":true,
   "results":{
      "type1":{
         "id":"type1"
      },
      "type2":{
         "id":"type2"
      }
   }
}

Desired output is
type1,type2

I am using Gson for serialization and deserialization.
Answer: These are the steps you should be doing when using gson

get keys of the json objects which are inside "results" alone
get it as json object which has keys and values
collect the entry set our of the JSON
create an iterator so that later you can extract the keys

Here is code that does the same job:
public static void main(String[] args) throws Exception {

        String json = "{\r\n" +
                "   \"status\":true,\r\n" +
                "   \"results\":{\r\n" +
                "      \"type1\":{\r\n" +
                "         \"id\":\"type1\"\r\n" +
                "      },\r\n" +
                "      \"type2\":{\r\n" +
                "         \"id\":\"type2\"\r\n" +
                "      }\r\n" +
                "   }\r\n" +
                "}";

        JsonParser parser = new JsonParser();
        JsonObject obj = parser.parse(json).getAsJsonObject();

        //get keys of the json objects which are inside "results" alone
        //get it as json object which has keys and values
        //collect the entry set our of the JSON
        //create an iterator so that later you can extract the keys
        Iterator<Entry<String, JsonElement>> iterator = obj.get("results")
                                                            .getAsJsonObject()
                                                            .entrySet()
                                                            .iterator();

        while(iterator.hasNext()) {
            //here you will get the keys like - type1 and type2
            System.out.println(iterator.next().getKey());
        }

    }

Code Edit: What @fluffy pointed makes complete sense. Made the change
Comment: You don't need to instantiate `Gson` here. `Gson` also applies deserialization one doesn't need here. `JsonParser` is a better choice.


A problem about the matrix equation $x^HAx+x^HB\bar{x}+x^TCx=0$.

Question: Let $A$, $B$, and $C$ be three $m\times m$ ($m\geq1$) complex constant matrices. For any $m$-dimensional complex-variable vector $x=(x_1,x_2,...,x_m)^T\in\mathbb{C}^m$, we denote its conjugate by
$$\bar{x}=(x_1^*,x_2^*,...,x_m^*)^T$$
and conjugate transpose
$$x^H=(x_1^*,x_2^*,...,x_m^*).$$
If the three matrices $A$, $B$, and $C$ satisfy
$$x^HAx+x^HB\bar{x}+x^TCx=0,\quad\text{for all }x\in\mathbb{C}^m,$$
prove that
$$x^HAx+x^HB\bar{x}+x^TCx
=x^HAx+\frac{1}{2}x^H(B+B^T)\bar{x}+\frac{1}{2}x^T(C+C^T)x,\quad\text{for all }x\in\mathbb{C}^m.$$
Answer: Note that $x^H B\overline{x}$ is a scalar. Therefore
$$x^H B\overline{x} = (x^H B\overline{x})^T = x^H B^T\overline{x}.$$
Same goes for $x^TCx$.


Host Windows Forms (C#) Inside MFC Application (VC++,VS6.0)

Question: After a bunch of reading this afternoon, and not getting any tangible results.  Is it possible to host a windows forms dialog inside of a MFC application that is still being developed using VC6.
The issue arises is that we have a large application that has never been upgraded with the new Visual Studios because VC6 always worked.  Now we need to add some of the C# functionality in it.  I am unable to do the /clr option as our project consists entirely of unmanaged C++. I did a search for "CWinFormsControl" within all our libraries/headers and didn't come up with anything.  I am unsure what to try next.
Also, forgive any ignorance as I am doing research and new to this depth of programming.
I have checked the following articles:

http://msdn.microsoft.com/en-us/library/676cbawx(v=vs.100).aspx
http://social.msdn.microsoft.com/Forums/en-US/vclanguage/thread/97fddc35-e94d-4587-8be0-0b573185eb63/
http://msdn.microsoft.com/en-us/library/ahdd1h97(v=vs.80).aspx
http://www.functionx.com/visualc/Lesson04.htm
http://social.msdn.microsoft.com/Forums/sk/vcgeneral/thread/c38db22e-cf61-4b47-bcc8-e6202c40d1b5
Answer: CWinFormsControl requires MFC 8.0.
You can make your managed assembly a COM server (e.g. ActiveX) and use it in MFC application like any other COM server.
Comment: Following the directions I went ahead and got a DLL built of my C# dialog.  How do I call/initialize it in C++ now?  Forgive the ignorance.
Comment: CoCreateInstance, call your form's ShowDialog method via early (#import +tlbexp) or late bing (IDispatch).
Answer: I don't have VC6 laying around to try this out, but I think it should be mostly possible; at least for a simple modal ShowDialog() scenario.
You'll create a new assembly/DLL using C++/CLI, compiled with the /clr flag.  This will expose an unmanaged API to your existing MFC code, using the usual <code>__declspec(dllexport)</code>.  The implementation will call into your C# code which lives it yet another assembly.
Comment: What is the best way to do this?  I'm very new to this.  Any pointers in the right direction would be helpful.


Why do I have low water pressure at the house from a tank located 100 feet up?

Question: I have a new 1000 gallon tank at 100 feet above my house. There is about 300 feet of 2 inch hose from the tank to my house. I have a small creek filling the tank about 600 feet away. The flow into the tank is about 2-3 gallons a minute. The water line from the creek to the tank has a hill in the middle, but still fills the tank. Right now the tank is full, the water pressure at the house from the 2 inch hose going into 3/4 inch PEX is only about 15psi. I have a flow rate of about 7 GPM at the house.
Is there a potential that the line from the creek is holding up the water from the tank to the house? What else could be holding up the water? I have walked the installation, everything is buried 3 feet down. If there was a break in the line, wouldn't the water be dirty?  It is crystal clear.
Thanks for the questions and clarity.
Comment: Tank should be full or is full?  Check if not sure.  Do you have filters and are they clean?
Comment: Have you done the walking yet? You need to know if water is getting into the tank and what the level is. "Should" should not be in your post.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: If you have 100 feet of head, it is physically impossible not to have 50 PSI at the house when in-house flows are stopped. If the gauge is accurate, the 15 PSI reading tells you exactly where the top of water is: it is 30 feet above the gauge.
Run a faucet wide open for a minute, shut it, and check pressure again.  If the gauge now reads lower, then most likely the tank is empty and the only column of water above you is what's left in the pipe.   If the gauge still reads 15 PSI, you may have a large pipe break in the tank at the "30' above the gauge" point.

Right now the tank should be full

"Should"?  You haven't walked the plant?
Understand that when you have a custom setup like this, it imputes upon you (or the person you hire) a certain responsibility to be familiar with the system, do regular inspections, and keep pathways clear to do that.
This situation should absolutely trigger a physical inspection of the system. Walk the pipe up to the tank, check the tank. If it's not full, check the pipe from the creek.
Comment: I'm pretty confident that he actually has about 35 ft of head. See https://diy.stackexchange.com/questions/287148/15-psi-at-the-house-from-a-tank-located-93-feet-up/287172#287172. In the comments from that question, he mentions that he has been getting 7.1 GPM from this system.
Comment: @popham I was assuming this was static pressure with no flow.
Comment: From comments on the duplicate question, he used a "My Elevation" app to find his tank height. From its docs, it looks like it maps GPS coordinates to a database of elevation information. It has good reviews, but I doubt that it would be immediately obvious to users if it was inaccurate. Does it interpolate grid data? Take the value of a closest grid point? How dense is the grid? (Those are rhetorical questions.)
Comment: I am fairly confident that the my elevation app is not very accurate.  Gave me completely different readings today.
Comment: I will use the accurate altimeter tomorrow to see if it gives me better heights.
Answer: Assuming 350 ft of 2" PVC pipe, 20 ft of 3/4" PEX pipe (to the point where you measured the flow rate), and 35 ft of head (from your 15 psi), I compute a flow rate between 5.0 GPM and 5.1 GPM for your system. This is close enough to your 7.1 GPM that I believe that your pressure measurement is correct and that your elevation measurement was incorrect.
To compute the 5.0 GPM to 5.1 GPM theoretic flow rate, I used the Williams & Hazen formula from https://pvcpipesupplies.com/media/documents/engineering_design_data.pdf and I used a chart from https://mrpexsystems.com/wp-content/uploads/2016/08/17-Pressure-Drop-Charts.pdf.
To do the calculation, you hypothesize a flow rate, find the associated head losses from the cited sources, compute the orifice velocity using Bernoulli's equation (algebraically it reduces to v = sqrt(2gh) = sqrt(2(32.2ft/s²)(35ft - head loss))), and multiply orifice velocity by the orifice's cross sectional area to get a flow rate. You iterate this process until the hypothesized flow rate agrees with the computed flow rate.
7.1 GPM is a nice flow rate. As long as you're in spec for any mechanical equipment, it shouldn't bother you.
Comment: The big challenge that is there is that the psi has increased by 1 pound today to 16.  I am not sure how this was accomplished.  There is good flow rate and I keep hoping it is an airlock that will work it's way out
Comment: The boiler needs a psi of 20  to start to work.
Comment: @John, you mentioned a hill in the line from the creek to your tank. Are there similar humps in the tank-to-house line? You can check your elevation at https://apps.nationalmap.gov/viewer/. You click on the icon with the `XY` for polling elevations. There's another icon that looks like a stack of 3 sheets of paper for layers. Under layers, turn on the "Imagery (NAIP Plus)" layer for a satellite image overlay.
Comment: @John, following http://article.sapub.org/10.5923.j.ijhe.20180703.02.html, I compute an air clearing velocity of 3.5 ft/s versus your 7 GPM flow rate's velocity of 0.7 ft/s in the 2" line. The air clearing velocity is predicated on a slope of 100 ft of fall per 350 ft of line. For air lock related head losses, the air's total height is roughly equal to its head loss. That's 65ft in your case. Good source: https://www2.gov.bc.ca/assets/gov/farming-natural-resources-and-industry/agriculture-and-seafood/agricultural-land-and-environment/water/livestock-watering/590304-5_understanding_gravity.pdf.
Comment: I just had the water running for an hour with the tank lid off.  Water pressure dropped to 12
Comment: what exactly does that mean regarding the 65 ft of air lock?  how would I clear that?
Comment: Regarding the terrain map, I am in canada and looking at the maps here they are lacking the granular data you are asking for.
Comment: @John, see point (4) of the Discussion section from http://article.sapub.org/10.5923.j.ijhe.20180703.02.html. If you've got a single air lock, then its air spans approximately 65 ft of elevation or (350ft/100ft)(65ft) = 230 ft of pipe length. If you've got multiple air locks, then the sum of their elevation spans adds up to 65 ft. It's wild to imagine. I would definitely invest some effort in confirming the elevation change before digging.
Comment: @John, on purging the air, see Figure 3 from https://www2.gov.bc.ca/assets/gov/farming-natural-resources-and-industry/agriculture-and-seafood/agricultural-land-and-environment/water/livestock-watering/590304-5_understanding_gravity.pdf. The second schematic under Figure 3 seems like your likely scenario, where a 7 GPM stream of water is flowing down the air pocket. The solution in that case would be to put an air purging valve at or near the top of the air pocket. Alternatively you could regrade away the trough prior to the air pocket. Again, this is assuming that air lock is your problem.
Comment: @John, I was thinking that maybe you could pump some more head into the system to get the critical velocity for a minute or two, but without knowing all of your system's details I would worry about breaking something with too much pressure.


Is it safe to replace the thermostat when furnace is shut off?

Question: I need to replace the thermostat in my basement. It is an old style round shape Honeywell mechanical non-programmable thermostat. The gas furnace is turned off (The switch is at OFF now). Is it electrically safe to open it up and replace it without shutting off the power to the whole basement?
Comment: Please be sure to not break it, and not throw it away. Those old, round, very reliable Honeywell's use a mercury switch and that should be properly recycled, not placed in trash. Or you can save it for the antique value it will probably get one day - the mercury is not a problem if it is not broken.
Comment: Thermostat is usually a low-cost age circuit (24v)... But I would suggest turning off the furnace circuit breaker, just to be absolutely sure.
Comment: After reading all comments, I think it is safe to turn off the circuit breaker to the furnace and then do the replacement. Right?
Comment: @PatrickLi Yes, it's always safe (and usually recommended) to turn the power off before doing any work to the system.
Answer: It is safe from an injury standpoint to replace that sort of thermostat regardless of the furnace being on or off, since the voltage in the thermostat wiring is 24 V or less.
However, you haven't stated why you want to replace it, or what sort of thermostat you intend to install.  If you're looking at a programmable unit, or even a model with Internet connection, be aware that you may need a separate power feed to operate the thermostat itself.  Read the requirements on whatever thermostat model you're considering installing before buying.
Comment: The replacement is exactly the same model.
Comment: @isherwood  Your comment makes no sense whatsoever.  All a thermostat does **is** to open or close a switch.  If you "cross the wires" while replacing the furnace might come on but that's it.
Comment: Fair enough. No need to be so blunt. I wasn't sure whether crossing the various switch circuits could be problematic is all.
Comment: @CarlWitthoft I've heard many stories of blown fuses and furnace control modules, where the homeowner reported "*I was just replacing the thermostat, and saw a little spark*". That little spark can be quite expensive. The safest option is to cut power to the system.
Answer: You should turn the system off using either the circuit breaker, or the servicemen's switch (if applicable).  If you're working on a live system, there's always the possibility of shorting a wire. This can lead to a blown fuse at best, or a fried furnace control module in the worst case.
While it's true that you're likely not going to hurt yourself, you could indeed damage the system.
Comment: This is just plain false.  The wires to a Honeywell thermostat **are** shorted whenever the furnace is on.
Comment: @CarlWitthoft At no time is `R` ever shorted to ground, `C` , nor is it ever shorted to both `Y` and `W` at the same time. All of these conditions can lead to a blown fuse, or a fried control module.


How do I call diffrent controller action method in mvc from webforms

Question: How do I call diffrent controller action method in mvc from webforms
I have created a controller having method name test and created another project in the same solution this time the webform and added the reference of the mvc application to the application and in page load of webform i wrote Response.RedirectToRoute("~/Home/Test");
this test method dosen't gets called
Comment: Can you provided more code so you have a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve)?
Comment: Do you want to call one controller method into another controller ? http://stackoverflow.com/questions/19172617/call-controllers-from-one-project-to-another-project
Answer: In a.Net solution you can have many web Applications. If you are referencing library project in a Web Application then you should have one Web root and one web site home page (http://localhost:1111). But if you have many web applications in one solution, each web application is as one standalone website, so each will have a unique home page like may be http://localhost:1111  (webforms application), http://localhost:1112 (MVC application). the ~/Home/Test in the webform project won't find anything because ~ mean the root of the current project(Webforms) which is http://localhost:1111, so the application should be looking at http://localhost:1111/Home/Test other than http://localhost:1112/Home/Test but the ~/Home/Test is in another webapplication.
I think that it where you are having problem. I think you should redirect to the full URL to get to another project http://localhost:1112/Home/Test


How to convert the standard Noda Timezone Id's from English to Localized Language?

Question: I am currently trying to localize my windowsphone Time App for a few countries. I am using Noda Time as it was extremely easy for a newbie. The problem I am facing that all the Timezone Id's are in standard English and I am searching for a way to get those Id's converted to Local Language strings.
One way would be too make Localized strings for each ID in every language. But it seems to be Highly inefficient as there are 500 timezones. Please suggest a way for me to get directly the TimeZone ID's converted into Local Language in a less time consuming way.
My code:
var now = Instant.FromDateTimeUtc(DateTime.UtcNow);
var tzdb = DateTimeZoneProviders.Tzdb;

var list = from id in tzdb.Ids
           where id.Contains("/") && !id.StartsWith("etc", StringComparison.OrdinalIgnoreCase)
           let tz = tzdb[id]
           let offset = tz.GetUtcOffset(now)
           orderby offset, id
           select new
           {
               DisplayValue = string.Format("(UTC{0}) {1}  {2}  ", offset.ToString("+HH:mm", null), now.WithOffset(offset).TimeOfDay.ToString("hh:mm tt",null),id)
           };

Comment: Just a quick note that I do hope to include CLDR data in Noda Time at some point. It would be useful for more than just time zone names. It's not clear to me yet whether we should adopt just the time zone bits for now, and then come back to the rest later, or wait to get everything in one go...
Comment: thank you @JonSkeet for looking into this matter.As per my view all in one go seems to be a better option than bits since each programmer has its own needs.So helping one and keeping the other waiting seems a bit unfair and we already have the TimeZoneNames Library to help us currently in getting the job done.
Answer: This isn't a current feature of Noda Time, so you will need to get the data elsewhere.
Localizations for time zones (and other items) are best found within the Unicode CLDR project.  You can write code to parse the various XML files included with the CLDR releases.  You'll also need to understand how the data is represented, and several edge cases.
Or, you can use the implementation that I've already completed.
Install the TimeZoneNames Nuget package:
PM>  Install-Package TimeZoneNames

Then you can easily resolve the time zone names to a localized display value:
// example input values
var names = TZNames.GetNamesForTimeZone("America/Los_Angeles", "en-US");

// example output values
Assert.Equal("Pacific Time", names.Generic);
Assert.Equal("Pacific Standard Time", names.Standard);
Assert.Equal("Pacific Daylight Time", names.Daylight);

This works for non-English locales as well.  It will produce valid text in any language, provided that the data exists in the CLDR.
The same library can also be used to get a list of time zone ids for a particular country.  This can be used to implement a two-dropdown selection list, where first you pick the country, and then you pick the time zone within the country.
var zones = TZNames.GetTimeZoneIdsForCountry("US");

You can take a look at the project's unit tests for further examples.
Comment: thank you so much @Matt for introducing me to this wonderful library.. U solved all my Problems. Thank you so much
Comment: Hey @Matt Johnson now that I am running Certification Kit on my Packages I am getting TimeZoneNames.dll built in debug mode error.I tried my best but could not get it to release mode
Comment: Thanks. Fixed in the latest version. [See here for details](https://github.com/mj1856/TimeZoneNames/issues/1).  Also, please in the future, report issues directly on GitHub. Thanks.


SoapRequest to NSString on iOS?

Question: I'm using an API generated by Sudzc.com from a WDSL. I have this method:
<code>- (SoapRequest*) getToolListAsXML: (id <SoapDelegate>) handler getEmptyFC: (BOOL) getEmptyFC repoid: (NSString* ) repoid
</code>
And I thought that It calls the webservice and receive an XML as string as the documentation generated by sudzc.com told me:

But I really don't know how the SoapDelegate works, if I want the response (the list as string) what I'm supposed to do? The examples are more confusing, it says:

But, obviously,
<code>NSString resp = [service getToolListAsXML:self action:@selector(getToolListAsXMLHandler:) getEmptyFC: NO repoid: @""];
</code>
doesn't work because of 'incompatible pointer types..."
I'm very new on this so sorry if what I'm saying has nonsense.
Thanks.
Answer: Try this
<code>    [service getToolListAsXML:self action:@selector(getToolListAsXMLHandler:) getEmptyFC: NO repoid: @""]
    - (void) getToolListAsXMLHandler: (id) value {

if([value isKindOfClass:[NSError class]]) {
        //NSLog(@"%@", value);
        return;
    }

    // Handle faults
    if([value isKindOfClass:[SoapFault class]]) {
        //NSLog(@"%@", value);
        return;
    }
    NSString * resp =(NSString *)value;
    }
</code>
you will get soap request in string
Comment: Finally works, there was a problem in the API I was using. Thanks.

SoapRequest to NSString on iOS?


How to prove that $m!n!(m+n)!|(2m)!(2n)!$ for every pair of positive integers $(m,n)$?

Question: I want to prove that

For every pair of positive integers $(m,n)$, the statement $m!n!(m+n)!|(2m)!(2n)!$ holds.

which is equivalent to

For every pair of positive integers $(m,n)$, the statement $$
\sum_{i=1}^{\infty}\left\lfloor\frac m{p^i}\right\rfloor+
\sum_{i=1}^{\infty}\left\lfloor\frac n{p^i}\right\rfloor+
\sum_{i=1}^{\infty}\left\lfloor\frac {m+n}{p^i}\right\rfloor
\le\sum_{i=1}^{\infty}\left\lfloor\frac {2m}{p^i}\right\rfloor+
\sum_{i=1}^{\infty}\left\lfloor\frac {2n}{p^i}\right\rfloor$$ holds for every prime number $p$.

I have tried setting $m=ap+c,n=bp+d$ with $a,b,c,d$ nonnegative integers and $c,d<p$. From that, the inequality becomes
$$
a+\sum_{i=1}^{\infty}\left\lfloor\frac a{p^i}\right\rfloor+
b+\sum_{i=1}^{\infty}\left\lfloor\frac b{p^i}\right\rfloor+
a+b+\left\lfloor\frac{c+d}{p}\right\rfloor+
\sum_{i=1}^{\infty}\left\lfloor\frac{a+b}{p^i}+\frac {c+d}{p^{i+1}}\right\rfloor
\\\le
2a+\left\lfloor\frac{2c}{p}\right\rfloor+\sum_{i=1}^{\infty}\left\lfloor\frac {2a}{p^i}+\frac{2c}{p^{i+1}}\right\rfloor\\+
2b+\left\lfloor\frac{2d}{p}\right\rfloor+\sum_{i=1}^{\infty}\left\lfloor\frac {2b}{p^i}+\frac{2d}{p^{i+1}}\right\rfloor$$
$$\iff \sum_{i=1}^{\infty}\left\lfloor\frac a{p^i}\right\rfloor+
\sum_{i=1}^{\infty}\left\lfloor\frac b{p^i}\right\rfloor+
\left\lfloor\frac{c+d}{p}\right\rfloor+
\sum_{i=1}^{\infty}\left\lfloor\frac{a+b+\frac {c+d}{p}}{p^i}\right\rfloor
\\\le
\left\lfloor\frac{2c}{p}\right\rfloor+\sum_{i=1}^{\infty}\left\lfloor\frac {2a+\frac{2c}{p}}{p^i}\right\rfloor\\+
\left\lfloor\frac{2d}{p}\right\rfloor+\sum_{i=1}^{\infty}\left\lfloor\frac {2b+\frac{2d}{p}}{p^i}\right\rfloor\text.$$
After that, I tried splitting cases based on whether $2c\ge p$, whether $2d\ge p$, and whether $c+d\ge p$. The case where $2c<p$, $2d\ge p$, and $c+d\ge p$ becomes
$$\sum_{i=1}^{\infty}\left\lfloor\frac a{p^i}\right\rfloor+
\sum_{i=1}^{\infty}\left\lfloor\frac b{p^i}\right\rfloor+
1+\sum_{i=1}^{\infty}\left\lfloor\frac{a+b+1}{p^i}\right\rfloor
\le
\sum_{i=1}^{\infty}\left\lfloor\frac {2a}{p^i}\right\rfloor+
1+\sum_{i=1}^{\infty}\left\lfloor\frac {2b+1}{p^i}\right\rfloor$$
$$\iff
\sum_{i=1}^{\infty}\left\lfloor\frac a{p^i}\right\rfloor+
\sum_{i=1}^{\infty}\left\lfloor\frac b{p^i}\right\rfloor+
\sum_{i=1}^{\infty}\left\lfloor\frac{a+b+1}{p^i}\right\rfloor
\le
\sum_{i=1}^{\infty}\left\lfloor\frac {2a}{p^i}\right\rfloor+
\sum_{i=1}^{\infty}\left\lfloor\frac {2b+1}{p^i}\right\rfloor$$
$$\iff
\sum_{i=1}^{\infty}\left(
\left\lfloor\frac a{p^i}\right\rfloor+
\left\lfloor\frac b{p^i}\right\rfloor+
\left\lfloor\frac{a+b+1}{p^i}\right\rfloor\right)
\le
\sum_{i=1}^{\infty}\left(
\left\lfloor\frac {2a}{p^i}\right\rfloor+
\left\lfloor\frac {2b+1}{p^i}\right\rfloor\right)\text.$$
How to carry on from there?
Answer: Let  $x=\frac{m}{p^i}$ and $y=\frac{n}{p^i}.$
Thus, by your work it's enough to prove that
$$[2x]+[2y]\geq[x]+[y]+[x+y],$$
which is not so hard.
Comment: By $[x]$, do you mean the floor function?
Comment: Yes, of course.
Comment: $[2\{x\}]+[2\{y\}]\geq\{x+y\},$ doesn't hold if ${x}={y}=\frac14$.
Comment: In your case $\{x+y\}=0.$ I can write a full proof if you want. It remains to write also three cases.
Comment: What is $x$ and $y$? And why does $\{x+y\}=0$?
Comment: We can think that they are non-negative numbers. $\{\frac{1}{4}+\frac{1}{4}\}=\{\frac{1}{2}\}=0.$
Comment: How to apply that to my work? And what is ${x}$, fractional part? Then ${\frac12}=\frac12$, not $0$.
Comment: Because we need to prove that $\left[\frac{2n}{p^i}\right]+\left[\frac{2m}{p^i}\right]\geq\left[\frac{m+n}{p^i}\right]+\left[\frac{n}{p^i}\right]+\left[\frac{m}{p^i}\right]$. Here $x=\frac{m}{p^i}$ and $y=\frac{n}{p^i}.$
Comment: And what is x, fractional part? Then $\{1/2\}=1/2$, not $0$.
Comment: Yes, it's was total wrong, Black out. Sorry.  but in all case it's not so hard. I see a proof of course.
Comment: I've marked this as a duplicate. Thank you anyway.


How can I play instrument notes in a web browser?

Question: I am creating a tool for a project where I take a data sequence and map characteristics from the data into musical notes and rests.
I need to be able to play whatever notes I want with a few different instrument options. I've written a lot of web based applications, but never had the need for playing arbitrary notes at runtime.
I know what I need, but have no clue what it's called or where to find it. I'm open to either java applet or unity3d libraries. Does anyone know of a library on either of those platforms that will help me? I don't have flash so that platform is out of the question.
Answer: You can play notes through javascript. Here is one app that does it: http://www.schillmania.com/projects/soundmanager2/
You can check out the demo for the api also: http://www.schillmania.com/projects/soundmanager2/demo/api/
There are probably other ways, but that's a start if you are looking for an example to start from.
Comment: Javascript would by far be the most preferable since it doesn't require an installed platform, I'll look into it.
Comment: It looks like it uses flash and html5 as a backup. I'm assuming it'll work though, I don't have speakers on this computer but when I get home and test it I'll mark it as the answer if it works well. Thanks
Comment: Yeah, html5 has extra features that the current one doesn't. The target date for it isn't until 2014, but most new browsers already support it.


Add some text around email addresses in multiple files

Question: I have a number of text files in a folder. The text in them is in this format:
%%%%%%%%%%@yahoo.com
%%%%%%@wanadoo.fr
%%%%email@example.com
%%firstname.lastname@example.com
%.firstname.lastname@example.com
%firstname.lastname@example.com
%firstname.lastname@example.com
%firstname.lastname@example.com
%firstname.lastname@example.com

I want to make changes in all the files text and make them like the following:
{"email":"%%%%%%%%%%@yahoo.com"}
{"email":"%%%%%%@wanadoo.fr"}
{"email":"%%%%firstname.lastname@example.com"}
{"email":"%%firstname.lastname@example.com"}

I want to make the complete files like this which are in a folder.
I have tried this:
awk '{ printf("{"email":"%s"}", $l);}' test

but it didn't work.
So, is there any way that I can modify the text in all the files in a folder like this?
Answer: $ sed 's/.*/{"email":"&"}/' file
{"email":"%%%%%%%%%%@yahoo.com"}
{"email":"%%%%%%@wanadoo.fr"}
{"email":"%%%%firstname.lastname@example.com"}
{"email":"%%email@example.com"}
{"email":"%.firstname.lastname@example.com"}
{"email":"%firstname.lastname@example.com"}
{"email":"%firstname.lastname@example.com"}
{"email":"%firstname.lastname@example.com"}
{"email":"%firstname.lastname@example.com"}

So to act on all files you could do
sed -i 's/.*/{"email":"&"}/' *

To keep a copy of the old files
sed -i.old 's/.*/{"email":"&"}/' *

Explanation

-i.old modify files in place instead of printing to stdout, and save a copy of each file before modification with an extension .old
s/old/new replace old with new
.* any characters on the line
& the matched pattern
Comment: Will it work if I replace `file` with the `folder` path?
Comment: @JafferWilson my answer assumes you are running commands inside the directory. If that is not the case, replace `file` with the actual `/path/to/file` and `*` with the actual `/path/to/directory/*`
Comment: We both slightly misread the desired output (missing second ", before : ).
Answer: No doubt more verbose, but to edit all files inside a directory:

If the directory is flat:
#!/usr/bin/env python3
import os
import sys

dr = sys.argv[1]

for file in [os.path.join(dr, f) for f in os.listdir(dr)]:
    newtext = "\n".join(['{"email":"'+l.strip()+'"}'for l in open(file).readlines()])
    open(file, "wt").write(newtext)

If the directory is recursive, and you need to convert files in subdirs as well:
#!/usr/bin/env python3
import os
import sys

dr = sys.argv[1]

for root, dirs, files in os.walk(dr):
    for file in files:
        file = os.path.join(root, file)
        newtext = "\n".join(['{"email":"'+l.strip()+'"}'for l in open(file).readlines()])
        open(file, "wt").write(newtext)

In both cases, the file's content changes into:
{"email":"%%%%%%%%%%@yahoo.com"}
{"email":"%%%%%%@wanadoo.fr"}
{"email":"%%%%firstname.lastname@example.com"}
{"email":"%%firstname.lastname@example.com"}
{"email":"%.email@example.com"}
{"email":"%firstname.lastname@example.com"}
{"email":"%email@example.com"}
{"email":"%email@example.com"}
{"email":"%firstname.lastname@example.com"}

To use it

Copy the script (either one) into an empty file, save it as edit_files.py
Run it with the directory as argument:
python3 /path/to/edit_files.py /path/to/files_to_convert

Note
This assumes all lines inside all files need to be edited. Please mention if we need to set a condition for either one, or both.
Comment: Since you're using Python already, you should use a proper JSON serialization, that will take care of escaping quotes correctly
Comment: @Kroltan posted a solution
Comment: @Kroltan agreed, but OP's desired output doesn't align with json format , simply because json file is a single dictionary, so to speak. OP has multiple dictionaries in single file
Comment: @Serg Multiple JSON documents in a file is actually a entirely common usage, given that whitespace is irrelevant, and non-pretty-printed JSON always fits in a line.
Comment: @Kroltan that's nice to know ! I might whip out something with json API when I have time. I've used it before, but never with multiple json documents in same file
Answer: With awk, use variable assignment to remove one level of quoting:
awk -v format='{"email":"%s"}\n' '{printf format, $1}'

Answer: You could use the stream editor sed for this:
sed -e 's/\(^.*\)$/{"email":"\1"}/g' source.txt

Comment: @JafferWilson you can use a shell glob to catch all the files, but you will see the edited contents of all the files printed to stdout and they will not be modified - to actually change all the files, add the `-i` flag
Comment: But it is not taking folder as input. `sed` take only file name as input here. I do not want to give one by one filename.
Comment: @Zanna Thank you for you advice. I will try it.
Answer: Perl way:
$ perl -lane 'print "{\"email\":\"$_\"}"' input.txt
{"email":"%%%%%%%%%%@yahoo.com"}
{"email":"%%%%%%@wanadoo.fr"}
{"email":"%%%%firstname.lastname@example.com"}
{"email":"%%email@example.com"}

This can be used on multiple files in a folder as so:
for file in * ; do perl -lane 'print "{\"email\":\"$_\"}"' "$file" > "$file".json ; done

Python and json API:
$ ls
input2.txt  input.txt  json_encode.py*
$ ./json_encode.py *
$ ls
input2.txt  input2.txt.json  input.txt  input.txt.json  json_encode.py*  json_encode.py.json
$ cat input.txt.json
{"email": "%%%%%%%%%%@yahoo.com"}
{"email": "%%%%%%@wanadoo.fr"}
{"email": "%%%%email@example.com"}
{"email": "%%firstname.lastname@example.com"}

And here's the script itself:
#!/usr/bin/env python
import json
import sys

for file in sys.argv[1:]:
     if __file__ in file or '.json' in file: continue
     with open(file,'r') as fd1:
         for line in fd1:
             data = { "email": line.strip() }
             with open(file+ ".json","a") as fd2:
                  json.dump(data,fd2)
                  fd2.write("\n")


ES6 filter in a filter is this possible?

Question: I have an Array that looks like this:

I need the id where slug === 'slug'
let activeFaq = this.faq.filter(obj => obj.items.filter(item => item.slug === 'slug'));
console.log(activeFaq.id);

This gives me an undefined. I should get 2729
Comment: `filter` returns an array
Comment: Are the slugs unique in the whole `faq` array? If not, what do you expect to happen if there are duplicates?
Comment: @FelixKling yes they are unique
Answer: There are multiple ways you could go about this. If you can use .flatMap, then one solution would be to flatten all items into a single array and then use .find:
const item = this.faq.flatMap(obj => obj.items).find(item => item.slug === 'slug')

However, flattening seems a bit unnecessary. An approach that avoid unnecessary computations would be a helper function with a boring loop:
function findItem(faqs, callback) {
  for (const faq of faqs) {
    const item = faq.find(callback);
    if (item) {
      return item;
    }
  }
}

const activeFaq = findItem(this.faq, item => item.slug === 'slug');

Answer: var activeFaq = this.faq.filter(obj => obj.items.some(item => item.slug === 'slug'))[0];
console.log(activeFaq.items[0].id); //2729

Comment: This is assuming there will only be 1 itemn there can be x amount of objects in items array
Comment: Loop over the activeFaq.items array for all the matching ids , where the item.slug condition satisfies.
Answer: let activeFaq = this.faq.reduce( ( obj ) => {
  const foundItem = obj.items.find( ( item ) => {
     return item.slug === 'slug'
  } )

  if( foundItem ) {
    acc = foundItem
  }

  return acc

}, null )

console.log(activeFaq.id);

Comment: While this code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn, and apply that knowledge to their own code. You are also likely to have positive feedback from users in the form of upvotes, when the code is explained.


What do the abilities on the hud next to Squadmates represent?

Question: Next to each of my active crew mates is a ability icon:

What do these represent? Is it necessary for me to manage which ability is listed here?
Answer: The last ability used. It is generally the ability they will use when you hit the squad member's quick ability key (Q and E on PC by default), unless it is ineffective against the current target, in which case they will use a more appropriate one. If it is greyed out, the ability is cooling down after use. A white flash represents the ability has just cooled down, and a blue icon represents the ability being available.
Answer: As near as I can tell, they represent the last active ability that you told your squad member to use.
Besides providing an 'at a glance' way of knowing what your companions cooldown status is, you can quickly activate these abilities by targetting an enemy and hitting Q or E on the PC. On the 360 and PS3, it's the left and right D-pad buttons.


Pagination in Codeigniter doesn't change page

Question: I have been doing a project in Codeigniter and the pagination is not fully working.
It is showing and going to the different pages however the number of the current page doesn't change. Always points to page 1, even if we are in the last page and the products from the last page are shown..
This is my code.
            $count=$this->client_model->get_clients_count();
            $this->load->library("pagination");
            //Configuration
            $config['first_tag_open'] = $config['last_tag_open']= $config['next_tag_open']= $config['prev_tag_open'] = $config['num_tag_open'] = '
';
            $config['first_tag_close'] = $config['last_tag_close']= $config['next_tag_close']= $config['prev_tag_close'] = $config['num_tag_close'] = '
';
            $config['cur_tag_open'] = '
';
            $config['cur_tag_close'] = "
";
            $config['base_url'] = base_url("employee/clients/");
            $config['total_rows'] = $count->count;
            $config['per_page'] = 10;
            $config['uri_segment'] = $page;
            $this->pagination->initialize($config);
            $pagination= $this->pagination->create_links();

At the begining I wasn't using uri_segment. I tried with it, and even $page/10 since there are 10 clients shown per page, but it isnt working.
The pagination is passed to the view and printed.
Comment: how about your query? do you optimize it for the offset?
Answer: I found the solution if
$config['uri_segment'] = $page;

is not recognized.
This is how my code looks like now.
        $count=$this->client_model->get_clients_count();
        $this->load->library("pagination");

        //Configuration
        $config['first_tag_open'] = $config['last_tag_open']= $config['next_tag_open']= $config['prev_tag_open'] = $config['num_tag_open'] = '
';
        $config['first_tag_close'] = $config['last_tag_close']= $config['next_tag_close']= $config['prev_tag_close'] = $config['num_tag_close'] = '
';
        $config['cur_tag_open'] = '
';
        $config['cur_tag_close'] = "
";
        $config['base_url'] = base_url("employee/clients/");
        $config['total_rows'] = $count->count;
        $config['per_page'] = 10;

        //Initialization
        $this->pagination->initialize($config);
        //new line of code
        $this->pagination->cur_page = $page;
        $pagination= $this->pagination->create_links();


Do you run a conduit under or over concrete wrap in the basement?

Question: My basement concrete wall is covered with a concrete wrap and is anchored to the wall. The walls are unfinished.
If you want to add an outlet down the wall to a workbench, do you run the conduit under or over the wrap?
Comment: What is a concrete wrap, exactly? A photo would help illuminate options.
Answer: On the inside--you don't want to mess with the wrap. By inside I mean close to your bench, not under the wrap. I thought I should expand under the wrap is a usually damp area that is somewhat corrosive I think of EMT for basements but messing with this barrier is not a good idea.
Comment: He is right, you don't want to do anything to that barrier, it is there for moisture protection. You can surface mount the conduit over it, or you can use surface mount wire duct (formerly called "Wiremold") into a receptacle box.


When onsettings event get fired

Question: The documentation as to when onsettings here is fired describes as following

Occurs when app settings are changed.

Does it mean this event is fired every time a control used on settings pane is changed? It seem to me this event is fired every time I hit Win+I to bring up the Settings charm. I have created some views on my page for Settings and when I change a value (e.g., for a toggle switch) then appropriate event is fired for that control. Can someone please clarify this.
Answer: That text looks rather like default boilerplate for an "onXXX" event, and it's definitely confusing, but the context of the samples should steer you in the right direction.  "when app settings are requested" would be more accurate, IMHO.
The event fires when there's a request made for the Settings charm, and your code would need to set up the appropriate command on the Settings flyout. It's not going to save anything on your behalf, and in fact, the the reference here is a good overview of what you'd need to do to save the settings changes automatically - essentially leveraging onChange events of the various controls you're using inside of the flyouts.
Comment: Thanks for your help. At least I am not the only one finding this documentation a bit confusing. Your links are really helpful.

When onsettings event get fired


Preservation Hamiltonian vector field

Question: Suppose I have the Hamiltonian vector field $X_H$ on the symplectic manifold $(M, \omega)$. Consider the symplectic transformation $P: M \rightarrow M$. Will the linear terms of $X_H$ be preserved (up to symplectic linear transformation) under any symplectic transformation $P$?
I am not sure, but I would think so.
Comment: If Q is the symplectic transformation generated by $X_H$, then Jacobian of Q, $DQ$ is also symplectic.
Answer: It is not true. There is a matrix associated to the linear terms, and you should compute the eigenvalues of the matrix, all the eigenvalues of the matrix are independent of coordinates transformations, which are, by means of your symplectic transformations.

Preservation Hamiltonian vector field


The Fourier transform of $\sin(x)\,\operatorname{rect}\left(\frac{x}{2}\right)$

Question: Can someone please find the Fourier transform of $x \mapsto \sin(x)\,\operatorname{rect}\left(\frac{x}{2}\right)$?

I know that
$$
\int_{-1}^1 \sin(x)\, e^{-ipx} \,\mathrm dx = 2i\,\frac{p\sin(1)\cos(p)-\cos(1)\sin(p)}{p^2-1},
$$
but when I try to calculate the inverse Fourier transform
$$
\int_{-\infty}^\infty\frac{p\sin(1)\cos(p)-\cos(1)\sin(p)}{p^2-1}\, e^{ipx}\,\mathrm dp
$$ with Jordan, I arrive at the conclusion that the integral is zero, because the residues of the function are zero. Can someone help me to solve the integral and return to the beginning function?
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Comment: Are you really supposed to find the inverse Fourier transform of the Fourier transform of $\sin(x)\operatorname{rect}(x/2)$? According to what you write in your first question you are supposed to find the inverse Fourier transform of $\sin(x)\operatorname{rect}(x/2).$
Comment: Note that the Fourier transform of a product is the convolution of the Fourier transforms of the factors. Please also tell us which convention of the Fourier transform you are using.
Comment: Please provide a definition of $\mbox{rect}$
Answer: Informally, using that $\widehat{f \cdot g} = \hat{f} \ast \hat{g}$ (Fourier transform of product is the convolution of the Fourier transforms of the factors) and that
$$
\widehat{\sin}(p)
= \int_{- \infty}^{\infty} \sin(x) e^{- i p x} \, \text{d}x
= \pi i \left(  \delta_{- p - 1} - \delta_{1 - p} \right)
$$
and
$$
\widehat{\text{rect}\left(\frac{\cdot}{2}\right)}(p)
= \int_{- \infty}^{\infty} \text{rect}\left(\frac{x}{2}\right) e^{- i p x} \, \text{d}x
= \int_{-1}^{1} e^{- i p x} \, \text{d}x
= 2 \text{sinc}(p)
$$
we obtain
$$
\widehat{\sin \cdot \text{rect}\left(\frac{\cdot}{2}\right)}(p)
= 2 \pi i \left( \text{sinc}(- p - 1) - \text{sinc}(1 - p) \right).
$$


is(':hover') works on jsfiddle but not from local file

Question: This example works, but if i create local file like this:

click

click

(removed all utf-8 bug-symbols from jsfiddle) - nothing works, and no errors in console. checked in Google Chrome 19.0.1084.46.
Comment: @scythargon 'Nikola K.' is right~ some code in there
Comment: @HackerWins i dont get what you say there...
Comment: @scythargon on your example(jsfiddle link), there're some utf-8 symbols.
Answer: try like this~
<!DOCTYPE HTML>

    <meta charset="UTF-8">
    <title>question</title>

click

click

Comment: it is an instruction to the web browser about what version of HTML the page is written in.


While loop seems to ignore "or" operator

Question: I'm having trouble figuring out what's wrong with my code for a "rock paper scissors" game for my Comp Sci class. The part I'm having trouble with is this:
while((userscore < 4) || (compscore < 4)){
    if(userhand.equalsIgnoreCase("R") && comphandint == 0){
            JOptionPane.showMessageDialog(null, "Rock vs. Rock: \nYou Tie");
        }
    else if(userhand.equalsIgnoreCase("R") && comphandint == 1){
            compscore += 1;
            JOptionPane.showMessageDialog(null, "Rock vs. Paper: \nYou Loose");
    ...
}

The loop works except for the fact that it loops until both userscore and compscore are equal to 4. I want it to loop until only one of the two hits 4. Any ideas?
Comment: you need to use `and` instead of `or` here
Comment: @Lashane that's what is was! thanks for the help.
Answer: You should use && (and) rather than || (or).
A simple logic table shows us the result of both;
        |  AND  |  OR

value1  | true  | true
value2  | false | false

result  | false | true

(This is for the benefit of others finding this question later)
So as you can see, with OR if either of the values are below 4 then true will be returned and the loop will be entered. With AND, as long as one of the values is 4 or above false will be returned and the loop will stop - as you wanted.
Hope this helps you, and anyone else who finds this question in future.


windows batch file: calling executable in another directory

Question: This seems like something simple, but I don't seem to be able to get it.
I have a directory called "test" with an executable hello.exe that basically prints "hello" onto the screen.
I want to execute this program from the current directory using relative paths.
So I write

test\hello.exe

Thinking it would execute the program "hello.exe" located in directory "test". But it doesn't. Am I missing something?
Comment: What is your current directory? "But it doesn't", so what does it do when you run the command?
Comment: @zxt, I was in a directory called, say, "base" that contains the folder "test". I would try to call the exe while I'm in "base", but nothing happens when I type in test\hello.exe
Answer: Try the following in the batch file:
<code>%~dp0test\hello.exe
</code>
The "%~dp0" is a variable that gets replaced with the full path of the batch file, so that it should work even if you don't set the current directory of the batch file.
Comment: Wonderful, that did the trick. I"m guessing cmd line doesn't like relative paths?


What determines mission difficulty?

Question: In XCOM: Enemy Unknown missions get more difficult as I advance in the game - at least in absolute terms.
I was wondering if the mission difficulty does or does not depends on

Elapsed time (ingame)
Plot progress
Research progress
other factors

Anyone has any insight into this?
Comment: Definitely not the plot, as I held off investigating the shard for a long time but enemies continued to get tougher. Research seems unlikely as it could easily unbalance the game if you happened to research too fast or too slow. Most likely either Elapsed time, or some kind of counter that goes up for each mission you undertake (and maybe those that you don't). There isn't really a good way to know for sure.
Comment: Probably very related: http://gaming.stackexchange.com/questions/87524/how-does-enemy-progression-work - Alien progression is really the primary way that missions get more difficult.
Comment: From my experience it is the "number" of aliens. i.e. a "very easy" only has 4-6 aliens, while a "very hard" has like 14+. I'm not 100% sure of the exact figures, so I posted this as a comment, not an answer.
Comment: @TheShiftExchange I'm not so sure this question is about nominal difficulty, I think they're more interested in actual difficulty, as in when tougher aliens are introduced, when missions come to have larger numbers of aliens, etc.
Comment: My first time getting deep into classic mode I was taking my time and every mission was getting really packed with very tough enemies. My next playthrough I rushed all the storyline stuff and breezed through it. it definitely feels like it is game time based and not related to story (with the small exception that the first encounter with a given species is story based).
Comment: I think its the elapsed time as well and in classic mode i wasn't able to capture an outsider but the elite mutons have came out and so did the sectopods!! haha
Answer: I do not know the exact equation but I am currently gathering data on a normal play-through.
I suspect according to my data so far that mission difficulty is strongly affected by the country's current panic level increased by the other countries panic levels on the same continent. I do not yet know if rewards increase the difficulty.
Small differences can be seen in missions under otherwise similar circumstances, for example the first abduction missions had every country at panic 1 and average continent panic at 1. Here I was given the option of an easy mission or a moderate mission, indicating some sort of random variable in the Difficulty calculation.
So far it seems that if an abduction awards a soldier then the mission will be more difficult than a similar mission under the same circumstances but it could also be random.
Answer: I think the game caluculates your difficulty level  based on story progress and research progress.
If you don't progress with the story ethereals will appear without getting the beacon. Same thing goes the other way. If you get really far with the story you get harder enemies too. Which one goes faster i dont really know.
Certain enemies are bound to certain types of missions. e.g. The Crissalid appears after your first terror mission.
Answer: Difficult levels are determined by type of aliens and their numbers. 6 groups of Sectoids are considered "Very Difficult", while 1 group of Mutons and 3 groups of Sectoids is equally noted as "Very Difficult".
Comment: Well, he actually asked what makes the game ramp up the difficulty level as you progress, not what characterises a difficult or easy mission.

What determines mission difficulty?


RewriteCond blank domain to the domain with the correct path

Question: How do I set redirects with following conditions:
Url http://domainname.be becomes http://www.domainname.be/nl/
Url http://www.domainname.be becomes http://www.domainname.be/nl/
Url http://domainname.be/nl/custompage/ becomes http://www.domainname.be/nl/custompage/
?
Rewrite conditions
RewriteCond %{HTTP_HOST} ^domainname.be [NC]
RedirectRule ^(.*)$ http://www.domainname.be$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^domainname.be [NC]
RewriteCond %{REQUEST_URI} ^/$
RedirectRule ^(.*)$ http://www.domainname.be/nl$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^www.domainname.be [NC]
RewriteCond %{REQUEST_URI} ^/$
RedirectRule ^(.*)$ http://www.domainname.be/nl$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/nl/custompage /Custompage.aspx?lang=nl [L,NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/nl/custompage/ /Custompage.aspx?lang=nl [L,NC]

But is doesn't work. Also, do you need to clear the browsercache in order to have the latest conditions?
Answer: Remove all of your existing rules and use this:
RewriteCond %{HTTP_HOST} ^(www\.)?domainname\.be$ [NC]
RedirectRule ^((?!nl/).*)$ http://www.domainname.be/nl/$1 [R=301,L]

And yes test it out in a different browser to avoid 301 caching issues.
Comment: it doesn't do anything now. Url `domainname.be` stays the same, also for url with `www`.
Comment: Make sure this rule is very first rule just below `RewriteEngine On` line.
Comment: still the same. I have added some more conditions in my question that I also use maybe it can help
Comment: Look at the latest edit. Make sure you have **no other rule** except this one and test from a different browser.
Comment: now I get this: http://www.domainname.be/nl//nl//nl//nl//nl//nl//nl//nl//nl//nl//nl//nl//nl//nl//nl//nl//nl//nl//nl//nl//
Comment: still the same, it even doesn't show my webpage anymore
Comment: Are you sure you don't have any other rewrite rule anywhere including in `/nl/` directory? What is happening when you enter `http://domain.com/` in your browser?