text:
Q: Https request reaching twice to server android My post request code as follows
When post request  to the server it reach twice in  to the server
and i am sure call httpRequest once.When i call once the request reach server twice or thrise;
private void invokePostOrderRestService(
            final RestPostDataCallback<Order> callback,
            final RequestOrder requestOrder) {
        String URL = BASE_URL + "postOrder";
        Log.e("post ordercccccc", "orderPosted");

        JSONObject jsonObject = convertOrderRequestToJson(requestOrder);

        if (jsonObject != null) {

            OrderProApplication
                    .getContext()
                    .getRestClient()
                    .postJsonObject(URL, jsonObject,
                            new ResponseListener<JSONObject>() {

                                @Override
                                public void onSuccess(JSONObject response) {
                                    // TODO Auto-generated method stub

                                    Log.e("Order Post Success","Post Order  Successssssssssssssssss");
                                    String status = "";
                                    try {
                                        status = response.getString("status");
                                    } catch (JSONException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }
                                    if (status.equals("OK")) {
                                        callback.onRestPostDataCompleted(
                                                ResultCode.RESULT_OK, null);
                                    } else {
                                        callback.onRestPostDataCompleted(
                                                ResultCode.RESULT_FAIL, null);
                                    }

                                }

                                @Override
                                public void onRestError(RestError error) {
                                    // TODO Auto-generated method stub

                                    Log.e("Order Post Failed","Post Order  failedddddddddddddddddddd");
                                    i = i + 1;
                                    callback.onRestPostDataCompleted(
                                            ResultCode.RESULT_FAIL, null);
                                }
                            });
        } else {
            callback.onRestPostDataCompleted(ResultCode.RESULT_FAIL, null);
        }

    }

And am pretty sure my url is correct.
Thanks:).

A: Most likely your method is being called twice. Check where you are calling out the method - this might be occurred thanks to misunderstanding of Activity/Fragment lifecycle.
Put a print in the beginning of your invoke method and check, if it prints out twice.


text:
Q: Number Theory Contest Problem Proof Based A positive integer n is called exceptional, if each positive integer d ≤ √n divides n. Either determine the largest exceptional n or prove that there exist arbitrarily large exceptional integers.
I tried a case with inequalities, one where k (optimistically hoping k!=n are the only solutions...) is less than or equal to sqrt(k!) and one where it is lower(the tricky one).

A: Let $n$ be say $\gt 12^2$. Then by Bertrand's Postulate (a theorem since the time of Chebyshev) there is a prime $p$ between $\frac{\sqrt{n}}{4}$ and $\frac{\sqrt{n}}{2}$, and also a prime $q$ between $\frac{\sqrt{n}}{2}$ and $\sqrt{n}$.
By our condition, $p$ and $q$ divide  $n$, so $pq$ divides $n$.
But $pq\gt \frac{n}{8}$. It follows that $n$ is of the form $pqk$, where $k\le 8$.
Now consider the primes $11$, $13$, and $17$. They cannot all divide $n$. If $n\ge 289$, this violates our condition.
Now it remains to examine the $n\lt 289$ to find the largest exceptional $n$. The search is quick and uninteresting.

redpajama_set_name: RedPajamaStackExchange


text:
Q: flutter_block: BlockProvider vs. RepositoryProvider I want some clarification on BlocProvider and RepositoryProvider. From official API reference, they provide the same functionality - they provide an instance of an object to its descendant widgets.
However, judging by the names, I guess BlocProvider should be used for Bloc objects only, and RepositoryProvider for everything else. Is this correct?

A: RepositoryProvider acts like Repository pattern
It's Data Provider provide data to Bloc, so Bloc do not need to know data come from cloud or sqflite or ...
And do merge/filter, see official example below
In the following LoginForm example
Repository is part of Bloc and you can use _userRepository.login
class LoginFormBloc extends FormBloc<String, String> {
      final emailField = TextFieldBloc(validators: [Validators.email]);
      final passwordField = TextFieldBloc();

      final UserRepository _userRepository;

      LoginFormBloc(this._userRepository);

      @override
      List<FieldBloc> get fieldBlocs => [emailField, passwordField];

      @override
      Stream<FormBlocState<String, String>> onSubmitting() async* {
        try {
          _userRepository.login(
            email: emailField.value,
            password: passwordField.value,
          );
          yield currentState.toSuccess();
        } catch (e) {
          yield currentState.toFailure();
        }
      }
    }

