text:
Q: How to make JScrollPane (In BorderLayout, containing JPanel) smoothly autoscroll I'm trying to have a JPanel of varying size (potentially much wider than the standard screen) inside of a JScrollPanel. Currently it works out great, and I have configured the scrollbars to work fine manually, however I would like the JPanel to "scroll" constantly to the left, so that over time the whole thing is displayed. All of the answers I found are specific to JTextArea and use Carets, or use rectToVisible. Neither of these will work because I'm trying to scroll internally to a single JPanel.
I've included what I believe to be all of the relevant code below.
center is the JPanel (of which Grid is a subclass, used to paint specifically a grid with some specific cells colored) with a BorderLayout that I would like to autoscroll.
public GuiViewFrame(Song playMe) {
  String[][] songArray = playMe.to2DArray();

  this.displayPanel = new ConcreteGuiViewPanel(playMe);
  main = new JPanel();
  main.setLayout(new BorderLayout());
  displayPanel.setLayout(new BorderLayout());
  center = new Grid(playMe);
  labels = new Labels(playMe);
  horiz = new Horiz(playMe);
  center.setPreferredSize(new Dimension(10 * songArray.length, 10 * songArray[0].length));
  horiz.setPreferredSize(new Dimension(10 * songArray.length, 10));
  horiz.setVisible(true);

  main.add(center, BorderLayout.CENTER);
  main.add(horiz, BorderLayout.NORTH);

  scroll = new JScrollPane(main,
        JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
  add(scroll, BorderLayout.CENTER);
  labels.setPreferredSize(new Dimension(20, 10 * songArray[0].length));
  labels.setVisible(true);
  add(labels, BorderLayout.WEST);

  JScrollBar horiz = scroll.getHorizontalScrollBar();
  InputMap im = horiz.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
  im.put(KeyStroke.getKeyStroke("RIGHT"), "positiveUnitIncrement");
  im.put(KeyStroke.getKeyStroke("LEFT"), "negativeUnitIncrement");
  im.put(KeyStroke.getKeyStroke("HOME"), "minScroll");
  im.put(KeyStroke.getKeyStroke("END"), "maxScroll");

  this.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  this.pack();
}

The project as a whole is to generate a view for playing music that combines MIDI and a GUI, but right now once MIDI plays enough of the song, the relevant notes are off screen. I would like to scroll at a rate to keep pace with MIDI.

A: You can set the value of the horizontal scrollbar to control what is currently visible:
JScrollBar horizontal = scroll.getHorizontalScrollBar();
horizontal.setValue( horizontal.getValue() + ??? );

You would need to use a Swing Timer to schedule the scrolling at an appropriate interval.
Simple example of using a Timer to scroll text:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;

public class TimerTest extends JPanel implements ActionListener
{
    JLabel timeLabel;
    JLabel scrollLabel;

    public TimerTest()
    {
        setLayout( new BorderLayout() );

        timeLabel = new JLabel( new Date().toString() );
        add(timeLabel, BorderLayout.NORTH);

        scrollLabel = new JLabel( "Some continuously scrolling text!!      " );
        add(scrollLabel, BorderLayout.SOUTH);

        int time = 1000;
        javax.swing.Timer timer = new javax.swing.Timer(time, this);
        timer.setInitialDelay(1);
        timer.start();
    }

    public void actionPerformed(ActionEvent e)
    {
        timeLabel.setText( new Date().toString() );
        String oldText = scrollLabel.getText();

        // Scroll right to left
        String newText = oldText.substring(1) + oldText.substring(0, 1);

        // Scroll left to right
//      int length = oldText.length();
//      String newText = oldText.substring(length-1, length)
//          + oldText.substring(0, length-1);

        scrollLabel.setText( newText );
    }

    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame("SSCCE");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( new TimerTest() );
        frame.setLocationByPlatform( true );
        frame.pack();
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowGUI();
            }
        });
    }
}

A: One possible solution might be to take advantage of JComponent#scrollRectToVisible and a Swing Timer
For example...

import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import javax.swing.Scrollable;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class ScrollTest {

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

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

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new JScrollPane(new TestPane()));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel implements Scrollable {

        public TestPane() {
            Timer timer = new Timer(40, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    JViewport viewport = (JViewport) getParent();
                    Rectangle viewRect = viewport.getViewRect();

                    if (viewRect.x + viewRect.width < getWidth()) {
                        viewRect.x += 2;
                        scrollRectToVisible(viewRect);
                    } else {
                        ((Timer)e.getSource()).stop();
                    }
                }
            });
            timer.start();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(1000, 200);
        }

        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.drawLine(0, 0, getWidth(), getHeight());
            g2d.dispose();
        }

        @Override
        public Dimension getPreferredScrollableViewportSize() {
            return new Dimension(200, 200);
        }

        @Override
        public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
            return 64;
        }

        @Override
        public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
            return 64;
        }

        @Override
        public boolean getScrollableTracksViewportWidth() {
            return getPreferredSize().width <= getParent().getSize().width;
        }

        @Override
        public boolean getScrollableTracksViewportHeight() {
            return getPreferredSize().height <= getParent().getSize().height;
        }

    }

}


text:
Q: Pass 2 arguments from a single file into function parameters I have a function:
def process(fa : {str:{str:str}}, state : str, inputs : [str]) -> [None]:

and the parameters' (state : str, inputs : [str]) arguments would come from the file (input_file.txt) with the contents:
even;1;0;1;1;0;1
even;1;0;1;1;0;x
odd;1;0;1;1;0;1

