text:
Q: How do you integrate custom providers into the Microsoft Web Deployment Tool? I am trying to extend the Microsoft Web Deployment tool and MSDeploy with a custom provider because I want to run custom tasks on the destination deployment machine as part of the process. The general documentation is pretty good outside of custom provider development, but the documentation for doing any sort of extension seems to be non-existent towards abysmal.
I've been researching this for several days now and have found some bits and pieces that have allowed me to get pretty far into the process without any real documentation. I've almost hacked my way through the process but now I have one final problem: MSDeploy will not recognize my custom provider.
I have created two classes one that extends Microsoft.Web.Deployment.DeploymentProviderFactory (which has both the Name and FriendlyName properties overriden to the name of my custom provider "archimedes"); the other extends Microsoft.Web.Deployment.DeploymentObjectProvider which also has an overriden Name property "archimedes". I did this by following the custom BatchProvider example you can find online. It looks like this:
ArchimedesProviderFactory (which extends DeploymentProviderFactory and has the Deployment ProviderFactory attribute assigned to the class):
public override string FriendlyName
{
    get { return "archimedes"; }
}

public override string Name
{
    get { return "archimedes"; }
}

The ArchimedesProvider class extends DeploymentObjectProvider and has this:
public override string Name
{
    get { return "archimedes"; }
}

In my sourcemanifest.xml file I have it added an entry:
<archimedes path="..." />

I have placed the assembly file that contains those classes in %program files%\IIS\Microsoft Web Deploy\Extensibility as I was directed too by the material I found online.
The funny thing is that during the build of a package in Visual Studio 2010, my providers are having code called on them from that directory - so VS is definitely connecting to my assembly placed in there somehow (for example I can throw exceptions and see that they were thrown during the process of building a package).
However during actual test deployment of the package from the generated .cmd file, I get an error that the factory for provider "archimedes" cannot be found. Also typing:
MSDeply -verb:dump -source:archimedes -debug

