text:
Q: Why should I use the command design pattern while I can easily call required methods? I am studying the command design pattern, and I am quite confused with the way of using it. The example that I have is related to a remote control class that is used to turn lights on and off.
Why should I not use the switchOn() / switchOff() methods of Light class rather than having separate classes and methods that eventually call switchOn / switchOff methods?
I know my example is quite simple, but that is the point. I could not find any complex problem anywhere on the Internet to see the exact usage of the command design pattern.
If you are aware of any complex real world problem that you solved that can be solved using this design pattern please share that with me. It helps me and future readers of this post to better understand the usage of this design pattern. Thanks
//Command
public interface Command {
  public void execute();
}

//Concrete Command
public class LightOnCommand implements Command {

  //Reference to the light
  Light light;

  public LightOnCommand(Light light) {
    this.light = light;
  }

  public void execute() {
    light.switchOn();        //Explicit call of selected class's method
  }
}

//Concrete Command
public class LightOffCommand implements Command {

  //Reference to the light
  Light light;

  public LightOffCommand(Light light) {
    this.light = light;
  }

  public void execute() {
    light.switchOff();
  }
}

//Receiver
public class Light {
  private boolean on;

  public void switchOn() {
    on = true;
  }

  public void switchOff() {
    on = false;
  }
}

//Invoker
public class RemoteControl {
  private Command command;

  public void setCommand(Command command) {
    this.command = command;
  }

  public void pressButton() {
    command.execute();
  }
}

//Client
public class Client {
  public static void main(String[] args) {
    RemoteControl control = new RemoteControl();
    Light light = new Light();
    Command lightsOn = new LightsOnCommand(light);
    Command lightsOff = new LightsOffCommand(light);

    //Switch on
    control.setCommand(lightsOn);
    control.pressButton();

    //Switch off
    control.setCommand(lightsOff);
    control.pressButton();
  }
}

Why should not I easily use code like the following?
 Light light = new Light();
 switch(light.command) {
  case 1:
    light.switchOn();
    break;
  case 2:
    light.switchOff();
    break;
 }

A: You don't have to. Design patterns are simply guidelines that some people in the past have found useful when writing applications of significant complexity.
In your case, if what you have to do is turn the light switch on and off, and not much else, the second option is a no brainer.
Less code is almost always better than more code.

A: The example ICommand you give is rather limited and is only of real use in a programming language that does not have lambda expressions.   Sprinter covers this well in his answers showing the use of command factories.
Most cases of the command pattern include other methods for example, CanRun and/or Undo.   These allows a button to update its enable state based on the state of the command, or a application to implement an undo stack.
Like most design patterns, the Command Pattern comes into its own where things get a little more complex.    It is also well know, so helps make your code clearly to most programmers.

A: The main motivation for using the Command pattern is that the executor of the command does not need to know anything at all about what the command is, what context information it needs on or what it does. All of that is encapsulated in the command.
This allows you to do things such as have a list of commands that are executed in order, that are dependent on other items, that are assigned to some triggering event etc.
In your example, you could have other classes (e.g. Air Conditioner) that have their own commands (e.g. Turn Thermostat Up, Turn Thermostat Down). Any of these commands could be assigned to a button or triggered when some condition is met without requiring any knowledge of the command.
So, in summary, the pattern encapsulates everything required to take an action and allows the execution of the action to occur completely independently of any of that context. If that is not a requirement for you then the pattern is probably not helpful for your problem space.
Here's a simple use case:
interface Command {
    void execute();
}

class Light {
    public Command turnOn();
    public Command turnOff();
}

class AirConditioner {
    public Command setThermostat(Temperature temperature);
}

class Button {
    public Button(String text, Command onPush);
}

class Scheduler {
    public void addScheduledCommand(Time timeToExecute, Command command);
}

Then you can do things such as:
new Button("Turn on light", light.turnOn());
scheduler.addScheduledCommand(new Time("15:12:07"), airCon.setThermostat(27));
scheduler.addScheduledCommand(new Time("15:13:02"), light.turnOff());

As you can see the Button and Scheduler don't need to know anything at all about the commands. Scheduler is an example of a class that might hold a collection of commands.
Note also that in Java 8 functional interfaces and method references have made this type of code even neater:
@FunctionalInterface
interface Command {
    void execute();
}

public Light {
    public void turnOn();
}

new Button("Turn On Light", light::turnOn);

Now the methods that are turned into commands don't even need to know about commands - as long as they have the correct signature you can quietly create a anonymous command object by referencing the method.

A: Let us focus on the non-implementation aspect of the command design, and some main reasons for using the Command desing pattern grouped in two major categories:

*

*Hiding actual implementation of how the command is executed

*Allow methods to be built around command, aka command extensions

Hide implementation
In most programming, you'll want to hide away implementation so that when looking at the top-most problem, it consists of a comprehensible subset of commands/code. I.e. You don't need/want to know the gory details of how a light is switched on, or a car is started. If your focus is to get the car started, you don't need to understand how the engine works, and how it needs fuel to enter the engine, how the valves work, ...
Indicating the action, not how it is done
A command gives you this kind of view. You'll immediately understand what the TurnLightOn command does, or StartCar. Using a command you'll hide the details of how something is done, whilst clearly indicating the action which is to be executed.
Allow changing of inner details
In addition, lets say you later on rebuild your entire Light class, or a Car class, which requires you instantiate several different objects, and possibly you need to something else before actually doing your wanted operation. In this case if you had implemented the direct access method, in a lot of places, you would need to change it in all places where you've coded it beforehand. Using a command, you can change the inner details of how to do stuff without changing the calling of the command.
Possible command extensions
Using a Command interface gives you an extra layer between the code using the command, and the code doing the actual action of the command. This can allow for multiple good scenarios.
Security extension, or interface exposure
Using a command interface, you can also limit access to your objects, allowing you to define another level of security. It could make sense to have a module/library with a fairly open access so that you could handle internal special cases easily.
From the outside, however, you might want to restrict the access to the light so that it is only to be turned on or off. Using commands gives you the ability to limit the interface towards a class.
In addition if you want, you could build a dedicated user access system around the commands. This would leave all of your business logic open and accessible and free of restrictions, but still you could easily restrict access at the command level to enforce proper access.
Common interface to executing stuff
When building a sufficient large system, commands gives a neat way to bridge between different modules/libraries. Instead of you needing to examine every implementation detail of any given class, you can look into which commands are accessing the class.
And since you are leaving out implementation details to the command itself, you could use a common method to instantiate the command, execute it and review the result. This allows for easier coding, instead of needing to read up on how to instantiate that particular Light or Car class, and determining the result of it.
Sequencing of commands
Using commands, you can also do stuff like sequencing of commands. That is since you don't really matter if you are executing the TurnOnLight or StartCar command, you can execute sequences of theses as they are executed the same way. Which in turns can allow for chains of commands to be executed, which could be useful in multiple situation.
You could build macros, execute sets of commands which you believe are grouped together. I.e. the command sequence: UnlockDoor, EnterHouse, TurnOnLight. A natural sequence of commands, but not likely to made into a method as it uses different objects and actions.
Serialisation of commands
Commands being rather small in nature, also allows for serialisation quite nicely. This is useful in server-client context, or program-microservice context.
The server (or program) could trigger a command, which then serialises the command, sends it over some communication protocol (i.e. event queue, message queue, http, ... ) to someone actually handling the command. No need to first instantiate the object at the server, i.e. a Light which could be light-weight (pun intended), or a Car which could be a really large structure. You just need the command, and possibly a few parameters.
This could be a good place to introduce to the CQRS - Command Query Responsibility Separation pattern for further studies.
Tracking of commands
Using the extra layer of commands in your system could also allow for logging or tracking commands, if that is a business need. Instead of doing this all over the place, you can gather tracking/logging within the command module.
This allows for easy changes of logging system, or addition of stuff like timeing, or enabling/disabling logging. And it's all easily maintained within the command module.
Tracking of commands also allows for allowing undo actions, as you can choose to re-iterate the commands from a given state. Needs a little bit of extra setup, but rather easily doable.

In short, commands can be really useful as they allow connection between different parts of your soon-to-be-large program, as they are light-weight easily remembered/documented and hides the implementation details when so needed. In addition the commands allows for several useful extensions, which when building a larger system will come in handy: i.e. common interface, sequencing, serialisation, tracking, logging, security.

A: You can do whatever you think but it is good to follow the pattern for usability of manageability of code.
In real life example, Light would be an interface. You have different implementations of Light like LEDLight, TubeLight
If you execute the concrete command through Inovker ( RemoteControl), you need not worry about changes in method name in Receiver. switchOn() in Light can be changed to switchOnDevice() in future. But it does not effect Invoker since ConcreteCommand (LightsOnCommand) will make relevant changes.
Assume the scenario, where you publish your interfaces to one service (Service A) and implementation in other services (Service B).
Now Service A should not know about changes in Receiver.
Invoker provides loose coupling between Sender & Receiver of the message.
Have a look at some more related SE questions:
Using Command Design pattern
Command Pattern seems needlessly complex (what am I failing to understand?)

A: There're couple of benefits of Command pattern that I've experienced. But first of all, I would like to remind that as all other patterns this pattern is also to increase code readability and bring some common understanding to your (probably) shared code base.
I use this pattern to transition from a method-oriented interface to a command-oriented interface. That means, I'm encapsulating method calls into concrete commands along with necessary data. It makes the code more readable yes but more importantly I can treat methods as objects which lets you easily add/remove/modify commands without increasing the complexity of the code. So it makes it easy to manage as well easy to read.
Secondly, since you've your methods as objects, you can store/queue them to execute them later. Or to cancel them even after you've executed them. This is where this pattern helps you to implement "Undo".
Finally, command pattern also used to decouple command execution and commands themselves. It's like a waiter doesn't know about how to cook the orders that he received. He doesn't care. He doesn't have to know. If he'd know that, he'd be working as a cook as well. And if the restaurant owner wants to fire the waiter, he/she ends up with having no cook as well. Of course  this definition is not special or related to command pattern only. That's explains why we need decoupling or dependency management in general.

A: The possibilities are many, but it'd typically be something like:

*

*building a command-line framework that abstracts out the parsing of options from the action. Then you can register an action with something like opts.register("--on", new LightOnCommand()).

*letting users drag and drop a sequence of actions to execute as a macro

