text:
Q: How to make a Windows service from .Net Core 3 Recently I had a need to convert a .Net Core 3.0 console application into a Windows Service.
As I didn't have a requirement to port this process to Linux, I could dispense with the multiple platform solutions that I had seen on Stackoverflow that dealt with any combination of .Net Framework, .Net Standard and .Net Core.
EDIT:  There is coming up for Visual Studio 2019 a worker template.  As it is pre-release, there will be some potential stability issues.  I could not get one of the references to work, so the solution I pose below should suffice until the template is stable. (see https://devblogs.microsoft.com/aspnet/net-core-workers-as-windows-services/)

A: *

*First create a .Net Core console application in Visual Studio 2019.  You will need to install the .Net Core 3 SDK prior to use.  Also insure you can reference the .Net Core 3 preview by specifying settings in Tools->Options->Preview Features, 'Use previews of the .NET Core SDK'

*Set the language version to at least 7.1 to support async Task for the Main method.  (Access the language version from the project settings->Build->Advanced->Language Settings). .Net Core 3 and Visual Studio 2019 support C# 8.0

*Add the Microsoft.Extensions.Hosting and the System.ServiceProcess.ServiceController packages.

Now go to Program.cs and copy the following:
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace AdvancedHost
{
    internal class Program
    {
        private static async Task Main(string[] args)
        {
            var isService = !(Debugger.IsAttached || args.Contains("--console"));

            var builder = new HostBuilder()
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<LoggingService>();
                });

            if (isService)
            {
                await builder.RunAsServiceAsync();
            }
            else
            {
                await builder.RunConsoleAsync();
            }
        }
    }
}

This code will support interactive debugging and production execution, and runs the example class LoggingService.
Here is a skeleton example of the service itself:
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Concurrent;

namespace AdvancedHost
{
    public class LoggingService : IHostedService, IDisposable
    {

        public Task StartAsync(CancellationToken cancellationToken)
        {
            // Startup code

            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            // Stop timers, services
            return Task.CompletedTask;
        }

        public void Dispose()
        {
            // dispose of non-managed resources
        }
    }
}

The final two files necessary to complete the project:
ServiceBaseLifetime.cs:
using Microsoft.Extensions.Hosting;
using System;
using System.ServiceProcess;
using System.Threading;
using System.Threading.Tasks;

namespace AdvancedHost
{

    public class ServiceBaseLifetime : ServiceBase, IHostLifetime
    {
        private readonly TaskCompletionSource<object> _delayStart = new TaskCompletionSource<object>();

        public ServiceBaseLifetime(IApplicationLifetime applicationLifetime)
        {
            ApplicationLifetime = applicationLifetime ?? throw new ArgumentNullException(nameof(applicationLifetime));
        }

        private IApplicationLifetime ApplicationLifetime { get; }

        public Task WaitForStartAsync(CancellationToken cancellationToken)
        {
            cancellationToken.Register(() => _delayStart.TrySetCanceled());
            ApplicationLifetime.ApplicationStopping.Register(Stop);

            new Thread(Run).Start(); // Otherwise this would block and prevent IHost.StartAsync from finishing.
            return _delayStart.Task;
        }

        private void Run()
        {
            try
            {
                Run(this); // This blocks until the service is stopped.
                _delayStart.TrySetException(new InvalidOperationException("Stopped without starting"));
            }
            catch (Exception ex)
            {
                _delayStart.TrySetException(ex);
            }
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            Stop();
            return Task.CompletedTask;
        }

        // Called by base.Run when the service is ready to start.
        protected override void OnStart(string[] args)
        {
            _delayStart.TrySetResult(null);
            base.OnStart(args);
        }

        // Called by base.Stop. This may be called multiple times by service Stop, ApplicationStopping, and StopAsync.
        // That's OK because StopApplication uses a CancellationTokenSource and prevents any recursion.
        protected override void OnStop()
        {
            ApplicationLifetime.StopApplication();
            base.OnStop();
        }
    }
}

ServiceBaseLifetimeHostExtensions.cs:
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace AdvancedHost
{

    public static class ServiceBaseLifetimeHostExtensions
    {
        public static IHostBuilder UseServiceBaseLifetime(this IHostBuilder hostBuilder)
        {
            return hostBuilder.ConfigureServices((hostContext, services) => services.AddSingleton<IHostLifetime, ServiceBaseLifetime>());
        }

        public static Task RunAsServiceAsync(this IHostBuilder hostBuilder, CancellationToken cancellationToken = default)
        {
            return hostBuilder.UseServiceBaseLifetime().Build().RunAsync(cancellationToken);
        }
    }
}

To maintain the service I use the 'sc' utility:
To create: sc create AdvancedHost binPath="C:\temp\AdvancedHost\AdvancedHost.exe"
        where 'AdvancedHost' is the service name and the value for binPath is the compiled executable.
For status: sc query AdvancedHost
To start: sc start AdvancedHost
To stop: sc stop AdvancedHost
To delete (once stopped): sc delete AdvancedHost
There are many more features contained in sc; just type 'sc' alone on the command line.
The results of sc can be seen in the services Windows control panel.


text:
Q: Cleanest way for automated dependency management in c++ Related question: C++ Build Systems - What to use?
I am struggling to find a nice build / dependency management tool for my c++ project, with the following desired features:

*

*able to specify a dependency by name, version

*dependencies' "include" directories are automatically included during compilation of my application

*the dependencies are automatically downloaded, built, and linked to my application

*transitive dependencies also have the above two behaviours

*ability to specify test-scope dependencies

*tests are automatically built and run, potentially with a memory leak check tool (e.g. valgrind)

*potentially run a coverage tool, e.g. gcov

*cross platform supported

I have used Maven, with the [nar-maven-plugin], and sometimes the [cmake-maven plugin]. However, this means I have to craft a [pom.xml per dependency]. This method isn't particularly nice, as at times, a [nasty pom.xml] has to be crafted to get things to work. Also, it doesn't support running valgrind (no support built in yet).
I have attempted using CMake as I've seen many projects use it, but I find that a lot of time is spent on "writing a build/dependency management system" instead of "using it". Yes it's true I can write many functions that go:
function(RequireSomeLib artifact)
  # ExternalProject_Add(SomeLib ... etc.)
  # find SomeLib package
  # add include dirs(artifact SomeLib_INCLUDE_DIRS)
  # if SomeLib is not just a header library, also link its built library to the artifact
  # for each of SomeLib's dependencies, do this same "call" (transitive dependencies' libraries must also be linked when building an executable)
endfunction()

for each dependency. Tedious, but currently the cleanest way I see going forward.
With the premise that CMake is used by libraries that my project depends on, is there a better method to solving this problem?
I have not seen or tried SCons, AutoTools, or QMake (yet).
In Java, the "retrieve dependencies, build, test, and publish" issue is much simpler ._.

A: All build systems for C++ will need you to code in dependencies and package detection. Every one of them has been created out of frustration with previous technologies, with the stated intent to remove the need for boilerplate code, and to create a complete, cross-platform, automated, easy to use solution, but at the end of the day, you will end up writing code besides your code for your package to be built.
If you look hard enough, you will find debates among advocates of each build system. I found one of such a couple years ago. Their arguments were so weak that I ended up abandoning the search.
I am a user of CMake for one simple reason: it was the first I could find some years ago that allowed me to spawn different build directories. I'm sure all modern build systems have implemented this idea already, but I stuck with CMake just because I became used to it. Honestly I have found very few sensible advantages over bare bones Makefile. I had to write boilerplate code for my CMakeFiles.txt, even though it was a C++ project without dependencies.
Some time later I decided to try out some different IDEs; I had the good fortune that Qt Creator runs on CMake projects; there is the other reason I stayed on CMake.
My advice to you is to visit each build system's webpage; check out their currently implemented features (not TODOs), comparisons to other systems, IDE support, and the complexity of the code you have to write for them. I am pretty sure you will not find a build system satisfying all of the requirements you have, so you will have to test them thoroughly to see which one works best for you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jenkins - Selecting SSH Host at Run time I have to mention the SSH host or SCP host while configuring the Job.
Is there any option by which we can select the host name in Run-time?
Just like we can select the Node name in which we want the script or shell commands to be executed, using Node Plugin
To be specific -
I am passing few files to a Host, it can either be DEV, QA, or PROD and then based on that a set of commands will be executed in that particular Host.
As set of commands/script is generic, only the Host changes, so I need to develop one single job and pass the Host name in the Run-time where the file will be placed.
Is there any way out ?
Please help
Thanks in advance


text:
Q: Android - Image rotation like door open I don't know it is possible or not but I really want to know if this possible . So I have sample Image But Not Same like that . just Rotate that image do work for my. Image is for Idea only.

A: This might help you. Check out this example
http://www.techrepublic.com/blog/software-engineer/use-androids-scale-animation-to-simulate-a-3d-flip/


text:
Q: Reading / Computing Hex received over RS232 I am using Docklight Scripting to put together a VBScript that communicates with a device via RS232. All the commands are sent in Hex.
When I want to read from the device, I send a 32-bit address, a 16-bit read length, and an 8-bit checksum.
When I want to write to the device, I send a 16-bit data length, the data, followed by an 8-bit checksum.
In Hex, the data that is sent to the device is the following:
AA0001110200060013F81800104D
AA 00 01 11 02 0006 0013F818 0010 4D

(spaced for ease of reading)

AA000111020006 is the protocol header, where:

*

*AA is the Protocol Byte

*00 is the Source ID

*01 is the Dest ID

*11 is the Message Type

*02 is the Command Byte

*0006 is the Length Byte(s)

The remainder of the string is broken down as follows:

*

*0013F818 is the 32-bit address

*0010 is the 16 bit read length

*4D is the 8-bit checksum

If the string is not correct, or the checksum is invalid the device replies back with an error string. However, I am not getting an error. The device replies back with the following hex string:
AA0100120200100001000000000100000000000001000029
AA 01 00 12 02 0010 00010000000001000000000000010000 29

(spaced for ease of reading)

Again, the first part of the string (AA00011102) is a part of the protocol header, where:

*

*AA is the Protocol Byte

*01 is the Source ID

*00 is the Dest ID

*12 is the Message Type

*02 is the Command Byte

The difference between what is sent to the device, and what the device replies back with is that the length bytes is not a "static" part of the protocol header, and will change based of the request. The remainder of the string is broken down as follows:

*

*0010 is the Length Byte(s)

*00010000000001000000000000010000 is the data

*29 is the 8-bit Check Sum

The goal is to read a timer that is stored in the NVM. The timer is stored in the upper halves of 60 4-byte NVM words.
The instructions specify that I need to read the first two bytes of each word, and then sum the results.
Verbatim, the instructions say:

*

*Read the NVM elapsed timer. The timer is stored in the upper halves of 60 4-byte words.

*Read the first two bytes of each word of the timer. Read the 16 bit values of these locations:
13F800H, 13F804H, 13808H, and continue to 13F8ECH.

*Sum the results. Multiply the sum by 409.6 seconds, then divide by 3600 to get the results in hours.