Returns the following:
    Microsoft.Web.Deployment.DeploymentException: Unknown factory 'archimedes'.
   at Microsoft.Web.Deployment.DeploymentProviderSettingCollection..ctor(String factoryName)
   at Microsoft.Web.Deployment.DeploymentProviderOptions..ctor(String factoryName)
   at MSDeploy.MSDeploy.GetObjectParameters(Dictionary`2 parameters, Boolean isDestination, DeploymentBaseOptions& retbaseOptions, DeploymentProviderOptions& re
tproviderOptions)
   at MSDeploy.MSDeploy.ExecuteWorker()
   at MSDeploy.MSDeploy.Execute()
   at MSDeploy.MSDeploy.Main(String[] unusedArgs)
Error count: 1.

So besides the fact that there appears to be no coherent, central source of documentation for custom provider development (does anyone know of a place, please do tell if you found one), my main problem is that for some reason Visual Studio will see and call my provider factory from the assembly file I dumped into the Extensibility folder, but the actual msdeploy/webdeploy does not see it. Does anyone have any ideas?
Thanks a ton...

A: OK, this was a simple mistake, although a non-obvious one since the package building portion accessed the code alright and called it from my provider assembly. The problem was that since just about everything in the web application targets the 4.0 framework the class library project I added with the custom provider code did as well. I had to set the target framework to 2.0 and it all started working. None of the error reporting was overly obvious.


text:
Q: Problems in supporting multiple resolutions I am having trouble managing my application layouts in three different resolutions; 720x1280, 1080x1920 and 1440x2560.
In drawable-xhdpi folder is the corresponding images to 720x1280 resolution.
The folder drawable-xxhdpi is the corresponding images to 1080x1920 resolution and in drawable-xxxhdpi to 1440x2560.
I began to adjust the screens in layout folders. The layout-sw360dp was setting screens for 720x1280 and the layout-sw480dp the 1080x1920.
When testing in the emulator 720x1280 all settings worked perfectly.
But to test the emulator 1080x1920, oddly taking this information in layout-sw360dp folder and not the layout-sw480dp.
In the case of adjusting each folder layout-sw360dp and layout-sw480dp, I'm using margin with values in 'dp' and emulator higher values (layout-sw480dp) are being dropped are being used and the values of the layout-sw360dp.
How can I manage three screen sizes correctly?

A: Well designed Android applications cater for varying screen sizes, the screen size being a function of both resolution and density. Using several layout-sw###dp folders allows you to vary the layout according to the width of the display, e.g. showing fewer elements and controls on a small screen and perhaps more detail on a large one.
The 'sw' in the layout folder name is the 'shortest width' a display must have in device independent pixels (dip). One dip = 1 real pixel on a 160 density screen. So on a 320 density screen, 2 real pixels make up one dip.
Your nexus 5 has 480/160 = 3 real pixels per dip. So with a width resolution of 1080, that is 360dip wide.
Your nexus 4 has 320/160 = 2 real pixels per dip. So with a width resolution of 768, that is 384dip wide.
Neither device is more than 480 dip wide so both use the sw360dp folder.
Both devices are physically very similar in size. The Nexus 5 (5.4inch screen) has more pixels than the Nexus 4 (4.7inch screen) but the pixels are physically smaller. So it is correct that the same layout is used for both. The UI should look the same on both devices, assuming you correctly specify the size and layout of your various UI elements in dip.
As a further example, I have an old tablet (10inch screen) with a resolution of 800x1280 and a low density of 149, hence is 859dip wide. You can comfortably display far more info on a screen that size than on a Nexus 4/5, hence you might consider creating a layout-sw720dp for that.
So you appear to be doing exactly the right thing already by designing different layouts for different screen sizes. Just remember that resolution is not the same thing as screen size. Screen size is a combination of resolution and density.
As for your drawables, you are also already doing the right thing by using drawable-xhdpi, drawable-xxhdpi etc with appropriate resolution images in each one. So for example a small device with an extremely high density would likely use the 1440x2560 images and the sw360dp layout. My low res tablet would use the 720x1280 images, unless you'd put something in drawable-mdpi which is where it would look first.
So firstly you'd create appropriate resolution images in the drawable folders so that they would look as good as possible on different resolution screens. Then create appropriate swxxxdp for your layouts so they take up the appropriate space depending on the physical screen size, i.e. make good use of available screen space on large devices and don't clutter up small ones. It's likely you would want to go further and create -land and -port versions of each as well.
It is worth noting that even if you only have one layout folder and one drawable folder, your application will still work on all devices. Android simply looks for the best choice and if there is only one, it'll use that. Adding in the various folders simply allows you to make your app look as good as possible on a range of devices.
Everything I have discussed here and more is explained in detail at http://developer.android.com/guide/practices/screens_support.html.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Serial Ports, CreateFile and SetCommState I'm using Windows API's CreateFile and SetCommState functions to open a number of serial ports to read and write from, selecting ports using this notation:
\\?\COM1

I've been logging performance closely, and for some odd reason the CreateFile call takes about as much time as the SetCommState calls do (about 4.1 seconds).
I find this very odd and makes me suspect that both CreateFile and SetCommState perform a set of similar tasks with the windows subsystem that handles serial port communication.
Could there be a way to speed up one of both calls, or eliminate one, for example calling CreateFile in such a way it already uses the DCB I've got prepared to call SetCommState with?

A: The documentation you posted suggests calling GetCommState to initialize the DCB structure.  I wonder if the delay is because you're setting something you don't care about?  For what it's worth, I've noticed much bigger delays opening Bluetooth virtual COM ports than regular or USB ports.


text:
Q: How to define a Hex type in JavaScript using Flow? I'm building a React component which, as part of its props, recieves a value which can be a string to be parsed as hexadecimal color.
I can check if the value is a string type, but I'd like to be more specific and only accept a string that looks like a hex colour, without adding validation logic to the component itself.
I'm trying to define the Types using Flow.js, so my question is:
Is there any way to check this as a Type using Flow.js? And how would that implementation look like?


text:
Q: Getting null values in asp.net mvc model when passing values through angular js I have created model in asp.net mvc with constructor to create new guid id for ID field which inherits from base class. Now i pass values for two parameters of the model other than ID from html page using angular js while calling the $http.post service. At web api I am receiving the null values only id is getting generated.
Model:
public class EngineeringTeamDTO : Entity
{
    public EngineeringTeamDTO() : base()
    {

    }
    public EngineeringTeamDTO(Guid ID) : base(ID)
    {

    }

    [MaxLength(50)]
    public String TeamName { get; set; }

    public String Note { get; set; }
}

Web api
public IHttpActionResult PostEngineeringTeamDTO(EngineeringTeamDTODemo engineeringTeamDTO)
{
    //code
}

So here in this web api I am getting null values for TeamName and Note parameter when calling the web api through the angular js. If i remove the constructor from model it works fine. But constructor is needful for me.
Angular Code:
   $scope.addteam = function (ETD) {
    debugger

    $http.post($rootScope.addEngTeam, ETD).success(function (data) {
        alert("ADDED")

    }).error(function (data) {
        $scope.Space = "Error" + data;
    });

}

Html Code:
  <input type="text"   name="TeamName" ng-model="ETD1.TeamName" required  />
                                <input type="text"  name="Note" ng-model="ETD1.Note" required />
      <input type="button" value="Add"  ng-click="addteam(ETD1)"/>


text:
Q: Cant open port on Windows 2012R2 I really never had problem with Windows Firewall, however today on new installation i`m trying to open port 110 but i cant.
My firewall rule is: printscreen
telnet myip 110
Connecting To myip...Could not open connection to the host, on port 110:
Connect failed

If i change "Remote Port" to "Any", everything works fine.

A: You generally implement firewall rules based on destination port. Most applications (client-side) choose a random source port when the initiate communication. For example, your web browser uses random TCP source ports against destination port 80.
So, the correct way to go is to allow destination port 110, source port any.
Heres some background: Ephemeral ports on Wikipedia


text:
Q: VB6 installer on 64-bit OS on x64 CPU I had a VB6 application setup file that was working perfectly on Windows Server 2003 32-bit OS.
Now the customer has moved to Windows Server 2012 64-bit on Intel Xeon CPU E5 which is x64-based processor.
The installer gives the error:

Setup Bootstrap for Visual Basic Setup Toolkit has stopped working

The error occurs when the installer is Copying Files and Processing VB6STKIT.DLL
What is the solution?


text:
Q: is it possible to implement Jquery Datatable ajax server side export operations(PDF , EXCEL, CSV)? i need to implement Datatable server side ajax export options. i search over internet found https://datatables.net/forums/discussion/5505/server-side-processing-with-export-to-csv-and-pdf but i have some problems while implementing this.
Thanks in advance..


text:
Q: How to loop a function to perform a task every 15 minutes (on the 0/15/30/45 minute mark)? I have a program running on a Raspberry Pi, and I want to pull some data from a thermometer every 15 minutes at 0, 15, 30 and 45 minutes past the hour.
I have tried this using a while loop, I previously used time.sleep(900) effectively, but this sometimes drifted away from 0, 15, 30 and 45 minutes past the hour.
At the moment I currently have this;
from datetime import datetime

def run(condition):
    while condition == True:
        if (datetime.now().minute == (0 or 15 or 30 or 45)):
            #perform some task
        temperature_store()

For sake of simplicity I have not got into what temperature_store() does, but it reads the temperature from a sensor plugged into the Pi and then prints it.
I want temperature_store() to occur every 15 minutes, but currently, it is happening every second.
I am aware that it is probably because I have the logic/syntax of the while loop wrong, but I cannot figure it out. (Do not have much experience with python scripts and delays in time).

A: There's two ways to do this: the 'easy' way, and the stable way.
The easy way is simply to do the following:
from datetime import datetime
from time import sleep

def run(condition):
    while datetime.now().minute not in {0, 15, 30, 45}:  # Wait 1 second until we are synced up with the 'every 15 minutes' clock
        sleep(1)

    def task():
        # Your task goes here
        # Functionised because we need to call it twice
        temperature_store()

    task()

    while condition == True:
        sleep(60*15)  # Wait for 15 minutes
        task()

This essentially waits until we are synced up with the correct minute, then executes it, and simply waits 15 minutes before looping. Use it if you wish, it's the simplest way in pure Python. The issues with this are countless, however:

*

*It syncs up with the minute, not the second

*It's machine dependent, and may give incorrect readings on some machines

*It needs to run continuously!

The second method is to use cron-jobs, as suggested in the comments. This is superior because:

*

*It uses system-level events, not timers, so we can assure the best possible accuracy

*Since we're not waiting, there's no room for error

*It only runs the function once it gets the aforementioned event setter.

So, to use, simply (assuming you're on Linux):
from crontab import CronTab

cron = CronTab(user='username')  # Initialise a new CronTab instance
job = cron.new(command='python yourfile.py')  # create a new task
job.minute.on(0, 15, 30, 45)  # Define that it should be on every 0th, 15th, 30th and 45th minute

cron.write()  # 'Start' the task (i.e trigger the cron-job, but through the Python library instead

(obviously, configure username appropriately)
In yourfile.py, in the same path, simply put your code for temperature_store().
I hope this helps. Obviously, go with the first methods or even the suggestions in the comments if you prefer, but I just felt that the entire loop structure was a bit too fragile, especially on a Raspberry Pi. This should hopefully be something more stable and scalable, should you want to hook up other IoT things to your Pi.

A: I did the module test in case of the program that prints seconds every 15 seconds.
The below code does not contain sleep().
You can change second to minute in below code to do tasks every 15 minutes.
from datetime import datetime

while True:
    a = datetime.now().second
    if (a % 15) == 0:  # every 15 seconds
        print(a)  # ---- To do something every 15 seconds ---- #
        while True:  # discard any milliseconds or duplicated 15 seconds
            a = datetime.now().second
            if (a % 15) is not 0:
                break

But I think that cron or any other schduler modules are good choices.

A: I have come up with the following answer, using some of the logic from @geza-kerecsenyi 's answer
def run():
    first = True
    while first == True:
        second = True
        while second == True:
            if datetime.now().minute == 0 or datetime.now().minute ==15 or datetime.now().minute ==30 or datetime.now().minute == 45:
                action()
                sleep(899)

I am not sure which of these is better in terms of CPU or which is more effective to run, but the logic seems sound on both.
[@geza-kerecsenyi will mark your answer as correct]


text:
Q: Cannot delete Git tags which have special characters $ git tag
+"feature/04-28_v001-11"+
+"feature/04-28_v001-19"+

Above git tags not able to delete since + and " exist in the tags.

A: The error message
error: cannot lock ref 'refs/tags/+"feature/04-28_v001-11"+': unable to create directory for .git/refs/tags/+"feature/04-28_v001-11"+

indicates that you are not operating on POSIX. I assume you are on Windows.
As the error message indicates, Git is unable to create a directory containing the doublequote character. The conclusion is that the tag does not exist on the filesystem, but only in the packed-refs file.
WARNING: The following suggests a method to fix your problem, but you are messing with Git's database. Be sure to have a backup of the repository before you continue.
Before you continue, be sure the the repository is quiescent. No Git operations must be on-going. Close all UIs including code editors and IDEs that would access the repository.
Now, make a backup of the file
.git/packed-refs

just in case you break something.
To remove the tag, edit this file with a modern source code editor that can cope with Unix-style line-terminators (LF instead of CRLF) (any editor but Notepad will do). Look up the lines mentioning the tags, and delete the lines and the lines following them if they begin with the caret ^.
That is, when you start with
# pack-refs with: peeled fully-peeled sorted
9e72299d[...] refs/heads/master
57689754[...] refs/tags/bad/one
^b73b6860[...]
03706a09[...] refs/tags/bad/two
^ed20caaf[...]
f9d1d51c[...] refs/tags/good/one
^4974cb42[...]

you remove the bad ones, you should end with
# pack-refs with: peeled fully-peeled sorted
9e72299d[...] refs/heads/master
f9d1d51c[...] refs/tags/good/one
^4974cb42[...]

Call git tag to verify the result.


text:
Q: C++: std::vector.push_back() и классы В своей программе я создал класс Score. В нем я создал пустой конструктор, а также конструктор, в котором передаваемая строка na по умолчанию равна unknown.
class Score{
    string name;
    int sc;

public:
    Score();
    Score(const int &sc, const string &na = "unknown"){
        this -> name = na;
        this -> sc = sc;
    }
};

Далее я хочу создать вектор объектов класса, который будет заполняться по мере считывания из специально заготовленного файла.
using namespace std;
int main(){
    ifstream F;
    string name;
    int score;
    vector<Score> v;

    F.open("score.txt");
    if( ( F.is_open() ) && ( !F.eof() ) ){
        F >> name;
        F >> score;
        v.push_back(score,name);
    }
    F.close();
return 0;
}

На данном этапе компилятор выдает ошибку -
<...>\main.cpp:60: error: no matching function for call to 'std::vector<Score>::push_back(int&, std::string&)'
         v.push_back(score,name);
                               ^

Искренне не понимаю, что я делаю не так и прошу помочь разобраться. Заранее благодарю.

A: Используйте emplace_back - это более лаконично и производительно. Тогда Вы сможете писать как писали изначально:
v.emplace_back(score, name);

Это будет работать только в режиме C++11 или C++14, но сейчас уже все основные компиляторы хорошо поддерживают эти стандарты (но пока не включат их по умолчанию, например g++ и clang++ требуют ключ -std=c++11).
Еще несколько замечаний:

*

*Вы ничего не потеряете, заменив const int & на int - даже наоборот

*Вашу проверку потока можно заменить просто на if (F) - там идет преобразование в bool, эквивалентное вызову good()

*Вместо open можно использовать просто конструктор ifstream, принимающий имя файла, а вызывать close вручную в этом примере вообще не обязательно, так как F тут же выходит из области видимости, и файл закроется в деструкторе

*Менее очевидная доработка: если вы намерились копировать строку, передаваемую в конструктор, то наиболее эффективно передавать ее по значению, а в конструкторе переносить со строками это плохая идея из-за small string optimization, и вообще подводных камней тут очень много, так что отзываю эту рекомендацию <_<

Смотрите книжки Effective C++ и Effective Modern C++ за подробностями

A: Нужно писать так v.push_back(Score(score,name));


text:
Q: Which type of transactions does waves platform have for smart accounts and smart assets? How many transactions does waves have? will Waves Smart contracts add another transaction type to the waves platform? And where to find examples of those transactions?

A: There are currently 15 different types of transactions in the Waves Blockchain. Yes, Waves platform added a new transaction for setting a script which called SetScript transaction and a new transaction for smart assets called SetAssetScript transaction.
You can check all transactions examples here.


text:
Q: Scrapy Shell Unresponsive for Certain Urls I'm working on a web crawler on the NIH grant database and I am running into an issue with scrapy's shell when I try to inspect the response object.
After entering this command:
scrapy shell https://projectreporter.nih.gov/project_info_results.cfm?aid=8535284&icde=27160266

I get this output as the shell starts up:
$ 2015-11-20 01:18:10 [scrapy] INFO:

Scrapy 1.0.3 started (bot: tutorial)
2015-11-20 01:18:10 [scrapy] INFO: Optional features available: ssl, http11
2015-11-20 01:18:10 [scrapy] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'tutorial.spiders', 'SPIDER_MODULES': ['tutorial.spiders'], 'LOGSTATS_INTERVAL': 0, 'BOT_NAME': 'tutorial'}
2015-11-20 01:18:10 [scrapy] INFO: Enabled extensions: CloseSpider, TelnetConsole, CoreStats, SpiderState
2015-11-20 01:18:10 [scrapy] INFO: Enabled downloader middlewares: HttpAuthMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, DefaultHeadersMiddleware, MetaRefreshMiddleware, HttpCompressionMiddleware, RedirectMiddleware, CookiesMiddleware, ChunkedTransferMiddleware, DownloaderStats
2015-11-20 01:18:10 [scrapy] INFO: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware
2015-11-20 01:18:10 [scrapy] INFO: Enabled item pipelines:
2015-11-20 01:18:10 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6027
2015-11-20 01:18:10 [scrapy] INFO: Spider opened
2015-11-20 01:18:11 [scrapy] DEBUG: Crawled (200) <GET https://projectreporter.nih.gov/project_info_results.cfm?aid=8535284> (referer: None)
[s] Available Scrapy objects:
[s]   crawler    <scrapy.crawler.Crawler object at 0x101465d10>
[s]   item       {}
[s]   request    <GET https://projectreporter.nih.gov/project_info_results.cfm?aid=8535284>
[s]   response   <200 https://projectreporter.nih.gov/project_info_results.cfm?aid=8535284>
[s]   settings   <scrapy.settings.Settings object at 0x1028bbbd0>
[s]   spider     <DefaultSpider 'default' at 0x1047b7510>
[s] Useful shortcuts:
[s]   shelp()           Shell help (print this help)
[s]   fetch(req_or_url) Fetch request (or URL) and update local objects
[s]   view(response)    View response in a browser
2015-11-20 01:18:12 [root] DEBUG: Using default logger
2015-11-20 01:18:12 [root] DEBUG: Using default logger

Unfortunately it freezes there and never continues on, therefore I can't manipulate the response object or move forward.
If I put in the same command with any other url, I get this response almost immediately:
$ scrapy shell https://reddit.com
2015-11-20 01:20:24 [scrapy] INFO: Scrapy 1.0.3 started (bot: tutorial)
2015-11-20 01:20:24 [scrapy] INFO: Optional features available: ssl, http11
2015-11-20 01:20:24 [scrapy] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'tutorial.spiders', 'SPIDER_MODULES': ['tutorial.spiders'], 'LOGSTATS_INTERVAL': 0, 'BOT_NAME': 'tutorial'}
2015-11-20 01:20:24 [scrapy] INFO: Enabled extensions: CloseSpider, TelnetConsole, CoreStats, SpiderState
2015-11-20 01:20:24 [scrapy] INFO: Enabled downloader middlewares: HttpAuthMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, DefaultHeadersMiddleware, MetaRefreshMiddleware, HttpCompressionMiddleware, RedirectMiddleware, CookiesMiddleware, ChunkedTransferMiddleware, DownloaderStats
2015-11-20 01:20:24 [scrapy] INFO: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware
2015-11-20 01:20:24 [scrapy] INFO: Enabled item pipelines:
2015-11-20 01:20:24 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6028
2015-11-20 01:20:24 [scrapy] INFO: Spider opened
2015-11-20 01:20:24 [scrapy] DEBUG: Redirecting (301) to <GET https://www.reddit.com/> from <GET https://reddit.com>
2015-11-20 01:20:25 [scrapy] DEBUG: Crawled (200) <GET https://www.reddit.com/> (referer: None)
[s] Available Scrapy objects:
[s]   crawler    <scrapy.crawler.Crawler object at 0x107ea0d10>
[s]   item       {}
[s]   request    <GET https://reddit.com>
[s]   response   <200 https://www.reddit.com/>
[s]   settings   <scrapy.settings.Settings object at 0x1092f7bd0>
[s]   spider     <DefaultSpider 'default' at 0x10ba31490>
[s] Useful shortcuts:
[s]   shelp()           Shell help (print this help)
[s]   fetch(req_or_url) Fetch request (or URL) and update local objects
[s]   view(response)    View response in a browser
2015-11-20 01:20:26 [root] DEBUG: Using default logger
2015-11-20 01:20:26 [root] DEBUG: Using default logger