*registering a callback when some event is triggered, like on(Event.ENTER_ROOM, new LightOnCommand())
The general pattern here is that you've got one piece of the code responsible for figuring out that some action needs to be taken without knowing what that action is, and another piece of the code knows how to do an action but not when to do it.
For instance, in that first example, the opts instance knows that when it sees a command line option --on, it should turn the lights on. But it knows this without actually knowing what "turn the lights on" means. In fact, it could well be that the opts instance came from a third-party library, so it can't know about lights. All it knows about is how to accociate actions (commands) with command-line options that it parses.

A: Design patterns are basically developed to solve complex problem or in other words we can say that they are used to prevent your solution to become complex. They provide us the flexibility to add new functionalities in future without making much changes in our existing code. Open for extension, closed for modification.
Command Pattern basically encapsulates a request as an object and thereby letting you parameterize other objects with different requests and support undoable operations.
When we see a remote control that is a best example of command pattern. In this case we have associated a concrete command to each button and that command has an information of the receiver to act upon.
In your example of switch case, suppose if you want to associate a button on remote control to fan instead of light then again you will have to change the existing code because you need to associate a button with a command. This is the essence of command pattern where it provides you a flexibility to associate any command with a button so that at run time you can change the functionality. Although in general TV remote you don't have this feasibility i.e. you can't make volume up button to work as volume down. But if you use any application to control your TV then you can assign any button any of the available command.
Further, using command pattern you can have a set of commands for a particular functionality to achieve, i.e. macro command. Hence if you think at a broader level then this pattern can get you the flexibility to extend functionalities.
Command pattern help us in decoupling invoker(remote control) and Receiver (Light,Fan,etc) with the help of command object(LightOnCommand, FanOffCommand, etc).


text:
Q: Does anyone know the name of this component?
I think what this does is give power to the Ethernet cable that is attached to the satellite above the house.

A: Assuming you're referring to the small black box with ethernet cable plugged into both sides and a smaller side wire coming off, it appears to be a Power Over Ethernet (PoE) adapter.  With compatible equipment at the other end of the cable, this can power low current draw items from the ethernet cable, thus not requiring any additional power supply.

redpajama_set_name: RedPajamaStackExchange


text:
Q: (plural noun) "are" never "a" good idea. I'd like to know how to explain the grammar in this kind of sentences. It seems to me that the plural noun here works like a collective noun... Or does it purely depend on the context rather than some grammatical rules? Thank you.
For example: (A random quote from an online article)
"While we can't confirm the footage mix-up, these kinds of accusations are never a good thing."

A:
These kinds of accusations are never a good thing

Here, in the above sentence,
Are is used in association with accusations. (accusations = more than 1 accusation)
Whereas, A is used in association with good thing. (not good things but thing)


text:
Q: Turn off PEAR Errors I'm using PEAR's Mail_Queue and unfortunately there are many deprecation warnings (this is a common SO topic). Of course I can modify php's config to silence non-fatal errors but even then it seems that PEAR's mail_mime is outputting header information when it throws an error of any kind.
Is there a simple way to turn off PEAR errors completely so that I can modify header information after making a call to mail_queue?

A: This are not "PEAR errors" that can be turned off. As you said yourself, it's PHP spilling out the warnings, and you can only tell PHP not to output them.
Use the following code before using Mail_Queue to silence the warnings:
error_reporting(error_reporting() & ~E_DEPRECATED & ~E_STRICT);


text:
Q: Apache + SVN + DAV + pwauth + authz = 403 I maintain a group of SVN repositories behind Apache2 with mod_svn_dav, and I'm using pwauth to authenticate users (with mod_authnz_external). I have Require directives for valid-user and group svn. This has worked very well for me, but it has now become necessary to introduce more granular permissions - i.e. to restric access to certain repos only to certain users. From what I understand the best (easiest) way to accomplish this is to use the built in authz functionality, by setting AuthzSVNAccessFile to a file which lists who can access what. This is what I have set out to do. My current site config looks like this (with log config etc removed for clarity):
<VirtualHost *:81>
    <Location />
            allow from 127.0.0.1
            DAV svn
            SVNParentPath /var/svn
            SVNListParentPath On
            AuthType Basic
            AuthName "SVN repository"
            AuthBasicProvider external
            AuthExternal pwauth
            AuthzSVNAccessFile /var/svn/dav_authz
            Require valid-user
            Require group svn
    </Location>
    <IfModule mod_authnz_external.c>
            AddExternalAuth pwauth /usr/sbin/pwauth
            SetExternalAuthMethod pwauth pipe
    </IfModule>
</VirtualHost>

Side note: Yes, *:81 - I actually have this running behind nginx and svn.mydomain.com proxies through that to port 81.
This is what dav_authz looks like:
[/]
myuser = rw
* =

[RepoOne:/]
myuser = rw
* =

[RepoTwo:/]
mysuser = rw
someone = rw
* =

It is my expectation that this will give "myuser" read/write access to everything, "someone" read/write access only to RepoTwo, and everyone else politely told to f-off (even if they are valid users and in the svn group). That is not what happens. No matter what I try, I cannot get anything other than a grumpy 403 from the server. This disappears if I revert to not using AuthzSVNAccessFile, and I can log in as normally (if the user is valid and belongs to svn group) again. I have tried different orders of my directives (putting [/] last for example), different format of user names (someuser, someuser@system, someuser/system, someuser\system), removing the repo configs and just having the [/] rule, setting the [/] rule to * = rw, even emptying the file altogether, giving www-data ownership of dav_authz, etc, etc, etc - each time restarting Apache between changes - each time getting the same 403. Apache logs show myuser accessing the site, and the 403 response, error log shows nothing other than my Apache restarts.
I'm out of ideas and need help! Can you?
JS

A: Some notes (from Path-Based Authorization SVNBook chapter):

*

*Restrictions are inherited from parent to child

*No mentions of user means "no access"

i.e you have to add users only in roots, where you redefine access-level. This I way I'll try something like
[/]
myuser = rw

[RepoTwo:/]
someone = rw

Unrelated: I prefer for readability and manageability operate by groups inside sections of AuthzSVNAccessFile, not users, even if group at some moment is single-user


text:
Q: How do I obtain a shorter output (ciphertext) result from RSA 1024-bit encryption? I understand that the output of RSA encryption will be equal to the length of the key's modulus (128 bytes in this case). The code for my RSA encryption is:
public byte [] RSAEncrypter () throws Exception {
  byte[] inBytes = textfield1.getString().getBytes();
  if (newRSApubKey == null){
    throw new Exception("Generate RSA keys first!");
  }
  AsymmetricBlockCipher eng = new RSAEngine();
  eng = new PKCS1Encoding(eng);
  eng.init(true, newRSApubKey);
  return eng.processBlock(inBytes, 0, inBytes.length);
}

I processed the resulting output using hex encoding to obtain 256 characters as follows;
textfield2.setString(new String(hex.encode(eng.processBlock(inBytes, 0,
inBytes.length))));

I processed the same output using base64 encoding to obtain 172 characters as follows;
textfield3.setString(new String(Base64.encode(eng.processBlock(inBytes, 0,
inBytes.length))));

However, I saw a PDF available here in which the authors were able to obtain 128 characters; even though they did not mention how this is arrived at. Please, I think it's as a result of the encoding (right?) used. What encoding alternative do I have? Or what do I do to this line of code to achieve an output of of at least 128 characters?

A: The only way to get 128 characters is to treat each byte as if it were a character. In that case you must allow characters that are outside of the printable range, so you must allow everything below 0x20 and 7F. You could get this by using a C / C++ array of characters (char* or char[]) and storing the length, as C does not separate between characters and bytes. So in that sense it may just be a linguistic confusion.


text:
Q: Are there any other methods to convert Span Bytes into a Convertable base64? Span<byte> MySpan = stackalloc byte[] { 12, 21, 32 };
MessageBox.Show(Convert.ToBase64String(MySpan.ToArray()));

This block of code is the method I tried
with success, but ToArray allocates memory, for this
I want to find a way to be able to convert the Span of Bytes
into a Convertable base64 or atleast ToList since has a more flexible constraint. Is there any way to do this?
Without the use of the ToArray method, I'm very new to Span by the way Thank you in advance.

A: .Net 4.8 does not contain methods supporting Span/Memory, since these where added later. So your options would be

*

*Update your code to .Net core 2.1.

*Find third party implementation.

*Write your own ToBase64 method.

*Reuse buffers

With regard to the forth point, if you have any memory issue it is probably because you are doing this repeatedly. If so it is usually a good idea to reuse buffers as much as possible. So you can use Span.CopyTo to copy your data from one span to a span wrapping your buffer. You can then use one of the ToBase64String overloads that takes a length to specify how many bytes to convert. But even if you do this the strings will also need allocation, so you might want something like the Base64.EncodeToUtf8 method in .Net core 2.1.