You can inject your Repository to Bloc
code snippet
class LoginForm extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocProvider<LoginFormBloc>(
      builder: (context) =>
          LoginFormBloc(RepositoryProvider.of<UserRepository>(context)),
      child: Builder(
        builder: (context) {
          final formBloc = BlocProvider.of<LoginFormBloc>(context);

          return Scaffold(
            appBar: AppBar(title: Text('Simple login')),
            body: FormBlocListener<LoginFormBloc, String, String>(
              onSubmitting: (context, state) => LoadingDialog.show(context),
              onSuccess: (context, state) {
                LoadingDialog.hide(context);
                Navigator.of(context).pushReplacementNamed('success');
              },
              onFailure: (context, state) {
                LoadingDialog.hide(context);
                Notifications.showSnackBarWithError(
                    context, state.failureResponse);
              },

you can reference https://flutterawesome.com/create-beautiful-forms-in-flutter/
for official example https://bloclibrary.dev/#/architecture
The bloc layer can depend on one or more repositories to retrieve data needed to build up the application state.
class Repository {
    final DataProviderA dataProviderA;
    final DataProviderB dataProviderB;

    Future<Data> getAllDataThatMeetsRequirements() async {
        final RawDataA dataSetA = await dataProviderA.readData();
        final RawDataB dataSetB = await dataProviderB.readData();

        final Data filteredData = _filterData(dataSetA, dataSetB);
        return filteredData;
    }
}

class BusinessLogicComponent extends Bloc<MyEvent, MyState> {
    final Repository repository;

    Stream mapEventToState(event) async* {
        if (event is AppStarted) {
            try {
                final data = await repository.getAllDataThatMeetsRequirements();
                yield Success(data);
            } catch (error) {
                yield Failure(error);
            }
        }
    }
}

A: Simple Answer
Same as BlocProvider.
BlockProvider provides the bloc to its children through BlockProvider.of(context). In most cases, developers create a new BlocProvider and that gets available to the rest of the subtree.
Now come to RepositoryProvider
RepositoryProvider provides the repository to its children through RepositoryProvider.of(context). When developers create a new RepositoryProvider and that gets available to the rest of the subtree.


text:
Q: how to unpack binary in javascript? I am trying to port over some existing code from python to javascript, and am unsure how to go about the following line.
var1, var2 = struct.unpack('<II', buf[:8])

It should be getting two ints from a buffer. The buffer starts in binary, but at this point it has been converted to bytes (ie. bytes(buf)).
Example Buffer:
<Buffer 35 8a 0a 24 16 ed ea 42 88 28 b1 20 b1 cf c9 a1 c9 cc 5c 0b 18 b0 70 3a 8c b8 83 ee d6 ca 55 bf f9 75 1c 94 46 8c 17 03 01 00 20 5a 17 be 43 ba 08 a6 ... >

A: If your buffer is a node.js Buffer:
var buf = new Buffer([0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00]);

console.log(buf.readUInt32LE(0), buf.readUInt32LE(4));

If your buffer is a typed arrays:

let buf = new Uint8Array([0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00]);
    uint32 = new Uint32Array(buf.buffer);

console.log(uint32[0], uint32[1]); // 255 and 65535 on little endian architectures

If your buffer is a standard array:

let buf = [0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF];

let var1 = buf[0] * 0x1000000 + (buf[1] << 16) + (buf[2] << 8) + buf[3],
    var2 = buf[4] * 0x1000000 + (buf[5] << 16) + (buf[6] << 8) + buf[7];

console.log(var1, var2); // 255 and 65535 on all architectures

You might also be interested in destructuring assignment (since ES6):
let var1, var2;
[var1, var2] = [1, 2];


text:
Q: MYSQL using other tables This query:
SELECT
user_id,
count(base_item)
FROM items
WHERE base_item = '202'
group by user_id order by count(base_item)

Gives me this result:

which I want.
However, I also want it to exclude all user ids in the users table with a rank of 5 or greater. as shown here

A: Modify your where clause this way:
WHERE base_item = '202' AND user_id NOT IN (SELECT id FROM users WHERE rank > 5)

The portion in parentheses is called a subquery.  The result set of the subquery contains the id of all users with a rank greater than 5.  The addition to the where clause excludes all users in that result set.

A: Join with the users table and filter out rows with high rank
SELECT user_id, count(*) AS count
FROM items AS i
JOIN users AS u ON i.user_id = u.id
WHERE i.base_item = '202'
AND u.rank <= 5
group by user_id
order by count


text:
Q: Manual buttoncommand binding I have a custom DataGridColumn that creates controls manually for editmode like so
public class DataGridLookupColumn : DataGridTextColumn
{
    protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
    {
        var dataGridBoundColumn = cell.Column as DataGridBoundColumn;

        var dockPanel = new DockPanel { HorizontalAlignment = HorizontalAlignment.Stretch };

        var textbox = new TextBox { VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Stretch };
        var button = new Button { HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center };

        DockPanel.SetDock(button, Dock.Right);

        dockPanel.Children.Add(button);
        dockPanel.Children.Add(textbox);

        textbox.Style = cell.FindResource("TextboxWithoutRoundedCorners") as Style;
        button.Style = cell.FindResource("LookupButtonRed") as Style;

        if (dataGridBoundColumn != null)
        {
            var cellContent = cell.Content as TextBlock;
            var bindingExpression = cellContent != null ? BindingOperations.GetBindingExpression(cellContent, TextBlock.TextProperty) : null;

            if (bindingExpression != null)
            {
                BindLookupCommand(bindingExpression, button);

                var newBindning = new Binding(bindingExpression.ParentBinding.Path.Path)
                {
                    UpdateSourceTrigger = bindingExpression.ParentBinding.UpdateSourceTrigger,
                    Mode = bindingExpression.ParentBinding.Mode
                };

                textbox.SetBinding(TextBox.TextProperty, newBindning);
            }
        }

        return dockPanel;
    }

    private void BindLookupCommand(BindingExpression bindingExpression, Button target)
    {
        ICommand lookupCommand;

        if (CommandList.TryGetValue(bindingExpression.ParentBinding.Path.Path, out lookupCommand))
        {
            var bindning = new CommandBinding(lookupCommand);
            target.CommandBindings.Add(bindning);
            target.Command = lookupCommand;
        }

    }

    public Dictionary<string, ICommand> CommandList { get; set; }
}

As soon as i set the CommandProperty of the Button cant be clicked anymore. Is there anything else i need to do to get the binding to work?
I have verified that i get the correct CommandObject.
Thanks


text:
Q: Need to replace my data from json to csv file I'm working with json file but I need to replace it with csv file. Do I need to use a library to do that or can I change the jQuery get from json to csv? I've tried that but no luck not working.
My javascript code is th

$(document).ready(function() {
 $.ajax({
  url: 'somefile.json',
  type: "GET",
  dataType: "json",
  success: function (data) {
   $(".score-text").each(function( index, value ) {
          value.innerText = data['box'+(index+1)].total;
      });

      $(".data").each(function( index, value ) {
          var boxIndex = Math.floor(index/4);
          width = data['box'+(boxIndex+1)]['bar'+(index+1-boxIndex*4)];
          value.innerText = width;
          value.style.width = width;
      });
  }
 });
});

I'm using csv to array but getting some errors this is my code

$(document).ready(function() {
 $.ajax({
     url: "somefile.csv",
     success: function (csvd) {
         data = $.csv2Array(csvd);
     },
     dataType: "text",
     complete: function (data) {
         $(".score-text").each(function( index, value ) {
          console.log(data);
          value.innerText = data['box'+(index+1)].total;
      });

      $(".data").each(function( index, value ) {
          var boxIndex = Math.floor(index/4);
          width = data['box'+(boxIndex+1)]['bar'+(index+1-boxIndex*4)];
          value.innerText = width;
          value.style.width = width;
      });
     }
 });
});

Thanks

A: jQuery does not know about CSV files. You would need to request it as dataType: "text", then parse it yourself.


text:
Q: AI-enhanced fighter jet performs better after pilot knocked out This is a short story written prior to 1990, possibly significantly earlier. The plot is about a dogfight between a man piloting the latest generation of fighter jet, which had a built-in artificial intelligence, and several previous-generation enemy fighters.
I think maybe when the story begins, the pilot is on a test flight by himself or maybe just flying a patrol mission. If he is with other planes, they are destroyed shortly after the enemy jets are encountered. The pilot does his best, but, being outnumbered, he eventually takes a hit from a missile or gun, and the shrapnel hurts him badly.
As soon as he passes out (from blood loss?), the AI takes over completely and, in a short space of time, defeats all of the enemy fighters by virtue of having faster reactions and being able to maneuver at higher G's than a human can handle while remaining conscious. As the fighter returns to base, I think the closing lines are something along the lines of how the fighter cared tenderly for the pilot or similar.
Note that the AI of the plane is specialized for its function and is not human-like; it doesn't talk or anything like that. Also note that this is a fighter plane intended for operation in air, not space.
The only interesting thing about this otherwise unremarkable story is that it is implied without saying outright that humans had become obsolete as fighter pilots. I believe the new jet is described to the pilot as being full of features to assist him, but, in actual combat, he only lessened its effectiveness.

A: The story is The Man in the Gray Weapons Suit by Paul J. Nahin.
The pilot (we never learn his name, he is just referred to as the warrior) takes off from some form of aircraft carrier on a patrol mission in his plane Red Striker Five. Much is made of the deadly efficiency of his aircraft - the language used borders on the erotic for reasons that will become apparent.
He detects and engages multiple enemy aircraft. He destroys eleven of them but is jumped from behind by a twelfth and seriously injured:

As he realized his peril, the right wing took two hits: one on the tip and one on the trailing edge near the wing root. Red-hot, searing metal fragments tore through Red Striker Five's body, and one, the size of a man's thumb, ripped into the warrior's right leg, just below the knee. Muscle tissue, bone, and arterial fragments, mixed with shreds of flight-suit fabric, splattered the cockpit, and blood gushed from the wound.

And he switches over to remote control to allow the plane to fly him back:

he warrior knew, just before he passed out, that his survival was out of his control. He retained enough strength to slap the emergency combat palm switch at the side of his seat, and then he rapidly slid into unconsciousness. It was up to Red Striker Five to get them both home.

The plane then flies him home, destroying the twelfth enemy aircraft in the process:

When the enemy was only 700 meters behind, Red Striker Five popped her air brakes and lost 300 knots almost immediately. Simultaneously she pulled into a climb and did a full inside loop, coming down behind and on the tail of the snookered enemy aircraft. The defeated foe had a few milliseconds to realize his fatal error, and then Red Striker Five ripped him apart with two dozen strikes from her dual 20mm cannons. The flaming enemy debris flared out along a ten-mile track, but by then Red Striker Five, bearing her dying warrior home, was gone.

We discover at the end that the pilot is so emotionally connected to his plane that he has come to love it as if it were another human. As he is being stretchered away the story tells us:

The warrior smiled weakly through a pale white face lined with pain and shock. He looked up at Red Striker Five and saw not a technological marvel of electronics, armament, metallurgy, and computer programs. He saw both a warm and loving creature, and a being that had killed to save him. Killed with savagery and intelligence. His body filled with emotion, a feeling of passion that only later he would just barely begin to understand.
He looked at the battle-ravaged Red Striker Five, and just before he slipped into darkness again, he knew. He knew she'd be there when he came back. She'd wait for him, and he loved her.
And he knew she loved him too

As you say in the question, the AI is not the traditional SF AI like HAL 9000. It does not talk to the pilot or show any signs of emotion. However there is no implication that the pilot is holding back the AI. The implication is that they are a perfectly matched team.


text:
Q: Possible to Proguard Code Used for Tests but not in Release? Is there a way to use Proguard to comment out a line of source code so that it exists for tests but does not get into the release build?
I am working on an Android app and have ported tests to Google Espresso for instrumentation tests.  As a result, I had to add some code into the /src/ tree to notify Espresso when the app is busy, specifically it is a broadcast intent which is triggered by a static (and stateless) method.  I would like to not have production code create broadcasts that only tests ever listen to.
IdlingResourceBroadcaster.onBusy(getActivity(), MyActivity.class.getName());

The solution that I am looking for would be akin to C's #ifdef...#endif which would wipe out the one-liner above completely, or alternatively, akin to Log.v() which still retains the one-liner above but treats the contents of the method as NOOP.
I am not familiar with Proguard but from what I have read this does not seem possible.  Any suggestions or links to similar projects much appreciated.


text:
Q: How to cancel the write operation if there is no internet? Firestore firebaseFirestore.collection("Test").document("test123").set(hashMap);

I want to write this document inside the collection, But when the user was offline it is scheduled the operation until the Internet returns. But I want if there is no internet then it must cancel the write operation even if the internet is back.
If there is internet then will do the natural job and add the document to the server but if there is no internet I want to cancel the write operation even if the internet is back.

A: Not having an internet connection is not considered an error condition by the Firestore SDK. Instead if will keep the pending write in its local memory cache (and on disk, unless you disabled that) and send it to the server once the connection is established.
There is no configuration option or API call to prevent the Firestore SDK from caching pending writes. So you'll have to do something in your application code to accomplish the behavior you want.
The most common options are:

*

*Detect whether there's an internet connection before writing to the database, and only performing the set call when there is a conneciton.

*Add a completion listener to the set call, and set up a timer for how long you think a write should reasonably take. If the timer goes off before the write was completed, clear the local cache to cancel all pending writes.


text:
Q: Can I run the Linux Fortran compiler for Intel with Cygwin? I'm on Windows 7, 64-bit. Can I run the Linux Fortran compiler for Intel with Cygwin?

A: While Cygwin provides a POSIX-compatible layer for source code and scripts, it does not provide an ELF loader nor does it implement the Linux ABI, therefore it cannot run Linux binaries.

A: no (because cygwin binaries are WINDOWS binaries).
but you can setup a virtual machine (with virtualbox.org), install linux in it and then run the fortran compiler.

A: Better (easier to install and configure) than cygwin is http://andlinux.org and you can get intel fortran compilers through andlinux.

A: Yes, GCC (including GFortran) supports Cygwin, see:  http://gcc.gnu.org/install/specific.html#x-x-cygwin


text:
Q: UITableView tapping index doesnt scroll to section I have a tableView where I have implemented section headers and I have the section titles appearing along the right hand side. However, when I tap the index it doesn't scroll to that section even though I can see in my logs that it is returning the correct section.
Here is my method for tableView:sectionForSectionIndexTitles:atIndex
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {

NSLog(@"Title: %@", title);
NSLog(@"index: %d", index);

return [[UILocalizedIndexedCollation currentCollation] sectionForSectionIndexTitleAtIndex:index];
}

Any help would be great, thanks.

A: If you want to create alphabets scroll. This will helps.
-(void)viewDidLoad {

 //section index in tableview
    alphabetsArray = [[NSArray alloc] initWithObjects:@"#",@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z", nil];

}

-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{

 return alphabetsArray;

}


text:
Q: minio client works from local but not from docker container I have set up a minio server like so:
docker run -p 9000:9000 minio/minio server data &

the server works as I'm able to point my browser to http://172.17.0.2:9000 and login. If I use minio client from my console it is working too.
But I can't make it work from a docker container:
FROM fedora:latest

RUN mkdir /minio && \
    mkdir /minio/data

COPY ./script.sh /minio/script.sh

RUN \
    curl https://dl.min.io/client/mc/release/linux-amd64/mc > /usr/bin/mc && \
    chmod +x /usr/bin/mc

After that i run script.sh with a very simple docker-compose configuration and i have the following error:
sync_1  | + mc config host add local http://172.17.0.2:9000 minioadmin minioadmin --api S3v4 --lookup auto
sync_1  | Added `local` successfully.
sync_1  | ++ mc find local/test --newer-than 2d0h0m --ignore '*.html'
sync_1  | mc: <ERROR> Unable to stat `local/test`. Get http://172.17.0.2:9000/test/?location=: dial tcp 172.17.0.2:9000: i/o timeout.

(sync is the name of the service in the docker compose file and the command followed after the "+" are the results of running the script with bash -x option for debbugging).
What can be the reason? The server contains only small sample files.

A: docker-compose uses container_name as address, don't use docker ips directly.
If you running it with docker-compose, your minio-mc command should look like this:
...
mc config host add local http://minio:9000 minioadmin minioadmin --api S3v4 --lookup auto


text:
Q: Get Video or Video Info Without open Gallery Swift I am trying to get Video without open Gallery or UIImagePickerControllerlike I got success in getting images without open gallery. Is there any way to get files without open UIImagePickerController.
Can someone please explain to me how to get files without open UIImagePickerController. Any help would be greatly appreciated.
Thanks in advance.

A: For example, using the following code, you can get the latest user video:
import Photos

let options = PHFetchOptions()
options.fetchLimit = 1
let sortDescriptor = NSSortDescriptor(key: "creationDate", ascending: false)
options.sortDescriptors = [sortDescriptor]
let fetchResult = PHAsset.fetchAssets(with: .video, options: options)
if fetchResult.count == 0 {
    // user has no video...
    return
}
let asset = fetchResult[0]
let requestOptions = PHVideoRequestOptions()
let manager = PHImageManager.default()

Then, if you want to get the video itself, use the following code:
manager.requestAVAsset(forVideo: asset, options: requestOptions, resultHandler: { oAsset, oAudioMix, oDict in
    if let urlAsset = oAsset as? AVURLAsset {
        let url = urlAsset.url
        // use URL to get file content
    }
})

Otherwise, if you just want to play the video, use the following code:
manager.requestPlayerItem(forVideo: asset, options: requestOptions, resultHandler: { oPlayerItem, oDict in
    // do something with oPlayerItem
})

For more information you can read this


text:
Q: how to add tab content in seperate new tab in details page? On my product details page I have three tabs, with the help of the following code:

    <?php if ($detailedInfoGroup = $this->getChildGroup('detailed_info', 'getChildHtml')):?>

            <?php foreach ($detailedInfoGroup as $alias => $html):?>
            <?php
                    if(trim($html)=="") continue;
            ?>

<?php echo $this->escapeHtml($this->getChildData($alias, 'title')) ?>

<?php echo $html ?>

            <?php endforeach;?>

    <?php endif; ?>

The tab contents are like:

Now I want to create a new and separate product-collateral tab near the above mentioned tabs.
When I use the below line in catalog.xml it is adding the tab content to the same tab.
<action method="addToParentGroup"><group>detailed_info</group></action>

I want to create a separate tab like the above one, not add to the existing one.
How can this be done?

A: You have to create new Group for this. Add this to <catalog_product_view> handle.
<block type="catalog/product_view_description" name="product.description.sec" as="description_sec" template="catalog/product/view/description.phtml">
    <action method="addToParentGroup"><group>detailed_info_sec</group></action>
    <action method="setTitle" translate="value"><value>Description</value></action>
</block>
<block type="catalog/product_view_attributes" name="product.attributes.sec" as="additional_sec" template="catalog/product/view/attributes.phtml">
    <action method="addToParentGroup"><group>detailed_info_sec</group></action>
    <action method="setTitle" translate="value"><value>Additional Information</value></action>
</block>

Note, I have created a new group, named , detailed_info_sec, with two tabs, Description and Additional Information, you can add OR edit them as per your requirement.
To show this to frontend, add this block of code, to view.phtml

    <?php if ($detailedInfoGroup = $this->getChildGroup('detailed_info_sec', 'getChildHtml')):?>

            <?php foreach ($detailedInfoGroup as $alias => $html):?>

<?php echo $this->escapeHtml($this->getChildData($alias, 'title')) ?>

<?php echo $html ?>

            <?php endforeach;?>

    <?php endif; ?>

A: So you need to add the following code to app/design/frontend/<your_package>/<your_theme>/layout/local.xml :
<catalog_product_view>
    <reference name="product.info">
        <block type="core/template" name="product.tab.fourth" as="fourth_tab" template="path/to/your/template.phtml">
            <action method="addToParentGroup"><group>detailed_info</group></action>
            <action method="setTitle" translate="value"><value>Fourth Tab</value></action>
        </block>
    </reference>
</catalog_product_view>

You will need to create the template to display the content: app/design/frontend/<your_package>/<your_theme>/path/to/your/template.phtml
And also replace the value under the setTitle tag with the name you want to give to your tab.


text:
Q: Optimal substructure of shortest path and Dijkstra I have very well understood Optimal substructure property of shortest path. Which says that-

A shortest path from x to y via z contains a shortest path from x to
z.

Now I want to understand how Dijkstra's algorithm is exploiting this property. All Dijkstra does is- Find minimum at current time and finalise that vertex's shortest distance.
How Dijkstra's algorithm is making use of Optimal substructure property of shortest path?.
I have referred many sources and nowhere found any connecting relation in these two.


text:
Q: How to perform a drag-and-drop without holding down the mouse button? 1. Objective
My purpose is to build a rightmouse-click-menu like this:

When the user clicks on Grab and move, the button should disappear from the QScrollArea() and move quickly towards the mouse. When it arrives at the mouse pointer, the button should fade out and the drag-and-drop operation can start.

2. Minimal, Reproducible Example
I got something working, but it isn't perfect yet. Please copy-paste the code below and run it with Python 3.x (I use Python 3.7) and PyQt5.

Note: To make the line pixmap = QPixmap("my_pixmap.png") work properly, let it refer to an existing png-image on your computer.

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys

class MyButton(QPushButton):
    '''
    A special push button.
    '''
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setFixedWidth(300)
        self.setFixedHeight(30)
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.showMenu)
        return

    def showMenu(self, pos):
        '''
        Show this popup menu when the user clicks with the right mouse button.
        '''
        menu = QMenu()
        menuAction_01 = menu.addAction("action 01")
        menuAction_02 = menu.addAction("action 02")
        menuAction_03 = menu.addAction("action 03")
        menuAction_04 = menu.addAction("action 04")
        menuAction_grab = menu.addAction("grab")
        action = menu.exec_(self.mapToGlobal(pos))
        if action == menuAction_01:
            print("clicked on action 01")
        elif action == menuAction_02:
            print("clicked on action 02")
        elif action == menuAction_03:
            print("clicked on action 03")
        elif action == menuAction_04:
            print("clicked on action 04")
        elif action == menuAction_grab:
            print("clicked on grab")
            # 1. Start animation
            #      -> button moves to mouse pointer
            self.animate()
            # 2. After animation finishes (about 1 sec)
            #      -> start drag operation
            QTimer.singleShot(1000, self.start_drag)
        return

    def animate(self):
        '''
        The button removes itself from the QScrollArea() and flies to the mouse cursor.
        For more details, see the anser of @eyllanesc at
        https://stackoverflow.com/questions/56216698/how-display-a-qpropertyanimation-on-top-of-the-qscrollarea
        '''
        startpoint = self.window().mapFromGlobal(self.mapToGlobal(QPoint()))
        endpoint = self.window().mapFromGlobal(QCursor.pos())
        self.setParent(self.window())
        anim = QPropertyAnimation(
            self,
            b"pos",
            self,
            duration=1000,
            startValue=startpoint,
            endValue=endpoint,
            finished=self.hide,
        )
        anim.start()
        self.show()
        return

    def start_drag(self):
        '''
        Start the drag operation.
        '''
        drag = QDrag(self)
        pixmap = QPixmap("my_pixmap.png")
        pixmap = pixmap.scaledToWidth(100, Qt.SmoothTransformation)
        drag.setPixmap(pixmap)
        mimeData = QMimeData()
        mimeData.setText("Foobar")
        drag.setMimeData(mimeData)
        dropAction = drag.exec(Qt.CopyAction | Qt.MoveAction)
        return

class CustomMainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setGeometry(100, 100, 600, 300)
        self.setWindowTitle("ANIMATION TEST")

        # OUTER FRAME
        # ============
        self.frm = QFrame()
        self.frm.setStyleSheet("""
            QFrame {
                background: #d3d7cf;
                border: none;
            }
        """)
        self.lyt = QHBoxLayout()
        self.frm.setLayout(self.lyt)
        self.setCentralWidget(self.frm)

        # BUTTON FRAME
        # =============
        self.btn_frm = QFrame()
        self.btn_frm.setStyleSheet("""
            QFrame {
                background: #ffffff;
                border: none;
            }
        """)
        self.btn_frm.setFixedWidth(400)
        self.btn_frm.setFixedHeight(200)
        self.btn_lyt = QVBoxLayout()
        self.btn_lyt.setAlignment(Qt.AlignTop)
        self.btn_lyt.setSpacing(5)
        self.btn_frm.setLayout(self.btn_lyt)

        # SCROLL AREA
        # ============
        self.scrollArea = QScrollArea()
        self.scrollArea.setStyleSheet("""
            QScrollArea {
                border-style: solid;
                border-width: 1px;
            }
        """)
        self.scrollArea.setWidget(self.btn_frm)
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setFixedWidth(400)
        self.scrollArea.setFixedHeight(150)
        self.scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.lyt.addWidget(self.scrollArea)

        # ADD BUTTONS TO BTN_LAYOUT
        # ==========================
        self.btn_lyt.addWidget(MyButton("Foo"))
        self.btn_lyt.addWidget(MyButton("Bar"))
        self.btn_lyt.addWidget(MyButton("Baz"))
        self.btn_lyt.addWidget(MyButton("Qux"))
        self.show()

        self.setAcceptDrops(True)
        return

    def dropEvent(self, event):
        event.acceptProposedAction()
        print("dropEvent at {0!s}".format(event))
        return

    def dragLeaveEvent(self, event):
        event.accept()
        return

    def dragEnterEvent(self, event):
        event.acceptProposedAction()
        return

if __name__== '__main__':
    app = QApplication(sys.argv)
    QApplication.setStyle(QStyleFactory.create('Plastique'))
    myGUI = CustomMainWindow()
    sys.exit(app.exec_())

Run the script and you will see a small window with a few buttons in a QScrollArea():
STEP 1: Click on one of the buttons with your right mouse button. You should see a popup menu. Click on "grab".
STEP 2: The button moves to your mouse pointer. Don't move the mouse pointer.
STEP 3: As soon as your mouse pointer is over the button (don't move the mouse, wait for the button to arrive), click and hold the mouse button down.
STEP 4: Now move the mouse (while holding the mouse button down). You should be in a drag-and-drop operation, with the pixmap locked to your mouse!

Okay, it works, but there are a few downsides.

3. Problem
At the end of the animation, the flying button is under your mouse pointer. But if you move your mouse pointer a tiny bit, the button disappears and you miss the drag-and-drop operation.
In other words, what I got now is not very robust. The user can easily miss the drag-and-drop operation.
NOTE: Apparently the problem I describe here only appears on Windows (not on Linux). But I got to make this thing work on Windows...

4. Potential solution
I believe the following approach would be better, and still intuitive to the user:
As soon as the button arrives under the mouse pointer (the end of the animation), the button fades away. The drag-and-drop operation starts automatically, without the need to click and hold down the mouse button. The drag continues while you move the mouse pointer, until you click somewhere. That mouse press is the dropEvent().
Do you know how to implement this? Or perhaps you have another approach in mind?

5. Notes
My question is actually the sequel of this one:
How display a QPropertyAnimation() on top of the QScrollArea()?
Thank you @eyllanesc for solving that one ^_^

A: 1. Solution
Before presenting a solution, I want to express my gratitude to Mr. @eyllanesc for helping me. Without his help, I wouldn't have a solution right now.
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys, functools

class MyButton(QPushButton):
    '''
    A special push button.
    '''
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setFixedWidth(300)
        self.setFixedHeight(30)
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.showMenu)
        self.dragStartPosition = 0
        self.set_style(False)
        return

    def set_style(self, blink):
        if blink:
            background = "#d3d7cf"
        else:
            background = "#2e3436"
        self.setStyleSheet(f"""
            QPushButton {{
                /* white on red */
                background-color:{background};
                color:#ffffff;
                border-color:#888a85;
                border-style:solid;
                border-width:1px;
                border-radius: 6px;
                font-family:Courier;
                font-size:10pt;
                padding:2px 2px 2px 2px;
            }}
        """)
        self.update()
        return

    def showMenu(self, pos):
        '''
        Show this popup menu when the user clicks with the right mouse button.
        '''
        menu = QMenu()
        menuAction_01 = menu.addAction("action 01")
        menuAction_02 = menu.addAction("action 02")
        menuAction_03 = menu.addAction("action 03")
        menuAction_04 = menu.addAction("action 04")
        menuAction_grab = menu.addAction("grab")
        action = menu.exec_(self.mapToGlobal(pos))
        if action == menuAction_01:
            print("clicked on action 01")
        elif action == menuAction_02:
            print("clicked on action 02")
        elif action == menuAction_03:
            print("clicked on action 03")
        elif action == menuAction_04:
            print("clicked on action 04")
        elif action == menuAction_grab:
            print("clicked on grab")
            # Start animation -> button moves to mouse pointer
            self.animate()
        return

    def animate(self):
        '''
        The button removes itself from the QScrollArea() and flies to the mouse cursor.
        For more details, see the anser of @eyllanesc at
        https://stackoverflow.com/questions/56216698/how-display-a-qpropertyanimation-on-top-of-the-qscrollarea
        '''
        def start():
            startpoint = self.window().mapFromGlobal(self.mapToGlobal(QPoint()))
            endpoint = self.window().mapFromGlobal(QCursor.pos() - QPoint(int(self.width()/2), int(self.height()/2)))
            self.setParent(self.window())
            anim = QPropertyAnimation(
                self,
                b"pos",
                self,
                duration=500,
                startValue=startpoint,
                endValue=endpoint,
                finished=blink,
            )
            anim.start()
            self.show()
            return
        def blink():
            # Flash the button to catch attention
            self.setText("GRAB ME")
            QTimer.singleShot(10, functools.partial(self.set_style, True))
            QTimer.singleShot(100, functools.partial(self.set_style, False))
            QTimer.singleShot(200, functools.partial(self.set_style, True))
            QTimer.singleShot(300, functools.partial(self.set_style, False))
            QTimer.singleShot(400, functools.partial(self.set_style, True))
            QTimer.singleShot(500, functools.partial(self.set_style, False))
            finish()
            return
        def finish():
            # After two seconds, hide the button
            # (even if user did not grab it)
            QTimer.singleShot(2000, self.hide)
            return
        start()
        return

    def start_drag(self):
        '''
        Start the drag operation.
        '''
        # 1. Start of drag-and-drop operation
        #    => button must disappear
        self.hide()

        # 2. Initiate drag-and-drop
        drag = QDrag(self)
        pixmap = QPixmap("my_pixmap.png")
        pixmap = pixmap.scaledToWidth(100, Qt.SmoothTransformation)
        drag.setPixmap(pixmap)
        mimeData = QMimeData()
        mimeData.setText("Foobar")
        drag.setMimeData(mimeData)
        dropAction = drag.exec(Qt.CopyAction | Qt.MoveAction)
        return

    def mousePressEvent(self, event):
        '''
        Left or Right mouseclick
        '''
        def leftmouse():
            print("left mouse click")
            self.dragStartPosition = event.pos()
            return
        def rightmouse():
            print("right mouse click")
            return
        if event.button() == Qt.LeftButton:
            leftmouse()
            return
        if event.button() == Qt.RightButton:
            rightmouse()
            return
        return

    def mouseMoveEvent(self, event):
        '''
        Mouse move event
        '''
        event.accept()
        if event.buttons() == Qt.NoButton:
            return
        if self.dragStartPosition is None:
            return
        if (event.pos() - self.dragStartPosition).manhattanLength() < QApplication.startDragDistance():
            return
        self.start_drag()
        return

class CustomMainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setGeometry(100, 100, 600, 300)
        self.setWindowTitle("ANIMATION & DRAG AND DROP")

        # OUTER FRAME
        # ============
        self.frm = QFrame()
        self.frm.setStyleSheet("""
            QFrame {
                background: #d3d7cf;
                border: none;
            }
        """)
        self.lyt = QHBoxLayout()
        self.frm.setLayout(self.lyt)
        self.setCentralWidget(self.frm)

        # BUTTON FRAME
        # =============
        self.btn_frm = QFrame()
        self.btn_frm.setStyleSheet("""
            QFrame {
                background: #ffffff;
                border: none;
            }
        """)
        self.btn_frm.setFixedWidth(400)
        self.btn_frm.setFixedHeight(200)
        self.btn_lyt = QVBoxLayout()
        self.btn_lyt.setAlignment(Qt.AlignTop)
        self.btn_lyt.setSpacing(5)
        self.btn_frm.setLayout(self.btn_lyt)

        # SCROLL AREA
        # ============
        self.scrollArea = QScrollArea()
        self.scrollArea.setStyleSheet("""
            QScrollArea {
                border-style: solid;
                border-width: 1px;
            }
        """)
        self.scrollArea.setWidget(self.btn_frm)
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setFixedWidth(400)
        self.scrollArea.setFixedHeight(150)
        self.scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.lyt.addWidget(self.scrollArea)

        # ADD BUTTONS TO BTN_LAYOUT
        # ==========================
        self.btn_lyt.addWidget(MyButton("Foo"))
        self.btn_lyt.addWidget(MyButton("Bar"))
        self.btn_lyt.addWidget(MyButton("Baz"))
        self.btn_lyt.addWidget(MyButton("Qux"))
        self.show()

        self.setAcceptDrops(True)
        return

    def dropEvent(self, event):
        event.acceptProposedAction()
        print("dropEvent at {0!s}".format(event))
        return

    def dragLeaveEvent(self, event):
        event.accept()
        return

    def dragEnterEvent(self, event):
        event.acceptProposedAction()
        return

if __name__== '__main__':
    app = QApplication(sys.argv)
    QApplication.setStyle(QStyleFactory.create('Plastique'))
    myGUI = CustomMainWindow()
    sys.exit(app.exec_())

This is what I changed:

*

*I improved the animation. Not the top left corner but the middle of the button flies to your mouse pointer when you click "grab" in the rightmouse menu. This improvement makes it much easier to grab the button once the animation has finished.

*At the end of the animation, the button flashes for a short moment to catch the user's attention. The text on the button changes into "GRAB ME". The button's self.hide() function is NOT called for two seconds. So the user has two seconds time to initiate a drag-and-drop operation.

*Initiating the drag-and-drop operation happens in the usual way: hold down the leftmouse button and move the mouse pointer.

*If the user doesn't do anything for two seconds, the button will just disappear. Otherwise, the button would just sit there indefinitely.

2. Results
It works like a charm. Just copy past the code in a .py file and run it with Python 3.x (I got Python 3.7) and PyQt5:

3. Conclusion
I know that this solution is not exactly what I aimed at from the beginning: performing a drag-and-drop without holding down the mouse button. Nevertheless, I think the new approach is better because it's closer to the general intuition what a drag-and-drop actually is.


text:
Q: derived table equivalent for sybase 12.0 or how to do updates in batches I was doing update of big table in Sybase and had following code (declarations skipped):
-- get minimum id
set rowcount 1
select @min_id = id from table1 where id matches_some_condition

set rowcount 10000 -- batch size

select @max_id = id from
(select id from table1 where id >= @min_id and some_condition) a order by id

-- do updates
while (1 = 1)
 begin
   update table1
   set a = some_value
   where id >= @min_id and id <= @max_id and further_conditions

   waitfor delay '00:00:01'

   select @min_id = @max_id
   select @max_id = id from
    (select id from table1 where id >= @min_id and further_conditions
    ) a order by id

   if @min_id >= @max_id
      break

 end

So it's usual idea as you can see: take some ordered column (id) and update rows where id is between N and M. Loop until all rows are updated.
As you might see, in order to get @max_id I used set rowcount 10000 and then select @max_id = id from (select id from table1 where id >= @min_id and further_conditions) a. Now I need to do such update on database which is running Sybase ASE 12.0. The problem is that derived tables are only supported from 12.5, so select id from (select id from table1) a is not working. Any ideas how to fix it, perhaps algorithm can be changed? Of course, I can do needed updates with the help of cursor, but I was wondering if there was some better way.

A: Try to change code:
 select @max_id = id from
    (select id from table1 where id >= @min_id and further_conditions
    ) a order by id

to:
 select @max_id = max(id) from
 from table1
 where id >= @min_id and further_conditions

or
 select @max_id =  id
 from table1
 where id >= @min_id
 and further_conditions
 order by id


text:
Q: Browser content differs from curl content; Does the browser somehow manipulate it? I have a virtual machine with Ubuntu server 18.04 on which I am running an apache2 webserver with two virtual hosts. I configured one vhost to run as a reverse proxy for the other vhost. On the proxy I use the substitute_module to change some of the proxied content (text/html). As an easy start I want to slightly change the "Apache2 Default Ubuntu Page" (index.html) by exchanging the headline with "Substitute works!".
When I hit a curl on that site and check the html code, the headline was changed. But when I load the page with any browser (Firefox/Chrome/IE), the document remains unchanged from the original one.
What I did so far:

*

*empty the cache; using the network analysis tool of the browser says, that it didn't receive the content from cache

*check the server logs-> I get the same notifications there as when I access the document with curl e.g.:
[Fri Mar 13 18:09:43.093779 2020] [proxy:debug] [pid 3223:tid 139804452681472] proxy_util.c(2192): AH00943: http: has released connection for (127.0.0.1)
[Fri Mar 13 18:09:43.093940 2020] [filter:trace4] [pid 3223:tid 139804452681472] mod_filter.c(169): [client 10.0.2.2:50431] Content-Type 'text/html' ...
[Fri Mar 13 18:09:43.094262 2020] [filter:trace4] [pid 3223:tid 139804452681472] mod_filter.c(175): [client 10.0.2.2:50431] ... matched 'text/html'
[Fri Mar 13 18:09:43.094348 2020] [filter:trace2] [pid 3223:tid 139804452681472] mod_filter.c(188): [client 10.0.2.2:50431] Content-Type condition for 'substitute' matched

This is the interesting extract of the curl output:

          Substitute works!

This is the copied snippet from the html laoded by the browser:

          Apache2 Ubuntu Default Page

I suspect it might be some browser optimization that detects the manipulation and somehow reverses it? But I'm not too familiar with this topic, so I would be really happy about any explanations/hints where to search.
If any configuration details would be useful, I will gladly provide those.


text:
Q: why won't the messages be displayed or the if statements work when i press the submit button? My code:
<?PHP

session_start();
$db = mysqli_connect("127.0.0.1", "root", "root", "Authentication");

if(isset($_POST['sbtn'])){
    session_start();
$f_name = mysql_real_escape_string($_POST['f_name']);
$l_name = mysql_real_escape_string($_POST['l_name']);
$email = mysql_real_escape_string($_POST['email']);
$pass = mysql_real_escape_string($_POST['pass']);
$c_pass = mysql_real_escape_string($_POST['c_pass']);

if($pass == $c_pass){
    //create user
    $pass = md5($pass);
    $sql = "INSERT INTO users(email, password, f_name, l_name) VALUES($email, $pass, $f_name, $l_name)";
    mysqli_query($db, $sql);
    $_SESSION['message'] = "You are now registered welcome to UNDERLINE";
    $_SESSION['name'] = $f_name;
}else{
    //tell user they are not equal
    $_SESSION['message'] = "The two passwords did not match";
}
}

mysqli_close($db);
?>

This code for some reason will not allow me to add the information to the database it will also not display my session messages


text:
Q: How to create a method in controller for the IF condition to call in the view in ruby on rails? I am a newbie. I just want to create a method in the controller for the following code to avoid repeating again in the view. How can I write in a short and elegant way in ruby on rails?
<% @A = ....... %>
<% @B = ....... %>
<% @C = ....... %>
<% @D = ....... %>
<% @E = ....... %>

<% if (@A || @B || @C) %>
  <label> One: </label>
  <%= ... %>

  <label> Two: </label>
  <%= ... %>
<% end %>

<% if (@A || @B || @C || (@D && @E)) %>
  <label> Three: </label>
  <%= ... %>
<% end %>

A: assuming your model is called User and the code you provided is placed in "app/views/users/show.html.erb"
I suggest the following refactoring:
(you need to replace A,B,C,D and E with the appropriate logic and rename the methods to something more meaningful)
# in "app/helpers/users_helper.rb"
module UsersHelper
  def isABC
    return A || B || C
  end

  def isDandE
    return D && E
  end
end

# in "app/views/users/show.html.erb
<% if (isABC) %>
  <label> One: </label>
  <%= ... %>

  <label> Two: </label>
  <%= ... %>
<% end %>

<% if (isABC || isDandE) %>
  <label> Three: </label>
  <%= ... %>
<% end %>

You can read up on Rails helpers here: http://paulsturgess.co.uk/articles/49-using-helper-methods-in-ruby-on-rails
Basically the reponsibility of a controller is to accept incoming web requests, fetch the neccessary data (Model) and call the appropriate View for rendering.
Rails has Helpers that can be called from your Views. The idiom is that you put any advanced logic used in the view into the Helper


text:
Q: can't use bundle install I'm experiencing some difficulties when using the command: "bundle install". It's probably some kind of a trivial issue, but I would appreciate any help you can give. I am using linux ubuntu 11.04, ruby 1.9.3p125 (2012-02-16 revision 34643) [i686-linux]
The error message I get is this :
/var/www/hw2_rottenpotatoes$ bundle install
Using rake (0.9.2.2)
Using multi_json (1.0.4)
Using activesupport (3.1.0)
Using bcrypt-ruby (3.0.1)
Using builder (3.0.0)
Using i18n (0.6.0)
Using activemodel (3.1.0)
Using erubis (2.7.0)
Using rack (1.3.5)
Using rack-cache (1.0.3)
Using rack-mount (0.8.3)
Using rack-test (0.6.1)
Using hike (1.2.1)
Using tilt (1.3.3)
Using sprockets (2.0.3)
Using actionpack (3.1.0)
Using mime-types (1.17.2)
Using polyglot (0.3.3)
Using treetop (1.4.10)
Using mail (2.3.0)
Using actionmailer (3.1.0)
Using arel (2.2.1)
Using tzinfo (0.3.31)
Using activerecord (3.1.0)
Using activeresource (3.1.0)
Using bundler (1.1.3)
Using coffee-script-source (1.2.0)
Using execjs (1.2.13)
Using coffee-script (2.2.0)
Using rack-ssl (1.3.2)
Using json (1.6.3)
Using rdoc (3.12)
Using thor (0.14.6)
Using railties (3.1.0)
Using coffee-rails (3.1.1)
Using haml (3.1.4)
Using jquery-rails (1.0.19)
Using libv8 (3.3.10.4)
Using pg (0.13.1)
Using rails (3.1.0)
Using sass (3.1.12)
Using sass-rails (3.1.5)
Using sqlite3 (1.3.5)
Using therubyracer (0.9.9)
Using uglifier (1.2.2)
Unfortunately, a fatal error has occurred. Please report this error to the Bundler issue tracker at https://github.com/carlhuda/bundler/issues so that we can fix it. Please include the full output of the command, your Gemfile and Gemfile.lock. Thanks!
/home/n/.rvm/gems/ruby-1.9.3-p125/gems/bundler-1.1.3/lib/bundler/definition.rb:246:in `initialize': Permission denied - /var/www/hw2_rottenpotatoes/Gemfile.lock (Errno::EACCES)
    from /home/n/.rvm/gems/ruby-1.9.3-p125/gems/bundler-1.1.3/lib/bundler/definition.rb:246:in `open'
    from /home/n/.rvm/gems/ruby-1.9.3-p125/gems/bundler-1.1.3/lib/bundler/definition.rb:246:in `lock'
    from /home/n/.rvm/gems/ruby-1.9.3-p125/gems/bundler-1.1.3/lib/bundler/environment.rb:39:in `lock'
    from /home/n/.rvm/gems/ruby-1.9.3-p125/gems/bundler-1.1.3/lib/bundler/installer.rb:59:in `run'
    from /home/n/.rvm/gems/ruby-1.9.3-p125/gems/bundler-1.1.3/lib/bundler/installer.rb:12:in `install'
    from /home/n/.rvm/gems/ruby-1.9.3-p125/gems/bundler-1.1.3/lib/bundler/cli.rb:220:in `install'
    from /home/n/.rvm/gems/ruby-1.9.3-p125/gems/bundler-1.1.3/lib/bundler/vendor/thor/task.rb:22:in `run'
    from /home/n/.rvm/gems/ruby-1.9.3-p125/gems/bundler-1.1.3/lib/bundler/vendor/thor/invocation.rb:118:in `invoke_task'
    from /home/n/.rvm/gems/ruby-1.9.3-p125/gems/bundler-1.1.3/lib/bundler/vendor/thor.rb:263:in `dispatch'
    from /home/n/.rvm/gems/ruby-1.9.3-p125/gems/bundler-1.1.3/lib/bundler/vendor/thor/base.rb:386:in `start'
    from /home/n/.rvm/gems/ruby-1.9.3-p125/gems/bundler-1.1.3/bin/bundle:13:in `<top (required)>'
    from /home/n/.rvm/gems/ruby-1.9.3-p125/bin/bundle:19:in `load'
    from /home/n/.rvm/gems/ruby-1.9.3-p125/bin/bundle:19:in `<main>

my Gemfile is :
source 'http://rubygems.org'

gem 'rails', '3.1.0'

# Bundle edge Rails instead:
# gem 'rails',     :git => 'git://github.com/rails/rails.git'

# for Heroku deployment - as described in Ap. A of ELLS book
group :development, :test do
  gem 'sqlite3'
end
group :production do
  gem 'pg'
end

# Gems used only for assets and not required
# in production environments by default.
group :assets do
  gem 'therubyracer'
  gem 'sass-rails', "  ~> 3.1.0"
  gem 'coffee-rails', "~> 3.1.0"
  gem 'uglifier'
end

gem 'jquery-rails'

# Use unicorn as the web server
# gem 'unicorn'

# Deploy with Capistrano
# gem 'capistrano'

# To use debugger
gem 'haml'

and my Gemfile.lock is :
GEM
  remote: http://rubygems.org/
  specs:
    actionmailer (3.1.0)
      actionpack (= 3.1.0)
      mail (~> 2.3.0)
    actionpack (3.1.0)
      activemodel (= 3.1.0)
      activesupport (= 3.1.0)
      builder (~> 3.0.0)
      erubis (~> 2.7.0)
      i18n (~> 0.6)
      rack (~> 1.3.2)
      rack-cache (~> 1.0.3)
      rack-mount (~> 0.8.2)
      rack-test (~> 0.6.1)
      sprockets (~> 2.0.0)
    activemodel (3.1.0)
      activesupport (= 3.1.0)
      bcrypt-ruby (~> 3.0.0)
      builder (~> 3.0.0)
      i18n (~> 0.6)
    activerecord (3.1.0)
      activemodel (= 3.1.0)
      activesupport (= 3.1.0)
      arel (~> 2.2.1)
      tzinfo (~> 0.3.29)
    activeresource (3.1.0)
      activemodel (= 3.1.0)
      activesupport (= 3.1.0)
    activesupport (3.1.0)
      multi_json (~> 1.0)
    archive-tar-minitar (0.5.2)
    arel (2.2.1)
    bcrypt-ruby (3.0.1)
    builder (3.0.0)
    coffee-rails (3.1.1)
      coffee-script (>= 2.2.0)
      railties (~> 3.1.0)
    coffee-script (2.2.0)
      coffee-script-source
      execjs
    coffee-script-source (1.2.0)
    columnize (0.3.5)
    erubis (2.7.0)
    execjs (1.2.13)
      multi_json (~> 1.0)
    haml (3.1.4)
    hike (1.2.1)
    i18n (0.6.0)
    jquery-rails (1.0.19)
      railties (~> 3.0)
      thor (~> 0.14)
    json (1.6.3)
    libv8 (3.3.10.4)
    linecache19 (0.5.12)
      ruby_core_source (>= 0.1.4)
    mail (2.3.0)
      i18n (>= 0.4.0)
      mime-types (~> 1.16)
      treetop (~> 1.4.8)
    mime-types (1.17.2)
    multi_json (1.0.4)
    pg (0.13.1)
    polyglot (0.3.3)
    rack (1.3.5)
    rack-cache (1.0.3)
      rack (>= 0.4)
    rack-mount (0.8.3)
      rack (>= 1.0.0)
    rack-ssl (1.3.2)
      rack
    rack-test (0.6.1)
      rack (>= 1.0)
    rails (3.1.0)
      actionmailer (= 3.1.0)
      actionpack (= 3.1.0)
      activerecord (= 3.1.0)
      activeresource (= 3.1.0)
      activesupport (= 3.1.0)
      bundler (~> 1.0)
      railties (= 3.1.0)
    railties (3.1.0)
      actionpack (= 3.1.0)
      activesupport (= 3.1.0)
      rack-ssl (~> 1.3.2)
      rake (>= 0.8.7)
      rdoc (~> 3.4)
      thor (~> 0.14.6)
    rake (0.9.2.2)
    rdoc (3.12)
      json (~> 1.4)
    ruby-debug-base19 (0.11.25)
      columnize (>= 0.3.1)
      linecache19 (>= 0.5.11)
      ruby_core_source (>= 0.1.4)
    ruby-debug19 (0.11.6)
      columnize (>= 0.3.1)
      linecache19 (>= 0.5.11)
      ruby-debug-base19 (>= 0.11.19)
    ruby_core_source (0.1.5)
      archive-tar-minitar (>= 0.5.2)
    sass (3.1.12)
    sass-rails (3.1.5)
      actionpack (~> 3.1.0)
      railties (~> 3.1.0)
      sass (~> 3.1.10)
      tilt (~> 1.3.2)
    sprockets (2.0.3)
      hike (~> 1.2)
      rack (~> 1.0)
      tilt (~> 1.1, != 1.3.0)
    sqlite3 (1.3.5)
    therubyracer (0.9.9)
      libv8 (~> 3.3.10)
    thor (0.14.6)
    tilt (1.3.3)
    treetop (1.4.10)
      polyglot
      polyglot (>= 0.3.1)
    tzinfo (0.3.31)
    uglifier (1.2.2)
      execjs (>= 0.3.0)
      multi_json (>= 1.0.2)

PLATFORMS
  ruby

DEPENDENCIES
  coffee-rails (~> 3.1.0)
  haml
  jquery-rails
  pg
  rails (= 3.1.0)
  ruby-debug19
  sass-rails (~> 3.1.0)
  sqlite3
  therubyracer
  uglifier

A: Looks like bundler doesn't have rights to access Gemfile and/or Gemfile.lock make sure the permissions are right on those files.

A: Being on Ubuntu, you might want to work on your app in /home/<username>/ where you should have more permissions.
If you are working in the /var/ directory, you might need to use sudo everywhere.


text:
Q: URL Redirection while on video streaming using Javascript and Flask I have created an object recognition file that is successfully recognizing the objects like Apple and Mango. I have implemented the real time video streaming on Flask by following the tutorial from,
Video Streaming Blog
Here is my Flask File.
from flask import Flask, render_template, Response, redirect, url_for
from camera import VideoCamera
app = Flask(__name__)
@app.route('/')
def index():
    return render_template('index.html')
def gen(camera1):
    while True:
        label, frame = camera1.get_frame()
        yield b'--frame\r\nContent-Type: image/jpeg\r\n\r\n'
        yield frame
        yield b'\r\n\r\n'
def genlabel(camera1):
    while True:
        label, frame = camera1.get_frame()
        return label
@app.route('/form')
def form():
    return Response(genlabel(VideoCamera()),
                    mimetype='text')
@app.route('/video_feed')
def video_feed():
    label = gen(VideoCamera())
    return Response((label),
                    mimetype='multipar/x-mixed-replace; boundary=frame')
@app.route('/apple')
def add():
    return render_template('apple.html')

And Here is my rendered index.html file.

    <title>Video Streaming Demonstration</title>

Here will be date|time

It's not redirecting even when apple detected in video stream. Why ?


text:
Q: How to check files size I have a problem getting the size of a file.
I have the following code:
    File file = new File(path);
    FilenameFilter mediafilefilter = new FilenameFilter(){
        private String[] filter = {".txt"};
        @Override
        public boolean accept(File dir, String filename) {
            for(int i= 0;i< filter.length ; i++){
                if(filename.indexOf(filter[i]) != -1)return true;
            }
            return false;
        }
     };

     File[] flies = file.listFiles(mediafilefilter);

     if (files != null) {
        {
              if (files.length > 0)
                {
                      System.out.println("Totol is :" + files.length);
                      for (int j = 0; j < files.length; j++) //not work
                 }
        }
     }

some text file is 0 byte

A: Like that
list[0].length()/1024

list[0] is the first file in your array

A:    public long getFileSizes(File f) throws Exception{
                long s=0;
                if (f.exists()) {
                 FileInputStream fis = null;
                    fis = new FileInputStream(f);
                    s= fis.available();
                }
            return s;
        }


text:
Q: Como colocar 2 inputs lado a lado? Como posso colocar 2 input alinhados lado a lado?

<li>
<input type="text" /><input type="checkbox" />
</li>

A: É bem simples, o CSS tem isso:

.campo1 {
   float:left;
}
<input type="text" class="campo1" />
<input type="checkbox" />

Coloquei no GitHub para referência futura.


text:
Q: Finite expansion of this function I had this result as finite expansion of this function $$\frac{1}{(1-x)^2}$$ to order n in neighborhood of 0:
$$1+\sum_{i=1}^{n}{(x^i.(i+1)) }+0(x^n)$$ (where x tends to 0)is it true? And if yes should i prove it by mathematical induction?

A: (answer edited following modifications of the question)
Notice that your function is the derivative of $\frac1{1-x}$ which has a geometric series for its expansion at 0. You can expand your function by taking the term-by-term derivative of the geometric series.
If you do not want to use that argument, you can also obtain an expression for the $n$-th derivative of the function (inductively, using the form of the $(n-1)$-th derivative).


text:
Q: vb.net compare two tables and find differences I have two tables with the same strucure. a.ID*(varchar(10)), a.CODE_ASS(varchar(1))*  and b.ID*(varchar(10)), b.CODE_ASS(varchar(1))*
Table "a" contains 2010 data, and table "b" contain 2013 data.
These two tables should doesn't have the same number of rows in each, but common IDs should be identical. I need to compare tables and find differences.

As you can see in this example, green rows are ok, and red one should be an error.
ID 2, 4 and 5 are errors because there are some differences. ID 6, in "a" table, is ok even if it has been deleted in table "b".

A: It appears that you are using SQL tables, if you write a query to join the data on ID and select only where the values are different. Do you really want to assume that 0 = NULL?
SELECT a.ID FROM a INNER JOIN  b ON a.ID = b.ID WHERE a.ID<>b.ID;

If you want 0 = NULL then you need to change NULLs to 0 - that would look like the following.
SELECT a.ID FROM a INNER JOIN b ON a.ID = b.ID WHERE ISNULL(a.ID,0)<>ISNULL(b.ID,0);

ISNULL(param, value) will change the NULL to the value, in this case 0.
I am guessing you are using a recordset object so then all you have to do is loop through the results.


text:
Q: Why the space complexity of heapsort is `O(1)` with a recursive heapify procedure? When I was reading the space complexity of merge sort, I got the space complexity of that is O(n+logn). O(logn) is calculated when we consider the stack frame size of the recursive procedures.
But the heapsort also utilizes the recursive procedure, which is the heapify procedure. Why the space complexity of heapsort is O(1)?
and the code I am reading is
```java
public class HeapSort {
public void buildheap(int array[]){
    int length = array.length;
    int heapsize = length;
    int nonleaf = length / 2 - 1;
    for(int i = nonleaf; i>=0;i--){
        heapify(array,i,heapsize);
    }
}

public void heapify(int array[], int i,int heapsize){
    int smallest = i;
    int left = 2*i+1;
    int right = 2*i+2;
    if(left<heapsize){
        if(array[i]>array[left]){
            smallest = left;
        }
        else smallest = i;
    }
    if(right<heapsize){
        if(array[smallest]>array[right]){
            smallest = right;
        }
    }
    if(smallest != i){
        int temp;
        temp = array[i];
        array[i] = array[smallest];
        array[smallest] = temp;
        heapify(array,smallest,heapsize);
    }
}

public void heapsort(int array[]){
    int heapsize = array.length;
    buildheap(array);

    for(int i=0;i<array.length-1;i++){
        // swap the first and the last
        int temp;
        temp = array[0];
        array[0] = array[heapsize-1];
        array[heapsize-1] = temp;
        // heapify the array
        heapsize = heapsize - 1;
        heapify(array,0,heapsize);
    }
}

```

A: The space complexity of the Java code you posted is not O(1) because it consumes a non-constant amount of stack space.
However this is not the usual way to implement heapsort. The recursion in the heapify method can easily replaced by a simple while loop (without introducing any additional data structures like a stack). If you do that, it will run in O(1) space.

A: The heapify() function can by implemented tail-recursively.  Many functional languages guarantee that tail-recursive functions use a constant amount of stack space.


text:
Q: Do Hyperledger platforms have full/light-weighted nodes like Ethereum? I'm new to Blockchain and trying to understand if Hyperledger platforms (such as Fabric and Sawtooth) offer full/light nodes separation like Ethereum.
Thanks.

A: Don't know about STL, but Fabric doesn't have a light node.
There are 2 reasons for this:
1) The hash in the block header is simply a concatenated hash over the block data, and not a Merkle tree root. So you cannot prove efficiently that a Transaction exists in a block, without giving the entire block.
2) Unlike most Blockchains, Fabric is an execute-order Blockchain, which means that some transactions in the block may not be valid at all, and only at the time of commit, the peer checks if they are valid.


text:
Q: Visual Studio 2010 build with wrong framework I'm working on Visual Studio Profesionnal 2010.
In my solution I've got 2 projects
The first is a web site with targeted .net runtime 2.0
the second is a dll with targeted .net runtime 2.0
I add the output of the second as assembly of the first.
I build and rebuild and clean my solution
result : Build succeeded
But when I launch the projet in my web-browser ( in debug or release ).
I've got the Server Error :

This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded

Is there someone who had already the problem?
I think it can be a bug from Visual Studio 2010 but the hotline is very expensive
300€ the phone call.
More Information :
I opended my dll with reflector and saw that mscorlib is referenced 2 times
the first time Version = 2.0
and the second time version = 4.0

A: I am pretty sure that this means that you built with asp.net framework 3.5x, but your server only has 3.0x. Update the runtime on the server.

A: Open the .csproj file with text editor (e.g. Notepad) and see the references in there.
If there are references to frameworks higher than 2.0 remove them or change to 2.0 if possible, save and reload the project.

A: Your server can only support 3.0, Updating the server will resolve the issue..


text:
Q: Finding the smallest integer pair such that 123x+321y=1? How do I find the smallest integer pair $(x,y)$ such that $123x+321y=1$?

A: Both $123$ and $321$ are multiples of 3, so their sum is $= 0 \pmod 3$ for integers $x$ and $y$, so the sum cannot equal $1 \pmod 3$.

A: HINT;
Using Linear congruence theorem (Proof)
as the greatest common divisor $\textrm{gcd}(123,321)=3$ does not divide $1,$ there is no solution


text:
Q: grep is not recognized as an internal or external in windows I am trying to run this line
 scholar.py --txt-globals --author "albert einstein" | grep '\[G\]' | grep Results

In the CMD, but I confront this error. I know grep is for UNIX but how can I run this line in windows? I have windows 7.

A: CMD does not have grep like unix does. This applies to many commands, such as sed, awk, sudo, cat...etc.
However, if you use PowerShell instead of cmd, it has a Select-String cmdlet which will allow you to get similar results.
scholar.py --txt-globals --author "albert einstein" | Select-String '[G]' | Select-String 'Results'
I haven't tested the Regex. But if Select-String isn't giving you the required results you can install Grep for Windows.

A: You can install all these nice UNIX commands with Cygwin (https://www.cygwin.com/).

A: Use findstr instead grep, because cmd doesn't cover grep syntax as it works on Linux.


text:
Q: Dynamically making a link from an URL string in db table to a HTML/PHP page I am trying to make a PHP page that fetches results from a MySQL db table on a server (www.domain.com).
The table has the following fields:

ID    (ie: 1)
Date  (ie: 2014-12-06)
Text  (ie: Guns 'n Roses)
URL   (ie: https://www.youtube.com/watch?v=xxxxxxx)
Link  (ie: Watch on YouTube)

The URL is anchored in Link text to a webpage.
My query is easy and straightforward: a simple select * from table. When run, PHP page prints on screen the following table:
2014-12-06 --- Guns 'n Roses --- Watch on YouTube

where, by clicking on "Watch on YouTube", the actual address becomes:
www.domain.com/https://www.youtube.com/watch?v=xxxxxxx
How can I get rid of the server root and have a working link?
The code is:
<!DOCTYPE html>

<meta charset="utf-8">

<?php

require "parameters.php";

$con = mysqli_connect($host,$user,$password,$db);

if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
 }

$result = mysqli_query($con,"SELECT Date, Text, URL, Link FROM $db.$table_10 ORDER BY date desc");

echo "
";
echo "
Date	Text	Link
";
echo "

";

while($row = mysqli_fetch_array($result)) {
$safe_url = mysqli_real_escape_string($con, $row['URL']);
echo "
";
echo "" . $row['Date'] . "  	";
echo "" . $row['Text'] . "	";
echo "" . $row['Link'] . "	";
echo "
";
}
echo "
";

mysqli_close($con);
?>

Thank you for replying and helping me !

A: If a link isn't prefixed with a protocol it becomes relative to the page containing the link.
Webpage

becomes http://example.net/example.com/somepage when clicked
Webpage

becomes http: //example.com/somepage
When you're displaying the link, prefix it with http://
-
Here's a JSFiddle showing this, http://jsfiddle.net/7fnpg5o1/


text:
Q: Log4J Issue in Grails app which has a dependency on comons-logging I am adding a dependency to my Grails Project which brings in both commons-logging and log4j as transitive dependencies. When I run my app I then get an error
Error Error executing script RunApp: Could not initialize class
org.apache.log4j.LogManager (NOTE: Stack trace has been filtered. Use --verbose to see
entiretrace.) java.lang.NoClassDefFoundError: Could not initialize class
org.apache.log4j.LogManager

I tried to remove the commons-logging dependency as per this link by excluding the commons-logging. But it never helped. I see that commons-logging is not a direct dependency of the dependency I am adding. So if do
    runtime ('com.company.i18n:i18n:1.3.4')
    {
        excludes 'commons-logging'
    }

does it exclude all the commons-logging dependencies in my dependency ? Or only the immediate ones. How do I solve this issue?

A: I tried hard by excluding "log4j" from all the dependencies, but nothing worked. Finally I solved this by avoiding all the transitive dependencies and then adding what ever was necessary.
//add necessary dependencies.

runtime ('com.company.i18n:i18n:1.3.4')
{
    transitive = false
}


text:
Q: Eclipse launcher mis-parses final command line argument ending in backslash (\)? I have a command line Java program which I launch and run within Eclipse. When I configure the command line arguments, I noticed that it is difficult to express the arguments if the last letter of the last argument is a backslash (\). Is this a known bug, or is there a reasonable workaround?

Test code:
import java.util.Arrays;
public class hello {
    public static void main(String[] args) {
        System.out.println(Arrays.toString(args));
    }
}

Screenshot:

Test cases:
Format: String entered into the "program arguments" box
        -->  String printed by Arrays.toString()

C:\      -->  [C:]
C:\ D:\  -->  [C:\, D:]
C:\\     -->  [C:]
C:\\\    -->  [C:]
"C:\"    -->  [C:"]
"C:\\"   -->  [C:\]     (this seems to work, but why?)
'C:\'    -->  ['C:\']

Environment:

*

*Eclipse Mars and EPP Java Package 4.5.1.20150917-1200

*Oracle JDK 1.8.0_45 64-bit, Windows 8.1.

A: It seems using quotation marks and double quotes is the cleanest solution at the moment.
"C:\\"

C:\ "D:\\"

C:\ D:\ "E:\\"

A: The last backslash seems to get removed.
A workaround is then C:\ D:\ \


text:
Q: RxSwift, tests with RxBlocking do not end I'm trying to test a very simple view model:
struct SearchViewModelImpl: SearchViewModel {
    let query = PublishSubject<String>()
    let results: Observable<BookResult<[Book]>>

    init(searchService: SearchService) {
        results = query
            .distinctUntilChanged()
            .throttle(0.5, scheduler: MainScheduler.instance)
            .filter({ !$0.isEmpty })
            .flatMapLatest({ searchService.search(query: $0) })
    }
}

I'm trying to test receiving an error from service so I doubled it this way:
class SearchServiceStub: SearchService {
    let erroring: Bool

    init(erroring: Bool) {
        self.erroring = erroring
    }

    func search(query: String) -> Observable<BookResult<[Book]>> {
        if erroring {
            return .just(BookResult.error(SearchError.downloadError, cached: nil))
        } else {
            return books.map(BookResult.success) // Returns dummy books
        }
    }
}

I'm testing a query that errors this way:
func test_when_searchBooksErrored_then_nextEventWithError() {
    let sut = SearchViewModelImpl(searchService: SearchServiceStub(erroring: true))
    let observer = scheduler.createObserver(BookResult<[Book]>.self)

    scheduler
        .createHotObservable([
            Recorded.next(200, ("Rx")),
            Recorded.next(800, ("RxSwift"))
        ])
        .bind(to: sut.query)
        .disposed(by: disposeBag)

    sut.results
        .subscribe(observer)
        .disposed(by: disposeBag)

    scheduler.start()

    XCTAssertEqual(observer.events.count, 2)
}

To begin I'm just asserting if the count of events is correct but I'am only receiving one not two. I thought it was a matter of asynchronicity so I changed the test to use RxBlocking:
func test_when_searchBooksErrored_then_nextEventWithError() {
    let sut = SearchViewModelImpl(searchService: SearchServiceStub(erroring: true))
    let observer = scheduler.createObserver(BookResult<[Book]>.self)

    scheduler
        .createHotObservable([
            Recorded.next(200, ("Rx")),
            Recorded.next(800, ("RxSwift"))
        ])
        .bind(to: sut.query)
        .disposed(by: disposeBag)

    sut.results.debug()
        .subscribe(observer)
        .disposed(by: disposeBag)

    let events = try! sut.results.take(2).toBlocking().toArray()

    scheduler.start()

    XCTAssertEqual(events.count, 2)
}

But this never ends.
I don't know if there is something wrong with my stub, or maybe with the viewmodel, but the production app works correctly, emitting the events as the query fires.
Documentation of RxTest and RxBlocking is very very short, with the classic examples with a string or an integer, but nothing related with this kind of flow... it is very frustrating.

A: Your throttling your query with the MainScheduler.instance scheduler. Try removing that and see what happens. That is probably why your only getting one. You need to inject the test scheduler into that throttle when testing.
There are a few different ways to go about getting the right scheduler into your model. Based on your current code, dependency injection would work fine.
struct SearchViewModelImpl: SearchViewModel {
    let query = PublishSubject<String>()
    let results: Observable<BookResult<[Book]>>

    init(searchService: SearchService, scheduler: SchedulerType = MainScheduler.instance) {
        results = query
            .distinctUntilChanged()
            .throttle(0.5, scheduler: scheduler)
            .filter({ !$0.isEmpty })
            .flatMapLatest({ searchService.search(query: $0) })
    }
}

then in your test:
let sut = SearchViewModelImpl(searchService: SearchServiceStub(erroring: true), scheduler: testScheduler)

Also, rather than using toBocking(), you can bind the results events to the testable Observer.
func test_when_searchBooksErrored_then_nextEventWithError() {
    let sut = SearchViewModelImpl(searchService: SearchServiceStub(erroring: true), scheduler: testScheduler)
    let observer = scheduler.createObserver(BookResult<[Book]>.self)

    scheduler
        .createHotObservable([
            Recorded.next(200, ("Rx")),
            Recorded.next(800, ("RxSwift"))
        ])
        .bind(to: sut.query)
        .disposed(by: disposeBag)

    sut.results.bind(to: observer)
     .disposed(by: disposeBag)

    scheduler.start()

    XCTAssertEqual(observer.events.count, 2)
}

Although toBlocking() can be useful in certain situation, you get a lot more information when you bind the events to a testableObserver.


text:
Q: Inverse trigonometric functions in Calculator Is there a way to calculate inverse trigonometric functions in El Capitan's Calculator (ie. arcsine, arccosine, arctangent, etc.)? I've tried the usual alt, cmd, ctrl modifiers with the sin/cos/tan buttons to no avail. I'm especially annoyed because Spotlight does calculate arctangents and the result is claimed to come from Calculator itself, so I don't know if they dumbed the interface down or what.
Examples of operations that work from Spotlight but I have no clue how to do from Calculator:
atan(1)  # arctangent of 1 in radians
atand(1) # arctangent of 1 in degrees

A: To calculate atan() and atand() in Calculator under OS X El Capitan, do the following…

*

*Open Calculator.

*Press command2 on the  Mac's keyboard, to show the Scientific Calculator.

*To calculate inverse trigonometric functions, click the 2nd button (left side, second row, first button) on the calculator (or you can press and hold the shift key on the Mac's keyboard during a given operation) in order to change the tan button to display as: tan -1

*To change between calculating degrees and radians, toggle the button in the lower left corner of the Scientific Calculator between Deg and Rad.

*

*The default is to calculate degrees and the Rad button is shown.

*To  calculate radians, click the Rad button so it shows Deg. Note that Rad also appears in the left side of the main display.

Result for atand(1):

Result for atan(1):

A: Hit the shift key in Calculator in older versions of OS X to get all inverse trigonometric but also some other functions:

In El Capitan it works with the "2nd" button (the real keyboard's shift key should work as well):


text:
Q: Can an union's destructor be trivial? Given the following code:
struct Bar {
    Bar() { }
    ~Bar() { }
};

struct FooBase {
    // No virtual destructor
};

struct Foo : FooBase {
    Foo() : bar{} { }

    union {
        Bar bar;
    };
};

int main() {
    FooBase *p = new Foo;
    static_cast<Foo *>(p)->bar.~Bar();
    delete p;
}

I wish to detach Foo::bar's lifetime from its enclosing Foo.
As far as I know, delete p; is well-defined if and only if Foo's destructor is trivial.
Since Foo only contains an union, and is not supposed to destruct its bar itself, it looks like it is the case: informally speaking, that destructor does nothing.
But is this code actually well-defined according to the standard?
See it live on Coliru

A: First of all, [expr.delete] for me doesn't support your claim that "delete p; is well-defined if and only if Foo's destructor is trivial".

In the first alternative (delete object), if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined.

Since the static type is FooBase whereas the dynamic type is Foo, I'd expect that to be UB.
Furthermore, (even in case this is not UB) I think that the destructor of Foo isn't trivial.

[class.union]
A union-like class is a union or a class that has an anonymous union as a direct member. A union-like class X has a set of variant members. If X is a union its variant members are the non-static data members; otherwise, its variant members are the non-static data members of all anonymous unions that are members of X.

Thus Foo is a union-like class with bar (of type Bar which has a non-trivial destructor) being a variant member.

[class.dtor]
4) If a class has no user-declared destructor, a destructor is implicitly declared as defaulted [...].
5) A defaulted destructor for a class X is defined as deleted if

*

*X is a union-like class that has a variant member with a non-trivial destructor [...].

Therefore, I think that the implicitly defaulted destructor of Foo should be defined as deleted and must be user-provided.
(Declare Foo q; and see the compilation fail.)

A destructor is trivial if it is not user-provided and if

*

*[...] for all of the non-static data members of its class that are of class type (or array thereof), each such class has a trivial destructor.

I'd exepect that clause to extend to variant members as well since it doesn't say "non-variant data members".

You could have a virtual destructor in FooBase and then implement ~Foo() without including bar.~bar(); where it would be possible to destroy bar in advance without it being destructed again in ~Foo().
I'd however strongly advise against it since you'd have to somehow call ~bar for every static or dynamic Foo before it goes out of scope.


text:
Q: Dimension of $(l^\infty)^*$ mod $l^1$. We can consider $l^1$ as a subspace of $(l^\infty)^*$ because for every $x \in l^1$, there exists a bounded linear functional $T_x: l^\infty \to \mathbb{R}$ defined by $T_x(y) = \sum_n x_n y_n$. Furthermore $l^1$ is closed in $(l^\infty)^*$. I am interested in the dimension of the quotient space $(l^\infty)^*$ mod $l^1$ but I don't know where to even start. I solved a few problems about dimensions of quotient spaces for sequence spaces by considering linearly independent vectors, but here the notion of dual confuses me.

A: Suppose that $\ell_\infty^*/\ell_1$ is finite dimensional, and let $\{x_1,...,x_n\}$ be a finite subset of $\ell_\infty^*$ such that the set
$$\big\{x_1+\ell_1,...,x_n+\ell_n\bigr\}$$
is basis for the quotient $\ell_\infty^*/\ell_1$. Now, let $(e_n)$ be the standard Schauder basis of $\ell_1$. I.e. $e_n(k)=1$ when $k=n$ and $e_n(k)=0$ when $k\neq n$. Being a Schauder basis means that for every $x=(x(k))_{k=1}^{\infty}\in \ell_1$ we have that
$$\biggl|\biggl|x-\sum_{n=1}^{k}x(n)e_n\biggr|\biggr|_1\to 0$$
as $k\to \infty$. In other words $\overline{Y}=\ell_1$ where $Y=span(e_m:\,m\in \mathbb{N})$ (This shows that $\ell_1$ is separable). Now, its easy to check that
$$\tag{*}\ell_\infty^* = \overline{Y}\oplus Z$$
with $Z=span(x_k:\,1\leq k\leq n)$. Now, since both $\overline{Y}$ and $Z$ are separable by $(*)$ it follows that $\ell_\infty^*$ is separable, hence $\ell_\infty$ must be separable which cant be true. So, the quotient $\ell_\infty^*/\ell_1$ has infinite dimension.


text:
Q: Why do we need typename for type dependent on a template-parameter in C++ I looked up on Wiki for the keyword typename (http://en.wikipedia.org/wiki/Typename) and it gives an example which typename is required before T::bar
template <typename T>
void foo(const T& t)
{
   // declares a pointer to an object of type T::bar
   T::bar * p;
}

struct StructWithBarAsType {
   typedef int bar;
};

int main() {
   StructWithBarAsType x;
   foo(x);
}

Why doesn't C++ inspect StructWithBarAsType and find that T::bar is actually a type when generating code for foo(x)? Is it not possible or just an efficiency consideration?

A: it assumes that T::bar is a static member unless typename is specified beforehand.  afaict there is no technical limitation that would prevent compilers from being able to figure out during instantiation whether or not T::bar is a type, but to keep things a bit easier for compiler implementors, the decision was made.  It can make more of a difference than than one might think, consider
T::bar<a,b>c;

is this a variable c of type T::bar<a,b>, or is it a less than, comma, greater than?  T::bar < a followed by b > c?  C++ template syntax leaves a lot to be desired.

A: When parsing a template it may genuinely be impossible to determine whether a type or value is intended. An example is
int v = 2;
template <typename T>
void f() {
    T::value * v;
}

This code may either declare a pointer or imply an operation. Neither interpretation is particular useful. When the compiler is asked to make sense of this code it doesn't know the type T. Now, you could say: have it be prepared for both interpretation! ... but you would have a combinatorial explosion at hand if the next lines carry on with something similar.
I could imagine the compilers could in most cases correctly determine what is meant. However, without further context it is sometimes impossible. At the time typename was introduced I also think it was unexpected how often it is needed. To some extend that got fixed by auto and decltype(...) which get rid of many needs for nested types.


text:
Q: java.lang.NoSuchMethodError: org.json.JSONObject.getNames Exception I have included the required JAR downloaded from here: www.java2s.com/Code/Jar/j/Downloadjavajsonjar.htm in the Build Path of the project.
Yet, unable to resolve this error. What else could cause the problem?
My stack trace is shown below:
java.lang.NoSuchMethodError: org.json.JSONObject.getNames(Lorg/json/JSONObject;)[Ljava/lang/String;
at com.comp.cloud.portal.zRPCEngine.zCompRPC(zRPCEngine.java:641)
at com.comp.cloud.portal.zCompManager.CompSubscribe(zCompManager.java:1480)
at com.comp.cloud.portal.zCompManager.AddCompHD(zCompManager.java:310)
at com.comp.cloud.portal.zCompManager.LoadInventory(zCompManager.java:96)
at com.comp.cloud.portal.zCompCloudPortalUI.Login(zCompCloudPortalUI.java:333)
at com.comp.cloud.portal.portlets.Login.ExecuteLogin(Login.java:333)
at com.comp.cloud.portal.portlets.Login$button_login_clicked.buttonClick(Login.java:234)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.vaadin.event.ListenerMethod.receiveEvent(ListenerMethod.java:508)
at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:198)
at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:161)
at com.vaadin.server.AbstractClientConnector.fireEvent(AbstractClientConnector.java:984)
at com.vaadin.ui.Button.fireClick(Button.java:393)
at com.vaadin.ui.Button$1.click(Button.java:57)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:168)
at com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:118)
at com.vaadin.server.communication.ServerRpcHandler.handleInvocations(ServerRpcHandler.java:295)
at com.vaadin.server.communication.ServerRpcHandler.handleRpc(ServerRpcHandler.java:188)
at com.vaadin.server.communication.UidlRequestHandler.synchronizedHandleRequest(UidlRequestHandler.java:93)
at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:41)
at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1408)
at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:237)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:744)