With state being the first element (even/odd) and inputs being a list of the rest of the elements (1,0,x)
Is it possible to pass the contents from the file into the function as arguments?
I've tried comprehension but the return value is nothing near what I am trying to get, and I don't know what else to try after playing around with it for a bit:
proccess( fa, (item[0] for line in input_file for item in line.split(';')), (item[1:] for line in input_file for item in line.split(';') )

A: Something like this should do it:
for line in open('input_file.txt','rt'):
    state,*inputs = line.strip().split(';')
    process(fa,state,inputs)

A: The following snippet:
for line in input_file for item in line.split(';')

returns an iterator for each element in each line:
even
1
0
1
1
0
1
even
1
...

Your item[0] and item[1:] does not result in errors because each string ("even", "1", etc) can be indexed.
You can try :
proccess( fa,
   (line.split(';')[0] for line in input_file),
   (line.split(';')[1:] for line in input_file)
)

By the way you should note that:

*

*you are duplicating split() calls, and

*if input_file is a file then lines only come through once, and

*you are passing in generators not str/list of strings that the func expects.

redpajama_set_name: RedPajamaStackExchange


text:
Q: fetching data from firebase firestore using flutter I have an application where i need to get user real time location and push it into database using geoflutterfire , the code is working but i do not understand why it keeps generating multiple documents , while on the other side using the same plugin , we should use only collection reference , can any help me with this , Thank you

*

*Picture showing pushing data into firestore using geoflutterfire plugin ( but why it keeps
generating new documents , i just want to solely update the same document )

*

*Push data into firebase firestore

void updateDriverLocation(){
   Fluttertoast.showToast(msg: "Called");
   geoFlutterFire = Geoflutterfire();
   if(latitude != 0.0 && longitude != 0.0){
      GeoFirePoint geoFirePoint = geoFlutterFire.point(latitude: latitude, longitude: longitude);
      var map = HashMap<String,Object>();
      map['name'] = _firebaseAuth.currentUser!.uid;
      map['position'] = geoFirePoint.data;
      _firebaseFirestore.collection("Drivers").add(map);
   }
 }

*

*get data from firebase firebase

   void getDrivers(){
    geoFlutterFire = Geoflutterfire();
    GeoFirePoint geoFirePoint = GeoFirePoint(latitude, longitude);
    var ref = _firebaseFirestore.collection('Drivers');
    var locations = geoFlutterFire.collection(collectionRef: ref).within(center: geoFirePoint, radius: maxRadius, field: 'position');
    locations.listen((List<DocumentSnapshot> documentList) {
       for (var documentSnapshot in documentList) {
         Map<String,Object> map = documentSnapshot.get('geopoint');
         double lat = map['latitude'] as double;
         double lon = map['longitude'] as double;
         //_list.add(LatLng(lat, lon));
         markers.add(Marker(
                    markerId: MarkerId(DateTime.now().millisecond.toString()),
                    position: LatLng(lat,lon),
                    icon: BitmapDescriptor.defaultMarker
                ));
       }
    });
  }

*

*This is how i'm trying to listen to the data returned from firestore

A: _firebaseFirestore.collection("Drivers").add(map);

The .add() method creates a new document with a random ID every time. If you want to update a specific document then you must use update() on a DocumentReference. Try the following:
_firebaseFirestore.collection("Drivers").doc(_firebaseAuth.currentUser!.uid).update(map);

This will update current drivers document only.

GeoFlutterFire has the following to specify DocID:
geoRef.setDoc(String id, var data, {bool merge})


text:
Q: Searching for web links in an NSString I have an NSString with web links in it.  I need to find all web links in the string starting with http://.  What is the best way to do this?

A: The method
- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script

gives you the ability to run custom JavaScript.  The JavaScript might have access to the DOM, if so it should be simple to extract all of the anchor tags and return them.
Of course, I have only written the tiniest of iPhone apps and am not very familiar with JavaScript or the DOM, so I could be way off base here.
Looking at the DOM and JavaScript it may be as easy as
anchors = [htmlview_object stringByEvaluatingJavaScriptFromString @"document.anchors"];

but, again, I have don't really know what I am talking about.
Try this:
javascript = @"function return_links() {\n"
"    var a = new Array;\n"
"    for (i = 0; i < document.anchors.length; i++) {\n"
"        a.push(document.anchors[i].href);\n"
"    }\n"
"    return a.join(\"\\n\");\n"
"}\n"
"return_links();\n";
links = [htmlview_object stringByEvaluatingJavaScriptFromString javascript];

A: The best way is to find links in an NSString an HTML Parser, see Parsing HTML on the iPhone.  If you must use a regex (and see Can you provide some examples of why it is hard to parse XML and HTML with a regex? for why you shouldn't), PCRE seems to be available for the iPhone.  A common, and flawed, regex for links is /href="(.*?)"/.
Of course, the best parser available is probably the native html viewing widget, and since it gives you the ability to run JavaScript (see my original answer to your original question) you should be able to extract the anchors from the DOM (document.anchors) and write/rewrite whatever you need to using document.write() and the other DOM methods.


text:
Q: .NET MemoryCache: How does it enforce memory limit? .NET MemoryCache is a cache of C# objects. Some objects can have a complex structure, and other can have unsafe references. Is C# doing some magic for implementing the PhysicalMemoryLimit or is it just computing the shallow size of each object?
I suspect the later is the case. Still, if I put the same object multiple times in the cache (for tracking missing items, for instance), will the size be accounted a single time, or for each entry that contains that instance?

A: The .NET MemoryCache  is similar to the ASP.NET Cache class. If we look at the ASP.NET Cache we see a function called CacheItemRemovedCallback. This is triggerd when a Item is removed from the Cache.
This function gives a CacheItemRemovedReason with the callback function. If we look at the reasons, we see that a item can be removed from the cache because the system removed it to free memory. So while the PhysicalMemoryLimit gives the percentage of physical memory that the cache can use in a single tread, I think they leave it over to the system to clear the cache if it reach the limit.
If you really put a Cache item into the cache with the Add function it will add it as an new CacheItem instance. So it will be accounted multiple times. If you use the function AddOrGetExisting it will check if the item is allready in the cache. If so it will use that instance and not a new instance. So then it will be accounted once.
Hope this helps you in the right direction.

A: Reading the documentation, it appears the cache makes no attempt to compute the size of the objects it is caching. This makes sense because it is not something that can be done from within a process itself for arbitrary types (you can do it for fixed size structs, or arrays of fixed size structs, but that is about it); a bit of googling will confirm that to you. It does however know how much RAM is available on the computer; you can get this yourself from new Microsoft.VisualBasic.Devices.ComputerInfo().AvailablePhysicalMemory. So presumably the cache does two things:

*

*It tracks when each object was last used.

*Polls for memory statistics at some interval.

Then on each poll either the amount of available memory is within acceptable limits, or it is not. If it is within acceptable limits it does nothing. If it is not it starts removing items, with the item that was last accessed longest ago removed first. It keeps removing items until the memory gets back within acceptable limits.
If you think about it that is pretty much all you can do with the information available to the cache.
This strategy is OK, but it obviously breaks down if you have other objects holding references to items in the cache, because removing the item from the cache will not free it up for garbage collection. That is the point of the callback, to perform the clean-up to ensure there are no more references to the object.

A: Here's the source. The answer to your second question is obvious if you look at the implementation on Add method: referencesource.microsoft.com that is calling AddOrGetExisting.
I don't know about the size, but I guess that you're right in your assumption that there is no magic at all. Also if you're interested you may inspect the sources in-depth.

A: You can not easily set the PhysicalMemoryLimit or the CacheMemoryLimit members of the MemoryCache class as they do not have setters implemented (at least in the .Net 4.0 version).
I agree with the other answers in that AddOrGetExisting should be used if you want only a single instance of an object cached. If not you could cache the alternate items with a different key.


text:
Q: Display all videos from JSON (ASP.NET MVC) I have code for AJAX to get Links from table
Here is code
 <script>
  $('#display').click(function() {
    var vacancyId = $("#vacancy").val();
    var model = {
      vacancyId: vacancyId
    };

    $.ajax({
      url: '@Url.Action("Links", "Questions")',
      contentType: 'application/json; charset=utf-8',
      data: JSON.stringify(model),
      type: 'POST',
      dataType: 'json',
      processData: false,
      success: function(data) {
        var question2 = data[0];
        var videoHTML = '<video width="320" height="240" style="margin-left: 130px;margin-top: 20px;" controls>';
        videoHTML += '<source src="' + document.location.origin + "/uploads/" + question2.Linkes + ".webm" + '" type="video/webm">';
        videoHTML += '</video>';
        $(".videolist").append(videoHTML);
      }
    });
  });
</script>

Now I display only first video in array, but It can be about 10, I need to display all ten videos, how I need to rewrite code?

A: Your success function should be like this.
Post your Json sample data for accurate solution.
success: function(data) {
  var question2 = data;
  for (var i = 0; i <= question2.length-1; i++) {
    var videoHTML = '<video width="320" height="240" style="margin-left: 130px;margin-top: 20px;" controls>';
    videoHTML += '<source src="' + document.location.origin + "/uploads/" + question2[i].Linkes + ".webm" + '" type="video/webm">';
    videoHTML += '</video>';
    $(".videolist").append(videoHTML);
  }
}


text:
Q: Insert Data into database via mySQL using visual studio in C# So I'm trying to insert data into an SQL Database, which was created in Visual Studio 2017 via a Service-Based Database.
Here is the code
    private void save() {
        Book book = new Book();
        book.Id = System.Convert.ToInt32(idtxtbox.Text);
        book.title = titletxtbox.Text;
        book.author = authortxtbox.Text;

        string query = "INSERT INTO Book VALUES(" + System.Convert.ToInt32(idtxtbox.Text) + "," + titletxtbox.Text + "," + authortxtbox.Text + ")";

        using (conn = new SqlConnection(connString))
        using (SqlCommand command = new SqlCommand(query, conn)) {
            conn.Open();
            command.ExecuteNonQuery();// Error here
            conn.Close();
        }
            clear();
    }

If I enter data like
id = 001
title = "The Book"
Author = "Main Author"

I get an error that says " System.Data.SqlClient.SqlException: 'Incorrect syntax near 'Book'.' ". What am I doing wrong, and how can I fix it?

A: Try to do it this way and thus avoid sql injections:
 SqlConnection conexion;

 private void save() {

    conexion = cConexion.getConexion();

    SqlCommand comand = new SqlCommand();
    comand.Connection = conexion;
    comand.CommandText = "INSERT INTO Book(Id, title, author) VALUES(@Id, @title, @author)";
    comand.Parameters.Add("Id", SqlDbType.Int, 3).Value = this.idtxtbox.Text;
    comand.Parameters.Add("title", SqlDbType.NChar).Value = this.titletxtbox.Text;
    comand.Parameters.Add("author", SqlDbType.NChar).Value = this.authortxtbox.Text;
    comand.ExecuteNonQuery();

    clear();
 }

I like to use a connection class to handle the connections
class cConexion
{
    private static SqlConnection conexion;

    public static SqlConnection getConexion()
    {
        if (conexion != null)
        {
            return conexion;
        }
        conexion = new SqlConnection(Properties.Settings.Default.MyConnectionString);
        try
        {
            conexion.Open();
            return conexion;
        }
        catch (Exception e)
        {
            System.Windows.Forms.MessageBox.Show("Error" + e.Message);
            return null;
        }
    }

    public static void cerrarConexion()
    {
        if (conexion != null)
        {
            conexion.Close();
        }
    }
}


text:
Q: How to sort data in Mongo in a custom order How I can sort this data, using Mongo functionality:
Input
{ "_id" : 1, "domainName" : "test1.com", "hosting" : "hostgator.com" }
{ "_id" : 2, "domainName" : "test2.com", "hosting" : "aws.amazon.com"}
{ "_id" : 3, "domainName" : "test3.com", "hosting" : "aws.amazon.com" }
{ "_id" : 4, "domainName" : "test4.com", "hosting" : "hostgator.com" }
{ "_id" : 5, "domainName" : "test5.com", "hosting" : "aws.amazon.com" }
{ "_id" : 6, "domainName" : "test6.com", "hosting" : "cloud.google.com" }
{ "_id" : 7, "domainName" : "test7.com", "hosting" : "aws.amazon.com" }
{ "_id" : 8, "domainName" : "test8.com", "hosting" : "hostgator.com" }
{ "_id" : 9, "domainName" : "test9.com", "hosting" : "cloud.google.com" }
{ "_id" : 10, "domainName" : "test10.com", "hosting" : "godaddy.com" }

In order by hosting field, to get result, for example in this order:
1) First - all godaddy;
2) Second - all AWS;
3) and next, everything else.
Output
{
    "result" : [
            {

                    "_id" : 10,
                    "domainName" : "test10.com",
                    "hosting" : "godaddy.com"
            },
            {
                    "_id" : 2,
                    "domainName" : "test2.com",
                    "hosting" : "aws.amazon.com"
            },
            {
                    "_id" : 3,
                    "domainName" : "test3.com",
                    "hosting" : "aws.amazon.com"
            },
            {
                    "_id" : 5,
                    "domainName" : "test5.com",
                    "hosting" : "aws.amazon.com"
            },
            {
                    "_id" : 7,
                    "domainName" : "test7.com",
                    "hosting" : "aws.amazon.com"
            },
            {
                    "_id" : 1,
                    "domainName" : "test1.com",
                    "hosting" : "hostgator.com"
            },
            {
                    "_id" : 4,
                    "domainName" : "test4.com",
                    "hosting" : "hostgator.com"
            },
            {
                    "_id" : 6,
                    "domainName" : "test6.com",
                    "hosting" : "cloud.google.com"
            },
            {
                    "_id" : 8,
                    "domainName" : "test8.com",
                    "hosting" : "hostgator.com"
            },
            {
                    "_id" : 9,
                    "domainName" : "test9.com",
                    "hosting" : "cloud.google.com"
            },
    ]
    }

With this example i want to return results in more relevant way for user. And in origanl task I want to sort this using few another collections, which serve additional information.
But will be good enough if you helps me with previous task?
UPD: About second part of question.
One more task is how to return sortable data from one collection in dependence of another.
Example:
first collection the same which was given before:
 { "_id" : 1, "domainName" : "test1.com", "hosting" : "hostgator.com" }
 ...

second collection, provide some additional info about hosting:
{ '_id': 123, 'quality':'best', 'hostings': ["hostgator.com",  "aws.amazon.com"]},
{ '_id': 321, 'quality':'good', 'hostings': ["cloud.google.com"]},
{ '_id': 345, 'quality':'bad', 'hostings': ["godaddy.com"]},

And in result, I need to return from first collection data in this order:
1) First all good hostings
2) second all good
3) third all bad
Output:
{
"result" : [
        //Best:
        {
                "_id" : 1,
                "domainName" : "test1.com",
                "hosting" : "hostgator.com"
        },
        {
                "_id" : 4,
                "domainName" : "test4.com",
                "hosting" : "hostgator.com"
        },
        {
                "_id" : 8,
                "domainName" : "test8.com",
                "hosting" : "hostgator.com"
        },
        {
                "_id" : 2,
                "domainName" : "test2.com",
                "hosting" : "aws.amazon.com"
        },
        {
                "_id" : 3,
                "domainName" : "test3.com",
                "hosting" : "aws.amazon.com"
        },
        {
                "_id" : 5,
                "domainName" : "test5.com",
                "hosting" : "aws.amazon.com"
        },
        {
                "_id" : 7,
                "domainName" : "test7.com",
                "hosting" : "aws.amazon.com"
        },

       // Good:
        {
                "_id" : 9,
                "domainName" : "test9.com",
                "hosting" : "cloud.google.com"
        },
        {
                "_id" : 6,
                "domainName" : "test6.com",
                "hosting" : "cloud.google.com"
        },

       //Bad
        {
                "_id" : 10,
                "domainName" : "test10.com",
                "hosting" : "godaddy.com"
        }
]
}

UPDATE 2
I get good answer and example on previous example. Thank you so much! But I stack with another example.
I need to compare IDs of 3 collections to sort in order - first: friend, second: 'requests', and: other users.
Input
db.friends.find({userId: currentUser});
    // {"_id" : "PgC7LrtaZtQsShtzT", "userId" : "tHuxnWxFLHvcpRgHb", "friendId" : "jZagPF7bd4aW8agXb",}