My knowledge of bits, and bytes, and all other things is a bit cloudy. The first thing I need to confirm is that I am understanding the read protocol correctly.

*

*I am assuming that when I specify 0010 as the 16 bit read length, that translates to the 16-bit values that the instructions want me to read.

*The second thing I need to understand a little better is that when it tells me to read the first two bytes of each word, what exactly constitutes the first two bytes of each word?

*I think what confuses me a little more is that the instructions say the timer is stored in the upper half of the 4 byte word (which to me seems like the first half).
I've sat with another colleague of mine for a day trying to figure out how to make this all work, and we haven't had any consistent results with our trials.
I have looked on the internet to find something that would explain this better in the context being used.
Another worry is that the technical data I am using to accomplish this project isn't 100% accurate in their instructions, and they have conflicting information or skipping information throughout their publication (which is probably close to 1000 pages long).
What I would really appreciate is someone who has a much better understanding of hex / binary to review the instructions I've posted, and provide some feedback on my interpretation of the instructions provided, and provide any information.


text:
Q: Use WEKA API to perform LSA on train and test set I need to use Weka and its AttributeSelection algorithm LatentSemanticAnalysis to do text classification. I have my dataset split into training and test sets on which I want to apply LSA. I have read some posts regarding LSA, however I have not found how I can use it on to seperate datasets and keep them compatible. This is what I have so far but runs out of memory...:
AttributeSelection selecter = new AttributeSelection();
weka.attributeSelection.LatentSemanticAnalysis lsa = new weka.attributeSelection.LatentSemanticAnalysis();
Ranker rank = new Ranker();

selecter.setEvaluator(lsa);
selecter.setSearch(rank);
selecter.setRanking(true);

selecter.SelectAttributes(input);
Instances outputData = selecter.reduceDimensionality(input);

Edit1
In responce to @Jose's reply I added a new version of my source code. This leads to an OutOfMemoryError:
AttributeSelection filter = new AttributeSelection(); // package weka.filters.supervised.attribute!
LatentSemanticAnalysis lsa = new LatentSemanticAnalysis();
Ranker rank = new Ranker();
filter.setEvaluator(lsa);
filter.setSearch(rank);
filter.setInputFormat(train);

train = Filter.useFilter(train, filter);
test = Filter.useFilter(test, filter);

Edit2
The error I am getting:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at weka.core.matrix.Matrix.getArrayCopy(Matrix.java:301)
at weka.core.matrix.SingularValueDecomposition.<init>(SingularValueDecomposition.java:76)
at weka.core.matrix.Matrix.svd(Matrix.java:913)
at weka.attributeSelection.LatentSemanticAnalysis.buildAttributeConstructor(LatentSemanticAnalysis.java:511)
at weka.attributeSelection.LatentSemanticAnalysis.buildEvaluator(LatentSemanticAnalysis.java:416)
at weka.attributeSelection.AttributeSelection.SelectAttributes(AttributeSelection.java:596)
at weka.filters.supervised.attribute.AttributeSelection.batchFinished(AttributeSelection.java:455)
at weka.filters.Filter.useFilter(Filter.java:682)
at test.main(test.java:44)

A: As AttributeSelection is a filter, you can apply it in batch mode (-b option) to a training & a test subset at once, thus representing the test dataset according to the dimensions defined in the training set.
You can check how to do this in a program at Use Weka in your Java code - Filter - Batch filtering.


text:
Q: Trying to convert an excel named range of strings (text with spaces) into a string array Trying to convert an excel named range of strings (text with spaces) into a string array to use in a access database query. Basically, pull in list of names from excel, query database using those names, then return data related to those names back to excel.  I found some related answers here:
Excel VBA: Range to String Array in 1 step
but the "sArray" (string array) is not populating when I run the loop to convert from the variant array to the string array. Here is my code:
Dim theRange As Variant
Dim sArray() As String
Dim i As Long

Application.ScreenUpdating = False
Application.Calculation = -xlCalculationManual
Application.DisplayAlerts = False

activeworksheet = ("Sheet2")

theRange = range("SecurityID").Value
size = UBound(theRange)

For i = 1 To 5
    ReDim sArray(1 To 5)
    sArray(i) = CStr(theRange(i, 1))
Next i

A: There are a number of small error.  This will work on the ActiveSheet:
Sub marine()
    Dim theRange As Variant
    Dim sArray() As String
    Dim i As Long
    Range("A1:A5").Name = "SecurityID"
    Application.ScreenUpdating = False
    Application.Calculation = -xlCalculationManual

    'Application.DisplayAlerts = False
    'activeworksheet = ("Sheet2")

    theRange = Range("SecurityID").Value
    Size = UBound(theRange, 1)
    ReDim sArray(1 To Size)
    For i = 1 To Size
        sArray(i) = CStr(theRange(i, 1))
        MsgBox sArray(i)
    Next i
End Sub

A: Dim vSecurityID As Variant
Dim lngCounter As Long

vSecurityID = Range("SecurityID").Value

For lngCounter = LBound(vSecurityID) To UBound(vSecurityID)
    Debug.Print vSecurityID(lngCounter, 1)
Next lngCounter

A: You are very close. Just a couple of quick things:
Sub test()
    Dim theRange As Variant
    Dim sArray() As String
    Dim i As Long

    Application.ScreenUpdating = False
    Application.Calculation = -xlCalculationManual
    Application.DisplayAlerts = False

    theRange = Sheets("Sheet2").Range("SecurityID").Value

    ReDim sArray(1 To 5)
    For i = 1 To 5
        sArray(i) = CStr(theRange(1, i))
    Next i

    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
    Application.DisplayAlerts = True
End Sub

*

*Specify the sheet name with the Range (ActiveWorksheet is a reserved term)

*You only need to ReDim your destination array once, before your loop

*Setting the size = UBound(theRange) is not necessary

*Don't forget to re-enable screen updates, calcs, and alerts at the end