A: About java.lang.NoSuchMethodError :
This error is a runTime error which occurs as a result of missing method definition in the classes available in the ClassPath. After the classLoader loads the class, linking phase fails to link the method call as the requested method is not available in the ClassPath classes
This error generally occurs when you compile and test your code in one environment (generally local machine) and you deploy your code in another environment.
We will consider the following example for our use case : java.lang.NoSuchMethodError: org.json.JSONTokener
Why the classes are not available in the ClassPath despite creating a uber jar? :
It's because classes are loaded at runtime and if loader finds multiple classes with same signature, it loads the first one it encounters. If that class doesn't have the required method, we will get the NoSuchMethodError.
Gist is that classLoader fails to find the exact class which we want it to load.
How to find which class is getting load?
We can use following code snippet in the main method to find out the class which is getting loaded.
ClassLoader classloader = org.json.JSONTokener.class.getClassLoader();
URL res = classloader.getResource("org/json/JSONTokener.class");
String path = res.getPath();
System.out.println("Core JSONTokener came from " + path)

What to do after finding the path of class from which it is getting loaded?
If you find that the library that is getting loaded is coming from some other path in the machine, you have to make sure that the desired library gets loaded. The best method to do so is to shade your jar and rename the references in your project.
How to shade a jar and rename references in Scala/Java?
In Scala, you can add
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.7")