db.requests.find({userId: currentUser});
   // looks like friend but with 'requesterId'

And now I need to aggregate 'users' collection, define the score which matches with previous two collections (friends, requests).
Using provided answer, I managed result but only with one collection. How can I make this with 3 or multiple?

A: You can project each of the hosting into separate type denoted by integers, and finally sort on these integers. Illustrated in the aggregation pipeline below
[
{$lookup: {
    from: 'secondCollectionStoringQuality',
    localField: 'hosting',
    foreignField: 'hostings',
    as: 'nw'
    }},
{$unwind: '$nw'},
{$project: {
        domainName: 1,
        hosting: 1,
        type: {
            $cond: [
                {$eq: ['$nw.quality', 'best']},
                0,
                {$cond: [
                    {$eq: ['$nw.quality', 'good']},
                    1,
                    2
                    ]}
            ]
        }
    }},
    {$sort: {type: 1}}
]

A: Above answers works if the data exists in an array. And you can achieve this without $lookup and $project.
.aggregate([
   {$addFields: {
      sortId: {
         $cond: [{$eq: ['$hosting', 'godaddy.com']},0,
            {$cond: [{$eq: ['$hosting', 'aws.amazon.com']},1,2]
      }
   }},
  {$sort: {sortId: 1}}
])

A: I would use $addFields and $switch to make things a bit more clearer and simpler (this is mongoose format):
[
  {
    $addFields: {
      new_field_to_sort: {
        $switch: {
          branches: [
            { case: { $eq: ['$hosting', 'godaddy.com'] }, then: 0 },
            { case: { $eq: ['$hosting', 'aws.amazon.com'] }, then: 1 },
          ],
          default: 2,
        },
      }
    },
  },
  {
     $sort: {
       new_field_to_sort: 1,
     }
  }
]

A: How about this solution ?
1) N number of conditions.
2) Required Sorting order can be passed by parameter.
[{
        "$lookup": {
            "from": "secondCollectionStoringQuality",
            "localField": "hosting",
            "foreignField": "hostings",
            "as": "nw"
        }
    },
    {
        "$unwind": "$nw"
    },
    {
        "$project": {
            "domainName": 1,
            "hosting": 1,
            "type": {
                "$indexOfArray": [
                    ["best", "good"], "$nw.quality"
                ]
            }
        }
    },
    {
      "$project": {
          "domainName": 1,
          "hosting": 1,
          "type": {
              "$cond": [ {"$eq":["$type", -1]},  10000, "$type"]
          }
      }
    },
    {
        "$sort": {
            "type": 1
        }
    }
]


text:
Q: C++ : Skipping variable value from user This is my program need: user has to enter numerator or denominator or both and i need to display the lowest ratio possible. If it is 6/9 then should displayed as 2/3.
I used hcf calculation to convert the ratio. But I am stuck in the part : 'user can enter numerator or denominator or both`
Here is my code skeleton:
class number
{
  public:
    int num;
    int denom;
    number()
 {
    num=1;
    denom=1;
 }
    void getvalue(int x, int y)
    {
      num=x;
      denom=y;
    }
    void ratiocalculation()
    {
    }
};
int main()
{
    int x,y;
    number obj1;
    cout<<"Enter num and denom";
    cin>>x>>y;
    ...........
    ........
}

This code cover the the user can enter both numerator and denominator part.
Here how to get only numerator or only denominator.

A: You need to decide on a way to communicate the two options with the user. For instance you can have something like this:
cout << "Select an option:\n"
     << " 1: to enter both numerator and denominator\n"
     << " 2: to enter only numerator\n"
     << " 3: to enter only denominator\n"
     << " 4: to exit\n";

int option;
cin >> option;

And then it should be obvious how to continue. As entering only a numerator and a denominator is not distinguishable(from what is being entered stand point) there is no other way to deal with both options.

A: You can do something like the following example, where you assure that input is a number.
#include <iostream>
#include <cctype>
#include <string>
#include <algorithm>

bool is_number(const std::string& s)
{
  return !s.empty() && std::find_if(s.begin(),
    s.end(), [](char c) { return !std::isdigit(c); }) == s.end();
}

int main()
{
  int x, y;
  std::string num;
  std::cout << "Enter numerator: ";
  std::getline(std::cin, num);
  while (!is_number(num)) {
    std::cout << "Input is not a number , enter again: ";
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<int>::max(), '\n');
    num.clear();
    std::getline(std::cin, num);
  }
  x = stoi(num);
  std::cout << "Enter denominator: ";
  std::getline(std::cin, num);
  while (!is_number(num)) {
    std::cout << "Input is not a number , enter again: ";
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<int>::max(), '\n');
    num.clear();
    std::getline(std::cin, num);
  }
  y = stoi(num);

  // GCD(x, y);

  return 0;
}


text:
Q: Creating Virtualenv using Anaconda Python Errors I'd been working on Python distribution from Anaconda, as default. To use virtual environments, installed virtualenv. It shows that it was installed in the default location as in Anaconda. But, while creating one, it shows error. I do not understand anything as I'm not a pro. Please help. Thanks!!
avijit@avijit-Inspiron-3521:~$ virtualenv --version
15.0.3
avijit@avijit-Inspiron-3521:~$ cd Downloads/alieturklmugermany/virtualbcf/
avijit@avijit-Inspiron-3521:~/Downloads/alieturklmugermany/virtualbcf$ virtualenv bcfenv1
New python executable in /home/avijit/Downloads/alieturklmugermany/virtualbcf/bcfenv1/bin/python
Installing setuptools, pip, wheel...
  Complete output from command /home/avijit/Downloa...f/bcfenv1/bin/python - setuptools pip wheel:
  Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
  File "/home/avijit/anaconda2/lib/python2.7/tempfile.py", line 32, in <module>
    import io as _io
  File "/home/avijit/anaconda2/lib/python2.7/io.py", line 51, in <module>
    import _io
ImportError: /home/avijit/Downloads/alieturklmugermany/virtualbcf/bcfenv1/lib/python2.7/lib-dynload/_io.so: undefined symbol: _PyCodec_LookupTextEncoding
----------------------------------------
...Installing setuptools, pip, wheel...done.
Traceback (most recent call last):
  File "/home/avijit/anaconda2/bin/virtualenv", line 11, in <module>
    sys.exit(main())
  File "/home/avijit/anaconda2/lib/python2.7/site-packages/virtualenv.py", line 711, in main
    symlink=options.symlink)
  File "/home/avijit/anaconda2/lib/python2.7/site-packages/virtualenv.py", line 944, in create_environment
    download=download,
  File "/home/avijit/anaconda2/lib/python2.7/site-packages/virtualenv.py", line 900, in install_wheel
    call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=SCRIPT)
  File "/home/avijit/anaconda2/lib/python2.7/site-packages/virtualenv.py", line 795, in call_subprocess
    % (cmd_desc, proc.returncode))
OSError: Command /home/avijit/Downloa...f/bcfenv1/bin/python - setuptools pip wheel failed with error code 1


text:
Q: Postman test save variable from JSON response body I have json response body like this
{
    "header": {
        "process_time": "27.842975",
        "server_time": "",
        "reason": "",
        "error_code": 0,
        "status_code": 200
    },
    "data": {
        "idx": "2",
        "component": {
            "id": 123,
            "name": "product",
            "properties": {
                "button_notification": false
            },
            "title": "",
            "data": [
                {
                  "status": 4,
                    "product_id": 1112323,
                    "stock": 21
                },
                {
                  "status": 4,
                    "product_id": 1114322,
                    "stock": 13
                },
                {
                    "status": 4,
                    "stock": 8,
                    "product_id": 1115342
                },
                {
                    "stock": 5,
                    "status": 4,
                    "product_id": 1115234
                },
                {
                    "stock": 5,
                    "status": 4,
                    "product_id": 1115442
                }
            ]
        }
    },
    "errors": []
}

I want to save two product_id values which have the most two stock than other
here my code
var jsonData = JSON.parse(responseBody);
let productId-1 = jsonData.data.component.data[2].product_id
let productId-2 = jsonData.data.component.data[3].product_id
pm.environment.set("productId-1",productId-1)
pm.environment.set("productId-2",productId-2)

A: The most simple solution to your problem would be implementing bubble sort for finding the product with the most stock.

let arr = jsonData.data.component.data;
for(let i = 0; i < arr.length - 1; i++){
    for(let j = 0; j < arr.length - 1 - i; j++){
        if (arr[j].stock < arr[j+1].stock) {
            let temp = arr[j];
            arr[j] = arr[j+1];
            arr[j+1] = temp;
        }
    }
}
pm.environment.set("productId-1", arr[0]); //product with most stock
pm.environment.set("productId-2", arr[1]); //product with second most stock


text:
Q: ¿como poner la imagen y nombre del usuario cuando inicia sesión? me podrían decir como hacer que muestre la imagen y el nombre del usuario cuando inician sesión en una pagina web.
Gracias.

A: Puedes usar una variable de sesión o cookie donde tengas el nombre del usuario y la url de la imagen, cuando el login es correcto
$_SESSION['uname'] = "Juan Pérez";
$_SESSION['uimg'] = "/img/pic.jpg";

y para mortar

Saludos <?= $_SESSION['uname'] ?>

<img src="<?= $_SESSION['uimg'] ?>">


text:
Q: Why is my pip braking after updating My pip broke after I ran
pip install --upgrade pip

When I run this command
pip -V
or any other commands I get
Traceback (most recent call last):
  File "/usr/bin/pip", line 9, in <module>
    from pip import main
ImportError: cannot import name main

Why is it breaking? I have python3 installed. I have a solution but I need to understand why it broke after upgrading to the latest version.

A: pip authors were warning for many years to not import pip. Finally at version 10 they restructured their code.
Your /usr/bin/pip was not upgraded (probably because pip install -U pip installed new /usr/local/bin/pip) so it uses the old API before renaming.
If that's the case I recommend to put /usr/local/bin before /usr/bin in $PATH.


text:
Q: Datatable Reload page after click Page Number 2 or Next Page In my project I want datatable to display record on website in PHP.
My question is that if we click on Page Number 2 or next Page than page must reload and than come back to the page 2 or next page.
Is there anyone who can help me with this.

A: As Mohit said, if you want serverside processing with a PHP script, you'll need to define the Ajax properties. There's some good examples on the DataTables website for this - look here and here.


text:
Q: showing and hiding div on mouse over n mouse out in javascript i have 3 divs with id 1,2,3 , all i want is to show div with id 2 when mouse over on div with id 1 and show div 1 when mouse out event on div 2. and along with that div 3 appears when a button is clicked on div 2 with id btn n if we mouse out of the div 3 again div 1 appears and and we again mouseover the div 1 div 3 appears. n they must appear at the same place...use javascript  plz...here is simple html code...

     <input type="button" id="btn">