In [1]:

^^^ the 'In [1]:' indicating the request and response was carried out correctly.
What's more, if I download the html of my initial url as a local file via 'Save As' and query that using the scrapy command:
$ scrapy shell file://127.0.0.1/path/to/file.html

I get the scrapy shell to work as intended.
I guess this was a long winded way of asking, what is it about the url that I am using that is tripping up the scrapy shell? is it the fact that I had to submit a search to arrive at the page? something else? Any help would be greatly appreciated.


text:
Q: conditional @Autowired? I have a HsqldbReconciler (for "work" with a HSQLDB database) which I autowired, like:
@Autowired
HsqldbReconciler hsqldbReconciler;

In Future there will be a OracleReconciler, MssqlReconciler, etc. I will need to use them accordingly to the type of connection a user has chosen.
How should I implement this? Usually I would have a kind of factory, which returns only the needed Reconciler. The only way in spring, I can currently imagine, is to Autowire an instance of each Reconciler, then use one of them in the code. Is there a better way?

A: make a Factory Class that will contain all your beans, e.g
@Component
class Factory{
  @Autowired HsqldbReconciler hsqldb;
  @Autowired OracleReconciler oracle;
  @Autowired MssqlReconciler mssql;

  public Object getInstance(String type){
    switch(type){
     case "mssql" : return mssql;
     case "oracle" : return oracle;
     // and so on
     default : return null;
   }

  }

}

Now use this Factory as follows
class SomeClass{

  @Autowired private Factory factory;

  public Object someMethod(){
    Object reconciler = factory.getInstance("mssql");
    ((MssqlReconciler)reconciler).someMethod();
  }
}

A: Define them in your Config with the same name, but different conditions:
@Bean(name = "dbReconciler")
@Conditional(HsqldbReconcilerEnabled.class)
public ReconcilerBase getHsqldbReconciler() {
    return new HsqldbReconciler();
}
@Bean(name = "dbReconciler")
@Conditional(OracleReconcilerEnabled.class)
public ReconcilerBase getOracleReconciler() {
    return new OracleReconciler();
}
@Bean(name = "dbReconciler")
@Conditional(MssqlReconcilerEnabled.class)
public ReconcilerBase getMssqlReconciler() {
    return new MssqlReconciler();
}

create conditions reading from app.properties:
HsqldbReconciler.enabled=true
OracleReconciler.enabled=false
MssqlReconciler.enabled=false

like this:
public class HsqldbReconcilerEnabled implements Condition {
    private static final String PROP_ENABLED = "HsqldbReconciler.enabled";
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
         String property = context.getEnvironment().getProperty(PROP_ENABLED);
         return Boolean.parseBoolean(property);
    }
}
// etc...

use like:
@Autowired
@Qualifier("dbReconciler")
ReconcilerBase dbReconsiler;

ensure you're not enabling multiple beans at the same time.


text:
Q: Gate io error INVALID_SIGNATURE in app script I try to get data from Exchange Gate.io by app script.
This is my code:
function data() {
var key = "***"
var sec = "***"
var timestamp = Math.floor(Date.now() / 1000)

var base = "https://api.gateio.ws";
var prefix = "/api/v4"
var pat = '/wallet/total_balance'

var sign = "timestamp=" + timestamp;

Logger.log(sign)

  var signature = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512, sign, sec);
  signature = signature.map(function(e) {
    var v = (e < 0 ? e + 256 : e).toString(16);
    return v.length == 1 ? "0" + v : v;
}).join("");

    var params = {
        'method': "get",
        'headers': {
                      'Accept': 'application/json',
                      'Content-Type': 'application/json',
                       'KEY': key,
                       'Timestamp': timestamp,
                       'SIGN': signature,

                      },
        'muteHttpExceptions': true,
    };

   var data = UrlFetchApp.fetch(base + prefix + pat, headers=params);
   Logger.log(data)

}

I get the error:
{"label":"INVALID_SIGNATURE","message":"Signature mismatch"}

The Keys is valid problem in code.
to learn more check that: https://www.gate.io/docs/apiv4/en/#retrieve-user-s-total-balances

A: About the official document, when I directly access the URL, an error occurs. But, when I search it on Google and access it, I could open the document. From the document, I found the documentation for the authorization and the document for "Retrieve user's total balances". And also, I found the following sample python script from the official document.
import time
import hashlib
import hmac
import requests

def gen_sign(method, url, query_string=None, payload_string=None):
    key = ''        # api_key
    secret = ''     # api_secret

    t = time.time()
    m = hashlib.sha512()
    m.update((payload_string or "").encode('utf-8'))
    hashed_payload = m.hexdigest()
    s = '%s\n%s\n%s\n%s\n%s' % (method, url, query_string or "", hashed_payload, t)
    sign = hmac.new(secret.encode('utf-8'), s.encode('utf-8'), hashlib.sha512).hexdigest()
    return {'KEY': key, 'Timestamp': str(t), 'SIGN': sign}

host = "https://api.gateio.ws"
prefix = "/api/v4"
headers = {'Accept': 'application/json', 'Content-Type': 'application/json'}

url = '/wallet/total_balance'
query_param = ''
# for `gen_sign` implementation, refer to section `Authentication` above
sign_headers = gen_sign('GET', prefix + url, query_param)
headers.update(sign_headers)
r = requests.request('GET', host + prefix + url, headers=headers)
print(r.json())

In your situation, when this script is converted to Google Apps Script, I thought that it is your goal. When this python script is converted to Google Apps Script, it becomes as follows.
Sample script:
Before you use this script, please set the variables of key and secret.
function gen_sign_(key, secret, method, url, query_param = "", payload_string = "") {
  const t = (Date.now() / 1000).toString();
  const c1 = Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_512, payload_string, Utilities.Charset.UTF_8);
  const c2 = Utilities.formatString('%s\n%s\n%s\n%s\n%s', method, url, query_param, c1.map(b => ("0" + (b < 0 && b + 256 || b).toString(16)).slice(-2)).join(""), t);
  const c3 = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512, c2, secret, Utilities.Charset.UTF_8);
  const sign = c3.map(b => ("0" + (b < 0 && b + 256 || b).toString(16)).slice(-2)).join("");
  return { "KEY": key, "Timestamp": t, "SIGN": sign };
}

// Please run this function.
function main() {
  const key = "your api key";
  const secret = "your secret";

  const host = "https://api.gateio.ws";
  const prefix = "/api/v4";
  const url = "/wallet/total_balance";
  const method = "GET";

  const signature = gen_sign_(key, secret, method, prefix + url);
  const headers = { "Accept": "application/json", "Content-Type": "application/json", "muteHttpExceptions": true, ...signature };
  const res = UrlFetchApp.fetch(host + prefix + url, { method, headers });
  console.log(res.getContentText());
}

Note:

*

*When I tested the script using the sample variables of const key = "sample", const secret = "sample" and const t = "1234567890.123" for the python script in the official document and Google Apps Script, the same value of signature could be obtained as follows. Both requests are also the same.
  603899db07ca29e5240de397b8088271b765925ba29a67267b33ad0b076fc31b0cf98d623878d57bf824b58e5336fd74f1cd101e9377816c34fec2acb9358cb2

*So, when you test the above sample Google Apps Script and if an error occurs, please confirm your variables again. And, please show the error message.
References:

*

*computeDigest(algorithm, value, charset)

*formatString(template, args)

*computeHmacSignature(algorithm, value, key, charset)

*map()


text:
Q: JSON.registerObjectMarshaller doesn't work in bootstrap When I want to test a customized "render as JSON " method, I used the following code
class BootStrap{
def init = { servletContext ->
 ....
 println "change the json before format"
 JSON.registerObjectMarshaller(Date) {
     println "JSON DATE MARSHAL"
     return it.format("yyyy-MM-dd HH:mm:ss")
     }
 println "change the json after format"
 }
}

but what printed in the console is like this:

| Compiling 1 source files
| Running Grails application
Active MQ start. ConsumerURL is failover:ssl://xxx.
change the json before format
change the json after format
|Server running. Browse to http://xxx

the strange thing is that the "JSON DATE MARSHAL"didn't be printed.
But it worked when I put the code in a controller.
I don't know what happened.
Any suggestion will be appretiated.

Update:
Like railsdog said, it seems the closure in the init didn't work.
What I supposed the date format in JSON is like this:2016-12-15 16:44:21
But what I get is 2016-12-15T08:44:21Z.
When I put the marshaller in controller, it worked, and the date format in JSON is as expected:
2016-12-15 16:44:21.
I also get the console output:"JSON DATE MARSHAL".

A: I would assume that registering the object marshaller doesn't actually execute/invoke the closure, hence no debug is emitted.

A: Instead of registering marshaller check out property grails.databinding.dateformats in your grails application config. You can add there more different date formats which should be handled by your app.