to ./project/plugins.sbt and then use the sbt commandsbt assembly to generate a fat jar-file.
Now to shade the jar use following code in your sbt:
assemblyShadeRules in assembly := Seq(
ShadeRule.rename("org.json.**" -> "shadedJson.@1")
.inLibrary("org.json" % "json" % "20180813")
.inAll
)

What this will do is, rename all the references of regex
org.json.** to shadedJson.** in your code as well as in the library that you have included in your dependencies and shade the jar with changes.
Now when you run your program, it will find both the jars in the classPath, but since you have renamed the references in your code and your jar, that will be the one which will be loaded by classLoader and not the other ones.
In Java, you can use maven-jar-plugin and maven-shade-plugin to create a shaded jar in java.
https://examples.javacodegeeks.com/enterprise-java/maven/maven-jar-plugin-example/
<build>
<plugins>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.3</version>
</plugin>
</plugins>
</build>

now to rename reference in java, you have to use relocation pattern in maven-shade-problem as mentioned in the following link:
http://maven.apache.org/plugins/maven-shade-plugin/examples/class-relocation.html
How to check if jar is shaded or not?
Simple, just explode the jar and search for class name as per your rename. eg in our case you can search for shadedJson
Command to explode :
jar -tf
*redirect the output to a file and search in that file.