A: try
 $( "#div2" ).mouseover(function() {
      $("#div1").hide();
    $("#div2").show();
    });

More Info: LINK
EDIT: additional info LINK2

A: You need to include jquery first.
Then try
 $('#div1').mouseover(function() {
    $('#div1').style.display='none';
    $('#div2').style.display='block';
 });
 $('#div2').mouseout(function() {
    $('#div1').style.display='block';
 });
 $('#btn').onclick(function() {
    $('#div3').style.display='block';
 });

I hope, this works ;)
You could also try to use
 $('#div1').style.visibility='hidden';

instead of
 $('#div1').style.display='none';

A: Something in Pure Javascript:


text:
Q: Python - numpy mgrid and reshape Can someone explain to me what the second line of this code does?
objp = np.zeros((48,3), np.float32)
objp[:,:2] = np.mgrid[0:8,0:6].T.reshape(-1,2)

Can someone explain to me what exactly the np.mgrid[0:8,0:6] part of the code is doing and what exactly the T.reshape(-1,2) part of the code is doing?
Thanks and good job!

A: The easiest way to see these is to use smaller values for mgrid:
In [11]: np.mgrid[0:2,0:3]
Out[11]:
array([[[0, 0, 0],
        [1, 1, 1]],

       [[0, 1, 2],
        [0, 1, 2]]])

In [12]: np.mgrid[0:2,0:3].T  # (matrix) transpose
Out[12]:
array([[[0, 0],
        [1, 0]],

       [[0, 1],
        [1, 1]],

       [[0, 2],
        [1, 2]]])

In [13]: np.mgrid[0:2,0:3].T.reshape(-1, 2)  # reshape to an Nx2 matrix
Out[13]:
array([[0, 0],
       [1, 0],
       [0, 1],
       [1, 1],
       [0, 2],
       [1, 2]])

Then objp[:,:2] = sets the 0th and 1th columns of objp to this result.

A: The second line creates a multi-dimensional mesh grid, transposes it, reshapes it so that it represents two columns and inserts it into the first two columns of the objp array.
Breakdown:
np.mgrid[0:8,0:6] creates the following mgrid:
>> np.mgrid[0:8,0:6]
array([[[0, 0, 0, 0, 0, 0],
        [1, 1, 1, 1, 1, 1],
        [2, 2, 2, 2, 2, 2],
        [3, 3, 3, 3, 3, 3],
        [4, 4, 4, 4, 4, 4],
        [5, 5, 5, 5, 5, 5],
        [6, 6, 6, 6, 6, 6],
        [7, 7, 7, 7, 7, 7]],

       [[0, 1, 2, 3, 4, 5],
        [0, 1, 2, 3, 4, 5],
        [0, 1, 2, 3, 4, 5],
        [0, 1, 2, 3, 4, 5],
        [0, 1, 2, 3, 4, 5],
        [0, 1, 2, 3, 4, 5],
        [0, 1, 2, 3, 4, 5],
        [0, 1, 2, 3, 4, 5]]])

The .T transposes the matrix, and the .reshape(-1,2) then reshapes it into two a two-column array shape. These two columns are then the correct shape to replace two columns in the original array.


text:
Q: How are low-level I/O models mapped into stream I/O abstraction? High-level languages often expose stream-based I/O abstraction to the programmer, where blocking or non-blocking streams offer select/read/write operations. (AFAIK, message-based I/O seems is usually an even higher-level abstraction built on top of streams.)
But at the low level, the communication between the CPU and the hardware devices uses interrupts, programmed (polled) I/O, or DMA.
How can all of them map well into the same stream I/O abstraction that (as far as I can tell) completely hides the difference between these very different low-level models? Are there any cases where a high-level developer who uses stream I/O abstraction should actually be concerned about the difference between interrupt-driven and programmed I/O?

A: Interrupt based IO does not map to streams well.
One particular example would be a select system call. It provides a way to wait for input on  arbitrary count of file descriptors but this API almost never manifests in stream API of high level libraries
Asynchronous IO also does not map to usual streams. This is why role of streams diminishes in modern libraries and gives way to more generic event driven APIs, for example C++ boost::asio, Java NIO. They are more effective for asynchronous and parrallel  applications and are a reaction for growing parallelization demand.
Note however, that internally, most of these APIs are still using same system interfaces still based on interrupts and good old buffers. It is possible,  because libraries are still hiding details behind layers of abstractions.
BTW, all these abstractions (streams,events,buffered IO) are interchangeable at expense of some performance. For example, streams can be created using events with some blocking queues, backward conversion could be provided by dedicated thread.


text:
Q: How do I fix my current openGL error, my cmakelist may be my issue I have included the library <GLUT/glut.h> and all my syntax is correct, yet I am receiving this error.
Undefined symbols for architecture arm64:
  "_glBegin", referenced from:
      triangle(float*, float*, float*) in main.cpp.o
  "_glClear", referenced from:
      displayTriangle() in main.cpp.o
  "_glClearColor", referenced from:
      _main in main.cpp.o
  "_glColor3f", referenced from:
      drawTetrahedron(int) in main.cpp.o
  "_glEnable", referenced from:
      _main in main.cpp.o
  "_glEnd", referenced from:
      triangle(float*, float*, float*) in main.cpp.o
  "_glFlush", referenced from:
      displayTriangle() in main.cpp.o
  "_glLoadIdentity", referenced from:
      displayTriangle() in main.cpp.o
  "_glMatrixMode", referenced from:
      reshapeWindow(int, int) in main.cpp.o
  "_glOrtho", referenced from:
      reshapeWindow(int, int) in main.cpp.o
  "_glVertex3fv", referenced from:
      triangle(float*, float*, float*) in main.cpp.o
  "_glViewport", referenced from:
      reshapeWindow(int, int) in main.cpp.o
  "_glutCreateWindow", referenced from:
      _main in main.cpp.o
  "_glutDisplayFunc", referenced from:
      _main in main.cpp.o
  "_glutInit", referenced from:
      _main in main.cpp.o
  "_glutInitDisplayMode", referenced from:
      _main in main.cpp.o
  "_glutInitWindowSize", referenced from:
      _main in main.cpp.o
  "_glutMainLoop", referenced from:
      _main in main.cpp.o
  "_glutPostRedisplay", referenced from:
      reshapeWindow(int, int) in main.cpp.o
  "_glutReshapeFunc", referenced from:
      _main in main.cpp.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
ninja: build stopped: subcommand failed.

My cmakefile I feel like is my issue, but I have no idea where to begin.

A: Please provide more details like your relevant section of CMakeLists.txt for getting more info and getting quicker help from community.
Now, coming to the error logs, it seems you are cross-compiling the source files using a arm-based compilers.
The error message "ld: symbol(s) not found for architecture arm64" looks to me as a linker issue and you should be having the find_package() and linking calls in CMakeLists.txt for OpenGL.
So to start with , you should follow two steps initially and see if it solves your problem:
1. Make sure the CMake build system is pointing to correct compiler tool chain path (arm compilers in here).
Refer official website of CMake for same:
https://cmake.org/cmake/help/book/mastering-cmake/chapter/Cross%20Compiling%20With%20CMake.html
2. Make sure you are linking OpenGL
find_package(OpenGL REQUIRED)
target_include_directories(your_executable_name PUBLIC ${OPENGL_INCLUDE_DIR})
target_link_libraries(your_executable_name PUBLIC ${OPENGL_LIBRARIES})


text:
Q: Dynamic Drop-Down with Links I am creating a home page for my website and need to utilize a dynamic textbox in order to simplify navigation.
There will be two html dropdown menus. As soon as the user selects a category from the first dropdown menu, all of the associated links from the selection will load into the second dropdown menu. When the user makes a selection from the second textbox, the webpage will take the user to the selected page. The key with the second dropdown menu is to make all of the items links so when the user makes the selection, they are essentially clicking on a link to the associated web page.
I have uploaded an html document which should give you an idea of what I'm looking for.
<!DOCTYPE html>

SELECTOR ONE

        <select>
            <option>Option 1</option>
            <option>Option 2</option>
            <option>Option 3</option>
            <option>Option 4</option>
            <option>Option 5</option>
            <option>Option 6</option>
            <option>Option 7</option>
        </select>

SELECTOR TWO

        <select>
            <option>Option 1 ITEM LINK</option>
            <option>Option 1 ITEM LINK</option>
            <option>Option 1 ITEM LINK</option>
            <option>Option 1 ITEM LINK</option>
            <option>Option 1 ITEM LINK</option>
            <option>Option 1 ITEM LINK</option>
            <option>Option 1 ITEM LINK</option>
            <option>Option 1 ITEM LINK</option>
            <option>Option 1 ITEM LINK</option>
        </select>

        <select>
            <option>Option 2 ITEM LINK</option>
            <option>Option 2 ITEM LINK</option>
            <option>Option 2 ITEM LINK</option>
            <option>Option 2 ITEM LINK</option>
            <option>Option 2 ITEM LINK</option>
            <option>Option 2 ITEM LINK</option>
            <option>Option 2 ITEM LINK</option>
            <option>Option 2 ITEM LINK</option>
            <option>Option 2 ITEM LINK</option>
        </select>

        <select>
            <option>Option 3 ITEM LINK</option>
            <option>Option 3 ITEM LINK</option>
            <option>Option 3 ITEM LINK</option>
            <option>Option 3 ITEM LINK</option>
            <option>Option 3 ITEM LINK</option>
            <option>Option 3 ITEM LINK</option>
            <option>Option 3 ITEM LINK</option>
            <option>Option 3 ITEM LINK</option>
            <option>Option 3 ITEM LINK</option>
        </select>

A: Simple, add a value attribute to your options, such as:
<option value="http://www.google.com">Option 3 ITEM LINK</option>

Create a change event:
$("select").change(function() {
    window.location.href = this.value;
});


text:
Q: How to insert current datetime into a table in a trigger? - PLSQL I've been working on a database that is has data stored about trips and reservations for these trips. I also have a table ReservationLog, which stores changes in status of a given resevation, and when they happenned.
I am told to create a trigger, working after adding new reservation, which also creates a new entry in ReservationLog table. However, when trying to compile the code I get an error:
PLS-00049 - incorrect binding variable "NEW.LOG_DATE"
The table ReservationLog looks like this:
CREATE TABLE  RESERVATIONLOG
(
    ID INT GENERATED ALWAYS  AS IDENTITY NOT NULL,
    RESERVATION_ID INT,
    LOG_DATE DATE,
    STATUS CHAR(1),
    CONSTRAINT RL_PK PRIMARY KEY
    (
        ID
    )
    ENABLE
);

RESERVATION_ID is a foreign key
The code for trigger function looks like it:
CREATE OR REPLACE TRIGGER AddReservationTrigger
    AFTER INSERT ON
    RESERVATION
    REFERENCING OLD AS OLD NEW AS NEW
    FOR EACH ROW
    DECLARE  V_TODAY DATE;

    BEGIN

        SELECT SYSDATE INTO V_TODAY FROM DUAL;
        INSERT INTO RESERVATIONLOG
            (
             RESERVATION_ID,
             LOG_DATE,
             STATUS
            )
            VALUES
            (
             :new.RESERVATION_ID,
             :new.LOG_DATE,
             :new.STATUS
);
    end;