text:
Q: Theme not applied on custom view (Android) I'm making a view which I'm going to use as a background for various other views. It could contain a TextView, a Button, a LinearLayout etc.
Based on the selected theme (the app allows you to change themes while running) the background image of this view should be different. However, nothing seems to happen. The background is not set. It works on a "native" View (like TextView or Button)
View (note: I've played around and changed super class a few times in order to get it working):
public class HorizontalContainerBar extends TextView
{
    public HorizontalContainerBar(Context context)
    {
        super(context);
    }

    public HorizontalContainerBar(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public HorizontalContainerBar(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
    }
}

This is part of themes.xml:
<style name="Theme" parent="android:style/Theme">`
        <item name="android:windowTitleSize">20dip</item>
        <item name="horizontalContainerBarStyle">@style/horizontal_container_bar_first</item>
</style>
<style name="Theme.First">
        <item name="horizontalContainerBarStyle">@style/horizontal_container_bar_first</item>
</style>

This is part of styles.xml:
<style name="horizontal_container_bar" parent="@android:style/Widget.Button">
    <item name="android:padding">10dp</item>
    <item name="android:textColor">#ffffff</item>
    <item name="android:gravity">center_vertical|left</item>
</style>

<style name="horizontal_container_bar_first" parent="@style/horizontal_container_bar">
    <item name="android:background">@drawable/panel_first</item>
</style>

This is a part of the attrs.xml:
<attr name="horizontalContainerBarStyle" format="reference"/>

(not inside a declare-stylable tag - but it used to be)
This is inside my layout file:
<com.myapp.views.HorizontalContainerBar android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:text="hello">
</com.myapp.views.HorizontalContainerBar>

Does anyone have any idea what I'm doing wrong here?


text:
Q: plugins loader if one server is down I don't know to give a title with it but i just want to explain it through my example.
I have a problem like this now. I get all my third party libraries from the cdn site like google..
Example:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
My problem is if ever there is an Internet failure my site will be affected because i can't get my third party libraries..
I think that its better for me to have an alternative source which is local sources..
But how to switch to local sources (like http://localhost:123/jquery/) when ever there is downtime in my Internet so that my site will not be affected even if there is an Internet downtime.
The reason I want to use the cdn like google because of bandwidth issues...
Please give me an idea..
Actually I read about Yepnope.js but its not clear to me if it is the solution to my problem. Is anyone has an idea?

A: You will need a copy of the library on your computer of course and you can also put one on your server in case the CDN goes down (unlikely with Google!).
 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
 <script>window.jQuery || document.write('<script src="path-to-your-local-copy/jquery-1.11.1.min.js"><\/script>')
</script>


text:
Q: UITableView not interacting after modyifing the bounds on a UIModalPresentationCustom Basically, I am trying to present a custom modal view with a specific size and position since I was able to manage this through popover on iOS 7. But on iOS it seems they change things.
I manage to achieve this with the following:
Presentation:
            UpViewController *upViewController = [[UpViewController alloc] init];
            upViewController.delegate = self;

            UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:upViewController];

            navigationController.modalPresentationStyle = UIModalPresentationCustom;

            [self presentViewController:navigationController animated:YES completion:nil];

In UpViewController.m:
- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];

    self.navigationController.view.superview.bounds = CGRectMake(-350, -30, 320, screenSize.height-(44+20));

}

My problem is after my modal view has been presented. We cannot interact with the UITableView that has been added to the view. Anyone has encounter this problem?

A: Seems I found my own solution
instead of setting the bounds, I set the navigationController.view.frame:
- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];

    self.navigationController.view.frame = CGRectMake(screenSize.width-320, 44, 320, screenSize.height-(44));

}


text:
Q: Get sha of the last commit before pull After pull, git lists the files modified since the last pull.
The question is, how to get this list after some more work was done on local repo.
e.g.
$ git checkout feature/default2
$ git pull
Updating 5420c70..b8eec49
Fast-forward
 application/configs/application.ini                                 |   1 +
 application/modules/product/forms/Search.php                        |   3 ++
 public/themes/default/bootstrap/buttons.less                        |  25 -----------
 public/themes/default/css/cmspanel.css                              | 234 ++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------------------------
 public/themes/default/css/products.css                              |  57 ++++++++++++++++++++----
 public/themes/default/css/style.css                                 | 270 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------------------------------------
 public/themes/default/gfx/icons/menu-drop-dark.png                  | Bin 0 -> 160 bytes
 public/themes/default/gfx/icons/more.png                            | Bin 0 -> 120 bytes
 public/themes/default/layouts/scripts/footer.phtml                  |  26 ++++++++++-
 public/themes/default/layouts/scripts/gallery.phtml                 |   2 +
 public/themes/default/layouts/scripts/home.phtml                    |   2 +
 public/themes/default/layouts/scripts/layout.phtml                  |   2 +
 public/themes/default/layouts/scripts/products.phtml                |  22 ++++-----
 public/themes/default/less/cmspanel.less                            |  26 +++++++++++
 public/themes/default/less/nav.less                                 |   4 +-
 public/themes/default/less/products.less                            |  61 +++++++++++++++++++++----
 public/themes/default/less/style.less                               |  59 ++++++++++++++++++++++---
 public/themes/default/less/widgets.less                             |  37 +++++++++++++++-
 public/themes/default/modules/cms/scripts/widgets/random.phtml      |   6 +--
 public/themes/default/modules/default/scripts/widgets/submenu.phtml |   2 +-
 public/themes/default/modules/product/scripts/index/view.phtml      |  44 +++++++++---------
 public/themes/default/modules/product/scripts/widgets/search.phtml  |  16 +++++++
 22 files changed, 584 insertions(+), 315 deletions(-)
 create mode 100644 public/themes/default/gfx/icons/menu-drop-dark.png
 create mode 100644 public/themes/default/gfx/icons/more.png

The 5420c70 is the state before pull.
How to determine that 5420c70 sha?
If I'm correct, the ORIG_HEAD is the state before the last pull (any pull, not the pull which introduced some changes).
Im looking for some magic alias like git checkout SOME_HEAD to do git checkout 5420c70 for me.
I'm trying to setup a git review alias, which should diff all the files modified since the last pull, which was not up-to-date.
In a basic case, something like this works:
git pull
# lists some chanes file
git diff --name-status ORIG_HEAD..
# diffs them

but I'm looking for something like this:
git pull
# lists some chanes file
git pull
# up-to-date, no changes
git diff --name-status ORIG_HEAD..
# diffs the files since the last pull which was not up-to-date

A: I think you could check reflog, i.e. HEAD@{1}, e.g. it diff --name-only ..HEAD@{1}.
As another option, you could do git fetch then do git log -p ..@{upstream} to see upcoming changes, and then git merge FETCH_HEAD to bring the changes into your working copy.

A: After looking in the reflog, I've found that this is what I was looking for:
git reflog --oneline | grep -m 1 "pull " | cut -d' ' -f1)

This will return just one sha of the previous successfull pull, which may be used in show, log, diff etc.

A: If i understand what you want, git pull isnt the command you need, You should look at git fetch
when that has completed you can do
git diff HEAD...origin  note you need 3 dots instead of the usual 2
That will give  a single diff of all changes. When your happy you can merge them in the usual way with git merge or by using git cherry-pick to select only certain ones

A: git log -n 1 --pretty=format:%H


text:
Q: waiting for run Saga middleware i have a problem with redux-saga actually in my configureStore.js i have :
sagaMiddleware.run(mysaga);

I want a code execute only when my saga returns something

A: If I understand what you said even if you did not say much, the solution you want is actually:

reduxSagaMiddleware return a task:
Middleware.run (saga, ... args)

Dynamically run saga. Can be used to run Sagas only after the applyMiddleware phase.
... the method returns a Task descriptor.

from redux-saga
So you will have a task.done that return a promise and you can do:
task.done.then(() => {
      // this code will be executed only when the saga is finished
});


text:
Q: Integer Array to Base64 String So I am struggling a bit to convert some code written in java to APEX.
The struggle here is that I have an integer array as one of my encryption key, it looks something similar to this below:
[242, 2, 56, 23, 15, 5, 12, 105, 19, 47, 116, 89, 25, 152, 200, 215]

and in java I convert it to 128 bytes
[-14, 2, 56, 23, 15, 5, 12, 105, 19, 47, 116, 89, 25, -104, -56, -41]

and then to Base64 I get 8gI4Fw8FDGkTL3RZGZjI1w== that is then used as the IvParameterSpec() in the jave Crypto package.
However, I can't figure out to save my life how to do that in apex? The integer array will be an initialization vector for "AES128" encryption.
I tried this:
List<Integer> values256 = new List<Integer>{242, 2, 56, 23, 15, 5, 12, 105, 19, 47, 116, 89, 25, 152, 200, 215};
List<Integer> values128 = new List<Integer>();
    for(Integer bytes : values256){

        if(bytes > 127){
            values128.add((256-bytes)*-1);
        }else{
            values128.add(bytes);
        }
    }

String encodedString = String.fromCharArray(values128);
String myBase64String = EncodingUtil.base64Encode(Blob.valueof(encodedString));
System.Debug(values128);
System.Debug(myBase64String);

But my base64 string looks like this: 77+yAjgXDwUMaRMvdFkZ776Y77+I77+X which is very different from what I get in Java. Any idea on what I am doing wrong?
EDIT: I wanted to add that I am really new to the world of encryption so I may be missing some obvious fundamentals! So feel free to correct me...

A: String.fromCharArray is going to create a UTF-8 encoded string, which will alter the bytes in the stream. For example, 242 will be encoded as two bytes instead of one. Any value outside 0-127 will be encoded as multiple bytes when using this function, including all negative integers. Since we can't really work with binary data directly in Apex Code, just store the base-64 encoded value directly in a string or some persistent storage (e.g. a custom setting).

public class Base64 {
    static String[] codes = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split('');

    // Encodes integers 0-255 into base 64 string
    public static String encode(Integer[] source) {
        // Preallocate memory for speed
        String[] result = new String[(source.size()+2)/3];
        // Every three bytes input becomes four bytes output
        for(Integer index = 0, size = source.size()/3; index < size; index++) {
            // Combine three bytes in to one single integer
            Integer temp = (source[index]<<16|source[index+1]<<8)|source[index+2];
            // Extract four values from 0-63, and use the code from the base 64 index
            result[index]=codes[temp>>18]+(codes[(temp>>12)&63])+(codes[(temp>>6)&63])+codes[temp&63];
        }
        if(Math.mod(source.size(),3)==1) {
            // One byte left over, need two bytes padding
            Integer temp = (source[source.size()-1]<<16);
            result[result.size()-1] = codes[temp>>18]+(codes[(temp>>12)&63])+codes[64]+codes[64];
        } else if(Math.mod(source.size(),3)==2) {
            // Two bytes left over, need one byte padding
            Integer temp = (source[source.size()-2]<<16)|(source[source.size()-1]<<8);
            result[result.size()-1] = codes[temp>>18]+(codes[(temp>>12)&63])+(codes[(temp>>6)&63])+codes[64];
        }
        // Join into a single string
        return String.join(result, '');
    }
}

A: I took the code from @sfdcfox to use in my own project, and was getting out an almost correct answer.  I tweaked the code, and just wanted to post it here for anyone else that might want it.
public class Base64 {
    static String[] codes = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split('');

    // Encodes integers 0-255 into base 64 string
    public static String encode(Integer[] source) {
        Integer length = source.size();
        // Preallocate memory for speed
        String[] result = new String[(length+2)/3];
        // Every three bytes input becomes four bytes output
        Integer size = length - Math.mod(length, 3);
        Integer resultIndex = 0;
        for(Integer index = 0; index < size;) {
            // Combine three bytes in to one single integer
            Integer temp = (source[index++]<<16|source[index++]<<8)|source[index++];
            // Extract four values from 0-63, and use the code from the base 64 index
            result[resultIndex++]=codes[temp>>18]+(codes[(temp>>12)&63])+(codes[(temp>>6)&63])+codes[temp&63];
        }
        if(Math.mod(length,3)==1) {
            // One byte left over, need two bytes padding
            Integer temp = (source[length-1]<<16);
            result[result.size()-1] = codes[temp>>18]+(codes[(temp>>12)&63])+codes[64]+codes[64];
        } else if(Math.mod(source.size(),3)==2) {
            // Two bytes left over, need one byte padding
            Integer temp = (source[length-2]<<16)|(source[length-1]<<8);
            result[result.size()-1] = codes[temp>>18]+(codes[(temp>>12)&63])+(codes[(temp>>6)&63])+codes[64];
        }
        String base64Encoded = String.join(result, '');
        // Join into a single string
        return EncodingUtil.base64Decode(base64Encoded);
    }
}


text:
Q: Redirect any urls to 404.html if not found in urls.py in django How can I redirect any kind of url patterns to a created page "404.html" page if it doesn't exist in the urls.py rather than being shown the error by django.

A: In your views.py, just add the following code (No need to change anything in urls.py).
from django.shortcuts import render_to_response
from django.template import RequestContext

def handler404(request):
    response = render_to_response('404.html', {},
                              context_instance=RequestContext(request))
    response.status_code = 404
    return response

Put a custom 404.html in templates directory.
source : click here

A: There is no need to change anything in your view or url.
Just do these 2 steps, in your settings.py, do the following
DEBUG = False
ALLOWED_HOSTS = ["*"]

And in your app directory (myapp in this example), create myapp/templates/404.html where 404.html is your custom error page. That is it.

A: Make a view that'll render your created 404.html and set it as handler404 in urls.py.
handler404 = 'app.views.404_view'

Django will render debug view if debug is enabled. Else it'll render 404 page as specified in handler404 for all types of pages if it doesn't exist.
Django documentation on Customizing error views.
Check this answer for a complete example.

A: Go to your project settings.py and set DEBUG = True to  DEBUG = False
Then Django redirects all NOT set patterns to not found.
In additional if you want to customize 404 template , in your project urls.py
set
handler404 = 'app.views.404_view'
then in your projects view.py
from django.shortcuts import render_to_response
from django.template import RequestContext

def handler404(request):
    response = render_to_response('404.html', {},
                                  context_instance=RequestContext(request))
    response.status_code = 404
    return response

and Finally, in your templates add 404.html and fill it with what you want to show end user.


text:
Q: Strip special characters from string, retain, alphabets, numbers and punctuation marks I am trying to clean a string from all special characters and retain everything else, including punctuation marks.
mystring = "Q18. On a scale from 0 to 10 where 0 means 'not at all interested' and 10 means 'very interested', how interested are you in helping to address problems that affect poor people in poor countries?"

My effort so far:
newlabel = re.sub('[^A-Za-z0-9]+', ' ', newstring)

Output:
Q18 On a scale from 0 to 10 where 0 means not at all interested and 10 means very interested how interested are you in helping to address problems that affect poor people in poor countries

How can I retain the punctuation marks in the regex I currently have or is there a better solution?

A: Solved,
print (newstring.decode('unicode_escape').encode('ascii','ignore'))

Output:
Q18. On a scale from 0 to 10 where 0 means not at all interested' and 10 means very interested', how interested are you in helping to address problems that affect poor people in poor countries?

A: If all you need to change is to retain the dot than adding it to the regex will solve that.
re.sub('[^A-Za-z0-9\.]+', ' ', mystring)

A: Just add backslash before each punctuation mark in the regular expression .....


text:
Q: Relating input to output with Neural Network and optimizing inputs using Genetic Algorithm I'm currently doing proces optimization for laser cutting - in MATLAB. I am trying to relate the process parameters with the cutting quality such as e.g.:
Inputs (Process parameters)

*

*Cutting speed

*Laser power

*Assist gas pressure

Outputs (Quality parameters)

*

*Cutting depth

*Cutting width

I am first training a Neural Network model in order to predict the cutting quality from the process parameters.
[inputs,targets] = lasercutting_dataset;

nLayers = 2;            % number of hidden layers
trainFcn = 'trainlm';   % Levenberg Marqhart training function

net = fitnet(nLayers,trainFcn);

This works fine, and for now I am not interested in the performance.
Next I want to optimize (maximize) the input parameter cutting speed using Genetic Algorithm. This means my fitness function (object function) is 1/cutting speed.
I have made a matlab function for my fitness function:
function y = fitness(x)

    y = 1/x(1);

end

Next i set the number of design variables and their upper and lower bounds:
nvars = 3;    % Number of variables
LB = [130 8130  4470];   % Lower bound
UB = [175 11255 8250];  % Upper bound

Next i define my constraint on the cutting width (I will be adding one for the depth as well).
function [c, ceq] = constraints(net,x)

    outs = net(x)

    c = [outs(2)+495; outs(2)-505];
    % 495 <= outs
    % outs <= 505

    ceq = [];

end

This function is the one causing problems!
Lastly I make handles for the functions and start the optimization:
[x,fval] = ga(@fitness_func,nvars,[],[],[],[],LB,UB,@(x) ConstraintFunction(net,x));

I have tried defining an input vector for the neural network (net()) inside the constraints function which was independent of x - this worked fine:
dummyInput = [value; value; value];
net(dummyInput);

I'm among others getting the error, that my functions constraints is not getting enough input parameters.
The problem seems to be something with passing the dynamically changing "x" to a function and then predicting on it, using the output for a set of dynamically changing constraints.
Any ideas as to what might be the problem?
I've been using THIS and THIS for inspiration.
Any help is appreciated - sorry for the long questiong. I have several articles on the matter - none of which explains the problem in matlab, merely the procedure.

A: By maximizing 1/x, this will give you the slowest cutting speed for which the constraints hold. I assume you want to maximize the cutting speed, not minimize it.
Also your constraint function is not really valid. Constraints need to be given in the form x <= 0. So if the outputs should be bounded, the constraints become x >= 495 <=> 0 >= 495 - x and x <= 505 <=> x - 505 <= 0
In your function you however write c = [outs(2)+495; outs(2)-505]; which should then rather be c = [495 - outs(2); outs(2) - 505].
Regarding the extra parameter in your function, maybe this doc can be of help.


text:
Q: AG Grid - CellRender - Read CheckBox Value In AG Grid, Using CellRender - I have shown a checkbox in the grid column using the template as shown below
cellRenderer = (params) => {
    if ((params.data.IsReview != undefined) && (params.data.IsReview  == true)) {
        return '<input type="checkbox" class="mycheckbox" ';
    }

Once User select's the checkbox in UI, how do I get the values of the checkbox, Since its not directly bind to grid data model, how can i read the check box value from cell render template?


text:
Q: Use raw SQL in an ORM query Is it possible to make edits or override the ORM's generated SQL with your own raw SQL? Or is the ORM expected to be flexible enough to build pretty much any query I could imagine?
Specifically here's the query I'm trying to make, perhaps it isn't too hard to build via the ORM anyway though I'm not able to see any obvious path to build it. Here's the model:
class AllocationStatus(Base):

    STATUS_RESERVED = 1
    STATUS_RELEASED = 2
    STATUS_CHOICES = (
        (STATUS_RESERVED, "Reserved"),
        (STATUS_RELEASED, "Released"),
    )

    __tablename__ = 'allocation_status'

    id = Column(Integer, primary_key=True)
    allocation_id = Column(Integer, ForeignKey('allocation.id'))
    allocation = relationship('Allocation')
    status = Column(Integer())

The idea is that for a given foreign key ID for allocation_id, I would want to know the latest record in allocation_status.
In order to achieve this in raw SQL, the following query is what I'm aiming for:
SELECT allocation_status.*
FROM allocation_status
LEFT JOIN allocation_status allocation_status2
    ON allocation_status.allocation_id = allocation_status2.allocation_id
    AND allocation_status.id < allocation_status2.id
WHERE allocation_status2.id IS NULL;

A: The answer by @Abdou is the proper way to go, but you could also run your textual SQL using Query.from_statement():
session.query(AllocationStatus).\
    from_statement(text("""
        SELECT allocation_status.*
        FROM allocation_status
        LEFT JOIN allocation_status allocation_status2
               ON allocation_status.allocation_id = allocation_status2.allocation_id
              AND allocation_status.id < allocation_status2.id
        WHERE allocation_status2.id IS NULL;""")).\
    all()

Note the use of text().

A: You can build it by aliasing the Model first and then using that alias as the second table to an outer join.
The following assumes that you already have a session that is bound to a working engine:
from sqlalchemy.orm import aliased
from sqlalchemy import and_

allocation_status2 = aliased(AllocationStatus)
session.query(AllocationStatus).\
    outerjoin(allocation_status2,
              and_(AllocationStatus.allocation_id == allocation_status2.allocation_id,
                   AllocationStatus.id < allocation_status2.id)).\
    filter(allocation_status2.id.is_(None)).all()

I hope this helps.


text:
Q: DateTime.Parse with overflow Is there an alternative to DateTime.Parse that will accept an overflowing date or month like this?
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Tests
{
    [TestClass]
    public class DateTimeTest
    {
        [TestMethod]
        public void TestOverflowOfDay()
        {
            var dt = DateTime.Parse("2020-01-32");

            var str = dt.ToString();

            Assert.AreEqual("2020-02-01 00:00:00", str);
        }
    }
}

This code results in a System.FormatException on the DateTime.Parse line.

String was not recognized as a valid DateTime

Can I parse the string allowing overflow so it will be treated as "2020-02-01"?
That seems to be standard in other languages/implementations.

A: I don't know how you could do this without rolling your own. If you know the format of your datetimes, you can do the following, or something similar.
        static void Main(string[] args)
        {
            var date = GetCustomDateTime("2020-01-32");

            Console.WriteLine(date.ToString("yyyy-MM-dd HH:mm:ss"));
        }

        private static DateTime GetCustomDateTime(string dateTimeString)
        {
            var split = dateTimeString.Split('-');
            var yearMonth = DateTime.ParseExact($"{split[0]}-{split[1]}", "yyyy-MM", CultureInfo.InvariantCulture);

            return yearMonth.AddDays(int.Parse(split[2])-1);
        }

This is not affected by daylight savings time, sourced here.

Arithmetic or comparison operations on local date and time values do
not consider whether a particular value is ambiguous or invalid, nor
do they take account of the effect of any adjustment rules that result
from the local time zone's transition to or from daylight saving time.


text:
Q: Ошибка в инициализации локальной переменной Ошибка: error C4700: использована неинициализированная локальная переменная "in". Как устранить ошибку?
void write_inverse_list(LIST* head)
{
    FILE* in;
    LIST* p;
    fclose(in);

    in = fopen("C:\\Users\\Admin\\Desktop\\in.txt", "w");
    if (head)
    {
        while (head->next)
        {
            p = head;
            fprintf(in, "%s ", p->word);
            head = p->next;
            delete p->word;
            delete p;
        }
        fprintf(in, "%s", head->word);
        delete head->word;
        delete head;
        head = NULL;
    }
        else
        {
         fclose(in);
         in = fopen("C:\\Users\\Admin\\Desktop\\in.txt", "w");
        }
         fclose(in);
}
int main()
{
    LIST* head = NULL;
    head = read_list(head);
    head = osnova(head);
    write_inverse_list(head);
}

A: FILE* in;
LIST* p;
fclose(in);

Скажите, зачем вы закрываете то, чего не открывали? Вот здесь и есть источник проблемы - вы закрываете нечто, что никакого отношения к какому-то файлу не имеет - in не имеет никакого значения.
Для того, чтобы устранить эту конкретную ошибку - достаточно удалить строку fclose(in);.
Еще - все же желательно проверять, что файл открылся, т.е. значение in после fopen.
И совершенно непонятны вот эти телодвижения -
else
{
    fclose(in);
    in = fopen("C:\\Users\\Admin\\Desktop\\in.txt", "w");
}
fclose(in);

Зачем? Какой в этом смысл?...


text:
Q: Insert GEOMETRY value using PostgreSQL 9.3 I want to insert GEOMETRY values into a table. For which I have a table with three columns as shown below:
Table: geo
create table geo
(
  p1 float,
  p2 float,
  Paths GEOMETRY
);

Input values: I have following values
p1 = 22.9901232886963
p2 = 87.5953903123242

In SQL Server I used this:
INSERT INTO geo(Paths)
VALUES (geometry = geometry::STGeomFromText('POINT (22.9901232886963 87.5953903123242)'
,4326);

Question: Is there any function of GEOMETRY to calculate points in PostgreSQL 9.3 version?

A: This works for me by referring: http://www.postgresql.org/docs/current/static/functions-geometry.html.
The function:
point(point(double precision, double precision);

So I need to convert the function: using ::geometry
Finally the insert statement looks like:
insert into geo values(22.9901232886963 87.5953903123242,
point(22.9901232886963 87.5953903123242)::geometry);

Am I right?


text:
Q: Swift Type does not conform to protocol The error occurs on the class VendingMachine: VendingMachineType{}
I can't seem to find the discrepancy that is causing the problem. Did I miss something or am I looking in the wrong area?
If I understand protocols correctly it essentially determines a blue-print for classes to follow and as far as I have looked I cannot find where the function does not follow the blue-print that the protocol sets.
Protocol:
protocol VendingMachineType {
    var selection: [VendingSelection] { get }
    var inventory: [VendingSelection: ItemType] { get set }
    var amountDeposited: Double { get set }

    init(inventory: [VendingSelection: ItemType])
    func vend(selection: VendingSelection, quantity: Double) throws
    func deposit(amount: Double)
    func itemForCurrentSelection(selection: VendingSelection) -> ItemType?
}

Class:
class VendingMachine: VendingMachineType {
    let selection: [VendingSelection] = [.Soda, .DietSoda, .Chips, .Cookie, .Sandwich, .Wrap, .CandyBar, .PopTart, .Water, .FruitJuice, .SportsDrink, .Gum]

    var inventory: [VendingSelection: ItemType]
    var amountDesposited: Double = 10.0

    required init(inventory: [VendingSelection : ItemType]) {
        self.inventory = inventory
    }

    func vend(selection: VendingSelection, quantity: Double) throws {
        guard var item = inventory[selection] else {
            throw VendingMachineError.InvalidSelection
        }

        guard item.quantity > 0 else {
            throw VendingMachineError.OutOfStock
        }
        //at this point we have an item and a quantity implement a cancel button as homework here.

        //time to reduce quantity by amount purchased

        item.quantity -= quantity
        inventory.updateValue(item, forKey: selection)

        //here we are checking to see if we have enough money and throwing an error if they do not
        let totalPrice = item.price * quantity
        if amountDesposited >= totalPrice {
            amountDesposited -= totalPrice
        } else {
            let amountRequired = totalPrice - amountDesposited
            throw VendingMachineError.InsufficientFunds(required: amountRequired)
        }
    }

    func itemForCurrentSelection(selection: VendingSelection) -> ItemType? {
        return inventory[selection]
    }

    func deposit(amount: Double) {
        amountDesposited += amount
    }
}

Any help or pointers in the correct direction is appreciated.

A: I copied your code into IBM Sandbox, and had to make a few simplifications since you have not pasted all of the code. Nevertheless, I got the same first error. The second error is what explains the issue:
protocol requires property 'amountDeposited' with type 'Double'

You have misspelled the property in your class definition.

A: Your VendingMachine's amountDeposited is a stored property. But protocol can declare computed properties only.


text:
Q: Percentage Problem: Can someone help me with finding the right percentage? In this article, we have the data that police officers have around 50 million interactions with the public and 1000 Fatal shootings but later they say "... those interactions led to fatal shootings about 0.00002 percent of the time."
How exactly does it work? Shouldn't it be:
(1000/50Mil)*100 = 0.002% instead?

A: $1000$ over $50000000$ is $0.00002$, but just like my students do, they forget, hopefully just because of math ignorance, that percentage is over $100$
It's like saying that $150$ over $300$ students are girls, thus the percentage of girls is $0.5\%$
The correct percentage of fatal shootings is $0.002\%$, like you said correctly in your post.
Remark. I find tons of math mistakes on the papers. The most recent? On a national famous journal  in an article about smoking they said that "[...] yearly  17 millions euro go up in smoke." A mistake is a MISTAKE if you miss 3 orders of magnitude...


text:
Q: Checking Vegetation height accuracy in urban areas I have digitized vegetation as polygons covering the canopy of trees in urban areas. Are there any suggestions to check the accuracy of height. I have been manually validating with visual checks, comparing to google earth street view with kmz/kml, though these check are time consuming its the most reliable so far. Please advise if there are easier alternatives.

A: Google Earth uses SRTM DEM data as source of elevation for most part of the world (see here). DEM is mostly DTM, do not considers any object over the surface. So Google Earth might not be a good source for you. I'd recommend few ideas,

*

*use high-res elevation data (ie. LiDAR)

*volumetric shadow analysis

*in-situ height information (ie. survey or inventory data)

*high-res SAR Interferometry

In my opinion, a carefully sampled survey data might be a better source of information.


text:
Q: How to order script input files by their timestamp? I am creating a bash script in which I need to check timestamps of input data and order the files by their timestamp and finally merge them into one big data file. Timestamps can be totally random but they have to contain year, month, day and time - examples :
[2016-05-14 11:17:01] 0.000000
[11:17:01 2016-05-14] 0.000000
[2016 11:17:01 05-14] 0.000000

There will be more then 100 entries per second, so I have to choose a method that will check timestamps of two files and sort them accordingly. I have created something VERY provisional - it just appends the files :
for var in "$@"
do
    cat "$var" >> $TMPDIR/input #$TMPDIR/input is the big file
done

I don't necessarily want exact commands, an idea how to do that would be also perfect.

A: In linux you can get access/modify/change timestamp, which should be helpful.
Hope that helps, you can find commands which maintain file stats :)


text:
Q: My php code gets commented out by the browser
Possible Duplicate:
PHP: Code gets turned into HTML <!— Comments? -->

I have some very, very simple php code.

        <title>Something</title>

Something

        <?php
            $val = $_POST['a'];
            echo 'Value: ' . $val . '
;
        ?>

When I press the submit button in an form I've made, the browser comments out the php code like this:

Anyone knows what this is?

A: Are you using CMS?
This looks like Joomla behavour for PHP code when you just insert it in template without using special module.

A: PHP is a server-side language. It is evaluated on the server, and the results of the evaluation replace the code itself.
This is by design and it would terrible if the PHP source code for every page were included in the HTML comments (eg you can see database passwords, etc.).
You cannot see PHP from the client (i.e. HTML source).

A: Yes, you're missing a closing ' at the end of your echo statement.


text:
Q: Unable to write in a file after django app deployment on aws ec2 using nginx and gunicorn I have deployed my Django online judge project on AWS EC2 using Nginx and Gunicorn I am taking user code in a string variable and writing it to a file in my project directory and it's working fine in development server but after deployment the program unable to write code in the file. for eg:-
lets say a user have submitted code in c++ language so I took that code in a string variable and I open the my .cpp file via open() function in my views.py and writing the code in it.
filepath = os.path.join(settings.BASE_DIR, 'language', 'forcpp.cpp')
cpp_code=open(filepath,"w")
cpp_code.write(user_problem_code)
cpp_code.close()

I have tried to modify path in every possible way but got unlucky in every try
I have my files in language folder in which I want to write user submitted code and my views.py are in problempg application
my project directory structure:
online_judge_project/
                    account/
                    homesrc/
                    language/ /* directory containing files in which I want to write */
                            forcpp.cpp
                    media/
                    oj/
                      settings.py
                    problempg/  /* application containing views.py */
                             views.py
                    static/
                    staticfiles/
                    template/
                    manage.py

settings.py
"""
Django settings for oj project.

Generated by 'django-admin startproject' using Django 4.0.5.

For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""

from importlib.resources import path
from pathlib import Path
import os
from .info import *

EMAIL_USE_TLS = EMAIL_USE_TLS
EMAIL_HOST = EMAIL_HOST
EMAIL_HOST_USER = EMAIL_HOST_USER
EMAIL_HOST_PASSWORD = EMAIL_HOST_PASSWORD
EMAIL_PORT = EMAIL_PORT
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATE_DIR=os.path.join(BASE_DIR,'template')
FILES_DIR=os.path.abspath(os.path.join(BASE_DIR,'language'))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ['SECRET_KEY']

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ["localhost","<MY_IP_ADDRESS>"]

# Application definition

INSTALLED_APPS = [
    'widget_tweaks',
    'account.apps.AccountConfig',
    'problempg.apps.ProblempgConfig',
    'homescr.apps.HomescrConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'ckeditor',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'oj.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'oj.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_ROOT= os.path.join(BASE_DIR,'staticfiles')
STATIC_URL = 'static/'
MEDIA_ROOT= os.path.join(BASE_DIR,'media')
MEDIA_URL='/media/'
LOGOUT_REDIRECT_URL = "index"

STATICFILES_DIRS=[
    os.path.join(BASE_DIR, 'static'),
]

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

from django.contrib.messages import constants as messages

MESSAGE_TAGS = {
    messages.DEBUG: 'alert-info',
    messages.INFO: 'alert-info',
    messages.SUCCESS: 'alert-success',
    messages.WARNING: 'alert-warning',
    messages.ERROR: 'alert-danger',
}

may be the path I am using in development is different in EC2 server. I have develop this project on a windows machine and I am deploying it on Ubantu EC2 server or it's due to Nginx?


text:
Q: Compare methods to terminate running a function after time period I have a program, which opens a lot of urls and downloads pictures .
I have a function of the program, which manages link's opening and pictures downloading, which contains a for loop and performs some operations on the priority queue. I want to run this function, but no longer than the set time period. For example if this function is running longer than 1 hour I want to terminate it and run the rest of the program (other functions).
I was trying to find some solutions, and I found two question here on stack.
The first solution use only time module First solution
The second use also the multiprocessing module
Second solution. Can some one suggest which one will be more appropriate to use in my program? I will write a pseudocode of my function:
def fun():
 for link in linkList:
   if link not in queue:
     queue.push(link)
   else:
     queue.updatePriority(link)
 if queue:
   top = queue.pop()
   fun(top)

This function is called in other function:
def run(startLink):
 fun(startLink)
And the run() function is called in other module.
Which method is better to use with a program which contains a lot of modules and performs a lot of

A: The asyncio module is ideal for this task.
You can create a future, then use asyncio.wait which supports a timeout parameter.

A: Using multiprocessing here would be a little bit tricky, because fun is consuming a priority queue (I'm assuming a Queue.PriorityQueue) that is coming from some other part of the program. That queue cannot easily be passed between processes - you would need to create a custom multiprocessing.BaseManager subclass, register the Queue.PriorityQueue class with it, and start up the Manager server, instantiate a PriorityQueue on the server, and use a Proxy to that instance everywhere you interact with the queue. That's a lot of overhead, and also hurts performance a bit.
Since it appears you don't actually want any concurrency here - you want the rest of the program to stop while fun is running - I don't think there's a compelling reason to use multiprocessing. Instead, I think using the time-based solution makes more sense.


text:
Q: use of declared types in WCF I am using [ServiceKnownType(typeof(Document))] for every  operation contract in my WCF interface class.I want to avoid using this KnownType.Instead use the DeclaredTypes in web.config. can i get any help on how to configure the DeclaredTypes in Web.config file.

A: The option to add known types in configuration only applies to data contracts, not to service contracts. If the type of which Document derives from is always the same (and not System.Object), you can do that by using the config option (more info at MSDN), which would look something like this:
<configuration>
  <system.runtime.serialization>
    <dataContractSerializer>
      <declaredTypes>
        <add type="MyNamespace.DocumentBase, MyAssembly, Version=...">
          <knownType type="MyNamespace.Document, MyAssembly, Version=..."/>
        </add>
      </declaredTypes>
    </dataContractSerializer>
  </system.runtime.serialization>
</configuration>

If this doesn't apply, then another option would be to pass this option to the DataContractSerializer constructor, which you can do by using some behavior which can be applied to the whole service. The post to replace the DataContractSerializer with the NetDataContractSerializer is a good starting point for you (instead of replacing the serializer, just return another DataContractSerializer instance, but always adding typeof(Document) to the known types passed to it.


text:
Q: Why is the Connection header not being set on my HttpListener response? I am attempting to create a C# web socket server - I know this is re-inventing the wheel a little bit but its more of a coding excercise than for a real-life application.
I have created the Listener and am able to recieve requests, I have read the spec for websockets and have managed to setup the initial headers for the handshake, but i cannot seem to set the "Connection" header?
Here is the code i am using upon recieving a request and validating it is a new websocket upgrade handshake;
string wsGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
string retCon = ctx.Request.Headers["Sec-WebSocket-Key"] + wsGuid;
Console.WriteLine("Upgrade, key recieved: " + ctx.Request.Headers["Sec-WebSocket-Key"]);
System.Security.Cryptography.SHA1 s = new System.Security.Cryptography.SHA1CryptoServiceProvider();
byte[] retBy = s.ComputeHash(Encoding.ASCII.GetBytes(retCon));
string retStr = Convert.ToBase64String(retBy);
Console.WriteLine("Return string: " + retStr);
ctx.Response.Headers.Add("Sec-WebSocket-Accept", retStr);
ctx.Response.Headers.Add("Access-Control-Allow-Origin", "*");
ctx.Response.Headers.Add("Upgrade", "WebSocket");
ctx.Response.Headers.Add("Connection", "Upgrade");
ctx.Response.StatusCode = 101;
ctx.Response.OutputStream.Flush();
ctx.Response.OutputStream.Close();

This works fine, but when i attempt to open a websocket connection in javascript running on chrome i get the error
WebSocket connection to 'ws://localhost:4455/' failed: Error during WebSocket handshake: 'Connection' header is missing
Upon inspecting the response headers in Fiddler i can see the response looks like this;
HTTP/1.1 101 Switching Protocols
Upgrade: WebSocket
Content-Length: 0
Server: Microsoft-HTTPAPI/2.0
Sec-WebSocket-Accept: k3N0odnsp2f9eanXsFN7EILQExo=
Access-Control-Allow-Origin: *
Date: Mon, 17 Aug 2015 12:30:05 GMT
EndTime: 13:30:05.865
ReceivedBytes: 0
SentBytes: 0

which of course is infact missing the Connection header, even though i specified to add it in the C# code? What is going on here, am i adding headers wrong or am i unable to modify the Connection header using this method?
Any help would be appreciated, thanks.


text:
Q: How to build the war file for a Clojure Noir Web application? I was able to use these commands to generate and run a sample web app from instrcution on this web site
https://github.com/ibdknox/lein-noir
lein new noir my-project-name
lein run

( I am using Leiningen 2.0.0-preview10 on Java 1.7.0_09 Java HotSpot(TM) Client VM )
The starter web app does run ok but I want to generate the war file which I can deploy manually to my application server (Websphere).
What command or configuration for Leingen 2 is needed  to generate a war file for a Noir project?
To clarify, this command "lein new noir webpoc2"  generate a noir project with this .clj file
(defproject webpoc1 "0.1.0-SNAPSHOT"
            :description "FIXME: write this!"
            :dependencies [[org.clojure/clojure "1.4.0"]
                           [noir "1.3.0-beta3"]]
            :main webpoc1.server)

If I add Ring to the cl file
:ring {
                   :handler webpoc1.server/handler

}

, and run lein ring uberwar, I get this :
Exception in thread "main" java.lang.RuntimeException: No such var: webpoc1.server/handler, compiling:(
/servlet.clj:1)
        at clojure.lang.Compiler.analyze(Compiler.java:6281)
        at clojure.lang.Compiler.analyze(Compiler.java:6223)
        at clojure.lang.Compiler$InvokeExpr.parse(Compiler.java:3497)
        at clojure.lang.Compiler.analyzeSeq(Compiler.java:6457)
        at clojure.lang.Compiler.analyze(Compiler.java:6262)
        at clojure.lang.Compiler.analyze(Compiler.java:6223)
        at clojure.lang.Compiler$BodyExpr$Parser.parse(Compiler.java:5618)
        at clojure.lang.Compiler$FnMethod.parse(Compiler.java:5054)
        at clojure.lang.Compiler$FnExpr.parse(Compiler.java:3674)
        at clojure.lang.Compiler.analyzeSeq(Compiler.java:6453)
        at clojure.lang.Compiler.analyze(Compiler.java:6262)
        at clojure.lang.Compiler.analyzeSeq(Compiler.java:6443)
        at clojure.lang.Compiler.analyze(Compiler.java:6262)
        at clojure.lang.Compiler.analyze(Compiler.java:6223)
        at clojure.lang.Compiler$InvokeExpr.parse(Compiler.java:3548)
        at clojure.lang.Compiler.analyzeSeq(Compiler.java:6457)
        at clojure.lang.Compiler.analyze(Compiler.java:6262)
        at clojure.lang.Compiler.analyze(Compiler.java:6223)
        at clojure.lang.Compiler$InvokeExpr.parse(Compiler.java:3497)
        at clojure.lang.Compiler.analyzeSeq(Compiler.java:6457)
        at clojure.lang.Compiler.analyze(Compiler.java:6262)
        at clojure.lang.Compiler.analyze(Compiler.java:6223)
        at clojure.lang.Compiler$BodyExpr$Parser.parse(Compiler.java:5618)
        at clojure.lang.Compiler$FnMethod.parse(Compiler.java:5054)
        at clojure.lang.Compiler$FnExpr.parse(Compiler.java:3674)
        at clojure.lang.Compiler.analyzeSeq(Compiler.java:6453)
        at clojure.lang.Compiler.analyze(Compiler.java:6262)
        at clojure.lang.Compiler.analyzeSeq(Compiler.java:6443)
        at clojure.lang.Compiler.analyze(Compiler.java:6262)
        at clojure.lang.Compiler.access$100(Compiler.java:37)
        at clojure.lang.Compiler$DefExpr$Parser.parse(Compiler.java:518)
        at clojure.lang.Compiler.analyzeSeq(Compiler.java:6455)
        at clojure.lang.Compiler.analyze(Compiler.java:6262)
        at clojure.lang.Compiler.analyze(Compiler.java:6223)
        at clojure.lang.Compiler.compile1(Compiler.java:7030)
        at clojure.lang.Compiler.compile1(Compiler.java:7025)
        at clojure.lang.Compiler.compile(Compiler.java:7097)
        at clojure.lang.RT.compile(RT.java:387)
        at clojure.lang.RT.load(RT.java:427)
        at clojure.lang.RT.load(RT.java:400)
        at clojure.core$load$fn__4890.invoke(core.clj:5415)
        at clojure.core$load.doInvoke(core.clj:5414)
        at clojure.lang.RestFn.invoke(RestFn.java:408)
        at clojure.core$load_one.invoke(core.clj:5227)
        at clojure.core$compile$fn__4895.invoke(core.clj:5426)
        at clojure.core$compile.invoke(core.clj:5425)
        at user$eval3.invoke(NO_SOURCE_FILE:1)
        at clojure.lang.Compiler.eval(Compiler.java:6511)
        at clojure.lang.Compiler.eval(Compiler.java:6500)
        at clojure.lang.Compiler.eval(Compiler.java:6501)
        at clojure.lang.Compiler.eval(Compiler.java:6477)
        at clojure.core$eval.invoke(core.clj:2797)
        at clojure.main$eval_opt.invoke(main.clj:297)
        at clojure.main$initialize.invoke(main.clj:316)
        at clojure.main$null_opt.invoke(main.clj:349)
        at clojure.main$main.doInvoke(main.clj:427)
        at clojure.lang.RestFn.invoke(RestFn.java:421)
        at clojure.lang.Var.invoke(Var.java:419)
        at clojure.lang.AFn.applyToHelper(AFn.java:163)
        at clojure.lang.Var.applyTo(Var.java:532)
        at clojure.main.main(main.java:37)
Caused by: java.lang.RuntimeException: No such var: webpoc1.server/handler
        at clojure.lang.Util.runtimeException(Util.java:170)
        at clojure.lang.Compiler.resolveIn(Compiler.java:6740)
        at clojure.lang.Compiler.resolve(Compiler.java:6710)
        at clojure.lang.Compiler.analyzeSymbol(Compiler.java:6671)
        at clojure.lang.Compiler.analyze(Compiler.java:6244)
        ... 60 more
Subprocess failed

Since I am new to Noir (and Clojure), I am at a loss trying to figure this out

A: Answering my question/ documenting my travails in leingen noir ring dependencies for other newbies. You may generate  a noir project with "lein new noir ... " command , but update these files as follows if you want a war file .
project.clj
(defproject noir3 "0.1.0-SNAPSHOT"
            :description "FIXME: write this!"
            :dependencies [[org.clojure/clojure "1.4.0"]
                           [noir "1.3.0-beta10"]
                           [hiccup "1.0.2"]
                           [cheshire "4.0.3"]
                           ]
            :plugins [[lein-ring "0.7.5"]]
            :ring {:handler noir3.server/handler}

            :main noir3.server)

server.clj
(ns noir3.server
  (:require [noir.server :as server]))

;;(server/load-views-ns 'noir3.views)

(server/load-views "src/noir3/views/")

(def handler (server/gen-handler {:mode :dev
                                  :ns 'noir3}))

(defn -main [& m]
  (let [mode (keyword (or (first m) :dev))
        port (Integer. (get (System/getenv) "PORT" "8080"))]
    (server/start port {:mode mode
                        :ns 'noir3})))

Then , run the following

*

*"lein run"  (check if your pages are accessible),

*"lein  ring   server" (check if your pages are accessible),

*and finally "lein  ring war"  -- you should see as war file in
target dir

A: Have you declared the handler in webpoc1.server which you are referencing? Something like this:
(def handler
  (server/gen-handler {:mode :prod
                       :ns *ns*}))

http://www.webnoir.org/tutorials/others/ offers instructions on how to use Noir with Ring.


text:
Q: How to move to the foot of the web page dynamically I have been asked to move the focus of the web page to the bottom of the page from the click of a button. I've tried using Focus() but that doesn't seem to work, which I think is something to do with the Postback.
Does anyone have any other ideas how to do this?

A: Add an anchor (A tag) just above the footer (or at the top of the footer content), and assign a name to it; e.g.

This will not be visible. However, it allows you to add #footer to the URL and the browser will scroll down to it. For example, add another link:
see footer

Test how it works on this example:
How to move to the foot of the web page dynamically
Notice #9115063 in the URL above.
If you look at the source of this page, close to the top of this answer, you'll find this:


text:
Q: getting only first
* of
* Here is the problem. I have a websites and few subpages
subpages:
DAMSKIE,
MĘSKIE,
DZIECIĘCE,
SPORT,
AKCESORIA,
PREMIUM,
TOREBKI,
WYPRZEDAŻ,
On each of it are few categorizing elemens like "Półbuty", "Klapki" etc.
I can get Subpages but i can't get the list of categorizing elements (Półbuty, Klapki etc). If list looks like: "Półbuty", "Klapki", "Obcasy" my code gets only "Półbuty", but he doesn't get "Klapki" or "Obcasy".
[Image of subpages+the list of elements im trying to get][1]
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Crawler_Shoes
{
    public class Crawl
    {
        private static string navBar = "megamenu__item";
        private const string shoesTypes = "sidebar-section__wrapper sidebar-section__wrapper--categories";
        private static string mainSite = "https://www.eobuwie.com.pl/";
        public static List<string> categoriesNames = new List<string>();
        public static List<string> linksNames = new List<string>();
        public static List<string> categoriesOfCategoriesNames = new List<string>();
        private readonly List<Shoes> shoes = new List<Shoes>();

        public static async Task<IEnumerable<HtmlNode>> HttpClient(string site, string descendant, string equals)
        {
            var httpClient = new HttpClient();
            var html = await httpClient.GetStringAsync(site);
            var htmlDocument = new HtmlDocument();
            htmlDocument.LoadHtml(html);
            return htmlDocument.DocumentNode.Descendants(descendant)
                .Where(node => node.GetAttributeValue("class", "").Equals(equals)).ToList();
        }
        public static async Task GetCategories()
        {
            var menu = await HttpClient(mainSite, "li", navBar);
            foreach (var nav in menu)
            {
                //links.Add(nav.Descendants("a").FirstOrDefault().ChildAttributes("href").FirstOrDefault().Value);
                categoriesNames.Add(nav.Descendants("a").FirstOrDefault().InnerText); //gets names of categories
                linksNames.Add(nav.Descendants("a").FirstOrDefault().ChildAttributes("href").FirstOrDefault().Value); //gets links for categories
                if(categoriesNames.Last() == "\n\t\t\tWyprzedaż\t\t")
                {
                    categoriesNames.Remove(categoriesNames.Last());
                    linksNames.Remove(categoriesNames.Last());
                }
            }
            Crawl.GetCategoriesofCategories();
        }
        public static async Task GetCategoriesofCategories()
        {
                for (var i = 0; i <= categoriesNames.Count-1; i++)
                {
                    var categories = await HttpClient(linksNames.ElementAt(i), "ul", shoesTypes);
                    categoriesOfCategoriesNames.Add(categoriesNames.ElementAt(i));
                    foreach(var li in categories)
                    {
                        categoriesOfCategoriesNames.Add(li.Descendants("a").FirstOrDefault().ChildAttributes("href").FirstOrDefault().Value);
                    }
                }

        }
    }
}

The part with the problem:
    public static async Task GetCategoriesofCategories()
            {
                    for (var i = 0; i <= categoriesNames.Count-1; i++)
                    {
                        var categories = await HttpClient(linksNames.ElementAt(i), "ul", shoes

Types);
                    categoriesOfCategoriesNames.Add(categoriesNames.ElementAt(i));
                    foreach(var li in categories)
                    {
                        categoriesOfCategoriesNames.Add(li.Descendants("a").FirstOrDefault().ChildAttributes("href").FirstOrDefault().Value);
                    }
                }

        }

A: I had success with this:
string url = "https://www.eobuwie.com.pl/damskie.html";
HtmlWeb web = new HtmlWeb();
HtmlDocument doc = web.Load(url);
var sidebar = doc.DocumentNode.SelectSingleNode("//ul[@class='sidebar-section__wrapper sidebar-section__wrapper--categories']");
var categories = sidebar.SelectNodes("li");
foreach (var category in categories)
{
    var anchor = category.SelectSingleNode("a");
    string shoeCategory = anchor.InnerText.Trim();
    Console.WriteLine(shoeCategory);
}

It's a bit different than how you're doing it, but I at least hope you'll be able to take some hints from this and apply it to your own code.
If you need the links as well, add this:
string shoeCategoryLink = anchor.GetAttributeValue("href", string.Empty);


text:
Q: How to run a CMD command without openning a new window in Inno Setup I am using Inno Setup installer to setup an installer file, that can invoke the .exe that I just installed through its scripting, and launch it right after installation, with the following command:
[Run]
Filename: "{cmd}"; Description: "{cm:LaunchProgram,3mtxmail}"; \
    Flags: nowait postinstall skipifsilent runascurrentuser; \
    Parameters: "/b /k "" ""{app}\my.exe"" -c ""{app}\default.conf"" "" "

When my.exe is operating, it doesn't need any interface, and should only listen to any traffic on a specific port, and write that traffic info to a log file.
However, when I execute the installer and launched the program, it still brings up a new console window, which I think the /b should have prevented. I expect not to see this new console window, and actually don't see anything on the screen.
From https://technet.microsoft.com/en-us/library/bb491005.aspx, the /b should be the flag that indicates not to open new windows for the command.
What is the correct syntax?

A: It does not look like you need the cmd.exe for anything. Run your application directly instead:
[Run]
Filename: "{app}\my.exe"; Parameters: "-c ""{app}\default.conf""" \
    Description: "{cm:LaunchProgram,3mtxmail}"; \
    Flags: nowait postinstall skipifsilent runascurrentuser;

Though if your application is a console application, it will open its own console. To prevent that, add runhidden flag.
You can actually use the runhidden flag to hide even the cmd.exe console window. But if you have no need for the cmd.exe, you should not use it.


text:
Q: Different colors for edges of tcolorbox I am trying to make a tcolorbox where the right border is blue and the top border is green, but can't seem to find any options online or in the manuals for individual line colors. Is this possible?

A: You can use the library skins to add individual borders on every side of the box; see chapter 10 in the documentation.
Here's a small example.

\documentclass{article}
\usepackage{tcolorbox}
\tcbuselibrary{skins}
\begin{document}
\begin{tcolorbox}[
    sharp corners,
    boxrule=0mm,
    enhanced,
    borderline north={2pt}{0pt}{green},
    borderline east={2pt}{0pt}{blue},
]
A box with a blue right border and a green top border.
\end{tcolorbox}
\end{document}


text:
Q: AngularJS post data for WebApi My problem is related to angular post. My data sent with client is always empty-
null. But Fiddler sent with no problem.
WebApi is error
user.KullaniciAdi = 'user.KullaniciAdi' threw an exception of type 'System.NullReferenceException'
Apache Cordova Mobile Client - Null Data
Fiddler - Full Data
Table is Users.
My Surrogate Users Table:
namespace DiaryRestfulService.Models.ORM
{

 public class UserSurrogate
    {

        public int ID { get; set; }
        public string Username{ get; set; }
        public string Password{ get; set; }
    }
}

My Base User Class : Business Layer
public UserSurrogate InsertUser(UserSurrogate user)
        {
            Users kullanici = new Users()
            {
                Username= user.Username,
                Password = user.Password

            };
            db.Users.Add(kullanici);
            db.SaveChanges();

            return user;

        }

My User Controller :
    [HttpPost]
    public IHttpActionResult KullaniciEkle([FromBody] UserSurrogate user)
    {
        try
        {
            userornek.InsertUser(user);
            return Json("succ");

        }
        catch (Exception)
        {
            return NotFound();
        }

    }

And, my client;
<script>
  var app = angular.module('a', []);
    app.controller('b', function ($scope, $http, $httpParamSerializerJQLike) {

        $scope.Ekle = function () {

            var data =({ Username: $scope.username, Password: $scope.password });

            console.log(data);

            var url = {
                method: 'POST',
                url: 'http://localhost:51975/api/User/KullaniciEkle',
                headers: {
                    'Content-Type': 'application/json; charset = utf-8'
                }

            };

            $http(url, "'" + $httpParamSerializerJQLike(data)+"'").then(function (responce) {
                alert("Oldu");
            }, function (responce) {
                console.log(responce.headers);
                console.log(responce.data);
                console.log(responce.status);
                console.log(responce.config);
     alert("Olmadı");
            });
        }
    });

</script>

Where do i make the mistake?
Help me please.

A: I've tried all of them, nothing's changed. ( JSON.stringify including)
   <script>
      var app = angular.module('a', []);
        app.controller('b', function ($scope, $http) {

            $scope.Ekle = function () {

                var data =({ KullaniciAdi: $scope.username, Sifre: $scope.password });

                console.log(data);

                var url = {
                    method: 'POST',
                    url: 'http://localhost:51975/api/User/KullaniciEkle',
                    headers: {
                        'Content-Type': 'application/json; charset = utf-8'
                    }

                };

                $http(url,data).then(function (responce) {
                    alert("Oldu");
                }, function (responce) {
                    console.log(responce.headers);
                    console.log(responce.data);
                    console.log(responce.status);
                    console.log(responce.config);
         alert("Olmadı");
                });
            }
        });

    </script>

A: To me it looks like you adding the body data in the incorrect way.
Try change the $http setup and define the body in the data section as this
$http({
    method: 'POST',
    url: 'http://localhost:51975/api/User/KullaniciEkle',
    headers: {
        'Access-Control-Allow-Origin': '*',
        'Content-Type': 'application/json'
    },
    data: JSON.stringify(data),
}).
success(function (data) {
    alert("Oldu");
}).
error(function (message, status) {
    console.log(message);
});

A: I did it!!!
Thanks for everything.
Running code:
https://learn.microsoft.com/en-us/aspnet/core/security/cors
My Controller:
 [EnableCors(origins: "*", headers: "*", methods: "*")]
 public class UserController : ApiController

My Client Post Form Script:
<script>
      var app = angular.module('a', []);
        app.controller('b', function ($scope, $http) {

            $scope.Ekle = function () {

                var veri = { KullaniciAdi: 'test', Sifre: 'test2' };
                var adres = 'http://localhost:51975/api/User/KullaniciEkle';
                var req = {
                    method: 'POST',
                    url: adres,
                    data: JSON.stringify(veri),
                    headers: {
                        'Accept': 'application/json',
                        'Content-Type': 'application/json',
                 },}

                $http(req).then(function () {
                    alert("oldu");

                }, function () {

                    console.log(veri);
                    alert("olmadı");

                    });
            }

        });

    </script>


text:
Q: how to show imageview to full screen using clickableAreaImages library I am using ClickableAreasImages library while loading image from url i am facing the problem.
image is not showing full screen.
getting this
output
Layout
<RelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:fitsSystemWindows="true"
   android:gravity="center"
   tools:context=".MainActivity">

   <ImageView
        android:id="@+id/imageView"
        android:adjustViewBounds="true"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitCenter"
        android:layout_centerVertical="true"/>
</RelativeLayout>

Java
    image = (ImageView) findViewById(R.id.imageView);

    Glide.with(mContext)
            .load(Uri.parse("https://www.mcdonaldjoneshomes.com.au/sites/default/files/floorplans/images/hermitage-standard-lhs-2546x1900_0.png"))
            .apply(new RequestOptions().placeholder(R.drawable.site1).error(R.drawable.site1).fitCenter())
            .into(image);

    image.setImageResource(R.drawable.firstandsecondfloorplan);

     ClickableAreasImage clickableAreasImage = new ClickableAreasImage(new PhotoViewAttacher(image), this);

        // Define your clickable area (pixel values: x coordinate, y coordinate, width, height) and assign an object to it
        List<ClickableArea> clickableAreas = getClickableAreas();
        clickableAreasImage.setClickableAreas(clickableAreas);

i am using
//glide
implementation 'com.github.bumptech.glide:glide:4.8.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0'

Any Suggestion would be highly appreciated


text:
Q: run two services in a docker image How to run two services in a docker image?
I have CMD ["/datomic/run.sh"] but I also want
CMD ["bin/console -p 8080 dev datomic:free://localhost:4334/"] as well to run after the first one started. Both commands takes up shell.
How to do this?

A: Well you can use Supervisord to Run multiple services in a container.
Have a look to this document from docker docs !!
(https://docs.docker.com/config/containers/multi-service_container/)


text:
Q: module 'tensorflow' has no attribute 'tanh' I am trying to repeat what is shown in this tutorial: https://www.kaggle.com/alexisbcook/deep-reinforcement-learning
When I run this code:
# Check version of tensorflow
import tensorflow as tf
tf.__version__

I am getting this error:

module 'tensorflow' has no attribute 'version'

When I run this piece of code I am not getting any error:
from kaggle_environments import make, evaluate
from gym import spaces

class ConnectFourGym:
...

Then running this code without error:
# Create ConnectFour environment
env = ConnectFourGym(agent2="random")

But when I try to run the following code
import os
from stable_baselines.bench import Monitor
from stable_baselines.common.vec_env import DummyVecEnv

# Create directory for logging training information
log_dir = "ppo/"
os.makedirs(log_dir, exist_ok=True)

# Logging progress
monitor_env = Monitor(env, log_dir, allow_early_resets=True)

# Create a vectorized environment
vec_env = DummyVecEnv([lambda: monitor_env])

I am getting the following error:

module 'tensorflow' has no attribute 'tanh'

The error is pointing these lines causing the problem:
----> 2 from stable_baselines.bench import Monitor
...
----> 1 from stable_baselines.a2c import A2C
...
----> 1 from stable_baselines.a2c.a2c import A2C
...
----> 9 from stable_baselines.common import explained_variance, tf_util, ActorCriticRLModel, SetVerbosity, TensorboardWriter
...
----> 7 from stable_baselines.common.base_class import BaseRLModel, ActorCriticRLModel, OffPolicyRLModel, SetVerbosity,
...
---> 16 from stable_baselines.common.policies import get_policy_from_name, ActorCriticPolicy     ...
--> 375 class LstmPolicy(RecurrentActorCriticPolicy):

Why this is happening? How can I fix this problem?

A: I fixed the problem by specifying TensorFlow version:
# Check version of tensorflow
!pip install -q 'tensorflow==1.15.0'
import tensorflow as tf
tf.__version__

This code snippet installs TensorFlow version 1.15.0 and prints

'1.15.0'


text:
Q: How to find the rectangle center point (origin position)? If I have a rectangle and I try to rotate it, how to find the rectangle center point (origin position)?
I know these $3$ corners of the rectangle:

*

*left top: $(0,5)$

*left bottom: $(0,0)$

*right top: $(5,5)$

A: Use the fact that the centre $(h,k)$ of a rectangle is the midpoint of the diagonals:
$h=\frac{0+5}2, k=\frac{5+0}2 $

Alternatively, use the fact the centre $(h,k)$ of a rectangle is  equidistant from the corners, so that $$(h-0)^2+(k-0)^2=(h-0)^2+(k-5)^2=(h-5)^2+(k-5)^2$$
Use the 1st two to get $h$ and the last two to get $k.$

A: Or May be the simplest one: where the two line joining the midpoints of opposite sides intersects.

A: There is a reason the question is posed with three points. It's to allow for the fact that the  rectangle may be at an angle to the axes. In the OP, it happens to be in line with the axes.
The key is to prove that for all rectangles, the mid points of the diagonals are coincidental at the centre of the rectangle and that you can therefore ignore the third point and instead concentrate on the bottom left and top right points in isolation.


text:
Q: How to use vue-select in a simple HTML page? It is my first "try" with Vue + vue-select.
I have imported Vue and vue-select like it is explained in the vue-select documentation.
And my first try is this simple HTML page :
    <!DOCTYPE html>

    <link
      rel="stylesheet"
      href="https://unpkg.com/vue-select@latest/dist/vue-select.css"
    />

Vue Select

      <v-select :options="options"></v-select>

When I try this page, I have these errors in the console :

What it is wrong in this first try? When I understand this first example, it will be easier for the rest.

A: I just checked your code and seems this issue is due to the vue version you are using. I just used version 2.* and it is working.
Demo :

Vue.component("v-select", VueSelect.VueSelect);
new Vue({
  el: "#app",
  data: {
    selected: 'foo',
    options: ["foo", "bar", "baz"]
  }
});

<link rel="stylesheet" href="https://unpkg.com/vue-select/dist/vue-select.css"/>

Vue Select

  <v-select :options="options" v-model="selected"></v-select>

Update : Here is the Vue 3 version of v-select

const { createApp } = Vue
const { createVuetify } = Vuetify

const vuetify = createVuetify()

const app = createApp({
  template: '#app-template',
  data: () => ({
    items: ['Foo', 'Bar', 'Fizz', 'Buzz'],
  }),
}).use(vuetify).mount('#app')

<link rel="stylesheet" href="https://unpkg.com/@vuetify/nightly@3.0.0-next-20220604.0/dist/vuetify.css"/>
<link rel="stylesheet" href="https://unpkg.com/@mdi/font@6.x/css/materialdesignicons.min.css"/>


text:
Q: Cypher query with select first item from collect in neo4jclient I have the following code but I don't know how to do it in C# using the graphclient. It's the RETURN nodes[0] that confuses me.
What it does is that it will return all nodes and their properties with a distinct value of name.
PROFILE MATCH (t:Node { Mapped: true})
WITH t.name as t, collect(t) AS nodes
RETURN nodes[0]

Current implementation required me to get all and then use LINQ to get the distinct but this is slower:
 var res = graphClient.Cypher
                    .Match(match)
                    .Return(t => new
                    {
                        N = Return.As<string>("t.name")
                        LA = Return.As<double>("t.lat"),
                        LO = Return.As<double>("t.lon")
                    })
                    .OrderBy("t.name")
                    .Results;

//TODO: THE DISTINT NEEDS TO BE IN THE QUERY INSTEAD OF AFTER RESULT.
return res.Where(p => p.N != null).GroupBy(p => p.N).Select(grp => grp.FirstOrDefault());

A: You're probably going to want a proper result class instead of trying an anonymous type for this, so if you have this:
public class Location{
    [JsonProperty("name")]
    public string Name {get;set;}
    [JsonProperty("lat")]
    public double Lat { get; set; }
    [JsonProperty("lon")]
    public double Lon { get; set; }
}

You can then write the query as:
var query = client.Cypher
    .Match("(t:Node {Mapped: true})")
    .With("t.name AS t, collect(t) AS nodes")
    .Return(() => Return.As<Location>("nodes[0]"));

Which if you look at:
query.Query.DebugQueryText

You should see:
MATCH (t:Node {Mapped: true})
WITH collect(t) AS nodes
RETURN nodes[0]