text:
Q: header('Location:') its not working correctly Im trying to devellop a search system, and Im having a problem..
I have a index.php file and a search.php file in the same directory, and I want that When the user writes in the search field and submit I want to go to my search page.
But I dont understand what is happening because I go to this page: localhost/project/tpl/search/ but everything is white, I dont have errors but is not showing the contet of my "search.php" file!
I alraedy tried with: header('Location: http://localhost/project/tpl/search/'); But I have the same issue!
Somebody there knows what might be happening?
 <?php
        if(isset($_POST['search']))
        {
            $search = $_POST['s'];
            $search = setUri($search);
            header('http://localhost/project/tpl/search/');
            echo $search;
        }
        ?>
             <form  name="search" method="post" >
                <input id="test" type="search" name="s" placeholder="Search..." required="required" onfocus="if(this.placeholder == 'Search...') {this.placeholder=''}" onblur="if(this.placeholder == ''){this.placeholder ='Search...'}" />
                <input type="submit" class="expand" name="search"></button>
             </form>

I have my project folder inside htdocs, my project folder is this:

Then search.php is inside tpl folder, like this:

A: You forgot the location keyword on your header() function.
Must be..
header("location:http://localhost/project/tpl/search/");

Warning : Also, you are trying to echo content after the header() which will not be visible whatsoever..
Remove the echo and add an exit after your header() call..
if(isset($_POST['search']))
        {
            $search = $_POST['s'];
            $search = setUri($search);
            header('location : http://localhost/project/tpl/search/');
            //echo $search;
            exit;
        }

A: Your header doesn't have the location keyword.

A: You can try this
 header('Location: http://localhost/project/tpl/search/');


text:
Q: How to fix: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Core Java? I am just a beginner in java and working on core java....not on any tool such as Netbeans or Eclipse. It is simply notepad based and running on cmd. I am providing a simple code for connecting with the database and performing basic operations. I am getting a continuous exception - ClassNotFoundException when I'm using com.mysql.jdbc.Connection and when I use java.sql.DriverManager instead of that..I get another error with No suitable driver found for jdbc:....
Please help me out guyz..I'm stuck with this...I have done the same with Netbeans..it worked perfectly there...but not with cmd.
     import java.sql.*;
     public class JDBCExample
     {
        static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
        static final String DB_URL="jdbc:mysql://localhost/company";
        static final String USER="root";
        static final String PASSWORD="root";
            public static void main(String args[])
            {
              Connection conn=null;
              Statement stmt=null;
             try
             {
               Class.forName("com.mysql.jdbc.Driver");  //tried java.sql.DriverManager as well
        System.out.println("Connecting to Database...");
        conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/company","root","root");
        System.out.println("Creating Statement...");
        stmt=conn.createStatement();
        String sql="Update login set password=123 where id=1";
        Boolean ret=stmt.execute(sql);
        System.out.println("Return value is: "+ret.toString());
        int rows=stmt.executeUpdate(sql);
        System.out.println("Rows impacted: "+rows);
        sql="Select *from login;";
        ResultSet rs=stmt.executeQuery(sql);
        while(rs.next())
        {
            String id=rs.getString("id");
            String user=rs.getString("username");
            String pass=rs.getString("password");
            System.out.println("ID: "+id);
            System.out.println("username: "+user);
            System.out.println("password: "+pass);
        }
        rs.close();
        stmt.close();
        conn.close();
    }
    catch(SQLException se)
    {
        se.printStackTrace();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        try
        {
            if(stmt!=null)
                stmt.close();
        }
        catch(SQLException se2)
        {

        }
        try
        {
            if(conn!=null)
                conn.close();

        }
        catch(SQLException se)
        {
            se.printStackTrace();
        }
    }
    System.out.println("End");
}

}


text:
Q: Angular 2 Route module not imported when using with webpack I am just a beginner with Angular 2. I am trying to build a TODO app using
Angular 2 with webpack bundeler. I am facing an issue where RouterModule is not loading when trying to implement Angular Component Routing.
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { BrowserModule }  from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { ToDoModule } from './todos/todo.module';
import { HeaderComponent } from './app-header.component';

const ROUTES: Routes = [{
  path:'home', component: HeaderComponent
}];