/

Not sure what to do, I tried to assign a value to it: :new.LOG_DATE :=SYSDATE but it doesn't work. I feel like this is something stupid, but can't figure out what is wrong here.

A: You can refer to things like sysdate directly in your insert statement, e.g.:
CREATE OR REPLACE TRIGGER AddReservationTrigger
AFTER INSERT ON RESERVATION
REFERENCING OLD AS OLD NEW AS NEW
FOR EACH ROW
BEGIN

    INSERT INTO RESERVATIONLOG
        (
         RESERVATION_ID,
         LOG_DATE,
         STATUS
        )
        VALUES
        (
         :new.RESERVATION_ID,
         SYSDATE,
         :new.STATUS
        );
end;
/

Side note: the reason you can't change :new.LOG_DATE is because this is an "AFTER" trigger on the RESERVATION table; the trigger fires after the insert has already been completed, so it doesn't make sense to change the value of that column.


text:
Q: Changing object value with onClick event Sorry to ask this again, but I wanted to add more code for context.
I am making a rock paper scissors game and want to change the playerChoice key when a button the button is pressed.
I want to add an onclick event to each button and run a function that will set the playerChoice property so it references the gameOptions index.

<!DOCTYPE html>

<title>Page Title</title>

Lapis, Papyrus Scalpellus

Make a Choice

<button id="Lapis">Lapis</button>
<button id="Papyrus">Papyrus</button>
<button id=Scalpellus>Scalpellus</button>

Game Results

const gameOptions = ["Lapis", "Papyrus", "Scalpellus"];

const newChoice = randomChoice();

console.log(newChoice);

const humanPlayer = {
  playerChoice: gameOptions[0],
};

const computerPlayer = {
  playerChoice: randomChoice(),
};

document.querySelector("#Lapis").onclick = function() {
  humanPlayer.playerChoice = gameOptions[0];
};

document.querySelector("#Papyrus").onclick = function() {
  humanPlayer.playerChoice = gameOptions[1];
};
document.querySelector("#Scalpellus").onclick = function() {
  humanPlayer.playerChoice = gameOptions[2];
};

console.log(humanPlayer);

//Random Choice
function randomChoice() {
  const theChoice = gameOptions[Math.floor(Math.random() * 3)];
  return theChoice;
}

//Players

function resultText(innerText){
  const paragraph = document.createElement('p');
  paragraph.innerText = innerText;
  document.body.appendChild(paragraph);
}

//Outcomes
function fight(){
  if(computerPlayer.playerChoice === humanPlayer.playerChoice){
     resultText("Its a Tie!20. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);
  }else if (computerPlayer.playerChoice === "Lapis"){
    if(humanPlayer.playerChoice === "Papyrus"){
     resultText("Human Player Wins!6. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);
    }else if( humanPlayer.playerChoice === "Scalpellus"){
       resultText("Computer Player Wins!5 You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);

    }
  }else if(computerPlayer.playerChoice === "Papyrus"){
    if ( humanPlayer.playerChoice === "Lapis"){
      resultText("Compter Player Wins!4. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);

    }else if( humanPlayer.playerChoice === "Scalpellus"){
      resultText("Human Player Wins!3. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);

    }
  }else if(computerPlayer.playerChoice === "Scalpellus"){
    if ( humanPlayer.playerChoice === "Lapis"){
      resultText("Human Player Wins!2. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);

    }else if( humanPlayer.playerChoice === "Papyrus"){
      resultText("Computer Player Wins!1. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);
    }
  }
}

fight()

A: You can use the following to keep your code simple:
var btns = document.querySelectorAll("button");
for (var i = 0; i < btns.length; i++){
  btns[i].addEventListener("click", btnHandler);
}

And then your handler function will be called each time a button is clicked without the need to repeat your code:
function btnHandler(el){
  switch (el.getAttribute("id")){
    case "Papyrus":
    ...
    default: break;
  }
}

It also allows you to pass the button element itself, so you can just pull out the ID attribute when needed, rather than having to pass a parameter for each different instance across separate calls. For the win condition check, you can eliminate several "if" statements by simply seeing if they're equal, and if they're not, only compare the human choice to the computer choice which would beat it and set the result thusly. It can be optimized further, but I imagine you would like to learn something from this so I've commented the fiddle as well.
For this example, I also moved the fight() function to the button handler so the player would have a choice, and the computer's choice would only be triggered at that point as well. There were a few instances in your original code which called functions and set variables, but didn't use them etc, as well as a few syntax errors.
See attached fiddle:
https://jsfiddle.net/s0toz3L8/2/


text:
Q: How to print a changed value of an array and revert it back to its previous value in Javascript? I have a script like this:

var board = [
  [0, 0, 0],
  [0, 0, 0],
  [0, 0, 0]
];

function test() {
  for (var i = 0; i < 3; i++) {
    for (var j = 0; j < 3; j++) {
      if (board[i][j] == 0) {
          board[i][j] = 1;
          another(board);
          board[i][j] = 0;

      }
    }
  }
}

var anotherBoard = [];

function another(anotherBoard) {
  console.log(anotherBoard);
}

If I'm not mistaken the output was supposed to go through the array and change only one 0 to 1 each time without changing the value of the array 'board'.
But the output is:
[ [0, 0, 0]
, [0, 0, 0]
, [0, 0, 0]
]
[ [0, 0, 0]
, [0, 0, 0]
, [0, 0, 0]
]
[ [0, 0, 0]
, [0, 0, 0]
, [0, 0, 0]
] ...

How can I get an output like this:
[ [1, 0, 0]
, [0, 0, 0]
, [0, 0, 0]
]
[ [0, 1, 0]
, [0, 0, 0]
, [0, 0, 0]
]
[ [0, 0, 1]
, [0, 0, 0]
, [0, 0, 0]
]
...

A: I ran your code by calling test(). I got the folllowing output:

So looks like it does what you want. You should watch out the context in which you're executing the code:

*

*check if you call the right test()

*is console.log() modified by the user?

*change var with let; I don't recommend ever using var until you need it

From what you said on how you get the output, I don't see the newlines, so something might be wrong with console.log(), or you're calling something else
Bonus: try to format your code better, it really makes a difference when you're sharing it

A: I think this is what you're looking for.

let boards = []

function addBoard() {
  console.log('adding a board')
  let onepos = boards.length < 3 ? boards.length : boards.length % 3,
    tmp = [
      [],
      [],
      []
    ]
  for (var i = 0; i < 3; i++) {
    for (var j = 0; j < 3; j++) {
      if (i === 0 && j === onepos) tmp[i][j] = 1;
      else tmp[i][j] = 0
    }
  }
  boards.push(tmp)
}

addBoard()
addBoard()
addBoard()
console.log(boards);


text:
Q: onreadystatechange event function I have started learning HTML Javascript events and I'm confused a little bit. this following function takes event as a parameter however it works well the same without a parameters and I'm wondering how is that happening. when I console.log(event.type); it still shows the readystate event regardless of argument passed in the function
document.onreadystatechange = function (event) {
    console.log(event.type);
    if (document.readyState === "complete") {
        console.log("Ready!");
        console.log(document.getElementById("some-div").innerText);
    }
}


text:
Q: Shift images LEFT or RIGHT - Beamer How can I shift the whole image with the caption?
\hspace*{4cm} moves only the image without the caption.
    \begin{frame}
    \frametitle{Complementary to Absolute Temperature (CTAT)}

    \begin{figure}[]
    \begin{circuitikz}[american,node distance = 30pt] \hspace*{4cm}
    \draw (0,0) node[ground]{} to[Tpnp,name=Q1] node[right,yshift = -0.6cm]{$Q_1$} ++(0,1) to[short] ++(0,1) node(v1){} to[I,invert,l^=$I_0$] ++(0,2)node[tground]{};
    \draw (Q1.B) |- (0,0);
    \draw (v1) to [short] ++(1,0) node[below,xshift = 0.2cm]{$v_D$} to [open,o-];
    \end{circuitikz}
    \caption{CTAT}
    \label{fig:CTAT}
    \end{figure}

    \end{frame}


text:
Q: SQL Binary Microsoft Access - Combining two tables if specific field values are equal I am new to Microsoft Access and SQL but have a decent programming background and I believe this problem should be relatively simple.
I have two tables that I have imported into Access. I will give you a little context. One table is huge and contains generic, global data. The other table is still big but contains specific, regional data. There is only one common field (or column) between the two tables. Let's call this common field CF. The other fields in both tables are different.
I'll take you through one iteration of what I need to do. I need to take each CF value in the regional, smaller table and find the common CF value in the larger, global table. After finding the match, I need to take the whole "record" or "row" from the global data and copy it over to the corresponding record in the smaller regional table (This should involve creating the new fields).
I need to do this for all CF values in the regional, smaller table. I was recommended to use SQL and a binary search, but I am unfamiliar. Let me know if you have any questions. I appreciate the help!

A: Not sure about the MS Access specific dialect, but in T-SQL, it would be something like:
Update Regional SET Regional.A = Global.A ...
FROM Global WHERE Regional.CF = Global.CF

And as long as CF is unique in Global, you should be there.


text:
Q: smartgwt + gwt-rpc or REST + spring Hi
I am currently working on a project and basing my design proposal on a SOA architecture and am including GWT components for UI . I am new to GWT and after reading through a week of posts of GWT and SmartGWT and trying out samples i would like to introduce SmartGWT into my organization w/o the server-side integration. That is because we already have spring services and would like them to remain re-usable through the organization. So my main interest is in the ui components of Smart GWT and in some fashion (either gwt-rpc or REST ) connect to the backend exposed services.
I am developing on SmartGWT 2.4 and gwt2.2+ . I have gone through the posts on GWT-rpc and tried using the sample api presented. However i ran into a couple issues .
Running the ListGridSample 'as is' i get the following ERROR although the application runs.
Am using the sample from here

23:31:37.101 [ERROR] [listgridtest] 23:31:37.088:RDQ5:WARN:ResultSet:isc_ResultSet_0 (created by: isc_OID_1):get: invalid index -1
com.smartgwt.client.core.JsObject$SGWT_WARN: 23:31:37.088:RDQ5:WARN:ResultSet:isc_ResultSet_0 (created by: isc_OID_1):get: invalid index -1    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:105)
    at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
    at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:157)
    at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessages(BrowserChannelServer.java:281)
    at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:531)
    at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:352)
    at java.lang.Thread.run(Thread.java:619)

I next wanted to remove all the redundant jars present in the example project and update the smartgwt jars and gwt-servlet jar to see if it is still compatible. I received this

23:37:06.584 [ERROR] [listgridtest] Unable to load module entry point class mytest.client.YourEntryPoint (see associated exception for details)
com.google.gwt.core.client.JavaScriptException: (TypeError): Object [object Object] has no method 'getNextGlobalIDForClass'
 stack: TypeError: Object [object Object] has no method 'getNextGlobalIDForClass'
    at unknown source
    at __gwt_jsInvoke (ttp://127.0.0.1:8888/listgridtest/hosted.html?listgridtest:76:35)
    at ttp://127.0.0.1:8888/listgridtest/hosted.html?listgridtest:280:16
    at z (ttp://127.0.0.1:8888/listgridtest/listgridtest.nocache.js:2:144)
    at ttp://127.0.0.1:8888/listgridtest/listgridtest.nocache.js:8:589
 arguments: getNextGlobalIDForClass,[object Object]
 type: undefined_method
 __gwt_ObjectId: 2
    at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:237)
    at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:129)
    at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:561)
    at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:269)
    at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91)
    at com.smartgwt.client.util.SC.generateID(SC.java)
    at com.smartgwt.client.widgets.BaseWidget.<init>(BaseWidget.java:102)
    at com.smartgwt.client.widgets.Canvas.<init>(Canvas.java:75)
    at mytest.client.YourEntryPoint.onModuleLoad(YourEntryPoint.java:24)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.google.gwt.dev.shell.ModuleSpace.onLoad(ModuleSpace.java:396)
    at com.google.gwt.dev.shell.OophmSessionHandler.loadModule(OophmSessionHandler.java:183)
    at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:510)
    at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:352)
    at java.lang.Thread.run(Thread.java:619)