text:
Q: Design reason behind setupUi() I'd like to know why, in your opinion, Qt engineers decided to put the setupUi() method in every generated form.
(for those who do not know how Qt works: setupUi() is a method which allocates in dynamic memory every button, texbox, widget which is inside the form. Every element's reference is stored inside a pointer member variable which is not even initialized to nullptr and it is placed under a public: access modifier, so that also looks like a somewhat dangerous situation until you actually call setupUi())
In my newby opinion, that totally violates RAII principle, because that means any Ui_Whatever class is actually not constructed by its constructor call: constructor just allocates the class itself, but it is unusable till we call Ui_Whatever::setupUi().
Which could be the design reason behind the choose of having:

*

*an empty compiler-generated default-constructor

*a method which do the real construction

(I'm asking 'cause I can't figure out myself any valid reason at all)
Thanks in advance!!

A: I agree, that it totally violates RAII principles. But I found a fairly easy workaround for that:
template<typename UiClass> class QtRaiiWrapper : public UiClass
{
public:
    QtRaiiWrapper(QMainWindow *MainWindow)
    {
        setupUi(MainWindow);
    }
};

...

#include "ui_Main.h"

class MainWindow : public QMainWindow
{
    Q_OBJECT
    ...
private:
    // Ui_MainWindow m_Ui; // no RAII
    QtRaiiWrapper<Ui_MainWindow> m_Ui; // RAII
};

(It might need some improvements, but this is the basic idea and works for me pretty well.)
Some more discussion on the topic:
Qt's choice of implementing the initialization via setupUi does not only lack RAII for this component, it can also make RAII impossible for other parts of your program, which is double bad. In my case, another object used the value of an GUI-Element for initialization (this way I could define the initial value in QtDesigner, rather than using a fake value there and overwriting it upon startup), but could not use RAII for that, because the GUI would only be initialized inside the body of the constructor of my MainWindow.
Therefore I disagree with Kuba Ober, you have not full control of when exactly you want the GUI to be initialized, as you can only do it inside the constructor body and not the initialization list (and following RAII, the initialization list is the place where perhaps most of all the initialization should happen). But luckily, C++ is awesome and we can write a workaround for that (as posted above). I also think this is far better than changing the way uic because as soon as other people try to compile your Code they will see a big surprise.

A: The Ui class is not really a full-blown C++ class, it's just a wrapper that is supposed to become an integral part of something else.
By relegating the initialization to the setupUi method, you have control over exactly when will the widgets be instantiated. You may need to execute some setup before that time, and it would be impossible to do if the Ui class's constructor was doing the instantiating.
The pointers in the Ui class are not owning pointers. You never have to explicitly delete them. All the object pointers within the Ui class point to QObject instances that are owned by other QObject instances. The root of the ownership tree is the widget you pass to setupUi.  The RAII is effectively delegated to the owning QObject instance; there's no reason to duplicate that in setupUi.
If you insist on having an initialized Ui object, you can modify the uic tool to nullptr-initialize the pointers in the constructor. It's a 5-10 line change that I leave to the reader's fancy :) It's a waste of CPU cycles, as far as I'm concerned, but perhaps it could be useful in a debug build.

A: The problem behind one or two-phased initialization of UI sub-object is that the code in setupUi(this) needs the dynamic type of the form (this parameter) to be the real static type (class) of the form. But during initialization of parent classes and members it is of static type of parent class, not the form itself.
So all virtual function calls and RTTI can work different when called in the initialization phase of form object construction.
After opening brace of constructor function the dynamic and static types of the object are always same.


text:
Q: Windows 7 keeps changing wireless adapter DNS to 192.168.100.10 Windows 7 keeps changing my wireless adapter DNS to 192.168.100.10. This usually happens when I log on to different wifi connection. Sometimes it's a coffee shop, work or home. Anyone have an idea how I can stop this?
I specify google DNS, but it gets changed.
Primary : 8.8.8.8
Secondary : 8.8.4.4
Here is my research effort :
Google Link to My Search As yo ucan see there are no issues related to the problem I am having

A: By not connecting to strange wifi connections.
You're picking up a DNS server by DHCP, which, you can reconfigure under your network adapter settings to use a specific DNS server or servers, rather than a DHCP-supplied one.  Of course, you risk not being able to connect to your DNS server of choice (and therefore lose the ability to browse the web in general) if you run into a captive portal that's relying on using its DNS server to direct you to a login page.


text:
Q: Use of Autoclosure
I found this example on https://www.swiftbysundell.com/posts/using-autoclosure-when-designing-swift-apis
I am little confuse between use of autoclosure and delaying operation. I want to know what will happen if I remove @autoclosure from this example. I know then curly braces required but other than that? Everywhere explanation is expression will get evaluated only after you call it. But every function will get evaluated when we call it. so How autoclosure helping it to delaying. Or just we get syntactic relaxation of not required to put curly braces around expression

A:
Or just we get syntactic relaxation of not required to put curly braces around expression

Exactly. It also hides the delayed evaluation from the caller.
Another example are the "short-circuiting" logical operators || and &&, for example
public static func ||(lhs: Bool, rhs: @autoclosure () throws -> Bool) rethrows -> Bool

so that in
let b = functionReturningBool() || otherFunctionReturningBool()

the second function is not called if the first one already returned
true.


text:
Q: IBM Worklight - How to use adapter domain and port properties taken from external file? I have a web service. Its domain and port can be changed. So I want to read port and domain from file or db. When this information change, I update them in db or file.
Adapter XML:
<domain>${adp.hostname}</domain>
<port>${adp.port}</port>

worklight.properties:
adp.hostname=localhost
adp.port=10080

This is working fine. But I'd like to take adp.hostname and adp.port from file or db.

A: Something to remember about adapters is that you cannot change in real-time any of the properties set in the adapter XML once it is deployed.
Once the adapter is deployed, it is transformed into an object and is stored in memory. At this time, then, you can no longer interact with its "setup".
The only thing you can do, is to decide what will be the value of these properties before your deploy the adapter. For example, a different set of properties for QA/TEST/UAT/PROD environments...

To setup external properties, starting Worklight 6.0 and above, you can read this  documentation topic: Configuring an IBM Worklight project in production by using JNDI environment entries
Specifically for Tomcat in its server.xml:
<Context docBase="app_context_path" path="/app_context_path">
  <Environment name="publicWorkLightPort" override="false"
    type="java.lang.String" value="9080"/>
</Context>

*

*You change app_context_path to your project's context (project name)

*You add environment child elements for each property you need

Important to remember: these properties must also exist in worklight.properties; those will be the default properties, and if using the above example they will be over-written and the environment properties will be used instead.
In the example above you can see that it will replace the default property publicWorkLightPort.


text:
Q: Need some information on Document Viewer in asp.net I m trying to prepare a document viewer in asp.net 4.0. My requirement for this viewer is that all users coming to my website will be able to view every document. uploaded by him on my web-server.
I want to know any third party free application/service/user-control i can use in my website and open all my documents (.doc, .docx, .xls, .xlsx, .ppt, .pptx, .pdf, .jpg, .gif, and other image formats.)
I found Adeptol Viewer, TX  TextControl. but this are very costly, ranging $5000 and above. can i get any cheap control..
EDIT : Also i want to know, is it possible to create such custom control in .NET and use it for our future use. If possible please guide me how i can achieve this. It is fine I can use Client Scripting like jQuery. for this
Awaiting for the reply from any technical experts who is willing to help/ support my question.

A: There is open source document viewer named Okyanux File Manager supporting only the documents which browsers support such as .swf, .wmv, .jpg, .gif and other image formats. You can also add .pdf support with Ron Schuler's open source PDF Viewer. It converts pdf files to images for previewing. I think other file types are not easy. You can add word and excel support with Spire.XLS which costs 900$.

A: Found the best and free solution for document viewer for all types of documents including edit feature..

*

*Google Docs viewer

*Zoho viewer

I found Zoho more interesting than google as it provides fantastic features compared to google.. editing of any document (.ppt or .xls) is just like you are using Microsoft Office in your browser.
Fantastic functionality and perfect solution.


text:
Q: How can I customize the color of the tabbedPane at swing builder? I want to customize the color of my tabbedPane to fit at the theme of my gui, but I don't know how to do it. I've tried lots of code but still nothing happens.
Here's my gui...

thnx in advance ^_^

A: For the JTabbedPane look and feel, set the UIManager settings as described in this post Controlling Color in Java Tabbed Pane
Relevant code:
  UIManager.put("TabbedPane.contentAreaColor ",ColorUIResource.GREEN);
  UIManager.put("TabbedPane.selected",ColorUIResource.GREEN);
  UIManager.put("TabbedPane.background",ColorUIResource.GREEN);
  UIManager.put("TabbedPane.shadow",ColorUIResource.GREEN);

  // now construct the tabbed pane
  tab=new JTabbedPane();

A: There are couple UIManager setting you can make before you create the GUI but they will be for every JTabbedPane:
This will change the selected tab color.
UIManager.put("TabbedPane.selected", Color.RED);

I don't see a setting for the border but you can hide it like so:
UIManager.put("TabbedPane.contentBorderInsets", new Insets(0, 0, 0, 0));

Lastly you can change the background of the tab pane like this:
tab.setBackground(Color.BLUE);


text:
Q: ObservableObject is updating all views and causing menus to close in SwiftUI I have this class which calls an API every 3 seconds (using a timer) and saves the result in the @Published array named items:
public class ApiAdapter: ObservableObject {

    @Published var items = [Item]()

    init() {

        api = Api(...)

        Timer.scheduledTimer(withTimeInterval: 3, repeats: true) { timer in
            api.getItems() { items in
                if let _items = items {
                    self.items = _items
                }
            }
        }
    }

}

The ApiAdapter is used throughout the entire app so I decided to make it an @EnvironmentObject.
In the main view of my app I'm accessing the apiAdapter.items array for displaying it in a list like so:
struct MainListView: View {

    @EnvironmentObject var apiAdapter: ApiAdapter

    var body: some View {
        NavigationView {
            List {
                ForEach(apiAdapter.items, id: \.hash) { i in
                    Text(i.name)
                    ...
                }
            }
            .navigationBarItems(trailing:
                                Menu {
                                    Picker(selection: $category, label: Text("Filter")) {
                                        Text("Category 1").tag(1)
                                        Text("Category 2").tag(2)
                                        Text("Category 3").tag(3)
                                    }
                                } label: {
                                    Image(systemName: "line.horizontal.3.decrease.circle")
                                        .imageScale(.large)
                                }
        }
    }
}

In MainListView I have also some Menus in the navigationBar which get closed every time the apiAdapter updates the items variable, so it makes it hard to use them.
How is it possible to update only the list and not the entire view? or even better how is it possible to update only the items that changed in the last api call?

A: Remove the EnvironmentObject from your MainListView. Create a new View for the List only like this:
struct ListView : View {
    @EnvironmentObject var apiAdapter: ApiAdapter

    var body : some View {
        List {
            ForEach(apiAdapter.items, id: \.hash) { i in
                Text(i.name)
            }
        }
    }
}

Now your subview only updates, while your main view remains the same and the Menu remains opened.
And your MainListView as follows:
struct MainListView: View {
    var body: some View {
        NavigationView {
            ListView() //<< here comes your ListView which refreshes independent
            .navigationBarItems(trailing:


text:
Q: Change the Size of SWIOTLB Permanently in Linux Kernel I work on Linux Debian with 64bit kernel version 4.19.0 and default SWIOTLB size 64M.
For the needs of a kernel driver that I develop I would like to use more than 64M SWIOTLB.
Is there any way to change the SWIOTLB size permanently.
I keep searching but it is not clear to me.
Thank you!

A: Giving swiotlb=65536 to kernel command line (e.g. /etc/default/grub) gives 128MB of swiotlb. To make this permanent, we can use update-grub command. If the hardware has hardware IOMMU, iommu=force intel_iommu=on usually removes the need for swiotlb.


text:
Q: How can i customize answer of Bot Framework Help Command? I use Bot Framework form flow for a Turkish Bot. I want to change help command's answer to turkish. Is there any options for this issue?
Thanks

A: You can use the Template attribute on top of your Form definition to override the Help string pattern. The pattern is located in the Resources.resx of Microsoft.Bot.Builder project.
[Template(TemplateUsage.Help, new string[] { "My custom Help message" })]

A: I think the following articles give you some information about how to localize your content by language. Bot Framework Localize content and localization in Bot Framework
Hope it will help to someone.


text:
Q: Save image temporarily using io for pre-processing without using disk resources My current project requires that i deal with uploaded files(mostly images) for pre-processing before i save them.
So far my main method has been to upload to Amazon s3 then download and work on them.
This is not ideal because i do not really need to save the uploaded image but rather the final product.
Is it possible to use the io module to save the Django InMemoryUploadedFile as bytes and somehow return an actual image from it? My attempts so far have failed miserably. Maybe i do not necessarily understand the io module well.
def temp_file(f):
    """
    CREATES TEMP FILE THAT DOES NOT GET UPLOADED
    f is the InMemoryUploadedFile of image
    """
    buffer = io.BytesIO()
    buffer.write(f.read())
    image = buffer.read()
    buffer.close()
    img = Image.open(image)
    return img

A: If you want to integrate an image you've uploaded in a PDF, you may want this kind of thing:
from io import BytesIO
from PIL import Image
from reportlab.pdfgen import canvas

def upload_view(request):
    image = request.FILES['image']
    imagebuffer = BytesIO()
    for chunk in image.chunks():
        imagebuffer.write(chunk)
    image = Image.open(imagebuffer)
    imagebuffer.close()
    response = HttpResponse(content_type='application/pdf')
    c = canvas.Canvas(response)
    c.drawImage(image, x, y)
    ...

A: Image.open() expects a filename or a file like object (with read(), seek(), and tell() methods). So you have to give the buffer object to Image.open(). Not closed and rewinded to the beginning.
def temp_file(f):
    return Image.open(io.BytesIO(f.read()))


text:
Q: Pandas: Passing two columns to an expanding_apply function I have the dataframe:
import pandas as pd
id = [0,0,0,0,0,1,1,1,1,1]
value = [1,3,2,5,4,4,3,2,1,5]
test = pd.DataFrame(zip(id, value), columns = ['id', 'value'])

And I want an expanding apply function that identifies whether we reach a new maximum value for a given id. The resulting dataframe should look like this:
   id  value  new_max
0   0      1        1
1   0      3        1
2   0      2        0
3   0      5        1
4   0      4        0
5   1      4        1
6   1      3        0
7   1      2        0
8   1      1        0
9   1      5        1

I can't seem to pass two columns to the expanding apply function.
I tried by creating a new column:
test['id_value'] = zip(test['id'], test['value'])

And passing the tuple on:
def new_max(x):
    v, w = list(zip(*x)[0]), list(zip(*x)[1])
    last_id = v[-1]
    last_value = w[-1]
    if any(j >= last_value for j in [w[i] for i, k in enumerate(v[0:-1]) if k == last_id]):
        return 0
    else:
        return 1

test['new_max'] = test['id_value'].apply(lambda x: pd.expanding_apply(x, new_max))

But I get the error:
AttributeError: 'tuple' object has no attribute 'dtype'

Any suggestions would be appreciated!

ONE SOLUTION THAT CIRCUMVENTS PASSING TWO COLUMNS
(though it would still be nice to know how to do this by passing two columns)
def new_max2(x):
    if any(j >= x[-1] for j in x[0:-1]):
        return 0
    else:
        return 1

test.groupby('id')['value'].apply(lambda x: pd.expanding_apply(x, new_max2))

A: This addresses the problem, not the general issue of passing multiple columns: I would use groupby and cummax, and then see whether we hit a new value.  For example:
grouped = df.groupby("id")["value"]
cummax = grouped.cummax()
cummax_is_new_value = cummax != cummax.groupby(df.id).shift()
df["new_max"] = cummax_is_new_value.astype(int)

gives me
>>> df
    id  value  new_max
0    0      1        1
1    0      3        1
2    0      2        0
3    0      5        1
4    0      4        0
5    1      4        1
6    1      3        0
7    1      2        0
8    1      1        0
9    1      5        1
10   2      1        1
10   2      1        0
10   2      0        0
10   2      1        0
10   3      1        1

Originally I was only checking whether the value was the same as the previous value, but that failed on cases like [1, 0, 1], where the second 1 is both equal to the cumulative maximum and not the same as the previous value.  This way we're always working with the grouped cumulative values, and so we really are only picking up the new cumulative values by group.

A: Its been a long time since I worked with apply like a couple releases ago minimum, so my recollection may be bad, or things may have changed. However, as I remember it the grouped data is passed automatically as the first argument.
The temptation when passing your own function to apply is to do this:
def user_func(df, arg1, arg2):
    return whatever_you_like

DF = pd.DataFrame(your_data)

DF.groupby('col1').appy(user_func(arg1, arg2))

but this is not the correct syntax. In fact the correct syntax for the last line is
DF.groupby('col1').apply(user_func, arg1, arg2)

Whether expanding_apply works in the same way I do not know and this may all be totally out of date, but might be worth a shot.

A: What I think is a more generic solution (not vectorised) using list comprehensions:
Let's say you have 2 columns, a and b.
df = pd.DataFrame(dict(a=[1,2,3], b=[4,5,6]))

And you want to calculate the running ratio of the sum of and and b
def myFunc(df):
    return df["a"].sum() / df["b"].sum()

Here is a solution that works provided your function takes a dataframe and outputs a single value
df.assign(sum_a_sum_b_ratio = [myFunc(d) for d in df.expanding()])

    a   b   sum_a_sum_b_ratio
0   1   4   0.250000
1   2   5   0.333333
2   3   6   0.400000


text:
Q: How do I pick a suitable SMD mosfet to control a 24V pneumatic valve with PIC32? I need to control a valve (https://datasheet.octopart.com/VXZ242FGA-SMC-datasheet-110849414.pdf) of which I do not know its power consumption and drawn current. I don't have the part yet and usually it is controlled by a PLC, but for my application, I need to control it myself using a PIC32 microcontroller. It operates on 24 Volts and the entire PCB is made with SMD components, so I prefer to use one of those.

A: If you're looking for the power required you missed it.

Solenoid coil specifications from page 2 of the datasheet. (Click for high-resolution.)
The worst case is 15 W on the DC versions so allow for \$ I = \frac P V = \frac {24}{15} \ \text A \$.
Go for a MOSFET that is rated at > 1 A and can be turned fully on by a logic-level output from your PIC32 - 3.3 V or 5 V, as required.


text:
Q: Trinamic TMC2209 STM32 UART not reading from device I've been struggling for ages, finally caved and asking for help now.
There are very little resources on STM32 for this driver that I have seen.
I can use the device with the STEP/DIR interface but I want to be able to do the more advanced things now with only the single UART line and not the STEP/DIR lines.
I am trying to control a TMC2209 in the most basic form to understand how it all works, without libraries and such.
I want to get basic controls working so I can understand it and build up my own code from there, right now the goal is to just talk to the thing and get it to spin.
I am using a STM32F103, I have setup the USART3 line (PC10) in signal wire half duplex mode and using the following code to try read from the CHOPCONF register.
       Sync = 0x05; // sync byte to start the Tx
       Address = 0x00; // MS1 and MS2 are pulled low so the device address is 0
       RegAddress = 0x6C; // Trying for a basic read from the CHOPCONF Reg
       motor_CRC = 0xCA;  // CRC that has been worked out

       HAL_UART_Transmit(&huart3,&Sync,sizeof(Sync),20);
       HAL_UART_Transmit(&huart3,&Address,sizeof(Address),20);
       HAL_UART_Transmit(&huart3,&RegAddress,sizeof(RegAddress),20);
       HAL_UART_Transmit(&huart3,&motor_CRC,sizeof(motor_CRC),20);

// Receive the data from the TMC2209

       HAL_UART_Receive(&huart3, &ReplySync, sizeof(ReplySync), 200);
       HAL_UART_Receive(&huart3, &ReplyMasterAddr, sizeof(ReplyMaster), 20);
       HAL_UART_Receive(&huart3, &ReplyAddr, sizeof(ReplyAddr), 20);
       HAL_UART_Receive(&huart3, &Reply1, sizeof(Reply1), 20);
       HAL_UART_Receive(&huart3, &Reply2, sizeof(Reply2), 20);
       HAL_UART_Receive(&huart3, &Reply3, sizeof(Reply3), 20);
       HAL_UART_Receive(&huart3, &Reply4, sizeof(Reply4), 20);
       HAL_UART_Receive(&huart3, &ReplyCRC, sizeof(ReplyCRC), 20);

       HAL_Delay(1000);

I expect the following : ( according to the Datasheet that is,,, )
ReplySync      >>> 0x05
ReplyMasterAddr>>> 0xFF
ReplyAddr      >>> 0xCA
Reply1         >>> 0x53
Reply2         >>> 0x00
Reply3         >>> 0x00
Reply4         >>> 0x10
ReplyCRC       >>> I dont know this one yet,,,,

But I am getting this :
ReplySync      >>> 0x05
ReplyMasterAddr>>> 0x00
ReplyAddr      >>> 0x5D
Reply1         >>> 0x09
Reply2         >>> 0x08
Reply3         >>> 0x00
Reply4         >>> 0x02
ReplyCRC       >>> 0x09

I am not sure if I am transmitting these in the correct order or maybe the HAL function should not be used for this at all ?
Any help or pointers in the right direction would be greatly appreciated.


text:
Q: txt file extract only 8 digit numbersand transform to date format I have a txt file that contains text and code.

Is it possible to extract all 8 digit numbers for this txt file 20131225 and 20131212, and transform them in the format 2013/12/25 .... and not only for these dates...also for future dates that will be added if an event is added to the txt file...so i dont know which dates this will be...and also display that in correct date format and echo only these dates out. I was thinking about preg replace but i dont succeed.... can soeone help me. thx

A: The data you have can be called a text file that contains data and code :), of course, but usually one would call that a  "HTML" document.
For parsing HTML with PHP there is the dom extension. Use it like this:
$html = <<<EOF

EOF;

$doc = new DOMDocument();
$doc->loadHTML($html);

// create an XPath selector to select the attributes containing the dates
$selector = new DOMXpath($doc);

// select all data-day attributes
foreach($selector->query('//@data-day') as $date) {
    // transform date format using date() and strotime()
    echo date('Y/m/d', strtotime($date->nodeValue));
}

For the date conversion I've used date() and strtotime(). You should read their manuals as well.

A: assuming this file is actually have this format for all strings, you can go with regexp, this will be faster neither xml/html parsing
next thing - I do not recommend using of strtotime, as soon as format is clear you can go with faster variant:
<?php

$s = "

";

preg_match_all('/data-day=\'([^\']*)\'/', $s, $matches);
foreach($matches[1] as $idx => $datevalue)
{
    $year = substr($datevalue, 0, 4);
    $month = substr($datevalue, 4, 2);
    $day = substr($datevalue, 6, 2);
    echo $year.'-'.$month.'-'.$day."\n";
}


text:
Q: Sometimes gdal.RasterizeLayer makes geometry invisible Honestly I don't know how to explain what's going on correctly but I'll try.
I have a table in postgres that I trying to rasterize, and I want to make a separate raster for every feature.
Everything works, but sometimes I get tif images that look like this:

So it's completely black and min and max values = 0. But if I change max value to 1 feature will appears:

This effect not a random. It always happens with this feature when I trying to make image where this feature in corner. If I make image where it feature in center everything fine.
Here is my code:
inp_lyr = outLayer #layer that contains only one feature
inp_srs = osr.SpatialReference()
inp_srs.ImportFromProj4('my_srs')

x_ncells = 1024
y_ncells = 1024

# Output
out_driver = gdal.GetDriverByName('GTiff')
out_source = out_driver.Create(output_tiff, x_ncells, y_ncells, 1, gdal.GDT_Int32)
out_source.SetGeoTransform((x_min, cellsize, 0, y_max, 0, -cellsize))
out_source.SetProjection(inp_srs.ExportToWkt())
gdal.RasterizeLayer(out_source, [1], inp_lyr, burn_values = [1], options =['ALL_TOUCHED=TRUE'] )

# Save and/or close the data sources
out_source.FlushCache()
out_source = None

What should I check here?


text:
Q: elsif statements not working in views I need help understanding the usage of elseif statements in the view for Rails. I have done it before but now I am doing it with SLIM and I can't seem to get it to work. I want it to print out the word "him" or "her" depending on the current user gender. The code I am using is printing out the elsif statement in text.
            a.profile_btn href="#" data-mfp-src='#ask_me'
              img alt="" src="/assets/login_icon2.png" /
          if current_user.gender == "male"
              span Ask Him Out
          elsif current_user.gender == "female"
                span Ask Her Out

The original code:
            a.profile_btn href="#" data-mfp-src='#ask_me'
              img alt="" src="/assets/login_icon2.png" /
              span Ask This User Out

A: Try
- if current_user.gender == "male"
   span Ask Him Out
- elsif current_user.gender == "female"
   span Ask Her Out


text:
Q: common field for various Info-path forms I want to design 6 info-path forms and publish them in SharePoint online. Each form has some common field(basically drop downs) that has predefined data, we called it master fields. The requirement is that all of these field will be populated from a single table/list into each form and forms will saved in their respective form library.
any suggestion, how to achieve it.

A: You create your lists in Sharepoint Online with all the necessary fields and values. In your InfoPath form, you make a data connection to pull this information in. You can then bind that to a drop down field.
It is pretty straight forward to do.

A: You may also want to look into template parts - basically, you can create a template part with these controls (using a SharePoint list for the data source for the drop downs, as suggested in Eric Alexander's reply) and add the template part as a custom control in InfoPath designer. Adding the template part to any form you work on will give you the same layout / controls / data source in all your forms.


text:
Q: Javascript How to delete element when button is clicked I'm trying to make my basic to do list better and I want to be able to delete a task when a button is clicked. How can I go about doing this? I've given the button dynamic ID's but cant seem to find out how to return that specific ID when a specific button is clicked.
Javascript
let Task = [];

function addTask(){
    //assign input to array
    var task = document.getElementById("userInput").value;
    Task.push(task);

    //creates node and shows where to find value
    let node = document.createElement("li");
    let textNode = document.createTextNode(
        document.getElementById("userInput").value
    );

    //create button for text node to delete
    const btn = document.createElement('button');
    btn.innerHTML = 'Delete';

    //adds task to webpage
    node.appendChild(textNode);
    document.getElementById("myList").appendChild(node);

    //Adds button to webpage, gives button dynamic ID
    document.getElementById("myList").appendChild(btn).id = Task.length;

}

A: If I understand correctly what you want is to assign a dynamic ID and return that ID by clicking the button, correct?
In this case you can try something like:
// Adds button to webpage, gives button dynamic ID
document.getElementById("myList").appendChild(btn);
btn.setAttribute("id", "myCustomId");

document.getElementById("myList").appendChild(btn);
btn.setAttribute("onclick", "alert('Current button ID: '+this.id)");


text:
Q: How to create a stack-like view in android
As you can see from the image , each card is stacked on top of each other. I am planning on using fragments for each card but I am wondering how to go about giving it the stacked card effect.
It would be great if someone could give me a pointer to help figure this out.
Also, feel free to ask for anything if what I have said is not clear enough.

A: At first hist try to search sonme libraries in net. There are a lot of them. Search on Android-Arsenal or GitHub with keywords:"tinder", "stack", "deck", etc.
As for me, http://android-arsenal.com/details/1/3079 this one is one of the best.


text:
Q: How to validate a hidden input field in a form / change validation behavior? I have a HTML form with several inputs which have the required attribute and thus are automatically validated when the form is submitted. This works fine, but I also have an input field of type='checkbox' that needs to be invisible/hidden due to special CSS styling, which changes a label's appeareance to display a styled checkbox. But this checkbox input field also needs to be validated (it has the required attribute).
So when the form is submitted, the browser (Chrome here) can't focus the invisible field, so it does nothing in the UI and gives the error
An invalid form control with name='consent' is not focusable.

How can I override the form validation to focus the label element instead of the invisible input element when it is invalid? Are there any useful form validation events that I can hook into to change this behavior?
Thanks in advance.
Edit: It's a bit similar to OPs question and this answer here: https://stackoverflow.com/a/23215333/15717315
Edit 2: I can optionally use jQuery.
This is what it looks like currently:

<div>
    <input type='checkbox' id='myfield' class='my-styled-checkbox' name='myfield' required>
    <label for='myfield'>
        The label
    </label>
</div>

Edit 3:
Alright, so I added an event listener to the submit event of the form. This successfully prevents the from from being submitted when the checkbox isn't checked.
document.getElementById("myform").addEventListener("submit", function(e) {
    var field = document.getElementById("myfield");
    if (field.checked) {
        field.setCustomValidity("");
        e.returnValue = true;
    }
    else {
        field.setCustomValidity("Invalid");
        e.returnValue = false;
    }
});

But it still throws the same error as in the OP, and the validation message does not display.

A: It would be helpful if you provided with a code example. Also to know if you are using any framework or library like react, angular, etc.
Css properties like

visibility: hidden;

or

display: none;

do not prevent you from editting the DOM with js code. So you should be able to change the field value before submitting.
Also, if the field is not editable by the user, you could just not make it into a required field and assign it a default value. That way you are certain it will never submit being empty.
Looks like you are trying to focus the field, this is not what you want, you should be trying to just change the field's value with js or jquery.


text:
Q: How to apply SSL/TLS certificate applied to cloudfront dist. to a domain on AWS Route 53? I set up a cloudfront distribution and assigned an SSL certificate to it:

The origin of the cloudfront is pointing here (maybe this is the problem??):

The SSL certificate itself is for domains *.populationsimulator.com and www.populationsimulator.com:

When I navigate to the cloudfront dist. URL (https://d2vnsaiy1f228n.cloudfront.net/), things look secure:

I set up the cloudfront dis. URL as an alias in my Route 53 domain:

But, when I navigate to the Route 53 URL (http://www.populationsimulator.com/), things don't look secure, but they load quickly enough for me to believe it's now pointing to the cloudfront dist. successfully?:

The site can't be reached when I try to include https in the URL (https://www.populationsimulator.com/):

Any tips on where I have gone wrong? Many thanks in advance for the help!

A: There are couple of things you need to fix:
1.First You need to add www.populationsimulator.com to CloudFront's Alternate Domain's Filed (CNAME)
2.. In route53, you have record for populationsimulator.com but not for www.populationsimulator.com, once www.populationsimulator.com added to CNAME in CloudFront, you can create an alias record in Route53 for www.populationsimulator.com.
Once above steps are done, you should be able to access the website using http://www.populationsimulator.com but not with https://populationsimulator.com.
To make https://populationsimulator.com, you need to get a cert with subject with
"populationsimulator.com" and populationsimulator.com into CNAME as well.


text:
Q: Regexp for extracting data in parenthesis and commas So, i have this :

"( ABC,2004 )"

And I would need to extract ABC in a variable and 2004 in another.
So what I have for now is this:

In: re.compile(r'([^)]*,').findall("(
ABC,2004 )")
Out: ['( ABC,']

A: If your inputs are always like that (begin with "( ", end with " )"), you can have your values as:
input_text.strip(" ()").split(",")

>>> "( ABC,2004 )".strip(" ()").split(",")
['ABC', '2004']

This will consume any parentheses at the edges inside the outer parentheses.
Also, if the commas can be surrounded/succeeded by spaces, you can:
[item.strip() for item in input_text.strip(" ()").split(",")]

A: Try just looking for "word" characters:
>> re.compile(r'\w+').findall("( ABC,2004 )")
['ABC', '2004']


text:
Q: Drag and drop position relative Why when the ball is placed relative positioning when you press the mouse it bounces? Absolute positioning is when this doesn't happen.

var ball = document.querySelector('.ball');

ball.onmousedown = function(event) {
  var shiftX = event.pageX - getCoords(this).left,
      shiftY = event.pageY - getCoords(this).top;

  this.style.position = 'relative';
  this.zIndex = 10000;

  function move(event) {
    this.style.left = event.pageX - shiftX + 'px';
    this.style.top = event.pageY - shiftY + 'px';
  }

  move.call(this, event);

  document.onmousemove = function(event) {
    move.call(ball, event);
  };

  this.onmouseup = function(event) {
    document.onmousemove = this.onmouseup = null;
  };

  return false;
};

ball.ondragstart = function() {
  return false;
};

function getCoords(elem) {
  var box = elem.getBoundingClientRect();

  return {
    top: box.top + window.pageYOffset,
    left: box.left + window.pageXOffset
  };
}
body {
  margin: 50px;
}

img {
  cursor: pointer;
}

I guess it's because of the padding of the body element. Please explain.

A: it seems i found answer
Implementing drag and drop on relatively positioned elements in JavaScript
and as it says, with relative position, your element contain offset of all objects in his parent-tag
and parent's margin and padding too
so when you try to get elemtn's position, you should count it's real offset in parent, see in my code example work with count index


text:
Q: How can i create new pinned shortcut in win7 shortcut at the first position? ( the left side of the taskbar) When i create a taskbar shortcut in win7 . its default position is at the end ( the right side of the taskbar). can i create a shortcut using i_shell_link and determine the specific location of this shortcut in the task bar ?

A:
Note  Applications cannot programmatically pin themselves to the taskbar. That functionality is reserved strictly for the user.

http://msdn.microsoft.com/en-us/library/dd391692(VS.85).aspx
Doing so would make Raymond Chen cry.


text:
Q: Append a list to specific columns in a csv with Pandas Hi Guys I can use some help if possible with Pandas: I have an existing csv that have the below structure:
column1  column2 column3 column4
1         ww        1     Sam
2         ss        2     Bill
                    3     Jack

list = [[4,Jin],[5,Carl]]

I want to write into the csv under column3 and column4 to have the below results: `
column1 column2 column3 column4
 1       ww        1       Sam
 2       ss        2       Bill
                   3       Jack
                   4        Jin
                   5       Carl

Any help in this? I know pandas read through rows yet how this can be done?

A: The data : fixed-width formatted
Your table needs to be read as it is a table of fixed-width formatted lines.
Thus using pandas.read_fwf.
import pandas as pd

pdcsv = pd.read_csv(inputcsv)
# reads
# column1  column2 column3 column4
#  1         ww       1     Sam
#  2         ss       2     Bill
#                     3     Jack

Appending Data

*

*Create a DataFrame for the rows to append, using only the desired columns 3 and 4:

lst = [[4,'Jin'],[5,'Carl']]
newrows = pd.DataFrame(lst, columns=pdcsv.columns[2:])
# column3 column4
#    4    Jin
#    5    Carl

*Use append. Use ignore_index=True to reset old indexes.

pdcsv = pdcsv.append(newrows, ignore_index=True)
pdcsv
#   column1 column2  column3 column4
# 0       1      ww        1     Sam
# 1       2      ss        2    Bill
# 2    None    None        3    Jack
# 3    None    None        4     Jin
# 4    None    None        5    Carl

Or use pd.concat like pdcsv = pd.concat([pdcsv, newrows], ignore_index=True)
Save
Using .to_csv(). Use index=False to not write a column for indexes.
pdcsv.to_csv('path\to\newfile.csv', index=False)

Creates real csv file (not fwf)

A: You can use pd.DataFrame.append for this:
#   column1 column2  column3 column4
# 0       1      ww        1     Sam
# 1       2      ss        2    Bill
# 2    None    None        3    Jack

lst = [[4, 'Jin'], [5, 'Carl']]

app = pd.DataFrame([[None, None, x[0], x[1]] for x in lst],
                   columns=['column'+str(i) for i in range(1, 5)])

df = df.append(app, ignore_index=True)

#   column1 column2  column3 column4
# 0       1      ww        1     Sam
# 1       2      ss        2    Bill
# 2    None    None        3    Jack
# 3    None    None        4     Jin
# 4    None    None        5    Carl

A: matrix = pd.read_csv(survey_dictionary)#, encoding="UTF-8")
fistElem = None
nullVector = matrix['column3'].isnull()
incr = 0
for isNull in nullVector:
    if isNull == True:
        fistElem = incr
        break
    incr = incr + 1
for source in list:
    if source[0] != fistElem:
        matrix.at[fistElem,'column3'] = source[0]
        matrix.at[fistElem,'column4'] = source[1]
matrix.to_csv(survey_dictionary, index =False, encoding='utf-8-sig')


text:
Q: How to set minimumfont size or minimumscalfactor(ios7) with the attributed string? How to set minimumfont size or minimumscalfactor(ios7) with the attributed string.
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
   paragraphStyle.lineBreakMode = self.lineBreakMode;
    paragraphStyle.alignment = self.textAlignment;

    NSDictionary *dictionary = @{ NSFontAttributeName: self.font,
                                  NSParagraphStyleAttributeName: paragraphStyle,
                                  NSForegroundColorAttributeName:self.textColor};

    [self.formattedText drawAtPoint:vLineRect.origin withAttributes:dictionary];

Please suggest how can i set minimumfont size in attributed string?

A: To replace minimumFontSize you need to use minimumScaleFactor with iOS 7 like this :
[_myLabel setMinimumScaleFactor:10.0/FONT]];

10.0 will be the minimum size.
And replace FONT by your custom font with the size ( [UIFont fontWithName:@"nameOfFont" size:15.0f], with the name of your font and the size you want ).
So with iOS 6 it would be the same as :
[_myLabel setMinimumFontSize:10.0];

Apple Documentation here.
You can add a test to use minimumFontSize with iOS 6 and minimumScaleFactor with iOS 7 :
if ([_myLabel respondsToSelector:@selector(setMinimumScaleFactor:)])
    [_myLabel setMinimumScaleFactor:10.0/FONT]];
else
    [_myLabel setMinimumFontSize:10.0];


text:
Q: How to check woocommerce single product tag I want to check product tag at single product page.
For example, when user access single product page
if that product tag is "adult"
redirect to main page.
I found is_product_tag() but this function only work at archive page.
Is there a way to know the tags on a single product page?

A: To check if the product has the tag, you can use has_term() or is_object_in_term().
has_term( 'tag_slug_or_ID', 'product_tag' )

Or:
// checking if the product has any tag
is_object_in_term( $product_id, 'product_tag' )

// checking if the product has a given tag
is_object_in_term( $product_id, 'product_tag', 'tag_slug_or_ID' )


text:
Q: When calling an AJAX post request to rails db, the return data is a list of generic objects In my rails app in my view, I am trying to call an ajax query with parameters of date_from and date_to that then route to an action in my controller which will query through the dates in my database. It should return this range of dates in the "success" feedback in the ajax code, but instead it returns, for example, "[object Object],[object Object],[object Object],[object Object]" if I were to pick a range of 1/1/2009 to 1/4/2009 (there are 4 objects for those 4 days). I would like the return data to be the objects and their column data in the database that I will eventually be able to use with a Highcharts timeplot. This is my code in question:
my JavaScript in the view:
function search() {
  var full_date_from = $( "#from" ).datepicker("getDate");
  var full_date_to = $( "#to" ).datepicker("getDate");

  var date_from = full_date_from.getMonth()+1 + "-" + full_date_from.getDate() + "-" + full_date_from.getFullYear();
  var date_to = full_date_to.getMonth()+1 + "-" + full_date_to.getDate() + "-" + full_date_to.getFullYear();

  $.ajax({
      url:"<%= url_for :controller => 'objects', :action => 'search' %>",
      data:'date_from=' + encodeURIComponent(date_from) + '&date_to=' + encodeURIComponent(date_to) + '&object_id=' + <%= @id %>,
      dataType: "json",
      cache:false,
      success:function (data) {
        $('#output').text(data); //outputs to

 on page
      }
  })
}

my search action in the controller:
def search
  @date_from = Date.strptime(params[:date_from], "%m-%d-%Y")
  @date_to = Date.strptime(params[:date_to], "%m-%d-%Y")
  @range = @object_data.where(:date => @date_from..@date_to)

  respond_to do |format|
   format.json { render :json => @range }
  end
end

current output of @range array to logger.debug() if date_from is 2009-01-01 and date_to is 2009-01-04
#<River::ActiveRecord_Relation:0xa6d4070>

each object of @range array in logger.debug() (I would like them to be string dates and I have tried .to_s and .to_formatted_s(param)
#<River:0xa595cf4>
#<River:0xa595b8c>
#<River:0xa595a38>
#<River:0xa595844>

A: I guess you're looking for something like this to return only desired attributes:
render :json => @range.select('data, date').to_json

or using map function:
render :json => @range.map{|object| {data: object.data, date: object.date}}.to_json

After getting the result in your success callback at client side, just iterate each of the objects inside of your data with something like that (coffeescript):
success: (data) ->
  for object in data
    $('#output').append(object.date);

You can also make sure that objects are received correctly with either console.log or alert:
console.log(data[0].date)
alert(data[0].date)


text:
Q: Opening and closing dropdown in html When I click on buttons nothing is happening. I am trying to make them open and close. How can I solve this?werrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
HTML

        <button class="dropdown-btn">{{item.streamName}}

        </button>

                    <button class="dropdown-btn">{{element.appName}}

                    </button>

                            <button class="dropdown-btn">{{sheet.sheetName}}
                            </button>

JAVASCRIPT
var dropdown = document.getElementsByClassName("dropdown-btn");
            var i;

            for (i = 0; i < dropdown.length; i++) {
            dropdown[i].addEventListener("click", function() {
                this.classList.toggle("active");
                var dropdownContent = this.nextElementSibling;
                if (dropdownContent.style.display === "block") {
                dropdownContent.style.display = "none";
                } else {
                dropdownContent.style.display = "block";
                }
            });
            }

A: Your code is working, but it will hide the content area only after the second click on the button because the initial value dropdownContent.style.display is empty string, but you check if it's equals to "block".
So the first click on the button set the content area to display: block.
You need to change the check to dropdownContent.style.display === ""
var dropdown = document.getElementsByClassName("dropdown-btn");
var i;

for (i = 0; i < dropdown.length; i++) {
    dropdown[i].addEventListener("click", function() {
        this.classList.toggle("active");
        var dropdownContent = this.nextElementSibling;
        if (dropdownContent.style.display === "block" || dropdownContent.style.display === "") {
            dropdownContent.style.display = "none";
        } else {
            dropdownContent.style.display = "block";
        }
    });
}


text:
Q: PHP/MySQL SET var = var - var I made a shop for my site, and got it working but realized it was lacking the ability to properly buy an item. to put it into perspective, you don't walk into a store, grab an item, buy it, grab it again, buy it, grab it again, etc. to get as many as you want. you grab them all at once. my site is lacking such feature. So, I have attempted to change the code that takes the stock, and so far am not succeeding.
I've tried the following:
function takestock($id, $count) {
global $mysqli,$db_table_prefix;
$stmt = $mysqli->prepare("UPDATE ".$db_table_prefix."shop
    SET stock = stock - ?
    WHERE
    id = ?");
$stmt->bind_param("ii", $id, $count);
$result = $stmt->execute();
$stmt->close();
return $result;}

and
function takestock($id, $count) {
global $mysqli,$db_table_prefix;
$stmt = $mysqli->prepare("UPDATE ".$db_table_prefix."shop
    SET stock = stock - $count
    WHERE
    id = ?");
$stmt->bind_param("ii", $id, $count);
$result = $stmt->execute();
$stmt->close();
return $result;}

and
function takestock($id, $count) {
global $mysqli,$db_table_prefix;
$stmt = $mysqli->prepare("UPDATE ".$db_table_prefix."shop
    SET stock = stock - ".$count."
    WHERE
    id = ?");
$stmt->bind_param("ii", $id, $count);
$result = $stmt->execute();
$stmt->close();
return $result;}

but I cant seem to take the count away from the stock!

A: The order that you bind parameters should correspond to the order you want to use them in your SQL statement. Here, the item count should come first and the id second. I.e., replace the following line:
$stmt->bind_param("ii", $id, $count);

With:
$stmt->bind_param("ii", $count, $id);


text:
Q: python: how to divide a matrix (dataframe) by a vector (dataframe) I need to divide a matrix (mat) by a vector (rowSums)
My matrix is a dataframe as:
mat = pd.DataFrame(
  data=[
    (1,0,0,0),
    (1,1,1,0),
    (0,0,1,0),
    (0,1,0,0),
    (1,0,1,0)],
    columns=['ind_1','ind_2','ind_3','ind_4'],
    index=['ct1','ct2','ct3','ct4','ct5'])

and the vector is:
rowSums = mat.sum(axis=1)

rowSums is:
ct1    1
ct2    3
ct3    1
ct4    1
ct5    2
dtype: int64

I need to divide mat / rowSums but I can't find the way.
I'm trying to replicate this command from R:
b = (mat / rowSums(mat))

And I need to get the following result:
         ind_1     ind_2     ind_3    ind_4
[ct1,] 1.0000000 0.0000000 0.0000000      0
[ct2,] 0.3333333 0.3333333 0.3333333      0
[ct3,] 0.0000000 0.0000000 1.0000000      0
[ct4,] 0.0000000 1.0000000 0.0000000      0
[ct5,] 0.5000000 0.0000000 0.5000000      0

A: You can use div with axis=0:
>>> mat.div(rowSums, axis=0)
        ind_1     ind_2     ind_3  ind_4
ct1  1.000000  0.000000  0.000000    0.0
ct2  0.333333  0.333333  0.333333    0.0
ct3  0.000000  0.000000  1.000000    0.0
ct4  0.000000  1.000000  0.000000    0.0
ct5  0.500000  0.000000  0.500000    0.0


text:
Q: Class not registered when I try to run setup I created a setup by Advanced Installer software for my program that I've written by c#. I installed my program on VMWare Windows7.
When I try to run it this message is displayed:

A: Here is a topic about COM registration: "Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))"
If it is a simple COM/Class registration, you should add them to COM page in your Advanced Installer project.
If you don't know what to add them to COM page you can also use this method to register them.

A: I used an API function in my program that checks internet connection,I think this function does not work on VmWare


text:
Q: Is $|abc|+|bcd|+|abd|+|acd|$ a norm on $\mathbb{R}^4$? We know about $L_p$ spaces that average of the $p$-th powers of a vector is a norm:
$$ |x|_p = \sqrt[p]{ \frac{x_1^p + \dots + x_n^p}{p}} $$
This means for example, this norm satisfies the triangle inequality (in this case, it's the Minkowski inequality):
$$ |x+y|_p  = \sqrt[p]{ \frac{(x_1+y_1)^p + \dots + (x_n+y_n)^p}{p}}
\leq   \sqrt[p]{ \frac{x_1^p + \dots + x_n^p}{p}}
+
\sqrt[p]{ \frac{y_1^p + \dots + y_n^p}{p}} = |x|_p + |y|_p $$
I'd like to know if we could use other symmetric polynomials as norms.  Let's define a function:
$$ f(x) =  \sum_{1 \leq i < j < k \leq n} |x_i x_j x_k|^3 $$
Does this satisfy triangle inequality?  E.g. is $f(x+y) < f(x) + f(y)$, where $x_i, y_i > 0$ ?  And if it is a norm we typically have constants such that:
$$ A ||\cdot ||_1 < ||\cdot||_2 < B ||\cdot||_1 $$
and I'd like to know possible constants $A$ and $B$, not even optimal.

Originally my question was if $|abc|+|bcd|+|abd|+|acd|$ is a norm on vectors $(a,b,c,d) \in \mathbb{R}^4$ and to compare it to the $L^3$ norm.
Please put absolute value signs as needed.  At least, what I've written s hould be true for $p$ even.

A: Let $p\geq 1$ and
$$ f(x) =  \sum_{1 \leq i < j < k \leq n} |x_i x_j x_k|^p $$
Then $f(1,0,\ldots,0)=0$ so it can not be a norm, let us fix that by redefining $f$ as $$ \tilde f(x) =  \sum_{1 \leq i \leq j \leq k \leq n} |x_i x_j x_k|^p $$
Now, $\tilde f(\alpha x)= \alpha^{3p} f(x)$ for $\alpha>0$ so it is still not norm, let us fix this by redefining $\tilde f$ as
$$ \hat f(x) =  \Big(\sum_{1 \leq i \leq j \leq k \leq n} |x_i x_j x_k|^p\Big)^{\frac{1}{3p}}.$$
Now, by computing the Hessian of $\hat f$, you will see that it is not always positive semi-definite. Hence $\hat f$ is not convex and therefore not a norm (and I don't think this can be fixed).

Conclusion: $f$ is not a norm and not even close from being so.


text:
Q: Case statement in a SQL query I am pretty new in SQL and have a question regarding a football database with the following tables:
Create Table Team(
TId char(3) Primary Key,                       // One example for a TId is "GER". It is an abbrevation for the country
Country varchar(50) Not Null,
Coach varchar(50) Not Null
)

Create Table Match(
MId Integer Primary Key,                      // Every match has an ID
Date date Null,
Stadium varchar(100) Not Null,
Team1 char(3) Not Null,
Team2 char(3) Not Null,
Foreign Key(Team1) references Team(TId),
Foreign Key(Team2) references Team(TId)
);

Create Table Goal(
MId Integer Null,
TId char(3) Null,
Player varchar(100) Not Null,
Minute Integer Null,
Primary Key(MId, Minute),
Foreign Key(MId) references Match(MId),
Foreign Key(TId) references Team(TId)
);

I need to write a SQL query that gives me a back a list of all matches with the date, the stadium and the number of goals both teams scored. It should be something like
Select date, stadium, Team1, Count(Goals Team1), Team2, Count(Goals Team2)

From match

...

I tried to start to count the goals for one team first and wanted to use a case statement but did not come that far:
Select s.SId, s.Team1,
Case When s.SId IN (Select distinct SId From Tor) Then Count(t.SId)
Else "Not In"
End As text
From Spiel s, Tor t, Team te
Where s.SId = t.SId
Group by s.SId

I'd be pleased if you have any idea how to do that. Thanks in advance.

A: Use a CTE to return the total goals for each match and team.
Then join Match to 2 copies of Team and 2 copies of the CTE:
with cte as (
  select mid, tid, count(*) goals
  from Goal
  group by mid, tid
)
select m.date, m.stadium,
  t1.tid team1, coalesce(c1.goals, 0) goals_1,
  t2.tid team2, coalesce(c2.goals, 0) goals_2
from `Match` m
inner join Team t1 on t1.tid = m.team1
inner join Team t2 on t2.tid = m.team2
left join cte c1 on c1.mid = m.mid and c1.tid = m.team1
left join cte c2 on c2.mid = m.mid and c2.tid = m.team2


text:
Q: Using a while loop to indefinitely reassign a variable, until that variable no longer belongs to a list? The purpose of this program is to deal out one 5-card hand from a standard 52-card deck.
I'm new to Python. Eventually I'd like to write a 5-card draw poker program, but first would like to know how to deal out 5 random non-repeating cards. The cards get dealt out and printed back to the user fine, but it is sometimes dealing duplicates. ie, the hand I'm dealt is Ah 2d 8h Ah Jc. Can't have two ace of hearts.
I'm trying to use a while True: construction to ensure that the same card isn't dealt twice. I studied C for awhile before Python and am confused here in syntax/construction. A do-while loop would seem to be handy, where it indefinitely reassigns the card to a random int as long as that card hasn't been drawn yet.
The code is also super long and I've just shown the process for assigning the first few cards. Using 52 if statements seems to a problem, but first I'd like to see if it can run with this construction, just fixing the while loop.
import random

# track a list of cards used
dealt_cards = ["Joker", "Joker2"]

for n in range (5):
    # generate a random int between 1 and 52 representing card
    card = random.randint(1,52)

    #check to see if this card has already been dealt,
    #and if so, re-deal
    while True:
        if card in dealt_cards:
            card = random.randint(1,52)
        else:
            break

    #assign each random int generation to a specific card in the
    deck,
    #and add the new card to dealt_cards

    #spades
    if card == 1:
        card = str(card)
        card = 'As'
        dealt_cards.append(card)
    if card == 2:
        card = str(card)
        card = '2s'
        dealt_cards.append(card)
    if card == 3:
        card = str(card)
        card = '3s'
        dealt_cards.append(card)
    if card == 4:
        card = str(card)
        card = '4s'
        dealt_cards.append(card)
    if card == 5:
        card = str(card)
        card = '5s'
        dealt_cards.append(card)
    if card == 6:
        card = str(card)
        card = '6s'
        dealt_cards.append(card)

I expect the program to return 5 unique non - repeating playing cards to the user, but it sometimes returns (deals) the same card twice in the same hand.

A: You can create all cards from 2 lists (suits, faces).
You can either make a shuffled copy of the deck or draw 5 random cards without replacement (random.sample):
import itertools
import random

suits = ['heart', 'tiles', 'clubs', 'pikes']
faces = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']

deck = set(itertools.product(faces, suits))

# get a mixed sample of all cards, use get first 5 cards
mixed = random.sample(deck, len(deck)) # get sample of all cards from deck (==shuffled copy)
five = mixed[:5]
print(five)

# to remove the just drawn cards from availables:
mixed = mixed[5:] # to remove the drawn cards for your mixed copy

# draw 7 non-repeated cards from deck
seven = random.sample(deck, 7)  # get 7 unique cards directly from deck
print(seven)

Output:
# five
[('6', 'pikes'), ('T', 'heart'), ('Q', 'pikes'), ('3', 'tiles'), ('J', 'clubs')]

# seven
[('A', 'tiles'), ('7', 'tiles'), ('8', 'tiles'), ('3', 'heart'), ('9', 'pikes'),
 ('6', 'heart'), ('T', 'clubs')]

Deckbuilding inspired by: codereview texas-holdem-poker-game
Takeing from a copy of deck that is preshuffled makes it easy to deal cards. Simply take from the front to "deal" and list.pop(0) this element.
Doku:

*

*itertools.product to create the deck from 2 lists

*random.sample

*random.shuffle for a inplace-shuffling of a list

Itertools product is a fance multiple for loop:
d = []
for s in suits:
    for f in faces:
        d.append((s,f))

print(d)

[('heart', 'A'), ('heart', '2'), ('heart', '3'), ('heart', '4'), ('heart', '5'),
 ('heart', '6'), ('heart', '7'), ('heart', '8'), ('heart', '9'), ('heart', 'T'),
 ('heart', 'J'), ('heart', 'Q'), ('heart', 'K'), ('tiles', 'A'), ('tiles', '2'),
 ('tiles', '3'), ('tiles', '4'), ('tiles', '5'), ('tiles', '6'), ('tiles', '7'),
 ('tiles', '8'), ('tiles', '9'), ('tiles', 'T'), ('tiles', 'J'), ('tiles', 'Q'),
 ('tiles', 'K'), ('clubs', 'A'), ('clubs', '2'), ('clubs', '3'), ('clubs', '4'),
 ('clubs', '5'), ('clubs', '6'), ('clubs', '7'), ('clubs', '8'), ('clubs', '9'),
 ('clubs', 'T'), ('clubs', 'J'), ('clubs', 'Q'), ('clubs', 'K'), ('pikes', 'A'),
 ('pikes', '2'), ('pikes', '3'), ('pikes', '4'), ('pikes', '5'), ('pikes', '6'),
 ('pikes', '7'), ('pikes', '8'), ('pikes', '9'), ('pikes', 'T'), ('pikes', 'J'),
 ('pikes', 'Q'), ('pikes', 'K')]


text:
Q: Does the dc.js script support E-commerce tracking We are trying to enable e-commerce tracking on our website.
Our current GA tracking code is modified to support display advertising, so the initial ga.js script was replaced by 'stats.g.doubleclick.net/dc.js'.
Could that be an issue for the e-commerce tracking?
Does the DoubleClick GA integration support e-commerce tracking?
Thanks


text:
Q: I want to extract all the decimal numbers from a string, how can I do that? I made this simple program with functions to calculate mean, median, and mode from a list of numbers. I want to select all the decimal numbers, whatever they are (10.00034, 1, $5.46, $0.90 or 0.5 for example from a string something like "5, 7 83 100, $5.07, and 7.834") from a string and cast them to float. How can I do that in Python 3? I want to capture all decimal numbers with leading zeros as floats including their leading zeros.
import string

def mode(x):
    if len(x) == 0:
        return 0
    else:
        theDictionary = {}
        for number in x:
            count = theDictionary.get(number, None)
            if count == None:
                theDictionary[number] = 1
            else:
                theDictionary[number] = count + 1
        theMaximum = max(theDictionary.values())
        for key in theDictionary:
            if theDictionary[key] == theMaximum:
                print("Mode: ", key)
                return key

def median(x):
    if len(x) == 0:
        return 0
    else:
        x.sort()
        midpoint = len(x) // 2
        print("Median: ", end=" ")
        if len(x) % 2 == 1:
            print(x[midpoint])
            med = x[midpoint]
        else:
            print((x[midpoint] + x[midpoint - 1]) / 2)
            med = (x[midpoint] + x[midpoint - 1]) / 2
        return med

def mean(x):
    if len(x) == 0:
        return 0
    else:
        theSum = 0
        theSum = float(theSum)
        for number in x:
            theSum = theSum + number
        average = theSum / len(x)
        print("Mean: ", average)
        return average

def main():
    lyst = []
    print ("Enter a list of numbers or enter to quit: ")
    numbers = input()
    if numbers == "":
        return 0
    else:
        lyst = numbers.split()
        lyst = [float(x) for x in lyst]
        print("List: ", lyst)
        mode(lyst)
        median(lyst)
        mean(lyst)
        main()

if __name__ == "__main__":
    main()

I tried a few things I found here on stackoverflow and they haven't worked. Any help would be appreciated.


text:
Q: How to remove a known last part from commands output string in one line? To rephrase - I want to use Bash command substitution and string substitution in the same line.
My actual commands are longer, but the ridiculous use of echo here is just a "substitution" for shortness and acts the same - with same errors ;)
I know we can use a Bash command to produce it's output string as a parameter for another command like this:
echo "$(echo "aahahah</ddd>")"
aahahah</ddd>

I also know we can remove last known part of a string like this:
var="aahahah</ddd>"; echo "${var%</ddd>}"
aahahah

I am trying to write a command where one command gives a string output, where I want to remove last part, which is known.
echo "${$(echo "aahahah</ddd>")%</ddd>}"
-bash: ${$(echo "aahahah</ddd>")%</ddd>}: bad substitution

It might be the order of things happening or substitution only works on variables or hardcoded strings. But I suspect just me missing something and it is possible.
How do I make it work?
Why doesn't it work?

A: Combine your commands like this
var=$(echo "aahahah</ddd>")
echo ${var/'</ddd>'}

A: When a dollar sign as in $word or equivalently ${word} is used, it asks for word's content. This is called parameter expansion, as per man bash.
You may write var="aahahah</ddd>"; echo "${var%</ddd>}": That expands var and performs a special suffix operation before returning the value.
However, you may not write echo "${$(echo "aahahah</ddd>")%</ddd>}" because there is nothing to expand once $(echo "aahahah</ddd>") is evaluated.
From man bash (my emphasis):

${parameter%word}
Remove matching suffix pattern.  The word is expanded to produce a
  pattern just as in pathname expansion.  If the pattern
  matches a trailing portion of the expanded value of parameter, then
  the result of the expansion is the expanded value of parameter
  with  the shortest  matching pattern (the ''%'' case) or the longest matching pattern (the ''%%'' case) deleted.


text:
Q: Co-existent classes in C++ What I need is to create two classes, that uses each other.
For example:
Class A contains objects of type Class B, and Class B contain objects of type Class A
But, when I compile, This is what happens: "error: ISO C++ forbids declaration of 'Map' with no type"
I modified my classes, to keep the Header (.h) file separated, but it didn't solved.
Perhaps, it's a basic question, but I don't know the keyword to search on google...
Code:
Cell.h:
Class Cell
{
public:
    Map *map;
}

Map.h:
Class Map
{
public:
    Cell *cell;
}

A: You want forward declaration and pointers.
//a.h
class B; //forward declare than a class B, exist somewhere, although it is not completely defined.

class A{
 map<string,B*> mapOfB;
};

//b.h
class A; //forward declare than a class A, exist somewhere, although it is not completely defined.
class B{
 map<string,A*> mapOfA;
}

and in your .cxx you would actually include the necessary headers
//a.cxx
#include "b.h"
A::A(){ /* do stuff with mapOfB */ }

//b.cxx
#include "a.h"
B::B(){ /* do stuff with mapOfA */ }

A: The problem in your case is that you have recursive includes. Cell.h includes Map.h which includes Cell.h. Instead of including like this just forward declare the classes:
In Cell.h:
class Map;

class Cell
{
    // ...
}

In Map.h:
class Cell;

class Map
{
    // ...
}

A: If class A contains a class B and class B also contains a class A then no, you cannot do that.
class B; // forward declaration of name only. Compiler does not know how much
         // space a B needs yet.

class A {
    private:
        B b; // fail because we don't know what a B is yet.
};

class B {
    private:
        A a;
};

Even if this would work there would be no way to construct an instance of either.
B b; // allocates space for a B
     // which needs to allocate space for its A
     // which needs to allocate space for its B
     // which needs to allocate space for its A
     // on and on...

The can however contain pointers (or references) to each other.
class B; // forward declaration tells the compiler to expect a B type.

class A {
    private:
        B* b; // only allocates space for a pointer which size is always
              // known regardless of type.

};

class B {
    private:
        A* a;
};


text:
Q: Simple calculus question Definition: $\Delta f(x) = f(x + \Delta x) - f(x)$. Find $\Delta^nf(x)$. My guess is
$$\Delta^nf(x)
 = f(x + n\Delta x) + \sum_{k=0}^{n}(-1)^kkf(x + (n-k)\Delta x) + (-1)^nf(x)$$
Is this guess correct?

A: Calculate the first few values:
$$\begin{align*}
\Delta^2f(x)&=\Delta\left(f(x+\Delta x)-f(x)\right)\\
&=\Big(f(x+2\Delta x)-f(x+\Delta x)\Big)-\Big(f(x+\Delta x)-f(x)\Big)\\
&=f(x+2\Delta x)-2f(x+\Delta x)+f(x)\;,
\end{align*}$$
$$\begin{align*}
\Delta^3f(x)&=\Delta\left(\Delta^2f(x)\right)\\
&=\Delta\Big(f(x+2\Delta x)-2f(x+\Delta x)+f(x)\Big)\\
&=\Big(f(x+3\Delta x)-2f(x+2\Delta x)+f(x+\Delta x)\Big)\\
&\qquad\quad-\Big(f(x+2\Delta x)-2f(x+\Delta x)+f(x)\Big)\\
&=f(x+3\Delta x)-3f(x+2\Delta x)+3f(x+\Delta x)-f(x)\;,
\end{align*}$$
and
$$\begin{align*}
\Delta^4f(x)&=\Delta\left(\Delta^3f(x)\right)\\
&=\Delta\Big(f(x+3\Delta x)-3f(x+2\Delta x)+3f(x+\Delta x)-f(x)\Big)\\
&=\Big(f(x+4\Delta x)-3f(x+3\Delta x)+3f(x+2\Delta x)-f(x+\Delta x)\Big)\\
&\qquad\quad-\Big(f(x+3\Delta x)-3f(x+2\Delta x)+3f(x+\Delta x)-f(x)\Big)\\
&=f(x+4\Delta x)-4f(x+3\Delta x)+6f(x+2\Delta x)-4f(x+\Delta x)+f(x)\;.
\end{align*}$$
Now look at those sequences of coefficients:
$$\begin{align*}
&1,-2,1\\
&1,-3,3,-1\\
&1,-4,6,-4,1
\end{align*}$$

*

*Do they match your formula?

*Are they familiar from some other context?

A: Your formula gives $\Delta f(x) = f(x+\Delta x)-2 f(x)$, so it can't be right.
Try computing the formula for $\Delta^2 f, \Delta^3 f$ and see if you can spot the pattern. Then verify by induction.
Here is the correct formula:

 $$\Delta^n f(x) = \sum_{k=0}^n (-1)^k \binom{n}{k} f(x+(n-k)\Delta x)$$


text:
Q: Calculate marginal pdf of $Y$ when marginal pdf of $X$ and conditional distribution of $Y$ is given The Question

So I have tried the formula
$f_{X,Y}(x,y)=f_{Y\mid X}(y\mid x)\cdot f_{X}(x)$ but I am not able to figure out the bounds and I am not sure what to do after the bounds are found
Please do let me know if you guys have any idea on how to solve this question

A: $$f_{XY}(x,y)=f_X(x)\cdot f_{Y|X}(y|x)=2x^2\mathbb{1}_{(0;1)}(x)\cdot\mathbb{1}_{(0;1/x)}(y)$$
now to calculate $f_Y(y)$ you have to integrate in X, that is
$$f_Y(y)=\int_0^1 2x^2dx=2/3$$
when $y \in[0;1]$
and
$$f_Y(y)=\int_0^{1/y} 2x^2 dx=\frac{2}{3y^3}$$
when $y>1$
To understand integral bounds it is useful to do a drawing of the integration area, first


text:
Q: memory leaks with NSAttributedStrings My app is book-like with 77 chapters each comprised of several pages. On each page, text is displayed in a UITextView. The data for this is stored in a dictionary of type [String: [NSAttrubutedString]]. The keys are chapters, the array elements associated with each chapter are the strings for each page in that chapter.
Instruments shows in the vicinity of 1800 memory leaks when the app first boots. I sometimes see 1 to 17 more leaks upon accessing other pages but this is rare and unpredictable. The 1800 varies and only appears once. I had no such issues when using non-attributed Strings. I might also add this is my first experience with attributed strings.
One example each of some leaks (sizes are total for that type):
    * Malloc / [NSConcreteMutableAttributedString replaceCharactersInRange:withString:] / 171 kB
    * Malloc 80 Bytes / -[NSRLEArray_makeNewListFrom:] 17 kB
    * _NSCFString / -[NSPlaceholderMutableString init]  23 kB
    * Malloc / [NSMutableRLEArray_setBlockCapacity:] / 25 kB
    * NSConcreteMutableAttributedString / _decodeObjectBinary 12 kB
Although I use the mutable version to form my strings I insert them into the arrays as the non-mutable NSAttributedString version. The dictionary of arrays is archived as a plist then read into dictionary of the same type when the app is booted. I thought this might be the issue but attempts to read directly from the archive produced the same leaks. I don't know why the leaked objects read as mutable.
I'm not sure what code, if any, would be helpful here, let me know.
Edit: I've replaced the dictionary with an array, [[NSAttributedString]] but still have the same issue. At least three of the leaked categories seem related to the same strings, the number of leaks in each is about the same.
Edit: I've eliminated my leaks by creating the dictionary live on viewDidLoad as opposed to reading it from an archive. But I'm still curious why this behavior with attributed strings versus strings.


text:
Q: Should I leave an unreachable break in a case where I throw an exception? Is it silly of me to leave unreachable break statements in a case that just throws an Exception anyway?  The defensive part of me wants to leave it there in the event that the logic changes.  Another part of me doesn't want other developers seeing compiler warnings on my code ("Unreachable code detected").
switch (someInt)
{
    case 1:
        // Do something
        break;
    case 2:
        // Do something else
        break;
    case 3:
        // Oh, we don't use threes here!
        throw new Exception("Business rules say don't use 3 anymore");
        break; // Unreachable...until the fickle business rules change...
    default:
        throw new Exception("Some default exception");
        break; // Unreachable...until...well, you get the idea.
}

What to do?
UPDATE
I see a few responses saying that removing the throw at a later date would cause a compiler error.  However, simply removing (or commenting) the throw without a break following it would stack the cases, which may be unintended behavior.  I'm not saying it's a likely scenario, but...well, is defensive programming about combating only likely scenarios?

A: I'd remove them. Several reasons:

*

*You don't need them at the moment

*Seeing lots of warnings always makes me nervous as you can lose real warnings in the noise coming from this type warning (assuming you have warn as error off).

A: I wouldn't "hide" it in the switch. I would throw ArgumentExceptions as soon as possible. That avoids side-effects and is also more transparent.
Somebody might add code before the switch at some point which uses someInt although it is 3.
For example:
public void SomeMethod(int someInt)
{
    if (someInt == 3)
        throw new ArgumentException("someInt must not be 3", "someInt");

    switch (someInt)
    {
        // ...
    }
}

A: By ignoring some compiler warnings you are reinforcing the bad behavior of ignoring any compiler warning. In my opinion, that's a greater risk than any advantage you gain from leaving the break statements in.
EDIT: I removed my original point about the compiler forcing you to put the break statements back in if the throw statements were to be removed. As payo pointed out, in some cases, the compiler wouldn't. It would just combine the case with the one below it.

A: Personally, I would never leave unreachable code in production code. It's fine for testing, but don't leave it as such.
You would never do this would you?
public void MyMethodThatThrows()
{
    throw new Exception();
    return;  // unneeded
}

so why keep the break?

A: I'd remove it.
It gets rid of the warnings, and even if the logic were to change and the Exception to be removed, you'd receive a compiler error saying that a break needs to be added back in.

A:
The defensive part of me wants to leave it there in the event that the
  logic changes.

What logic exactly is subject to change here? What happens when an exception is thrown is documented pretty well. And I think you can be reasonably sure that no later revision to C# will effect a breaking change of "all programs written so far are no longer working"  magnitude.
Even if there were no compiler warning, redundant code is not a good thing unless there is the possibility that the code might come into play by preventing bugs during routine maintenance, which in this case we cannot reasonably say that such a possibility exists.

A:
The defensive part of me wants to leave it there in the event that the logic changes.

Well, if you remove the throw and forget to add a break the compiler will let you know.
I see no reason for the break to be there.  It is redundant and you will just trigger a warning anyway, so I would remove it. There is no good reason to leave useless code around cluttering up your logic.

A: I wish my project sources were so cool and trouble-less, that I'd have to think about such minor cases of defensive programming :)
I mean there are so-o-o many pitfalls in software-development - COM and Interop, Security/Permissions and Auth, Certificates, that ... gosh, can't tell you how much code I'd have to write to defend myself from shooting in the foot.
Just remove this break, because it's redundant, it's confusing for fellows who knows that 'case' should end with break or return and should get being obvious for fellows that don't know this.

A: MSDN C# Reference states: "A jump statement such as a break is required after each case block, including the last block whether it is a case statement or a default statement."
So, doesn't "throw" constitute a "jump statement"? I think it does. Thus, "break" is not required, and the "unreachable" issue goes away. :)