@NgModule({
  imports: [
    BrowserModule,
    ToDoModule,
    RouterModule.forRoot(ROUTES)
  ],
  declarations: [
    AppComponent,
    HeaderComponent
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

And I have included router-outlet in the AppComponent's HTML. But when application loads it throws an error

Unhandled Promise rejection: Template parse errors:
  'router-outlet' is not a known element:

*

*If 'router-outlet' is an Angular component, then verify that it is part of this module.

*If 'router-outlet' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. (" -->

  [ERROR ->]"): AppComponent@2:0 ; Zone:  ; Task: Promise.then ; Value: Error: Template parse errors:(…) Error: Template parse errors:
  'router-outlet' is not a known element:
  1. If 'router-outlet' is an Angular component, then verify that it is part of this module.
  2. If 'router-outlet' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. (" -->
[ERROR ->]"): AppComponent@2:0

I did the same app using System.js it works fine. Can anyone please help me to figure out the issue? Thanks


text:
Q: How to fix automatically closing div tag in this case I have a question about appending data to a div in my html through jquery.
This is what I have in my html file:

This is my javascript file:
function checkCompletion(data){

    // IMPORTANT VALUES
    var app_important = ["submit_description", "app_icon", "address", "email"];
    var event_important = ["name", "datefrom", "dateto", "description", "email"];

    $("#errors").append("

");

    // LOOPS + HEADERS
    $("#errors").append("
App
");
    doLoop(data.app, app_important);

    $("#errors").append("
Events
");
    doLoop(data.events, event_important);
}

// ar           => app data array
// ar_important => important props app (array)
function doLoop(ar, ar_important) {
    $.each(ar, function(value) {
        $.each(ar_important, function(i) {
            if(ar[value][ar_important[i]] == '') $("#errors").append("
" + ar_important[i]+" is missing
");
            //else $("#errors").append("
 :) "+ar_important[i]+"
");
        });
    });
    $("#errors").append("

");
}

The data parameter is a JSON object with lots of data.
As you can see I do $("#errors").append("

");
But the div tag automatically closes so my errors aren't in it.
Does anyone know how I can fix this and still work with append?
Niels

A: You don't need to build strings like this. You're already building DOM nodes in most of your code.
All you need to do is append directly to those nodes. Just fix the creation of the
 elements, and then append to the inner most, which I think is what you're after.
function checkCompletion(data){

    var app_important = ["submit_description", "app_icon", "address", "email"];
    var event_important = ["name", "datefrom", "dateto", "description", "email"];

// make the outer `span6`
    var span6 = $("

")

// make the inner `well`, and append it to the span6
    var well = $("

").appendTo(span6);

// do all your appends to the `well` element,
//    passing it to `doLoop` so it can do the same
    well.append("
App
");
    doLoop(data.app, app_important, well);

    well.append("
Events
");
    doLoop(data.events, event_important, well);
}

function doLoop(ar, ar_important, well) {
    $.each(ar, function(value) {
        $.each(ar_important, function(i) {
           if(ar[value][ar_important[i]] == ''){
               well.append("
" + ar_important[i]+" is missing
");
           }
           //else{ errorAppend += "
 :) "+ar_important[i]+"
";
        });
    });

  // append the outer `span6` to `#errors`
    $("#errors").append(span6);
}

There are even cleaner ways to create the elements. Here's the same code, with a better approach.
function checkCompletion(data){

    var app_important = ["submit_description", "app_icon", "address", "email"];
    var event_important = ["name", "datefrom", "dateto", "description", "email"];

// make the outer `span6`
    var span6 = $("
", {"class":"span6"})

// make the inner `well`, and append it to the span6
    var well = $("
", {"class":"well"}).appendTo(span6);

// do all your appends to the `well` element,
//    passing it to `doLoop` so it can do the same
    $("
", {text: "App"}).appendTo(well);
    doLoop(data.app, app_important, well);

    $("
", {text: "Events"}).appendTo(well);
    doLoop(data.events, event_important, well);
}

function doLoop(ar, ar_important, well) {
    $.each(ar, function(value) {
        $.each(ar_important, function(i) {
           if(ar[value][ar_important[i]] == ''){
               $("
", {text: ar_important[i]+" is missing"}).appendTo(well);
           }
           //else{ errorAppend += "
 :) "+ar_important[i]+"
";
        });
    });

  // append the outer `span6` to `#errors`
    $("#errors").append(span6);
}


text:
Q: Wrapping __TransparentProxy of RemotingProxy in another Proxy throws RemotingException Goal
I have a couple of interfaces and some dlls that provide implementations for these interfaces. I want to load the implementation into a new AppDomain (so I can unload the dll later) and instatiate the implementation in the new AppDomain and then use a clientside(here the default AppDomain) proxy to wrap the actual implementation object. The goal is to create these ClientProxy instances once and change their actual implementations whenever while not loading the implementations assembly into the default AppDomain.
Problem
When calling a method on the ClientProxy __TransparentProxy object that gets another ClientProxy as argument I get the following Exceptions:
System.Runtime.Remoting.RemotingException:
'The argument type 'System.MarshalByRefObject' cannot be converted into parameter type 'IData'.'
With inner Exception:
InvalidCastException: Object must implement IConvertible.
When passing the __TransparentProxy obtained directly from the Server AppDomain the ClientProxy works.
Setup
Cloneable from: https://github.com/mailgerigk/remoting
Interfaces:
public interface IData
{
    int Foo { get; set; }
}

public interface ILogic
{
    void Update(IData data);
}

Interface Impl in _impl.dll:
public class DataImpl : MarshalByRefObject, IData
{
    public int Foo { get; set; }
}

public class LogicImpl : MarshalByRefObject, ILogic
{
    public void Update(IData data)
    {
        data.Foo++;
    }
}

Serverside AssemblyLoader:
class AssemblyLoader : MarshalByRefObject
{
    public Assembly Assembly { get; private set; }

    public AssemblyLoader(string assemblyFile)
    {
        Assembly = Assembly.LoadFrom(assemblyFile);
    }

    public object CreateInstance(string typeName)
    {
        return Activator.CreateInstance(Assembly.GetType(typeName));
    }
}

ClientProxy:
class ClientProxy : RealProxy
{
    private RealProxy innerProxy;

    public ClientProxy(Type interfaceType, object proxyObject)
        : base(interfaceType)
    {
        SetInnerProxy(proxyObject);
    }

    public void SetInnerProxy(object proxyObject)
    {
        innerProxy = RemotingServices.GetRealProxy(proxyObject);
    }

    public override IMessage Invoke(IMessage msg)
    {
        return innerProxy.Invoke(msg);
    }
}

Main:
class Program
{
    static void Main(string[] args)
    {
        var app = AppDomain.CreateDomain("ImplDomain", null,
            AppDomain.CurrentDomain.BaseDirectory, AppDomain.CurrentDomain.RelativeSearchPath,
            true);

        var assmblyLoader = app.CreateInstanceFromAndUnwrap(
            typeof(AssemblyLoader).Assembly.Location, typeof(AssemblyLoader).FullName,
            false, BindingFlags.CreateInstance, null,
            new object[]
            {
                "_impl.dll"
            },
            null, null) as AssemblyLoader;

        var dataImpl = assmblyLoader.CreateInstance("DataImpl") as IData;
        var logicImpl = assmblyLoader.CreateInstance("LogicImpl") as ILogic;

        logicImpl.Update(dataImpl); // Works
        Console.WriteLine(dataImpl.Foo); // prints 1

        var clientDataProxy = new ClientProxy(typeof(IData), dataImpl);
        var clientDataImpl = clientDataProxy.GetTransparentProxy() as IData;

        var clientLogicProxy = new ClientProxy(typeof(ILogic), logicImpl);
        var clientLogicImpl = clientLogicProxy.GetTransparentProxy() as ILogic;

        clientLogicImpl.Update(dataImpl); // Works
        Console.WriteLine(clientDataImpl.Foo); // prints 2

        clientLogicImpl.Update(clientDataImpl); // throws System.Runtime.Remoting.RemotingException
        Console.WriteLine(clientDataImpl.Foo);
    }
}

A: Without knowing your reasoning, from the example code provided, the ClientProxy class appears unnecessary since you could get the same behaviour just by using a RealProxy directly:
var clientDataProxy = RemotingServices.GetRealProxy(dataImpl);

That being said, you can of course create your own concrete RealProxy and have it work as expected - you are just missing an override to get the TransparentProxy from the innerProxy:
class ClientProxy : RealProxy
{
    ... everything else ...

    public override object GetTransparentProxy() => innerProxy.GetTransparentProxy();

    public object GetOuterTransparentProxy() => base.GetTransparentProxy();
}

...
var clientDataProxy = new ClientProxy(typeof(IData), dataImpl);
var clientDataImpl = clientDataProxy.GetOuterTransparentProxy() as IData;

var clientLogicProxy = new ClientProxy(typeof(ILogic), logicImpl);
var clientLogicImpl = clientLogicProxy.GetOuterTransparentProxy() as ILogic;
...

As it stands, your ClientProxy is returning a TransparentProxy to the outer object.
Edit: Based on the explanation in the comments I have added a secondary GetOuterTransparentProxy method that returns the outer base implementation. This would still allow the OOTB RealProxy.Invoke implementation to be used, while exposing the outer TransparentProxy to be reused.


text:
Q: ERR_EMPTY_RESPONSE error when the server takes more than 2min to respond I have written a web service using node & express that runs automation on request and responds with the finalized report.
I have used jquery ajax (tried fetch API as well) in the client side to start the automation in the server and on completion, reports are compressed as zip and sent to the client.
Issue:
When the server responds within 2 min, the zip is downloaded successfully but when the server takes more than 2 min to respond, the http request fails with "ERR_EMPTY_RESPONSE" though there is no issue in the server side.
I learnt that by default there is no timeout for the HTTP requests but I am not sure why am I facing this issue.
I would like to know the reason behind this behavior.
Snippet of ajax request made in the client side:
                var promise = $.ajax({
                    url: 'http://localhost:8001/test',
                    method:'POST',
                    xhrFields: {
                        responseType: 'blob'
                    },
                    success: function(res){
                        downloadFromBlob(res);
                    },
                    error: function(xhr, statusText, err){
                        alert(statusText);
                    },
                    data: options,
                });

Snippet from webservice (I have just tried to reproduce the issue here. The automation takes nearly 15 min to complete):
  router.get('/test/', runAutomation);
  async function runAutomation(req, res, next){
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
        const timeout = 120000;
        setTimeout(()=> {
            const path = 'reports.zip';
            res.download(path);
        }, timeout);
    },

A: This is caused not by the backend, but your browser - I have consistently seen the 2 minute timeout across all browsers at some point or another. You may want your backend to return a 202 Accepted immediately, and ping it for updates rather than trying to wait for it to complete in one shot.

A: In express, if we check /bin/www file content, by default it sets the timeout to 120000 ms as below
 server.setTimeout(120000);

We need to update it.
Ref: https://nodejs.org/api/http.html#http_server_settimeout_msecs_callback


text:
Q: More connections or more connection-pools? Here we have one component which generates different queries for a thousand websites.
This component is deployed on several webservers which hosts hundreds of them. Everything pointed to the same SQL Server.
Well, when we have performance issues, it's hard to find which site is generating the problem.
Due this reason, we've been implementing a strategy that injects the website url on Application Name configuration of the connection string, as shown in the image.

Well, the question is:
What's better? Having more connections as SRV-SITES-01 (Red mark) or One pool as SRV-SITES-02 (Blue mark).
What's the pro and cons about the two situations?
Thanks,
Armando

A: With one pool you are likely to get more reuse out of the connections. I understand you try to reduce the number of connections. So don't use too many pools.
Use one pool and instrument your application to find out which site is using most resources.


text:
Q: Performance Visibility for Z3 Is there a way to see what Z3 is doing under the hood? I would like to be able to see the steps it is taking, how long they take, how many steps, etc. I'm checking the equality of floating point addition/multiplication hardware designs with Z3's builtin floating point addition/multiplication. It is taking quite longer than expected, and it would be helpful to see what exactly it's doing in the process.

A: You can run it with higher verbosity:
z3 -v:10

This will print a lot of diagnostic info. But the output is unlikely to be readable/understandable unless you're really familiar with the source code. Of course, being an open source project, you can always study the code itself: https://github.com/Z3Prover/z3

A: If you're especially interested in e-matching and quantifiers, you can use the Axiom Profiler (GitHub source, research paper) to analyse a Z3 trace. The profiler shows instantiation graphs, tries to explain instantiations (which term triggered, which equalities were involved), and can even detect and explain matching loops.
For this, run z3 trace=true, and open the generated trace file in the profiler. Note that the tool is a research prototype: I've noticed some bugs, it seems to work more reliable on Windows than on *nix, and it might not always support the latest Z3 versions.


text:
Q: How to translate FIAT into English? I am translating a text in Portuguese to English from a Message of Our Lady, and there is this expression on the URGENT APPEALS Message nº 2,797:

"O Senhor dirá: Faça-se; e tudo será transformado."

The context is similar to:

"FIAT LUX"
  "Faça-se a luz"
  "Let there be light"

I translated it as :

"The Lord will say: (FIAT) Let there it be; and everything will be transformed."

Did I translate it correctly? If not, can somebody please answer a more perfect translation?

A:
The Lord will say "Let it be", and all will be changed.

You really have to go with the idiomatic and historical (and thus in this context expected) translation not the verbatim translation. That means for this instance of Latin Fiat!, you would choose the English Let it be!
Notice that the Portuguese translation isn't really especially "verbatim", at least from the Latin. (I have no Hebrew.) It's a third-person imperative of an intransitive pronominal/reflexive verb with a sense that better corresponds to "become". But it doesn't make sense to translate it that way because that's not what it's always been translated to in this context. And it isn't literally commanding the light  to make itself, either. :)
It isn't just Portuguese that does this same thing. Spanish bibles have historically translated the Latin Fiat lux into  Hágase la luz, which you'll note is the very same approach that Portuguese takes. It just isn't how English bibles have done it.


text:
Q: Adding comments to database columns and retrieving from AWS Glue I'm trying to incorporate a AWS GLUE Data Catalog to my Data Lake I'm building out. I'm using a few different databases and would like to add COMMENTS to columns in a few of these tables. These databases include Redshift and MySql. I usually add the comments to the column by doing something along the lines of
COMMENT ON COLUMN table.column_name IS 'This is the comment';

Now i know that Glue has a comment field that shows in the GUI. Is there a way to sync the comment field in Glue with the comments I add to the columns in a DB?

A: In order to update some meta information about a table that has been defined in AWS Glue Data Catalog, you would need to use a combination of get_table() and update_table() methods with boto3 for example .
Here is the most naive approach to do that:
import boto3
from pprint import pprint

glue_client = boto3.client('glue')

database_name = "__SOME_DATABASE__"
table_name = "__SOME_TABLE__"

response = glue_client.get_table(
    DatabaseName=database_name,
    Name=table_name
)
original_table = response['Table']

Here original_table adheres response syntax defined by get_table(). However, we need to remove some fields from it so it would pass validation when we use update_table(). List of allowed keys could be obtained by passing original_table directly to update_table() without any chagnes
allowed_keys = [
    "Name",
    "Description",
    "Owner",
    "LastAccessTime",
    "LastAnalyzedTime",
    "Retention",
    "StorageDescriptor",
    "PartitionKeys",
    "ViewOriginalText",
    "ViewExpandedText",
    "TableType",
    "Parameters"
]
updated_table = dict()
for key in allowed_keys:
    if key in original_table:
        updated_table[key] = original_table[key]

For simplicity sake, we will change comment of the very first column from the table
new_comment = "Foo Bar"
updated_table['StorageDescriptor']['Columns'][0]['Comment'] = new_comment

response = glue_client.update_table(
    DatabaseName=database_name,
    TableInput=updated_table
)

pprint(response)

Obviously, if you want to add a comment to a specific column you would need to extend this to
new_comment = "Targeted Foo Bar"
target_column_name = "__SOME_COLUMN_NAME__"
for col in updated_table['StorageDescriptor']['Columns']:
    if col['Name'] == target_column_name:
        col['Comment'] = new_comment

response = glue_client.update_table(
    DatabaseName=database_name,
    TableInput=updated_table
)

pprint(response)


text:
Q: MS Word master document embedding rather linking subdocuments When I add a subdocument to an MS Word master document using the outlining toolbar, I'm able to toggle the 'Collapse Subdocuments' button to see the hyperlink to the embedded document.  I'm also able to see updates to the text of the subdocument appear within the master.  However, sometime within the next few openings of the Master document, I'll find that the subdocuments can no longer be collapsed to show their links.  They also no longer update.  It appears that Word decided to just copy the text into the master document, and be done with it.  Is there a way to prevent this behavior so I don't have to keep reassembling the master document in vain hope that the this time updates will continue to be incorporated?

A: I don't have a root cause, but the following steps will work around the issue:
First, always save your document with all subdocuments collapsed.
To add more subdocuments:

*

*Expand the existing subdocuments.

*Add your new subdocument.

*Collapse all subdocuments, (at this point, you should be asked if
you want to save, click yes).

*You may or may not receive an error message stating that one of the
subdocuments is read-only.  Click OK

*Undo the subdocument insertion using Ctrl-Z

*Insert the subdocument again

*Once again collapse all subdocuments and respond yes when asked to save.

The second insertion of the subdocument will not receive the read-only error message.


text:
Q: Exponential Proof
Let $c(x)=\dfrac{3^x+3^{-x}}{2}$ and $s(x)=\dfrac{3^x-3^{-x}}{2}$.
Show that $(c(x))^2=\frac{1}{2}(c(2x)+1)$.

How does one go about solving this?
I have honesty tried substituting in logarithms but it doesn't seem to reduce to any simpler form.
My intuition is to equate the coefficients of c(x) and s(x) on both sides and find a common factor.

A: Let's just calculate, and see what happens:
$$
(c(x))^2 = \left(\frac{3^x + 3^{-x}}{2}\right)^2 = \frac{3^{2x} + 2 + 3^{-2x}}{4}\\
= \frac{1}{2}\left(\frac{3^{2x} + 3^{-2x}+2}{2}\right) = \frac{1}{2}\left(\frac{3^{2x} + 3^{-2x}}{2} + 1\right) = \frac12(c(2x) + 1)
$$


text:
Q: Can I use domain name instead of IP to connect SOCKS5 proxy server? I have domain name with correct A- and AAAA-records and my personal SOCKS5 Dante Server. Via IP all is okay, but when I try to connect via domain it's failed. So is it real to set up or impossible? Clients can resolve DNS of course.

A: Yes, You can use send domain name to socks5 server.
you can setup dante socks client where you need to edit /etc/socks.conf
Set "resolveprotocol" to "fake" in the client configuration file. then client will start passing the domain name to socks server directly.

A: The problem was because of incorrect IPv6 settings on server-side. So client tried by default connect to IPv6 version but server not responded.


text:
Q: Using docker in Jenkins pipeline fails In Jenkinsfile I am trying to download docker image and use in this docker image for all the git pull and frontend build stuff.
My jenkinsfile is so far:
pipeline {
    agent any

    stages {
       stage('Install Docker-CE') {
            steps {
                sh '''curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
                sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
                sudo apt-get update
                sudo apt-get install -y docker-ce'''
            }
        }
        stage('Start Docker') {
            steps {
                sh 'sudo service docker start'
                sh 'sudo service docker status'
            }
        }
        stage('Verify Docker') {
            steps {
                sh 'sudo docker run hello-world'
            }
        }

        stage('Build Back End') {
              steps {
                  git ([url : 'https://github....git', branch : 'develop', credentialsId : 'xxx' ])
              }
        }
}

The docker is installed and running, because in the 'Start Docker' step when I run sudo service docker status, it says: Docker is running
but when trying to do 'hello world' in the next step, it says docker: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?.
I also tried to run docker daemon with: sudo dockerd but it didn't help, this is the part of the output:
time="2021-07-28T08:45:04.782471391Z" level=error msg="failed to mount overlay: permission denied" storage-driver=overlay2
time="2021-07-28T08:45:04.782647045Z" level=error msg="exec: \"fuse-overlayfs\": executable file not found in $PATH" storage-driver=fuse-overlayfs
time="2021-07-28T08:45:04.783389746Z" level=warning msg="[graphdriver] WARNING: the aufs storage-driver is deprecated, and will be removed in a future release"
time="2021-07-28T08:45:04.810999832Z" level=warning msg="Your kernel does not support CPU realtime scheduler"
time="2021-07-28T08:45:04.811283522Z" level=info msg="Loading containers: start."
time="2021-07-28T08:45:04.816297382Z" level=warning msg="Running iptables --wait -t nat -L -n failed with message: `iptables v1.6.0: can't initialize iptables table `nat': Permission denied (you must be root)\nPerhaps iptables or your kernel needs to be upgraded.`, error: exit status 3"
time="2021-07-28T08:45:04.887136525Z" level=info msg="stopping event stream following graceful shutdown" error="<nil>" module=libcontainerd namespace=moby
time="2021-07-28T08:45:04.887859247Z" level=info msg="stopping event stream following graceful shutdown" error="context canceled" module=libcontainerd namespace=plugins.moby
time="2021-07-28T08:45:04.887889167Z" level=info msg="stopping healthcheck following graceful shutdown" module=libcontainerd
failed to start daemon: Error initializing network controller: error obtaining controller instance: failed to create NAT chain DOCKER: iptables failed: iptables -t nat -N DOCKER: iptables v1.6.0: can't initialize iptables table `nat': Permission denied (you must be root)
Perhaps iptables or your kernel needs to be upgraded.
 (exit status 3)

A: Ok, so the problem was I used sudo in sudo docker run hello-world. Without sudo it works...


text:
Q: Is this proof that the compositum of splitting fields is a splitting field correct? I'm thinking about the following claim:
Let $k^a$ be an algebraic closure of $k$, and let $K_i$ be a splitting field of $f_i$ in $k^a$ (the algebraic closure of $k$). Then the compositum of the $K_i$ is a splitting field for our family.
I wanted to prove this as follows. Let us remark that the compositum is defined as $$K:=k^a\left(\bigcup_{i\in I} K_i\right)$$ But then clearly $$f_i(X)=c\prod_{i\in I}(X-\alpha_i)$$ where $\alpha_i\in K$ by definiton and $K$ is generated by all the roots of all $f_i$. So $K$ is indeed a splitting field.
So now my first question is, does this work?
My second is why do we need $k^a$?
Thanks for your help


text:
Q: Argument 1 of Node.appendChild is not an object tengo un problema al hacer un appendChild al input con el resultado de una operacion que toma 2 inputs.
<input id="firstNumber" type="text" value="" /> + <input id="secondNumber" type="text" value="" /> = <input id="resultNumber" type="text" value="" />
<input type="button" value="Calculate" onclick="calculateSumListener();" />

para esto tengo la siguiente funcion.
function calculateSumListener() {
//Return the value of the input #firstNumber
var stringA = document.getElementById('firstNumber').value;
//Return the value of the input #secondNumber
var stringB = document.getElementById('secondNumber').value;

//your code goes here
let result = document.getElementById('resultNumber');

// reasignar
let value = parseInt(stringA) + parseInt(stringB);
result.appendChild(value); }

El error que presenta en Argument 1 of Node.appendChild is not an object.

A: La función appendChild permite "insertar" un elemento HTML dentro de otro, es decir que el argumento que le tienes que dar debe ser un HTMLElement, en tu ejemplo el argumento es de tipo number.
En su lugar usa:
result.value = value;

Espero te sirva.


text:
Q: Django custom user model meta overlaps when importing from another project I'm remaking a script to sync data from an old python2 project to a new with python3. The way the last programmer made it work appears to be by importing both, the new and old models into a script in the old project using:
sys.path.append("route to the new project")

It works for importing every model except for a custom user model from the new project, when I try to work with it, like using UserProfile.objects.all() it crashes with:
relation "user_userprofile" does not exist

LINE 1: SELECT "user_userprofile"."id" FROM "user_userprofile"
The right table is user_models_userprofile, because the app containing the model is "user_models" instead of "user".
The app_label from the imported model shows "user", which is probably the default app_label when extending AbstractUser, it is probably ignoring the app_label attribute from my model and using the one from AbstractUser.
Any ideas of how to make it work? Also sorry for my english.
EDIT
UserProfile model:
class UserProfile(AbstractUser):
    class meta:
        app_label = 'user_models'

    phone_number = models.IntegerField(default=0)
    mail = models.CharField(max_length=50, default='example@example.com')
    companies = models.ManyToManyField(Company)
    tour_completed = models.BooleanField(default=False)

    def __str__(self):
        return self.username

There is no 'User' model, its just that custom model.
I import the model using
sys.path.append('route to new project')
from user_models.models import UserProfile

A: Finally I found a way to correct the app_label and db_table from the user and the companies relation.
First import the model, and then overwrite the _meta atributes.
from user_models.models import UserProfile

UserProfile._meta.db_table="user_models_userprofile"
UserProfile._meta.app_label="user_models"
UserProfile.companies.through._meta.db_table="user_models_userprofile_companies"
UserProfile.companies.through._meta.app_label="user_models"

Is not the prettier way to do it but it works.


text:
Q: How do I build a wrapper (or launcher and receiver upon completion) for an external app in Android? I'm working with a partner who has an app (App A) that wishes to call my app (App B). Once called App A will then wait for App B to finish what it's doing and collect some data.
In the exact scenario I'm working in, App A collects user info (name, phone) and then needs to pass it to App B. App B will do some stuff with that info and when finished, needs to notify App A that it succeeded (or didn't succeed) to perform operations for user name_phone.
What do our apps need to know about each other for this to work?
I'm looking at startActivityForResult but I'm getting the impression that's something one would use within ones own application and not something App A can use to launch App B.
TIA

A: startActivityForResult() works fine between applications. You should take a look at Barcode Scanner by ZXing to see how they use startActivityForResult() for this very purpose.
App B will need to have an Activity with an <intent-filter> that will be stable, such as one using a custom action string. App B will also need to document what the Intent should look like (e.g., required action, required Uri if any, extras), and what will be returned via onActivityResult().
The author of App B could create a JAR file that provides a cleaner API for App A to use. ZXing did that with Barcode Scanner.


text:
Q: Link POM version and application version I have two versions in my projects.

*

*The version in my POM.xml which is used when the project is packaged, etc.

*The version I have put in a constant in my code so I can use it during runtime when I log, etc.

These should of course be the same, but sometimes I forget to change one or the other.
Is there a good way to define this version only once and have it used by both maven and code during runtime?

A: http://www.sonatype.com/books/mvnref-book/reference/resource-filtering-sect-description.html
Have a look at this, you should have a properties file, which has a certain property which refers to the version number. And using filtering you can set the version same both in maven artifact and application.

A: When you package your application using Maven, Maven will generate a directory META-INF/maven/<groupId>/<artifactId>/pom.properties. That file contains the version of your project according to the POM, and you could load that file from the JAR file on runtime in order to read your version number.
Only thing is, this file does only exist in a packaged project (be it a JAR, a WAR or an EAR). You might want to write some fallback mechanism for when you are running the code from your workbench.

A: This is some code that I usually use when I want the version specified in the pom file.
private final static String GROUP_ID = "my.group";
private final static String ARTIFACT_ID = "my-artifact";

private String getVersion() {
    String propFileName = "META-INF/maven/" + GROUP_ID + "/" + ARTIFACT_ID + "/pom.properties";
    Properties properties = new Properties();
    String version = "n/a";

    try {
        InputStream inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(propFileName);

        if (inStream != null) {
            properties.load(inStream);
            version = properties.getProperty("version", "n/a");
        }
    } catch (IOException e) { }
    return version;
}

And as mthmulders says in his answer, this file does only exist in a packaged project (in the final war/jar/any, not in the working directory).


text:
Q: C# WPF Bind Custom List to dynamically created Data-grid sort not working.. I have a custom list :
 public class HardwareTable : IEquatable<HardwareTable>
{

    public byte SectorNumber { get; set; }

    public byte SectionNumber { get; set; }

    public byte SectionStatus { get; set; }

    public override string ToString()
    {
        return "Sector Number: " + SectorNumber;
    }
    public override bool Equals(object obj)
    {
        if (obj == null) return false;
        HardwareTable objAsPart = obj as HardwareTable;
        if (objAsPart == null) return false;
        else return Equals(objAsPart);
    }
    public override int GetHashCode()
    {
        return SectorNumber;
    }
    public bool Equals(HardwareTable other)
    {
        if (other == null) return false;
        return (this.SectorNumber.Equals(other.SectorNumber));
    }

}

I fill my List with stuff
List<HardwareTable> ImpDataList = new List<HardwareTable>();
ImpDataList.Add(new ImportedDataList(){ SectorNumber=1,SectionNumber=3,SectionStatus=0}
ImpDataList.Add(new ImportedDataList(){ SectorNumber=2,SectionNumber=3,SectionStatus=0}
ImpDataList.Add(new ImportedDataList(){ SectorNumber=1,SectionNumber=5,SectionStatus=0}
ImpDataList.Add(new ImportedDataList(){ SectorNumber=1,SectionNumber=5,SectionStatus=1}
....

And I I have a dynamically created Data grid:
 TabItem ReturnedData = new TabItem();
 ReturnedData.Header = "Returned Data";
 var ReturnedDataGrid = new DataGrid();
 ReturnedDataGrid.AlternatingRowBackground = Brushes.LightBlue;
 ReturnedDataGrid.CanUserSortColumns = true;
 ReturnedDataGrid.IsReadOnly = true;
 ReturnedDataGrid.ItemsSource =ImpDataList; // When I do this it works but I cannot sort the data, also the data are not sorted when they are displayed.
 ReturnedData.Content = ReturnedDataGrid;
 tabControl.Items.Add(ReturnedData);

With the above approach I display the data, but the sorting does not work. I can understand that I need to bind the List to the data-grid but so far I have tried many approaches but non is working for my case.
One approach suggested that I do this :
CollectionViewSource itemCollectionViewSource;
itemCollectionViewSource = (CollectionViewSource)FindResource("ItemCollectionViewSource"));
itemCollectionViewSource.Source = ImpDataList;

ReturnedDataGrid.DataContext = "{StaticResource ItemCollectionViewSource}";
ReturnedDataGrid.ItemsSource = "{Binding}";

But I could not even display my list. It was displaying empty cells. At least in the initial approach I could display the data despite the fact that they were not sorted.
Any suggestion on how to proceed?


text:
Q: .NET Designer issues shadowing properties as readonly in inherited controls I am trying to create custom controls to provide some consistency to the design of an application. However when I shadow a property with a readonly alternatvie, I get designer errors at build time. Now I can delete the offending lines of code in the designer file and continue to build and run my application but firstly this is irritating, and secondly it tells me that I must be doing something fundamentally wrong!
Here's an example of a control that overrides datagridview
Class standardDataGridView
Inherits DataGridView

Public Sub New()
    MyBase.New()
    Me.RowHeadersVisible = False
    MyBase.SelectionMode = DataGridViewSelectionMode.FullRowSelect
    MyBase.MultiSelect = False
    Me.ReadOnly = True
    Me.BackgroundColor = Color.White
    Me.AllowUserToDeleteRows = False
    Me.AllowUserToResizeRows = False
    Me.AllowUserToAddRows = False
End Sub

Public Shadows ReadOnly Property SelectionMode As DataGridViewSelectionMode
    Get
        Return MyBase.SelectionMode
    End Get
End Property

Public Shadows ReadOnly Property MultiSelect As Boolean
    Get
        Return MyBase.MultiSelect
    End Get
End Property

End Class

In the first build after adding one of these controls to a form, or after changing any properties, the following lines get added to the designer file by Visual Studio:
Me.standardDataGridView1.MultiSelect = False
Me.standardDataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect

Which results in the following build errors
Property 'MultiSelect' is 'ReadOnly'.
Property 'SelectionMode' is 'ReadOnly'

As I say... I can remove the lines that Visual Stuido added, and continue, but where have I gone wrong to be getting this problem?

A: Try telling the forms designer to not serialize those properties:
Imports System.ComponentModel

<DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)> _
Public Shadows ReadOnly Property SelectionMode As DataGridViewSelectionMode
  Get
    Return MyBase.SelectionMode
  End Get
End Property

<DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)> _
Public Shadows ReadOnly Property MultiSelect As Boolean
  Get
    Return MyBase.MultiSelect
  End Get
End Property

Make sure to rebuild your solution.


text:
Q: Is it possible to embed an animated gif into html as a static image? So, the idea is simple: I've got a large number of GIFs and I have to create a gallery. I'd like to use FancyBox (probably this question won't be different if I used Lightbox or any other modal) which works nicely in terms of the modal itself, but I'd like thumbnails to be static, not animated. I wonder if there's some nice trick to insert those gifs as static images.
Note: in fact, I have to create a large number of small galleries, so it's not big deal that those GIFs are slower to load than separately generated static images.


text:
Q: get contents from another page using php? I'm not sure this is possible or not.
I want a php script when executed , it will go to a page (on a different domain) and get the html contents of it and inside the html there's links , and that script is able to get each link's href.
html code:

  Yahoo
  Google
  Facebook

The output code(which php will echo out) will be
http://yahoo.com
http://google.com
http://facebook.com
I have heard of cURL in php can do something like this but not exactly like this , i'm a bit confused , i hope some can guide me on this.
Thanks.

A: have a look at something like http://simplehtmldom.sourceforge.net/

A: Using DOM and XPath:
<?php
$doc = new DOMDocument();
$doc->loadHTMLFile("http://www.example.com/"); // or you could load from a string using loadHTML();
$xpath = new DOMXpath($doc);
$elements = $xpath->query("//div[@id='somediv']//a");
foreach($elements as $elem){
    echo $elem->getAttribute('href');
}

BTW: you should read up on DOM and XPath.


text:
Q: Display the values using query function I want to display the values according to the text that which is comes in the drop-down list. one of my friends from this platform helped me to develop that. But that function is only displaying based on two texts. can I add it one more text to generate details?
Here I'm adding the sheet for more clarification. Take a look and you will understand what I need. I want to display which comes under "insurance claim" when we select yes/no.
https://docs.google.com/spreadsheets/d/1VsLKHSZsTMeBctnINnsixKISgNkTHDV-dkO4ORsDjgI/edit#gid=595280251

A: You just need to add the  and F contains '"&$C2&"'" to your current formula on the cell A5 of the sheet RESULTS.
For more details please see the Query documentation
Your cell A5 will become this:
=query(LIST!A1:G,"Select * where B contains '"&$A2&"' and C contains '"&$B2&"' and F contains '"&$C2&"'")
If you want to have the values of both sheets in your RESULTS sheet, you can add the other sheet to the range of the query:
=query({LIST!A1:G;LIST2!A1:G},"Select * where Col2 contains '"&$A2&"' and Col3 contains '"&$B2&"' and Col6 contains '"&$C2&"'")


text:
Q: Spinner on Item selected pass on edittext I'm trying to work with the spinner. On the selected item, the item will go to the edit text. So for my interface is this:

For example, when the user click KLCC (one of the spinner item) it will go to the edit text under the Location Textview. I've tried with several options that I found on the internet, seems good, no error, but then something went wrong when I tried to insert the details, here's what it looks like after I've tried with the codes that I've tried just now:
on top of the page

and the interface keeps on. I mean there's 2 image button, 2 Name(edit text and text view) and same as the others. Before I implement the spinner all works perfectly well, until the spinner development.
(My spinner Id is = locationspinner and my edittext id is = edittext_location)
So here's the codes,
 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mRootView = inflater.inflate(R.layout.save, container, false);
    locationspinner = (Spinner)mRootView.findViewById(R.id.locationspinner);
    textforspinner = (EditText)mRootView.findViewById(R.id.editText_location);listlocation.add("Bukit Bintang");
    listlocation.add("Bukit Antarabangsa");
    listlocation.add("Brickfields");
    listlocation.add("Gombak");
    listlocation.add("Jalan Chow Kit");
    listlocation.add("Jalan Dang Wangi");
    listlocation.add("Jalan Tun Razak");
    listlocation.add("Jalan Hang Tuah");
    listlocation.add("Jalan Tunku Abdul Rahman");
    listlocation.add("KLCC");
    listlocation.add("Kampung Baru");
    listlocation.add("KL Sentral");
    listlocation.add("Lowyat");
    listlocation.add("Pavillion");
    listlocation.add("Pasar Seni");
    listlocation.add("Pudu");
    listlocation.add("Shah Alam");
    listlocation.add("Time Square");
    listlocation.add("Wangsa Maju");
    listlocation = new ArrayList<String>();

    ArrayAdapter<String> adp = new ArrayAdapter<String>(this.getActivity(),R.layout.save, R.id.editText_location,listlocation);
    adp.setDropDownViewResource(R.layout.save);
    locationspinner.setAdapter(adp);
    locationspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            switch(arg2){
                case 0:
                    textforspinner.setText("Value 0");
                    break;
                case 1:
                    textforspinner.setText("Value 1");
                    break;
                case 2:
                    textforspinner.setText("Value 2");
                    break;
                case 3:
                    textforspinner.setText("Value 3");
                    break;
                case 4:
                    textforspinner.setText("Value 4");
                    break;
                case 5:
                    textforspinner.setText("Value 5");
                    break;
                case 6:
                    textforspinner.setText("Value 6");
                    break;
                case 7:
                    textforspinner.setText("Value 7");
                    break;
                case 8:
                    textforspinner.setText("Value 8");
                    break;
                case 9:
                    textforspinner.setText("Value 9");
                    break;
                case 10:
                    textforspinner.setText("Value 10");
                    break;
                case 11:
                    textforspinner.setText("Value 11");
                    break;
                case 12:
                    textforspinner.setText("Value 12");
                    break;
                case 13:
                    textforspinner.setText("Value 13");
                    break;
                case 14:
                    textforspinner.setText("Value 14");
                    break;
                case 15:
                    textforspinner.setText("Value 15");
                    break;
                case 16:
                    textforspinner.setText("Value 16");
                    break;
                case 17:
                    textforspinner.setText("Value 17");
                    break;
                case 18:
                    textforspinner.setText("Value 18");
                    break;
                default:
                    textforspinner.setText("Nothing");
                    break;
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {

        }
    });*/
    InitializeViews();
    return mRootView;
}

I'm really sorry for my messy question with the big picture given. I really appreciate your help and your time to help me solve my issue :)
Thanks in advance! :D


text:
Q: Type error when messing up with lenses I am encountering a type error when trying to compile some lens code.
{-# LANGUAGE TemplateHaskell #-}

import Control.Lens.Setter (over)
import Control.Lens.Getter (view)
import Control.Lens.TH

data IL = IL {
  _ilL :: [Int]
}
  deriving (Show)

makeLenses ''IL

val = IL [1, 2, 3]

(val1, val2) = let l = ilL
       in  (over l tail val, view l val)

The error is:
Test.hs:17:35:
    Couldn't match expected type `Control.Lens.Internal.Getter.Accessor [Int] [Int]'
                with actual type `Control.Lens.Internal.Setter.Mutator [Int]'
    Expected type: Control.Lens.Getter.Getting [Int] s0 [Int]
      Actual type: ([Int]
                    -> Control.Lens.Internal.Setter.Mutator [Int])
                   -> IL -> Control.Lens.Internal.Setter.Mutator IL
    In the first argument of `view', namely `l'
    In the expression: view l val

This error goes away if I use ilL directly. However, I really need to make a lens definition using let. How can I solve this?

A: Yet another case of the dreaded monomorphism restriction.  Add {-# LANGUAGE NoMonormorphismRestriction #-} at the top of your file and it will compile just fine.
The reason is because when you do let l = ilL in ... without an explicit type signature (or the MR disabled) GHC wants to specialize the type of l as much as it can.  It first encounters its use in over l tail val and specializes to the type needed there, but this conflicts with the specialized inferred type in view l val.  The solution is to disable the MR or add explicit type signatures like
(val1, val2) =
    let l :: Lens' IL [Int]
        l = ilL
    in  (over l tail val, view l val)

This is very similar to a more simple case like
x = let y = 1
        z = 2 :: Int
        w = 3 :: Double
    in (z + y, w + y)

What should the type of y be?  With the MR the compiler wants to restrict the type of y to be a single type, but we would really like it to have the type Num a => a since this can work with Ints or Doubles.  With the MR turned off the compiler won't specialize the type of y and everything works as expected.  The alternative is to give y an explicit type signature, but why do all that work when we can make the compiler do it for us?


text:
Q: PHP- Multiple variables in mysql query I want to get the value from the Epic[2] column.
The mysql table looks like that:
ID  |  Epic[0] |  Epic[1] |  Epic[2] |  Epic[3]
-----------------------------------------------
440     xy        xy         xy           xy

I have three variables where the informations are stored.
$qualitybudget = "Epic"
$budgetType = "2"
$itemlevel = "440"

I tried the following:
$sql = "SELECT '$qualitybudget'['$budgetType'] FROM `randproppoints` WHERE id = '$itemlevel'";

Output looks like that:
SELECT 'Epic'['2'] FROM `randproppoints` WHERE id = '440'

As you see 'Epic'['2']  has the wrong syntaxing. The output for the working query should be like: Epic[2]
What is the right syntax handling in a mysql query like that?

A: Use
$sql = "SELECT `${qualitybudget}[$budgetType]` FROM `randproppoints` WHERE id = '$itemlevel'";

instead. This way, the column name is exactly formatted as you wish and encapsulated.
Note that the syntax ${xyz} has to be used to make it clear that only xyz is the name of the variable and that this is all to be printed here. Otherwise, PHP assumes it is an array and evaluates the following squared brackets for the same string insertion. Another example where this syntax has to be used is if for instance you had a variable $a = "thing"; and wanted
$b = "there are three $as";

to get "there are three things". It would not work as PHP would assume you address a variable $as, but the fix would seem like this:
$b = "there are three ${a}s";


text:
Q: faster way to sort two models by location in rails? I have two unrelated models. they need to be merged and sorted by distance and paginated.
I forgot that near can't be used for arrays, so I add sort to the combined model. I used near on the models first to get the Distance (the models doesn't have distance columns). but the response time is 1,5 seconds. any improvement?
EDIT: Forgot to mention I use Geocoder Gem. the "near" and "distance" is from that
      lat = current_user.latitude || -6.177
      lng = current_user.longitude || 106.8403

      directories = (Doctor.near([lat,lng],10_000))+(Hospital.near([lat,lng],10_000))

      directories = directories.sort_by{|a| a.distance}

      directories = Kaminari.paginate_array(directories).page(params[:page])


text:
Q: Rails form that requires multiple parameters from different models I'm currently practicing how to make a pedigree system, I have successfully implemented users who own dogs, but I want those users to be able to create a pedigree relationship to other dog's profiles like in pic related:
My view
My issue is that when I click the Submit button to create the relationship (or at least know if it works) I get a "The action 'new' could not be found for PedigreeController" error message. Here is my controller and as you can see I only have a create and a destroy method. I tried changing the url in the view to create but without luck. I have also added resources :pedigree to my route file.
 class PedigreeController < ApplicationController
  def create
    @dog = Dog.find(params[:dog_id])
    #@pedigree = pedigrees.build(dog_id: @dog.id, relative_id: @dog.id, relation_name: :string)
    @pedigree = @dog.build_pedigree(pedigree_params)
    if @pedigree.save
      flash[:success] = "Dog relative added."
      redirect_to access_dogmenu_path
    else
      flash[:danger] = "Unable to add this dog as relative"
      redirect_to access_dogmenu_path
    end
  end

  def destroy
    @pedigree = @dog.pedigrees.find(params[:id])
    @pedigree.destroy
    flash[:success] = "Relative removed."
    redirect_to access_dogmenu_path
  end

  private

  def pedigree_params
    params.require(:pedigree).permit(:dog_id, :relative_id, :relation_name)
  end
end

I have made a pedigree.rb model which is used to create the dogs relationships.
class Pedigree < ActiveRecord::Base
  belongs_to :dog
  belongs_to :relative, class_name: Dog
end

This is the dog.rb model
class Dog < ActiveRecord::Base
  belongs_to :user
  has_many :pedigrees
  has_many :relatives, through: :pedigrees, dependent: :destroy
end

Here is what I have currently in my view (which shows in every dog profile):
...

Relatives:

   <% for pedigree in @dog.pedigrees %>

     <%= pedigree.relative.dname %>'s - <%= pedigree.relative.relation_name %>
                     <%= link_to "Remove", pedigree, method: :delete %>

   <% end %>

Add this dog as your dog's relative:

  <%= form_for(Pedigree.new, url: new_pedigree_path) do |p| %>
  Select your dog:
  <%= p.collection_select(:dog_id, @dogs,:id, :dname, :prompt => "Select your dog") %>

  Select your dog relation to the dog from this profile:
  <%= select_tag(:relation_id, options_for_select([['Sibling', 1], ['Parent', 2], ['Grandparent', 3], ['Great-grandparent', 4], ['Child', 5], ['Grandchild', 6], ['Great-grandchild', 7]])) %>

 <%= p.submit 'Add Relation' %>
 <% end %>
...

To create a pedigree relation 3 things are needed:

*

*The dog_id of the current user's dog of choice (The collection_select seems to be working).

*The relative_id of the dog that will become a relative, in this case the relative_id should be taken straight from the show page for example http://localhost:3000/dogs/2 would be sending dog_id=2 into the form. Does anybody know how would I go about including this in my form?

*the relation_name like sibling, parent, etc. The drop down selector seems to be working ok.
Any help is greatly appreciated.

A: An html form looks like this:
<form method="post" action="/some/url">
  ...
  <input type="submit" value="Add Relation" />
</form>

And when you click on the Submit button, a request is sent to the url specified in the action attribute of the <form> tag.
You set the action attribute to:
url: new_pedigree_path

And, when you create the route:
resources :pedigree

you get the following path helpers:
photos_path returns /photos
new_photo_path returns /photos/new
edit_photo_path(:id) returns /photos/:id/edit (for instance, edit_photo_path(10) returns /photos/10/edit)
photo_path(:id) returns /photos/:id (for instance, photo_path(10) returns /photos/10)

http://guides.rubyonrails.org/routing.html#path-and-url-helpers
So, the url you set for the action attribute is: /pedigree/new, which tries to hit the new() action in the PedigreeController.
By default, form_for() creates a form with the action attribute set to /pedigree.  See here: http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html
And, your resources route gets you the following url-to-action mappings:

http://guides.rubyonrails.org/routing.html#crud-verbs-and-actions
If you check the chart for /pedigree when part of a post request--which is the type of request that form_for() sends(see the resulting html at the link above again)--the request will route to the create() action in the PedigreeController.

The relative_id of the dog that will become a relative,...  Does
  anybody know how would I go about including this in my form?

*

*When you create the form, you can create a hidden form field and set its value to the relative_id.  Then when the user submits the form, the name/value pair will be in the params hash.

*In the action that sends the form back, you can add the relative_id to the sessions hash, then look it up again when the user submits the form.

*In the action that sends the form back, you can set a cookie in the response: cookies[:name] = value. Then when the user submits the form, the cookie will be sent back to you in the headers of the request, and you can retrieve the value from the cookies hash.


text:
Q: Which exception for a missing external dependency? I have read that for good reasons, it's not possible to let pip resolve external dependencies (e.g. that are not available from PyPI).
My project requires two of them, so it should certainly check at startup if these dependencies are installed. If not, I would like to raise an exception, but is there anything standard for this situation? It doesn't look like an OSError, nor IOError. A RuntimeError looks a bit too general. Would an EnvironmentError be the right one? (It appeared in python 3.3, but the python documentation doesn't describe it).
I have seen some projects define their own Missing[External]DependencyError, but, unless it's possible to argue this is the best practice, I would prefer to use a standard one, if possible.

A: There is exceptions.ImportError
Edit: Sorry, that's Python2, in Python3 it's just ImportError, as in
raise ImportError('msg')


text:
Q: How to save/load script with collapsed cells in SpyderIDE? I made a huge spyder Script, with multiple cells with the #%% Seperator. Those may be collapsed and expanded on the left sidebar.
Is it possible to load a script with all cells collapsed? Now i need to collapse them all manually.
See this picture all but one cell is collapsed:

I seeked the internet for the problem and also looked into the IDE Preferences.


text:
Q: How correct calculate the probabilities of violation I have a task. Calculate the probability of a train driver's violation.
How i decide it.
1. I calculate how many the driver made trips during the period of his work (I took 2 years) (2230)
2. Then i calculate how many time he violated the rule(200)
3. Then i divide number of violations of the rule on number of trips
200/2230=0,089.

Is this way correct to calculate the probabilities of violation or not?
Cause can be cases when he can violate the rule many time in one trip and proportion can be (fake example) 200/100=200% of propability.
If my way to decide task is wrong, how should i calculate  the probabilities of violation?
(ideally example on R)

A: Take a look at Poisson distribution, which describes the probability of the number of recurrent event that may happen for a defined time interval.
But the limit is that:

*

*K is 0, 1, 2...and your probability is 0,089 which means the time interval is quite large.

*The events (violation) are probability not independent of each other, because the driver could try to be careful next time if he violates.