I read somewhere on the smartclient forums not to mix the smartgwtee and smartgwt jars so i double checked (because i was evaluating the ee edition b4this but that required a learning in the datasource concept ). So i am using gwt2.2+ and smart-gwt2.4.
I have read through the quick start pdf (quickly) and decided that although the server side integration may have benefits for a quick introduction within my organization it would not work.
So from an system standpoint if i understand correctly you could define your datasource for your partricular widgets and then use the GenericGwtService to pass on to your business services before or after you send back the DSresponse.
Can you kindly point me to a quick sample which actually does this in the latest version or a document which specifies exactly how to do it ? or an api or a forum post which addresses this for the latest versions.
Hopefully that would help me springify the sample miniapp.. which would help me POC.
Any input appreciated.
Thanks,

A: Answered something similar here - Smartgwt DataSource with gwt requestfactory etc
You can also look at JSON datasources
http://www.smartclient.com/smartgwt/javadoc/com/smartgwt/client/data/XJSONDataSource.html


text:
Q: Spring Boot test @After not deleting rows before next test I have the following @Before and @After in my Spring Boot integration tests:
@Before
public void setup() {
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
        .addFilter(springSecurityFilterChain).build();

    user = userRepository.save(
        new User("Joe", "Bloggs", "joe@example.com", "joe", passwordEncoder.encode("secret")));

    currency = currencyRepository.save(
        new Currency("GBP", "£%01.2f"));

    fund = fundRepository.save(
        new Fund("Nationwide", (double) 100, currency));

}

@After
public void teardown() {
    userRepository.delete(user);
    currencyRepository.delete(currency);
    fundRepository.delete(fund);
}

However, it doesn't seem that currencies are being deleted after each test and my tests are failing in error:
...
[ERROR] testGetFunds_whenNoToken_thenUnauthorized(biz.martyn.budget.FundsControllerTest)  Time elapsed: 3.268 s  <<< ERROR!
org.springframework.orm.jpa.JpaObjectRetrievalFailureException: Unable to find biz.martyn.budget.currency.Currency with id 437; nested exception is javax.persistence.EntityNotFoundException: Unable to find biz.martyn.budget.currency.Currency with id 437
Caused by: javax.persistence.EntityNotFoundException: Unable to find biz.martyn.budget.currency.Currency with id 437
...

After, if I query the test database, I see that rows haven't been deleted:
mysql> select * from currencies;
+----+---------------------+---------------------+---------------+------+---------------------+
| id | created_at          | deleted_at          | format        | name | updated_at          |
+----+---------------------+---------------------+---------------+------+---------------------+
...
| 437 | 2020-01-02 13:51:24 | 2020-01-02 13:51:23 | £%01.2f | GBP  | 2020-01-02 13:51:24 |
...
+----+---------------------+---------------------+---------------+------+---------------------+
5 rows in set (0.00 sec)

There should only be one unique entry for name but I guess as delete is not happening it is pulling duplicates for "GBP". My repository for currencies:
Currency.java
@Entity(name = "currencies")
@SQLDelete(sql = "UPDATE currencies SET deleted_at = now() WHERE id = ?")
@Where(clause = "deleted_at is null")
public class Currency {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  protected Integer id;

  @Column(unique = true, nullable = false)
  private String name;

  @Column(nullable = false)
  private String format;

  @Column(name = "created_at", updatable = false)
  @CreationTimestamp
  protected LocalDateTime createdAt;

  @Column(name = "updated_at")
  @UpdateTimestamp
  protected LocalDateTime updatedAt;

  @Column(name = "deleted_at")
  protected LocalDateTime deletedAt;

  protected Currency() {}

  public Currency(String name, String format) {
    this.name = name;
    this.format = format;
  }

  public Integer getId() {
    return id;
  }

  public String getName() {
    return name;
  }

  public void setName(final String name) {
    this.name = name;
  }

  public String getFormat() {
    return format;
  }

  public void setFormat(final String format) {
    this.format = format;
  }
}

User.java
@Entity(name = "users")
public class User implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = -8507204786382662588L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(nullable = false)
    private String firstName;

    @Column(nullable = false)
    private String surname;

    @Column(nullable = false, unique = true)
    private String email;

    @Column(nullable = false, unique = true)
    private String username;

    @Column(nullable = false)
    @JsonIgnore
    private String password;

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name="user_id")
    @JsonIgnore
    private List<Fund> funds;

    protected User() {}

    public User(String firstName, String surname, String email, String username, String password) {
        this.firstName = firstName;
        this.surname = surname;
        this.email = email;
        this.username = username;
        this.password = password;
    }

    public Long getId() {
        return id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    // standard getters and setters

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public List<Fund> getFunds() {
        return funds;
    }

    public void addFund(Fund fund) {
        funds.add(fund);
        fund.setUser(this);
    }

    public void removeFund(Fund fund) {
        funds.remove(fund);
        fund.setUser(null);
    }

    // public Fund getFund(int id) {
    //  fundRepository.findByIdAndUserId(id)
    //         .orElseThrow(() -> new EntityNotFoundException("Fund ID not found: "+id));
    // }
}

A: The delete method takes an object of Currency. Your Currency object has an ID which is auto-generated.
When you pass the same object that you passed to save to delete you did not set the ID that's the reason the delete operation never actually deletes the data you wanted to delete.
You can either use the object that is returned from save method or get a hold of the genearted-id and use deleteById method.
Here is an example for delete using the object.
@Before
public void setup() {
    user = repository.save(user);
}

@After
public void tearDown() {
    repository.delete(user);
}

Alternatively, you can use the same object to get the generated-id and use deleteById method.
If you take a look at SimpleJpaRepository which provides an implementation for JPA, you will find that if your ID is null then they are treated as a new entity and are never deleted.
    /*
     * (non-Javadoc)
     * @see org.springframework.data.repository.CrudRepository#delete(java.lang.Object)
     */
    @Override
    @Transactional
    @SuppressWarnings("unchecked")
    public void delete(T entity) {

        Assert.notNull(entity, "Entity must not be null!");

        if (entityInformation.isNew(entity)) {
            return;
        }

        // Other stuff
    }


text:
Q: Slider Control arrows are moving I have created an only CSS slider, couple of days ago and its seems the control arrows are positioned well when I open the page on my computer but they are moving when I zoom in or out on the page.How can I keep them always in position?
I can't figure out what I missing.
Here is the test page:
http://friendshipforever.co.uk/slider%20test/slider.html
CSS and HTML below:

#slider {
 text-align: center;
}

h2 {
 margin: 40px 0 25px;
 border-bottom: 1px solid #bbb;
 padding: 0 0 10px;
}

p {
 margin: 0 0 16px;
}

strong {
 font-weight: bold;
}

label, a {
 color: teal;
 cursor: pointer;
 text-decoration: none;
}
label:hover, a:hover {
 color: #000 !important;
}
* { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; }
label, #active, img { -moz-user-select:none;-webkit-user-select:none; }
.catch { display: block; height: 0; overflow: hidden; }
#slider {
 margin: 0 auto;
}
#description {
 margin: 25px auto;
 text-align: left;
 max-width: 650px;
 padding: 0 25px;
}
.respond {
 margin: 0 auto;
 max-width: 370px;
}

/* NEW EXPERIMENT */
/* Slider Setup */

input {
 display: none;
}

#slide1:checked ~ #slides .inner { margin-left:0; }
#slide2:checked ~ #slides .inner { margin-left:-100%; }
#slide3:checked ~ #slides .inner { margin-left:-200%; }
#slide4:checked ~ #slides .inner { margin-left:-300%; }
#slide5:checked ~ #slides .inner { margin-left:-400%; }

#overflow {
 width: 105%;
 overflow: hidden;
}

article img {
 max-width: 400px;
}

#slides .inner {
 width: 500%;
 line-height: 0;
}

#slides article {
 width: 20%;
 float: left;
}

/* Slider Styling */

/* Control Setup */

#controls {
 margin: -25% 0 0 0;
 width: 100%;
 height: 50px;
}

#controls label {
 display: none;
 width: 50px;
 height: 50px;
 opacity: 0.3;
}

#active {
 margin: 23% 0 0;
 text-align: center;
}

#active label img {
 display: inline-block;
 height: 70px;
 border-style: solid;
 border-width: 3px;
 border-color: black;
  opacity: 1;
   transition: opacity .25s ease-in-out;
   -moz-transition: opacity .25s ease-in-out;
   -webkit-transition: opacity .25s ease-in-out;
}
#active label img:hover {
opacity: 0.5;
}

#controls label:hover {
 opacity: 0.8;
}

#slide1:checked ~ #controls label:nth-child(2),
#slide2:checked ~ #controls label:nth-child(3),
#slide3:checked ~ #controls label:nth-child(4),
#slide4:checked ~ #controls label:nth-child(5),
#slide5:checked ~ #controls label:nth-child(1) {
 background: url('next.png') no-repeat;
 position: relative;
 float: right;
 margin: 0 350px 0 0;
 display: block;
}

#slide1:checked ~ #controls label:nth-child(5),
#slide2:checked ~ #controls label:nth-child(1),
#slide3:checked ~ #controls label:nth-child(2),
#slide4:checked ~ #controls label:nth-child(3),
#slide5:checked ~ #controls label:nth-child(4) {
 background: url('prev.png') no-repeat;
 position: relative;
 float: left;
 margin: 0 0 0 300px;
 display: block;
}