A: May be that you added the jar to your project build path, but you are not bundling it into your war deployed on Tomcat. Edit: You either bundled an older version of the jar or an older version of the jar is visible from your application classpath.


text:
Q: How to fix "error in colsums(is.na(codes))" in R I'm trying to import data from Estonian national database through r into powerbi, but sometimes the data gives me an error which i don't know how to resolve.
I have tried using different data from the same database and with some it works fine, but others throw an error.
I have this code:
library(stringr)
library('rsdmx')
data = readSDMX('http://andmebaas.stat.ee/restsdmx/sdmx.ashx/GetData/LET171/1+2+3+4+5+6+7+8+9+10+11+12+13+14.1+2+3/all?startTime=2010&endTime=2016')
DF = as.data.frame(data)
dsd = readSDMX("http://andmebaas.stat.ee/restsdmx/sdmx.ashx/GetDataStructure/LET171")
cls=slot(dsd, "codelists")
codelists <- sapply(slot(cls, "codelists"), function(x) slot(x, "id"))
for(i in codelists){
  kood <- str_sub(i, start= 10)
  if(kood!="OBS_STATUS"){
    assign(kood, as.data.frame(slot(dsd, "codelists"), codelistId = i))
  }
}

It works fine with some data, for example using these links
Data http://andmebaas.stat.ee/restsdmx/sdmx.ashx/GetData/RV021/1+2+3.1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+31+32+33+34+20+21/all?startTime=1919&endTime=2019
dsd http://andmebaas.stat.ee/restsdmx/sdmx.ashx/GetDataStructure/RV021
The code is supposed to import the data into powerbi and create tables with data and identifiers, but with the links currently in the code it throws the following error
Error in colSums(is.na(codes)) :
  'x' must be an array of at least two dimensions
In addition: Warning message:
In is.na(codes) : is.na() applied to non-(list or vector) of type 'NULL'

A: Looks like codes is a vector and that the colSums() function needs a matrix as argument. I did not go through all your example, but if you want to convert a vector into a matrix, you could do it with
codes <- as.matrix(codes, nrow=your_nrow, ncol=your_ncol)

where you can only give one of nrow or ncol.


text:
Q: Is a closed convex set $E$ in $\mathbb{R}^n$ equal to the closure of its interior? I have seen similar questions relating the interior of a convex set equal to the interior of its closure. However, I can't find anything that says if $E$ is a closed convex set, then $E = \overline{int E}$. If anyone would be willing to help me sketch a proof of this I would really appreciate it.
I would like to say that this is a simple as noticing that $int E$ is the set $E \setminus bd E$, therefore its closure is to re apply the boundary, but I don't think this is a sound argument.
Edit: Sorry, I should have added the assumption that the convex set has non empty interior.

A: A closed line segment in $\Bbb R^n$ with $n\ge 2$ is a closed convex set with empty interior, so it cannot be the closure of its interior. For $n\ge 1$ a singleton set (a set consisting of a single point) is a counterexample.