#slide1:checked ~ #active label:nth-child(1),
#slide2:checked ~ #active label:nth-child(2),
#slide3:checked ~ #active label:nth-child(3),
#slide4:checked ~ #active label:nth-child(4),
#slide5:checked ~ #active label:nth-child(5) {
 opacity: 0.5;

}

/* Slider Styling */

#slides {

 width:400px;
 margin: auto;

}

/* Animation */

#slides .inner {
 -webkit-transform: translateZ(0);
 -webkit-transition: all 800ms cubic-bezier(0.770, 0.000, 0.175, 1.000);
 -moz-transition: all 800ms cubic-bezier(0.770, 0.000, 0.175, 1.000);
    -ms-transition: all 800ms cubic-bezier(0.770, 0.000, 0.175, 1.000);
     -o-transition: all 800ms cubic-bezier(0.770, 0.000, 0.175, 1.000);
        transition: all 800ms cubic-bezier(0.770, 0.000, 0.175, 1.000); /* easeInOutQuart */

 -webkit-transition-timing-function: cubic-bezier(0.770, 0.000, 0.175, 1.000);
 -moz-transition-timing-function: cubic-bezier(0.770, 0.000, 0.175, 1.000);
    -ms-transition-timing-function: cubic-bezier(0.770, 0.000, 0.175, 1.000);
     -o-transition-timing-function: cubic-bezier(0.770, 0.000, 0.175, 1.000);
        transition-timing-function: cubic-bezier(0.770, 0.000, 0.175, 1.000); /* easeInOutQuart */
}

#slider {
 -webkit-transform: translateZ(0);
 -webkit-transition: all 0.5s ease-out;
 -moz-transition: all 0.5s ease-out;
 -o-transition: all 0.5s ease-out;
 transition: all 0.5s ease-out;
}

#controls label{
 -webkit-transform: translateZ(0);
 -webkit-transition: opacity 0.2s ease-out;
 -moz-transition: opacity 0.2s ease-out;
 -o-transition: opacity 0.2s ease-out;
 transition: opacity 0.2s ease-out;
}

#slide1:checked ~ #slides article:nth-child(1) .info,
#slide2:checked ~ #slides article:nth-child(2) .info,
#slide3:checked ~ #slides article:nth-child(3) .info,
#slide4:checked ~ #slides article:nth-child(4) .info,
#slide5:checked ~ #slides article:nth-child(5) .info {
 opacity: 1;
 -webkit-transition: all 1s ease-out 0.6s;
 -moz-transition: all 1s ease-out 0.6s;
 -o-transition: all 1s ease-out 0.6s;
 transition: all 1s ease-out 0.6s;
}

.info, #controls, #slides, #active, #active label, .info h3, .desktop, .tablet, .mobile {
 -webkit-transform: translateZ(0);
 -webkit-transition: all 0.5s ease-out;
 -moz-transition: all 0.5s ease-out;
 -o-transition: all 0.5s ease-out;
 transition: all 0.5s ease-out;
}

 <link href="sliderstyle.css" media="screen, projection" rel="stylesheet" type="text/css" />

  <input checked type=radio name=slider id=slide1 />
  <input type=radio name=slider id=slide2 />
  <input type=radio name=slider id=slide3 />
  <input type=radio name=slider id=slide4 />
  <input type=radio name=slider id=slide5 />

A: remove margin
#controls {
    height: 50px;
    /*margin: -25% 0 0;*/
    width: 100%;
}
#active {
    /*margin: 23% 0 0;*/
    text-align: center;
}


text:
Q: Save result of for loop in a vector I think I'm just too tired to see the mistake. I wrote a function to get the maximal value for two data sets from a 'for' loop:
plot_zu <- function(x) {for (i in 1:x){
    z=data_raw[grep(a[i], data_raw$Gene.names),]
    b=data_raw_ace[grep(a[i], data_raw_ace$Gene.names),]
    p<-vector("numeric", length(1:length(a)))
    p[i]<-max(z$t_test_diff)
    return(p)}
}

Imagine: a is a vector of names and the data set (data_raw(_ace)) is filtered by it. In the end, I would like to have all maxima values of column t_test_diff in a vector. After that I want to add the t_test_diff column values from data_raw_ace also.
So the problem is, that I get this:
[1] 1.210213 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000
[8] 0.000000 0.000000

So there is a problem with brackets or something but I cannot see it ( first value fits). Sorry for no good example but i think it is understandable and an easy to solve question.
If need be, I can add another example.
Thanks a lot!!
gratefully,
Hendrik

A: In the absence of data and even the call you make to this function, I'm going to offer an alternative based on what I think you are attempting. It appears you want to select only those rows of "data_raw" whose "Gene.names" column values are in the set defined by "a". If so, that is just:
 z <- data_raw[ data_raw$Gene.names %in% a , ]  # no loop needed

 b <- data_raw_ace[ data_raw_ace$Gene.names %in% a , ] # again no loop needed
 # Next step is unclear

If you want to use grep or grepl inside "[" then use sapply:
 z <- data_raw[ sapply(a, grep, x= data_raw$Gene.names), ]  # (still) no loop needed
 b <- data_raw_ace[ sapply(a, grep, x= data_raw_ace$Gene.names),  ]

When you do this, what is it that is desired?
p<-vector("numeric", length(1:length(a)))
p[i]<-max(z$t_test_diff)

If you want the maximum value for an identically named column in the two subset of data, then do this:
p <- pmax( z$t_test_diff, b$t_test_diff )

Based on you further comments above I (now) think maybe:
p <- apply( cbind(z$t_test_diff), abs(b$t_test_diff), 1, function(x) x[which.max(abs(x))])

A: vapply does this, eliminating the for loop.  Not tested.
vapply(1:x, FUN.VALUE=numeric(1), FUN=function(x) {
    z=data_raw[grep(a[i], data_raw$Gene.names),]
    b=data_raw_ace[grep(a[i], data_raw_ace$Gene.names),]  # Is this needed?

    return(max(z$t_test_diff))
})

A: It appears you are overwriting p in each new iteration by defining it inside the loop.


text:
Q: Recursive string decompression I'm trying to decompress strings that looks as follows:
Input: 4(ab)
Output: abababab
Input: 11ab
Output: aaaaaaaaaaab
Input: 2(3b3(ab))
Output: bbbabababbbbababab
The above examples all comes out correctly using the recursive method below but problems arise when I input something like:
Input: 4(ab)a
Expected output: ababababa
Input: 2(3b3(ab))a
Expected output:bbbabababbbbabababa
I realise the problems arise where in the return statement "return repeated". In its current state the recursion continues until it hits the end of the input string even after an ending parenthesis. Basically I don't know how to get it to break if reaching the ending parenthesis and then continue if there's anything left. In 2(3b3(ab))a it should return 2*(3b3(ab))+a, and now it returns 2*(3b3(ab))a. Any help is greatly appreciated, since I can't get my head around it.
public static String decompress(String compressedText) throws Exception
{
   //BASE CASE
    if(compressedText.length() == 1)
    {
        if(compressedText.charAt(0) == ')')
        {
            System.out.println("1: " + compressedText);
            return "";
        }
        else
        {
            System.out.println("2: " + compressedText);
            return compressedText;
        }

    }
    //END BASECASE

    if(compressedText.charAt(0) == '(')
    {
        System.out.println("3: " + compressedText);
        return decompress(compressedText.substring(1));
    }

    //IF DOUBLE DIGIT
    if(Character.isDigit(compressedText.charAt(0)) == true && Character.isDigit(compressedText.charAt(1)) == true)
    {
        if(compressedText.charAt(3) != '(')
        {
            System.out.println("4: " + compressedText);
            int i = Integer.parseInt(compressedText.substring(0,2));
            String repeated = new String(new char[i]).replace("\0", compressedText.substring(2,3));
            return repeated + decompress(compressedText.substring(3));
        }
        else
        {
            System.out.println("5: " + compressedText);
            int i = Integer.parseInt(compressedText.substring(0,2));
            String repeated = new String(new char[i]).replace("\0", decompress(compressedText.substring(2)));
            return repeated;
        }

    }
    //END DOUBLE DIGIT

    //IF SINGLE DIGIT
    if (Character.isDigit(compressedText.charAt(0)) == true)
    {
        if(compressedText.charAt(1) !='(')
        {
            System.out.println("6: " + compressedText);
            int i = Integer.parseInt(compressedText.substring(0,1));
            String repeated = new String(new char[i]).replace("\0", compressedText.substring(1,2));
            return repeated + decompress(compressedText.substring(2));
        }
        else
        {
            System.out.println("7: " + compressedText);
            int i = Integer.parseInt(compressedText.substring(0,1));
            String repeated = new String(new char[i]).replace("\0", decompress(compressedText.substring(1)));
            return repeated;
        }

    }
    //END SINGLE DIGIT

    //IF RIGHT PARENTHESIS
    if (compressedText.charAt(0) == ')')
    {
        if (compressedText.charAt(1) != ')')
        {
            System.out.println("8: " + compressedText);
            return "";
        }
        else
        {
            System.out.println("9: " + compressedText);
            return  decompress(compressedText.substring(1));

        }

    }
    //END

        System.out.println("10: " + compressedText);
        return compressedText.charAt(0)+decompress(compressedText.substring(1));

}

A: Use a tuple for the return value of the recursion, which provides the index of the closing parenthesis in addition to the accumulated string:
index 0 1 2 3 4 5 6 7 8 9 10
str   2 ( 3 b 3 ( a b ) ) a

  f(0)

  => 2 * f(1)[0] add f(f(1)[1] + 1)  // f(1)[1] is the closing index

    f(1) => 3 * b + 3 * f(5)[0] add f(f(5)[1] + 1)

    => f(5) returns (ab,8)

    f(1) => bbb + ababab add f(9) // str[9] is closing parenthesis

    => f(1) returns (bbbababab,9)

  => 2 * bbbababab add f(10)

  => bbbabababbbbabababa

JavaScript code:

var example = '2(3b3(ab)2(cd3(fg)))ab2(gh2(xz))';

console.log(example);
console.log(decompress(example));

function decompress(s){

  // returns tuple [accumulator, index of closing parenthesis]
  function f(i){

    var accum = '',
        mult = '',
        curr = '';

    // accumulate all parenthetical groups in this level
    while (i !== s.length){

      // closing parenthesis
      if (s[i] === ')'){

        // add the last decompression
        if (curr !== ''){
          accum += customReplicate(curr,mult);
        }

        // exit this call
        return [accum,i];
      }

      // character is a digit
      if (!isNaN(parseInt(s[i]))){

        // add previous decompression
        if (curr !== ''){
          accum += customReplicate(curr,mult);

          curr = '';
          mult = s[i];

        } else {
          mult += s[i];
        }

        i++;

      // character is a character
      } else if (s[i] !== '('){

        curr += s[i];
        i++;

      // parenthetical group
      } else if (s[i] === '('){

        // recursive call
        [tempAccum,index] = f(i + 1);

        accum += customReplicate(tempAccum,mult);
        mult = '';
        i = index + 1;
      }
    }

    return accum + customReplicate(curr,mult);
  }

  // initialize the recursion
  return f(0);
}

function customReplicate(str,times){
  return new Array(times === '' ? 1 : parseInt(times))
                 .fill(str).join('');
}

A: One thing that I've noticed is that you are "loosing" the last "a" when you return "" after outputting "8:". At that position the trailing chars should be handled as well, however you cannot simply return them there - neither directly nor by decompressing them -, because that would result in  bbbabaabaababbbabaabaaba.
Sadly, I didn't find a solution based on your code which returns the correct value (I guess there is some strange behavior in how you put the partly processed text into the recursion, but I'm not sure...).
However, I thought about how I would solve this compression thing and came up with two non-recursive solutions. Maybe they help you improve your solution. Side note: my solutions assume that the string is well-formed, that is it does not have any non-matching brackets etc.
(I used a repeat function that I've put at the end of my answer.)
The first solution uses a regular expression, which searches for the digits and the following part (either one char or a bracket-enclosed part which does not contain brackets itself). This way, the brackets and single-char decompressions are handled from the inside to the outside.
public static String decompressWithRegex(String s) {
    if ((s == null) || (s.length() == 0)) {
        return s;
    }
    // pattern for finding number with either bracket-enclosed, char-only part or single char
    Pattern p = Pattern.compile("(\\d+)((?:[^\\d\\(\\)]{1})|(?:\\([^\\d\\(\\)]+\\)))");
    String tmp = s;
    Matcher m = p.matcher(tmp);
    // start searching
    while (m.find(0)) {
        // first capture group returns count
        int count = Integer.parseInt(m.group(1));
        // second group is string to repeat (if it's bracket-enclosed, then remove brackets)
        String what = m.group(2).replace("(", "").replace(")", "");
        // build replacement part
        String replacePart = repeat(what, count);
        // replace it
        tmp = m.replaceFirst(replacePart);
        // reset matcher (source of matcher is now the new string)
        m.reset(tmp);
    }
    return tmp;
}

The second solution does not use regular expressions. Instead, it makes some assumptions about how the decompression can be handled:

*

*any number which is not followed by a bracket-enclosed part can be directly
decompressed in-place, which is done first

*the bracket-enclosed part is handled by finding the first closing bracket

*then from there back to start the opening bracket is searched

*this gets you the part to repeat

*left of the opening bracket there should be a number which is then searched and parsed

*now that we have all the information, the replacement part is built and put in the right place

*then the next closing bracket is searched if there is any, and this is handled as above

*if there is no closing bracket, the string is decompressed

Code:
public static String decompressWithSearching(String s) {
    if ((s == null) || (s.length() == 0)) {
        return s;
    }
    // replace non-groups first
    for (int i = s.length() - 1; i >= 0; i--) {
        // find digit that is not followed by bracket
        if (Character.isDigit(s.charAt(i)) && s.charAt(i + 1) != '(') {
            // string to repeat is right behind the digit
            String part = s.substring(i + 1, i + 2);
            // find complete digit
            String countStr = "";
            int j = i;
            for ( ; j >= 0 && Character.isDigit(s.charAt(j)); j--) {
                countStr = s.charAt(j) + countStr;
            }
            int count = Integer.parseInt(countStr);
            // build replacement part
            String replacePart = repeat(part, count);
            // replace part
            s = s.substring(0, j + 1) + replacePart + s.substring(i + 2);
        }
    }

    // replace nested parts
    int closing;
    while ((closing = s.indexOf(')')) > -1) {
        // find matching opening bracket
        int opening = s.lastIndexOf('(', closing);
        // text between is to be repeated
        String what = s.substring(opening + 1,closing);
        // find complete digit
        String countStr = "";
        int numPartIndex = opening - 1;
        while (numPartIndex >= 0 && Character.isDigit(s.charAt(numPartIndex))) {
            countStr = s.charAt(numPartIndex) + countStr;
            numPartIndex--;
        }
        int count = Integer.parseInt(countStr);
        // build replacement part
        String replacePart = repeat(what, count);
        // replace part
        s = s.substring(0, numPartIndex + 1) + replacePart + s.substring(closing + 1);
    }

    return s;
}

Utility method for repeating a String:
public static String repeat(String what, int times) {
    if ((times <= 0) || (what == null) || (what.length() == 0)) {
        return "";
    }
    StringBuilder buffer = new StringBuilder(times * what.length());
    for (int i = 0; i < times; i++) {
        buffer.append(what);
    }
    return buffer.toString();
}

A: I realize this is a Java question, but I usually write a small Ruby code to test an idea before implementing it in Java. If it interests anyone, here's my code :
def decompress(str)
  str.gsub!(/(\d+)([a-z])/i){$2*$1.to_i}       # Replace every subtring like "3b" and "11a".
  while str.include?('(') do
    str.sub!(/(\d+)\(([a-z]+)\)/){$2*$1.to_i}  # Replace the first inner group found
  end
  str
end

puts decompress("4(ab)")       == "abababab"
puts decompress("11ab")        == "aaaaaaaaaaab"
puts decompress("2(3b3(ab))")  == "bbbabababbbbababab"
puts decompress("4(ab)a")      == "ababababa"
puts decompress("2(3b3(ab))a") == "bbbabababbbbabababa"
#=> true, true, true, true, true

@jCoder wrote almost exactly the same thing in his first example, so no need to reinvent the wheel!


text:
Q: Recreate webservice HI,
My job was to create a webservice which acted as another webservice we have, so the client doesn't notice the difference. I created my entire webservice and it works fine as I use it and the outputs all are the same. The thing is, I created a clientapplication where I use the old webservice and if I change the url of the webreference to the new service and retry I get an error:

System.Web.Services.Protocols.SoapException:
  The server did not recognize the
  HTTP-header SOAPAction

If I look at the differences in the Reference.cs in my two webservices I notice there's a small difference in attributes which is I think the problem.
New service:
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "2.0.50727.3053")]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Web.Services.WebServiceBindingAttribute(Name="SprWebServiceSoap", Namespace="http://ws.hl7.trispark.com/")]
    public partial class SprWebService : System.Web.Services.Protocols.SoapHttpClientProtocol {

Old service:
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "2.0.50727.3053")]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Web.Services.WebServiceBindingAttribute(Name="SprWebServiceRemoteBinding", Namespace="http://ws.hl7.trispark.com/")]
    public partial class SprWebService : System.Web.Services.Protocols.SoapHttpClientProtocol {

And also the method which is used differs:
New:
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://ws.hl7.trispark.com/invoke", RequestNamespace="http://ws.hl7.trispark.com/", ResponseNamespace="http://ws.hl7.trispark.com/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
        public invokeResponse invoke(invoke inv) {

Old:
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Bare)]
        [return: System.Xml.Serialization.XmlElementAttribute("invokeResponse", Namespace="http://ws.hl7.trispark.com/types")]
        public invokeResponse invoke([System.Xml.Serialization.XmlElementAttribute("invoke", Namespace="http://ws.hl7.trispark.com/types")] invoke invoke1) {

First I thought the problem could be that my version was created in vs2008 and the old one in vs2005 so I recreated it in 2005, but that didn't change anything.
The thing is I don't have the code of the old one so I can't see what specific attributes is used.
Does anyone have any idea which attributes I have to set to get the same thing?
Thanks a lot!

A: Do you have the DLL of the old service?  If you have the DLL you could potentially use Reflector to reverse engineer it if it's a .net service.

A: My Guess would be to check the namespace used, I had a similar problem and it drilled down to be a difference in name space problem. Check for:
[WebService(Namespace = "http://tempuri.org/"]
This is default, which might be in your new webservice and your old webservice might be using some other namespace.

A: Try to compare the WSDL of both services - see if you can find any clue there.
To get it you add to the end of the URL  ?WSDL see example at http://aspnet.15seconds.com/010430/SampleService.asmx and http://aspnet.15seconds.com/010430/SampleService.asmx?WSDL respectively.
EDIT:
I am not a WSDL guru and so can't tell you where the issue is.
Another option you may consider is to compare sniffs of the requests to the services - this could provide other clues.

A: I realize this is an old question, but if your goal is to create a web servive that will be consume exactly like the old one, you should build the new one from the WSDL of the old one. You can do this automagically with visual studio :
http://bloggingabout.net/blogs/jschreuder/archive/2005/05/19/4124.aspx


text:
Q: Mongoose - Query returns nothing I have the following query:
app.get('/matches/:latMin/:latMax/:lonMin/:lonMax', function(req, res){
    var matches = City.find({
        "latitude": {$gt : String(req.param.latMin), $lt : String(req.params.latMax) },
        "longitude" : {$gt : String(req.param.lonMin), $lt : String(req.param.lonMax)}
    });
    matches.exec(function(err, match){
                 if(err){
                    console.log(err);
                     return res.send(err);
                 }
                console.log(match);
                res.json(match);
            });
});

Here is my schema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

module.exports = mongoose.model('City', new Schema({
    zip : {type : String, default: ''},
    latitude : {type : String, default: ''},
    longitude : {type: String, default: ''},
    city : {type: String, default: ''},
    state : {type: String, default: ''},
    county : {type: String, default: ''}
}), 'locations');

When I run the query in the Mongo shell, the expected results are sent.  However, the log in the above quotes returns [].  Is there something wrong I'm doing here?

A: I don't know if you want to use req.param or it is just a typo. Anyway, req.param is deprecated and you should use req.params.
I have set up your scenario and queries are working. Replace the var matches in your code for the following:
var matches = City.find({
    "latitude": {$gt : String(req.params.latMin), $lt : String(req.params.latMax) },
    "longitude" : {$gt : String(req.params.lonMin), $lt : String(req.params.lonMax)}
});


text:
Q: Suitable technology, framework, language for web-project I have a private "consumer-like" web-project on my mind that should have a nice design (most likely third party template), potentially a CMS environment to author static content (e.g. typo3) and foremost a fancy web application embedded in certain parts of the page.
Now coming more from the Enterprise-SW world - mostly backend and as mentioned above some application like web-interfaces I'm struggling getting hold on what technology to use for these class of web projects?
Java & Co (GWT, Vaadin, etc.) seem to be an overkill and more suitable for web-based applications. I'm not sure how well it integrates with common CMS solutions such as Typo3 & Co. as well.
Going directly to PHP or Rails on the other hand seems to be just enough to show some dynamic content and building a little more complex applications could turn out to be an issue. That said being inexperienced with PHP or Ruby.
Apache vs. Tomcat is also an issue if I want to host the end-result at low costs.
Any thoughts?

A: Choosing a web framework highly depends on your specific needs. You better try with a "proof of concept" using each framework you think will work.
About the hosting costs... Java hosting is more expensive than PHP. Not sure about Ruby.