text:
Q: How to generate a lookup table with sparse rows at compile time? I have a list of entries (keyA, keyB, value) that I would like to have converted to a two-dimensional lookup table at compile time. However, due to the size of the data in question and the sparsity of its entries, it needs to be stored as an array of pointers to rows ((*table[keyA])[keyB] = value), so that empty rows can be omitted. Storing it as a flat 2-dimensional array (table[keyA][keyB] = value) would not be suitable.
Specifically, I want to be able to write a segment of code like this:
using my_lut_t = struct sparse_lut<10, 10, int>

#define NUM_DEFS 4
constexpr std::array<my_lut_t::entry_t, NUM_DEFS> entries = {{
    {1, 1, 11},
    {1, 2, 12},
    {1, 3, 13},
    {2, 2, 22},
}};

constinit my_lut_t table(entries);

and have the compiled binary at the other end more-or-less contain this:
section .rodata
table:
    dd 0, row_1, row_2, 0, 0, 0, 0, 0, 0, 0
row_1:
    dw -1, 11, 12, 13, -1, -1, -1, -1, -1, -1
row_2:
    dw -1, -1, 22, -1, -1, -1, -1, -1, -1, -1

A table like this could just be assembled during runtime initialization, but that is not the purpose of this question; this question is only concerned with getting this to happen at compile time.
I've gotten as far as this implementation here:
#include <memory>
#include <array>
#include <iostream>

template<std::size_t A_COUNT, std::size_t B_COUNT, typename value_t, value_t sentinel = -1>
struct sparse_lut {
    using entry_t = struct { std::size_t a; std::size_t b; value_t value; };
    using table_row_t = std::array<value_t, B_COUNT>;

    std::array<std::unique_ptr<table_row_t>, A_COUNT> contents = {nullptr};

    template<typename Iter>
    constexpr sparse_lut(Iter& definitions) {
        for (const auto & entry: definitions) {
            if (contents[entry.a].get() == nullptr) { // regular unique_ptr::operator== isn't constexpr
                contents[entry.a] = std::make_unique<table_row_t>();
                contents[entry.a]->fill(sentinel);
            }
            (*contents[entry.a])[entry.b] = entry.value;
        }
    }

    value_t get(const std::size_t a, const std::size_t b) const {
        if (contents[a] == nullptr) return sentinel;
        return (*contents[a])[b];
    }
};

using my_lut_t = struct sparse_lut<10, 10, int>;

#define NUM_DEFS 4
constexpr std::array<my_lut_t::entry_t, NUM_DEFS> entries = {{
    {1, 1, 11},
    {1, 2, 12},
    {1, 3, 13},
    {2, 2, 22},
}};

constexpr my_lut_t table(entries);

int main() {
    for (std::size_t a = 0; a < 10; ++a) {
        for (std::size_t b = 0; b < 10; ++b)
            std::cout << table.get(a, b) << ' ';
        std::cout << '\n';
    }
    return 0;
}

This code does work correctly to generate the table at runtime if one replaces constexpr my_lut_t table(entries); with just const my_lut_t table(entries);. But forcing GCC to do that work at compile time with constexpr yields the following complaint:
In file included from /opt/compiler-explorer/gcc-12.2.0/include/c++/12.2.0/memory:76,
                 from <source>:1:
/opt/compiler-explorer/gcc-12.2.0/include/c++/12.2.0/bits/unique_ptr.h:1065:30: error: 'sparse_lut<10, 10, int>(entries)' is not a constant expression because it refers to a result of 'operator new'
 1065 |     { return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); }
      |                              ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ASM generation compiler returned: 1
In file included from /opt/compiler-explorer/gcc-12.2.0/include/c++/12.2.0/memory:76,
                 from <source>:1:
/opt/compiler-explorer/gcc-12.2.0/include/c++/12.2.0/bits/unique_ptr.h:1065:30: error: 'sparse_lut<10, 10, int>(entries)' is not a constant expression because it refers to a result of 'operator new'
 1065 |     { return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); }
      |                              ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Execution build compiler returned: 1

How can I assemble a sparse lookup table from this sort of entry list, at compile time?

A: This can be accomplished by using a custom allocator to allocate rows from a fixed buffer, rather than dynamically as normally done by new or make_unique.
It's not clear to me whether it's possible to do this and still use unique_ptr, since it does not have custom allocator support. But using just raw table_row_t* pointers, the following achieves the desired output, at the cost of needing to manually specify the number of rows ahead of time.
#include <memory>
#include <array>
#include <iostream>
#include <cassert>

template<typename T, std::size_t N>
struct ArraySlabAllocator {
    std::array<T,N>& slab;
    std::size_t next_available = 0;
    constexpr ArraySlabAllocator(std::array<T,N>& slab): slab(slab) {}
    constexpr T* allocate() {
        if consteval {
            assert(next_available < N); // Need more rows to allocate from!
            return &slab[next_available++];
        } else {
            if (next_available < N)
                return &slab[next_available++];
            else
                return new T();
        }
    }
};

template<std::size_t A_COUNT, std::size_t B_COUNT, typename value_t, value_t sentinel=-1, std::size_t SLAB_SIZE=0>
struct sparse_lut {
    using entry_t = struct { std::size_t a; std::size_t b; value_t value; };
    using table_row_t = std::array<value_t, B_COUNT>;

    std::array<table_row_t*, A_COUNT> contents = {nullptr};

    std::array<table_row_t, SLAB_SIZE> slab = {}; // we can allocate from *here* at compile time!

    template<typename Iter>
    constexpr sparse_lut(Iter& definitions) {
        auto allocator = ArraySlabAllocator(slab);
        for (const auto & entry: definitions) {
            if (contents[entry.a] == nullptr) { // regular unique_ptr::operator== isn't constexpr
                contents[entry.a] = allocator.allocate();
                contents[entry.a]->fill(sentinel);
            }
            (*contents[entry.a])[entry.b] = entry.value;
        }
    }

    constexpr value_t get(const std::size_t a, const std::size_t b) const {
        if (contents[a] == nullptr) return sentinel;
        return (*contents[a])[b];
    }
};

using my_lut_t = struct sparse_lut<10, 10, int, -1, 2>;

#define NUM_DEFS 4
constexpr std::array<my_lut_t::entry_t, NUM_DEFS> entries = {{
    {1, 1, 11},
    {1, 2, 12},
    {1, 3, 13},
    {2, 2, 22},
}};

constexpr my_lut_t table(entries);

int main() {
    for (std::size_t a = 0; a < 10; ++a) {
        for (std::size_t b = 0; b < 10; ++b)
            std::cout << table.get(a, b) << ' ';
        std::cout << '\n';
    }
    return 0;
}

From the assembled output:
        .size   std::__array_traits<std::array<int, 10ul>*, 10ul>::_S_ref(std::array<int, 10ul>* const (&) [10], unsigned long), .-std::__array_traits<std::array<int, 10ul>*, 10ul>::_S_ref(std::array<int, 10ul>* const (&) [10], unsigned long)
        .section        .rodata
        .align 32
        .type   table, @object
        .size   table, 160
table:
        .quad   0
        .quad   table+80
        .quad   table+120
        .zero   56
        .long   -1
        .long   11
        .long   12
        .long   13
        .long   -1
        .long   -1
        .long   -1
        .long   -1
        .long   -1
        .long   -1
        .long   -1
        .long   -1
        .long   22
        .long   -1
        .long   -1
        .long   -1
        .long   -1
        .long   -1
        .long   -1
        .long   -1


text:
Q: best open source UML designing tool for n-ary relation I'm trying to choose a tool for creating UML diagrams, What is the best open source tool to create N-ary Relations of Association in Class Diagrams ?
Thanks in advance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is my Jotai setter function not cumulatively building my array here?

const BulkEditProductImagesModal = () => {
  const [uploadedImages, setUploadedImages] = useAtom(atoms.productImages.bulk.uploaded)

  const handleUpload = (filename, base64) => {
    const payload = { sku: 'testItem01', base64 }
    const results = uploadProductImages([payload])
    setUploadedImages([...uploadedImages, payload])
  }

  // ....
}

Why would my uploadedImages variable not cumulatively build my array here as expected? I always end up with 1 entry in the array no matter how many times handleUpload() is called.


text:
Q: What Is Minimum And Maximum Processor State In Windows 7 Power Management? I am talking about this:

What should I set in minimum and maximum? I want good CPU performance but not overheated CPU and fan working like crazy.

A: These settings determine the range of performance states (or P-states) that Windows will use. In effect, this will vary the processor's clock speed and, if supported, voltage and FSB speed - increase them to meet the workload requirements, or decrease them to reduce power consumption and heat output.
To elaborate, most processors support a number of P-states, which are a combination of a frequency multiplier (also known as frequency ID or FID) and supply voltage (voltage ID or VID). A processor's clock speed is the product of FSB speed multiplied with the FID, so by choosing a lower multiplier, the clock speed can also be lowered. Some processors1 are also able to cut the FSB speed in half, resulting in what's known as SuperLFM (Super Low-Frequency Mode).
The number of P-states supported varies by processor, but is usually around 5-10. Since Windows allows a total of 100 different values for the processor state, this means that not every value will result in a different P-state being used. In other words, going from 100% to 99% or even 90% might have no effect whatsoever on the clock speed. Also, depending on which P-states are supported, the actual clock speed might differ considerably from what you might expect from the percentage; specifying 50% in Windows power options doesn't necessarily mean that your processor will run at 50% clock speed. For instance, on my Core 2 Duo T9550 with a nominal clock speed of 2.66 GHz, setting the processor state to 50% doesn't give a clock speed of 1.33 GHz, as might be expected. Instead, Windows chooses the lowest supported multiplier (FID 6), which results in a clock speed of ~1.6 GHz (FSB 266 MHz × multiplier 6 = 1596 MHz), or 60% of the nominal clock speed, as evidenced by the image below.2

Also, even if the minimum state is set to 1%, my processor won't go below ~800 MHz (SuperLFM), which is the lowest supported clock speed (FSB 133 MHz × multiplier 6 = 798 MHz); this is 30% of the nominal clock speed.
According to the documentation available here:

Windows Vista employs a DBS algorithm by using all available performance states that fall within the range described by these upper and lower limits. When choosing a new target performance state, Windows Vista chooses the closest match between the current power policy setting and the states available on the system, rounding up if necessary.

Intelligently choosing the percentages for Windows power options, then, involves finding out which P-states your processor supports, deciding the minimum and maximum clock speeds you wish to use and then entering the percentages that result in those clock speeds. There's no single correct answer as everything depends on your goals - whether you want to maximise performance or battery life, reduce temperatures or something else entirely. Experiment and see what works out best for you. Personally I've found that setting minimum and maximum to 5% (low enough to force lowest multiplier regardless of processor) and 100%, respectively, gives the best results. Yes, even on battery. While it might seem logical to set maximum processor state to less than 100% on battery, in my experience it's better to have the processor spend some time in the highest P-state and then return to idle as fast as possible, than to have it spend more time in some intermediate state.
For advanced tweaking, utilities like RMClock allow you to disable some P-states, as well as overclock and under- or overvolt your processor. While I personally haven't tried it, I've seen recommendations to only have two P-states enabled - the lowest possible multiplier (SuperLFM if supported) for idling, and the highest possible multiplier (at the lowest stable voltage) for everything else. Certainly something to consider playing around with if interested in such things. As long as you don't overclock or overvolt, the worst-case scenario is a BSOD and a restart.

1 For instance Intel Core 2 Duos, but not, I believe, newer Core i-series processors.
2 I'm using TMonitor to monitor the CPU clock speed and wPrime to push the processor to the maximum allowed speed.

A: These minimum and maximum refer to the minimum and maximum cpu power available.
If you set the maximum processor state in Power Management to 50% it should
offer up to 50% of its processing power when put under load.
Windows 7 is able to vary the processor clock frequency according to the processor usage. Minimum and maximum processor state control the range within which Windows varies the clock speed.
For example, assume that your CPU is capable of 0 to 2.4 GHz, meaning that your maximum processor speed is 2.4 GHz. A minimum of 25% and a maximum of 75% will make Windows vary the speed between 600 MHz (25%) and 1.8 GHz (75%) out of the 2.4 GHz processor. "On battery" and "plugged in" is for setting two different ranges for the discharging and charging states.
The point of reducing clock frequency is that, the higher the frequency, the more heat the processor will produce, and the more power it will consume. The lower the frequency, the more time it will take to complete processing (calculating).
The article How To Prevent Your Laptop From Overheating reports this :

Based on our experience, we have noticed that that the laptop
  overheats when the processor is running at 100% processor state.
  Reducing the processor state by a few notches results in the reduction
  of temperate by 10-20 C, which results in a minor performance dip.
We used Speccy to check for temperate during testing, based on
  which the processor running on 95% processor state gave the same
  performance (barely noticeable dip), with a drop of 10-20 C. You can
  keep an even lower processor state (such as 80-85%) to make sure that
  your laptop heats up even less.

A: Minimum and Maximum processor state is the percentage of CPU speed of which it will run at.
For Example, you have a CPU at 3.00Ghz, then
If you set the Minimum Processor state to 10% and maximum to 90% then your processor speed will vary from 0.3Ghz (10% of 3.00Ghz) and 2.7Ghz (90% of 3.00Ghz).
Lowering these would of course decrease performance under heavy workload. This is same kind of question like using a high speed CPU (3.00Ghz+) or a low speed CPU (~1.5Ghz) and number of cores matter.
For you are asking for Optimal settings then it would be:
Minimum processor state:
        On Battery: 10%
        Plugged in: 30%

**Do not change the Cooling policy.** (it is best when default)

Maximum processor state:
        On Battery: 80% (saves battery)
        Plugged in: 100%

And if you want the best performace all the time (at the cost of battery while on battery) then
Minimum processor state:
        On Battery: 20%
        Plugged in: 30%

**Do not change the Cooling policy.** (it is best when default)

Maximum processor state:
        On Battery: 100%
        Plugged in: 100%

And for the OverHeating topic, processor would not overheat (it will heat up tough) until you stress it, running heavy software like some heavy games can overheat it, it also depends on which processor and cooling system you are using, i would be able to help you more if you specify some more info
Actually it is a completely different topic.
If you want more info read these:
1) What is minimum and maximum processor state in power management?
2) Minimum and Maximum Processor State "Optimal" Setting?
3) What does the Minimum Processor State option in the Advanced options box of a Power Plan do?
Hoping this helps..
EDIT: Each CPU has a number of Processor State, We can not set the CPU other than these CPU states. I took those values just for example.

A: Its simple. For minimum set about 5%, for maximum set 100%. You get all power you need, but when is CPU idle, it goes to lowest possible frequency.
Dont worry about 5%,CPU newer can go so low. In my case (core2duo@3,2GHz) lower state is 2GHz even I set minimum to 5%.

A: Actually, all the people are answering from theory and books. I personally tried setting the maximum processor state at 30% and gain only 1 degree Celsius in overheat. I undervolted the processor to the minimum of getting a BSOD in 5 minutes of stress, and gained another 1 degree Celsius.
I stress the fact that the laptop, a Lenovo E540, is new, with cleaned exhaust channels, clean fan, new Thermal paste (best and most expensive on the market - about 25$ in a very tiny bottle). All this effort for only 2 degrees Celsius.
This is because it's kind of a cheap laptop for Lenovo, not in the T or W series.
The heatsink is very poor, and nothing on Earth can cope with that.
The processor likes to stay at around 50-52C when idle, and 70-75C at load. These figures are with the above tweaks and without.

A: To address the specific title question.
I think the state that these settings refer to is also known as P-State.
Meaning, it's a control over the peak CPU frequency (and as the link explains, also the voltage used).
There is also a more technical documentation of the implementation of the power saving techniques implemented in the Vista line of Windows operating systems.
To my understanding, this is where you can see the currently set maximum CPU frequency of the system:

A: First of all, many thanks to everyone who wrote here, as it has made this thread extensively explanatory (like nowhere else, as I searched, even if it's so extensively explanatory that average users like me can't understood).
I think many users asking this question because searching proper settings to improve performance (mainly on older PCs or/and systems), I'm trying to add some 'skipped' (or side) info in a way that 'average' user can understood about system performance, and maybe they try to further research and make some experiment with.
"Skipped" for "Average users, and under" (like me)
(as simple can be described)
I'd like to mention (also) that "Minimum processor state" on "Power Options" also affects (eg.) "Shutdown/Sleep/Hibernation - on Idle time" scheduled task(s) *if they have been set.
What happens when/if set "Minimum processor state" to a high value is, the CPU will never get idle mode to trigger the action of the activated *(if any) 'scheduled task' like for example: Shutdown/Sleep/Hibernation, "Cooling Policy", "Defender Updates" and so. note: Most of them are also depended on "Minimum processor state".
^ In short: Windows sets by default some scheduled tasks to reduce power consumption on "idle" state. But, at the same time, there is an by default 'prediction not to fall into inactivity' eg. when tasks such as video playback or file downloads and so are performed, And additionally (lets say) "drives" the "cpu consuming" priorities where needed, so everything can be adjusted individually and automatically.
! This means that you should not change "Minimum processor state" (as affects many factors) but >Set the depended program/service or whatever, If needed, Instead.< !
*ie.:
I think it's not wise to "frying" your cpu (if set to Minimum=100%) just because you need max performance (ex.) when you gaming, - but instead set to max only when you gaming and then revert to normal, but there's no need because windows successfully doing it automatically by default as when/if needed.
/!\ So, set it on your need but under 10%, only if you know exactly what you doing as you influence many factors by changing it. (I mentioned just some of them as for example) /!\
again: /!\ >Set the depended program/service or whatever, If needed, Instead.< /!\
ie.: In short and some kind of naively: (rough explain!)
Some procedures, or services, are not showed in "task manager" or there are 'into' the "svhost.exe", so,
if you insists, check "Task Scheduler">Task Scheduler (Local)>Task Scheduler Library> for running schedules. You can set/mode individual tasks & sub-tasks (general, Triggers, Actions, Settings) from there, to correlate processes with and schedule to run under settable circumstances.
For "diggers": "Individual settings" can be done by several ways, as (custom)"scheduled task", even with cmd file or even with a 3rd party program or accompanied Graphic card's optimizing program, etc. (but it's another thread. and needs some study about. ...)


text:
Q: Access mobile device property data Is there a way to access a mobile devices properties through C#. The purpose would be to display the device's serial number and iOS version for USB connected like an iPhone.
Using a WMI query like below access is given to the basic info accessible through the Computer Manager like DeviceID or PnpDeviceID. However I have been unable to find a property that gives the device serial number etc.
ManagementObjectSearcher(@"Select * From Win32_USBHub WHERE Description LIKE 'Apple Mobile Device%'")

or
ManagementObjectSearcher(@"Select * From Win32_PnPEntity")

or
ManagementObjectSearcher("@Select * From Win32_USBControllerDevice")

The device property menu I am referring to is in the picture below accessed by right click on a device and then clicking properties.

A: Placing the code below after lockdown.lockdownd_client_new_with_handshake(deviceHandle, out lockdownHandle, "Quamotion").ThrowOnError(); you will be able to access values like the serial number or iOS version. This is only a crude example:
        string t1;
        string t2;

        PlistHandle tested1;
        PlistHandle tested2;

        //Find serial number in plist
        lockdown.lockdownd_get_value(lockdownHandle, null, "SerialNumber", out
        tested1);

        //Find IOS version in plist
        lockdown.lockdownd_get_value(lockdownHandle, null, "ProductVersion", out
         tested2);

        //Get string values from plist
        tested1.Api.Plist.plist_get_string_val(tested1, out t1);
        tested2.Api.Plist.plist_get_string_val(tested2, out t2);

        //Place data in textboxes
        serialTXT.Text = t1.Trim();
        verTXT.Text = t2.Trim();

A: If you want to access properties such as the iOS version, your best bet may be to use imobiledevice-net.
You can install the imobiledevice-net NuGet package and then run a command like this:
ReadOnlyCollection<string> udids;
int count = 0;

var idevice = LibiMobileDevice.Instance.iDevice;
var lockdown = LibiMobileDevice.Instance.Lockdown;

var ret = idevice.idevice_get_device_list(out udids, ref count);

if (ret == iDeviceError.NoDevice)
{
    // Not actually an error in our case
    return;
}

ret.ThrowOnError();

// Get the device name
foreach (var udid in udids)
{
    iDeviceHandle deviceHandle;
    idevice.idevice_new(out deviceHandle, udid).ThrowOnError();

    LockdownClientHandle lockdownHandle;
    lockdown.lockdownd_client_new_with_handshake(deviceHandle, out lockdownHandle, "Quamotion").ThrowOnError();

    string deviceName;
    lockdown.lockdownd_get_device_name(lockdownHandle, out deviceName).ThrowOnError();

    deviceHandle.Dispose();
    lockdownHandle.Dispose();
}

The lockdown class will allow you to access other properties, such as the iOS version, as well.
It does come with a dependency on iTunes, though.


text:
Q: How do I prevent an ORA-08102 error I am getting an ORA error (08102 - Index Key Not Found) with several customers, and I have been unable to reproduce or explain it.  They have all been on the same index on the same table.
This error is tied to two tables - ALPHA and BRAVO.  ALPHA has a primary key on alpha_id. BRAVO links to ALPHA by a foreign key reference to ALPHA.alpha_id.  For these customers, all BRAVO rows point to a single APLHA row on the BRAVO table. We have an index on the BRAVO table whose only column is BRAVO.alpha_id.
That index, ALPHA_ID_FK, is generating the error when we go to delete rows. As I said, I have been unable to replicate this myself, but I'm getting reports of the same problem by several different customers.
We are sometimes able to rebuild the index to correct this issue, but even rebuilding the index is not working for all customers.
What is causing this error, and how can I better prevent it?

A: Disclaimer:
As @JustinCave wrote, you should contact Oracle support.
I give the following information without any warranty.
Source of Information:
I found the following metalink notes that analyze this problem:

*

*ORA-08102: Rebuilding Index does not correct ORA-8102 (Doc ID 96118.1)

*ORA-8102 CORRUPT INDEX, ORA-1499 EVEN AFTER DROPPING AND RECREATING INDEX (Doc ID 1081343.6)

Why does Rebuilding an Index not help?
Rebuilding the index may not help. 'REBUILD' uses the data of the existing index. If the data of the index is corrupt you will not get rid of this corruption. So a 'DROP INDEX ...' followed by a 'CREATE INDEX ...' is an option. But the create index may scan another index that contains the fields of the index to create. An if the index that is scanned is corrupt you still may create a corrupt index. Finally you may drop all indexes that my be used for creating your index and recreate them all. But it may also happen that your table is corrupt and then index recreation will generate again corrupt indexes. If this is the case you have to repair the corrupt table before you rebuild the indexes.
What is Corrupt?
To check what problems your table/indexes have you can issue the statement
ANALYZE TABLE <owner>.<table_name> VALIDATE STRUCTURE CASCADE;

It will generate a trace file with the appropriate errors, but maybe only an Oracle support engineer can read this trace output. The analyze statement may lock your table.
How to Repair a Table?
If rebuild or the recreation of one or more indexes does not help, because the table is corrupt then the table mus be rebuilt. This can be done by exporting the table with data pump (expdp) , dropping the table and importing the table with data pump (impdp) (or exp/imp for older Oracle versions). You may loosed data (of the corrupt rows) when doing this export import.


text:
Q: Forcing Eclipse to showing only errors Is it possible to tell Eclipse to show only errors in the console ?
It could be useful as I'm using external libraries that use the output to display unwanted data. I know that there is a button "Show Console when standard error changes", but, I'm looking for a filter rather.
Regards.

A: Eclipse (the Console view) shows two different outputs: The standard output (System.out) and the error output (System.err). Eclipse itself cannot distinguish between an actual error/exception logged by your programm running, and an external library which writes it copyright/licence information to the error stream.

A: You can redirect the System.out and/or System.err to another OutputStream using the System.setOut and System.setErr functions. This way you can create your own "Console view" or handle the output yourself. If you implement your custom OutputStream class, you can also send the data to the original OutputStream (original System.out or System.err).
PrintStream oldOut;

oldOut = System.out;
System.setOut(new PrintStream(new OutputStream() {
    @Override
    public void write(int b) throws IOException {
        // handle the "b" or
        // send it to old stdout:
        oldOut.write(b);
    }
}));

// do what you want with the stream and afterwards
System.setOut(oldOut);

Also be aware that it may be a problem if you do it in the UI thread. For me the application always hanged afterwards.
If you redirect these streams you can decide if you will forward it onto the standard output/error.


text:
Q: Apache Spark - Java -JSCH - Algorithm negotiation fail Getting the below exception while using Spark 2.0 and JSCH for file transmission. Spark lib uses 0.1.42 version and also came across option to override the built-in dependency.
It works fine in client mode, but when submitting to Yarn cluster, it fails with the below exception. Any suggestions, pls.
    1Connecting to xxxxxxxxxxxx.com port 22
    1Connection established
    1Remote version string: SSH-2.0-OpenSSH_7.4
    1Local version string: SSH-2.0-JSCH-0.1.42
    1CheckCiphers: aes256-ctr,aes192-ctr,aes128-ctr,aes256-cbc,aes192-cbc,aes128-cbc,3des-ctr,arcfour,arcfour128,arcfour256
    1SSH_MSG_KEXINIT sent
    1SSH_MSG_KEXINIT received
    1Disconnecting from xxxxxxxxxxxxxxx.com port 22
    18/09/26 10:56:50 ERROR Myclass: Error occurred in processing:
    com.jcraft.jsch.JSchException: Algorithm negotiation fail
com.jcraft.jsch.JSchException: Algorithm negotiation fail
    at com.jcraft.jsch.Session.receive_kexinit(Session.java:520)
    at com.jcraft.jsch.Session.connect(Session.java:286)
    at com.jcraft.jsch.Session.connect(Session.java:150)

If i try the overriding option to load the jars given in the spark submit command, then i get:
java.lang.LinkageError: loader constraint violation: when resolving method "org.slf4j.impl.StaticLoggerBinder.getLoggerFactory()Lorg/slf4j/ILoggerFactory;" the class loader (instance of org/apache/spark/util/ChildFirstURLClassLoader) of the current class, org/slf4j/LoggerFactory, and the class loader (instance of sun/misc/Launcher$AppClassLoader) for the method's defining class, org/slf4j/impl/StaticLoggerBinder, have different Class objects for the type org/slf4j/ILoggerFactory used in the signature
    at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:418)
    at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:357)
    at org.apache.commons.logging.LogFactory$Slf4jDelegate.createLocationAwareLog(LogFactory.java:174)
    at org.apache.commons.logging.LogFactory.getLog(LogFactory.java:111)

There is a question already here - JSch Algorithm negotiation fail
but that looks more from Java point of view, but am looking from Yarn and Spark.


text:
Q: fatal error C1001: An internal error has occurred in the compiler While compiling on x64 plattform I am getting following error:
c:\codavs05\hpsw-sc\ovpacc\tools\codaaccesstest\coda_access.cpp(1572): fatal error C1001: An internal error has occurred in the compiler.

(compiler file 'f:\dd\vctools\compiler\utc\src\p2\sizeopt.c', line 55)
To work around this problem, try simplifying or changing the program near the locations listed above.
Please choose the Technical Support command on the Visual C++
Help menu, or open the Technical Support help file for more information

------ Build started: Project: asyncexample, Configuration: Release Win32 ------

If I change settings to preprocessor file (Yes) i am not getting any error.
About my environment: Upgrading Microsoft Visual Studio 2005 to 2010
Please help.

A: I've encountered this error many times in VC++. Do the following steps. They've sometimes helped me with this issue:

*

*Take a look at the exact location, pointed out by compiler error.

*Find any external types or classes used there at that location.

*Change the order of "include path" of those files found in step 2 and rebuild the solution.

*I hope that help !!!!

A: I am getting same error with VC2012. Setting up the project properties Optimization to Disabled (/Od) resolved the issue.

A: In my solution, i've removed output dll file of the project, and I've made project rebuild.

A: I encountered the same error and spent quite a bit of time hunting for the problem. Finally I discovered that function that the error was pointing to had an infinite while loop. Fixed that and the error went away.

A: In my case was the use of a static lambda function with a QStringList argument. If I commented the regions where the QStringList was used the file compiled, otherwise the compiler reported the C1001 error. Changing the lambda function to non-static solved the problem (obviously other options could have been to use a global function within an anonymous namespace or a static private method of the class).

A: I got this error using boost library with VS2017. Cleaning the solution and rebuilding it, solved the problem.

A: I have had this problem with VS2015 while building locally in Windows.
In order to solve it, I deleted my build folder (Output Directory as seen in Properties/General) and rebuilt the project.
This always seems to help when strange things happen during the build.

A: I also had this problem while upgrading from VS2008 to VS2010.
To fix, I have to install a VS2008 patch (KB976656).
Maybe there is a similar patch for VS2005 ?

A: I got the same error, but with a different file referenced in the error message, on a VS 2015 / x64 / Win7 build. In my case the file was main.cpp. Fixing it for me was as easy as doing a rebuild all (and finding something else to do while the million plus lines of code got processed).
Update: it turns out the root cause is my hard drive is failing. After other symptoms prompted me to run chkdsk, I discovered that most of the bad sectors that were replaced were in .obj, .pdb, and other compiler-generated files.

A: I got this one with code during refactoring with a lack of care (and with templates, it case that was what made an ICE rather than a normal compile time error)
Simplified code:
void myFunction() {
    using std::is_same_v;
    for (auto i ...) {
       myOtherFunction(..., i);
    }
}

void myOtherFunction(..., size_t idx) {
    // no statement using std::is_same_v;
    if constexpr (is_same_v<T, char>) {
        ...
    }
}

A: I had this error when I was compiling to a x64 target.
Changing to x86 let me compile the program.

A: Sometimes helps reordering the code. I had once this error in Visual Studio 2013 and this was only solved by reordering the members of the class (I had an enum member, few strings members and some more enum members of the same enum class. It only compiled after I've put the enum members first).

A: In my case, this was causing the problem:
std::count_if(data.cbegin(), data.cend(), [](const auto& el) { return el.t == t; });

Changing auto to the explicit type fixed the problem.

A: Had similar problem with Visual Studio 2017 after switching to C++17:
boost/mpl/aux_/preprocessed/plain/full_lambda.hpp(203): fatal error C1001: An internal error has occurred in the compiler.
1>(compiler file 'msc1.cpp', line 1518)
1> To work around this problem, try simplifying or changing the program near the locations listed above.

Solved by using Visual Studio 2019.

A: I first encountered this problem when i was trying to allocate memory to a char* using new char['size']{'text'}, but removing the braces and the text between them solved my problem (just new char['size'];)

A: Another fix on Windows 10 if you have WSL installed is to disable LxssManager service and reboot the PC.


text:
Q: The degree of a polynomial is unique Let $\mathbb{F}$ be a field and let $P:\mathbb{F} \to \mathbb{F}$ be a polynomial (i.e, there exists a finite sequence $a_{0},\dots ,a_{n}$ of scalars in $\mathbb{F}$ such that $P(z)=\sum_{i=0}^{n}a_{i}z^{i}$ for all $z$ in $\mathbb{F}$). How can one prove that the degree of polynomial is unique or in other words ($a_{n} \neq 0,b_{m} \neq 0$ and $\sum_{i=0}^{n}a_{i}z^{i}=\sum_{i=0}^{m}b_{i}z^{i}$ for all $z \in \mathbb{F} \implies n=m $  )
Problem that I am facing:
If $\mathbb{F}$ is $\mathbb{R}$ or $\mathbb{C}$ then it's quite easy because each of these fields are infinite so the polynomial $\sum_{i=0}^{n}a_{i}z^{i}-\sum_{i=0}^{m}b_{i}z^{i}$ cannot have infinite roots due to Fundamental Theorem of Algebra but what if $\mathbb{F}$ is finite.

A: You don't, because $x^p\equiv x \bmod p$ in the field with $p$ elements, so the polynomials $x^p$ and $x$ are equivalent in $\mathbb F_p[x]$ using the test you have given (though the polynomials are distinct as polynomials and have different degrees as polynomials).
So how are you defining the degree of a polynomial?


text:
Q: On SLES8, after the second JnextPlan, an agent does not link in Workload Scheduler I'm having a problem with an agent on SLES8 with the Workload Scheduler. The first JnextPlan works fine, but the second fails, with conman giving an error. How can I do?

A: I think the library ligcc_s.so.1 is missing on the agent workstation. This is a library and usually it should be located in /lib. Try to look for it in other directories such as /usr/lib. When you have located it, make a soft link to it from the /lib directory and rerun JnextPlan.
If you can't locate it in your computer, contact the IBM Software Support.


text:
Q: Trying to make a blank list that is mutable on python I need to be able to add, delete, edit, and recall transactions in a list.
I opened a while loop, set the constants and defined an empty list. I then proceeded to create the menuing through if statements. Everything seems to work except I am unable to add to the list and then recall all added values.
This is what I have so far:
while True:

    addTransaction = "1"
    deleteTransaction = "2"
    editTransaction = "3"
    displayTransactions = "4"
    exit = "5"
    transactions = []

    menu = input("**********Main Menu***********\n1.  Add Transaction\n2.  Delete Transaction\n3.  Edit Transaction\n4.  Display Transactions\n5.  Exit the Program\n\nChoose a menu option from 1-4 or 5 to exit the program: ")
    if menu != "5":
        if menu == "1":
            newTransaction = (input("Enter new transaction: "))
            transactions.append(newTransaction)
            print("Added")
        elif menu == "2":
            target = input("Edit transaction: ")
            if target in transactions:
                transactions.pop(transactions.index(target))
                print("Removed")
            else:
                print("Transaction not found.")
        elif menu == "3":
            transactions[input("Enter the transaction key to edit: ")] = input("Enter the new transaction key: ")
        elif menu == "4":
            print("******************\n** Transactions **\n" + str(transactions) + "\n******************")
        else:
            print("Invalid input.")
    else:
        break

I am brand new to Python, trying to figure out how to use all of these functions

A: You just need to make sure transactions is not in the while loop. Because it was being reset to [] every iteration.
addTransaction = "1"
deleteTransaction = "2"
editTransaction = "3"
displayTransactions = "4"
exit = "5"
transactions = []

while True:

    menu = input("**********Main Menu***********\n1.  Add Transaction\n2.  Delete Transaction\n3.  Edit Transaction\n4.  Display Transactions\n5.  Exit the Program\n\nChoose a menu option from 1-4 or 5 to exit the program: ")
    if menu != "5":
        if menu == "1":
            newTransaction = input("Enter new transaction: ")
            transactions.append(newTransaction)
            print("Added")
        elif menu == "2":
            target = input("Remove transaction: ")
            if target in transactions:
                # Use remove to remeve the first occurance of a value
                transactions.remove(target)
                print("Removed")
            else:
                print("Transaction not found.")
        elif menu == "3":
            transactions[input("Enter the transaction key to edit: ")] = input(
                "Enter the new transaction key: ")
        elif menu == "4":
            # Use join to join elements in a list
            print("******************\n** Transactions **\n" +
                  ", ".join(transactions) + "\n******************")
        else:
            print("Invalid input.")
    else:
        break

You may also want to experiment with match. Which is a Python switch case basically
menu = "1"

match menu:
    case "1":
        # Code here for when menu = 1
    case "2":
        # Code here for when menu = 2
    case _:
        # Code here for when menu != 1 or 2
        print("Error")


text:
Q: Store data as JSON in MongoDB I am building a digital-card generator app in node.js. In this I want to store the card data as JSON in the MongoDB database. I am using mongoose ODM. but I think mongoose does not support the data-type of Json or object.
The card schema:
const digitalCardSchema = new mongoose.Schema(
  {
    userId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      required: true,
    },
    data: {
      type: String,
    },
  },
  {
    timestamps: true,
  }
);

How can I do that?

A: you can try this option - there is a Mixed schema type
https://mongoosejs.com/docs/schematypes.html#mixed


text:
Q: Can all structures have "lots of compactness" with respect to expansions by constants? This is one of those "surely not ..." questions that I embarrassingly can't answer at the moment.
Given a structure $\mathcal{A}$ in a language $\Sigma$ and infinite cardinals $\kappa<\lambda$, say that $\mathcal{A}$ is $(\kappa,\lambda)$-compact iff whenever $\Sigma'$ is an expansion of $\Sigma$ by constant symbols, $T$ is a $\Sigma'$-theory of cardinality $<\lambda$, and for every $S\subseteq T$ of cardinality $<\kappa$ there is a $\mathcal{B}_S\models S$ with $\mathcal{B}_S\upharpoonright \Sigma=\mathcal{A}$, then there is a $\mathcal{B}\models T$ with $\mathcal{B}\upharpoonright\Sigma=\mathcal{A}$.  For example, $\mathcal{A}$ is never $(\vert\mathcal{A}\vert^+,\vert\mathcal{A}\vert^{++}$)-compact, but if $\vert\mathcal{A}\vert<\kappa$ and $\kappa$ is measurable then $\mathcal{A}$-satisfiability is $(\kappa,\kappa^+)$-compact.
This is a notion I've thought about a bit in the specific case of $\mathcal{R}=(\mathbb{R};+,\times)$ (see here or here), but I'm also interested in it more generally. Very little about it is obvious to me. As a starting point, I'd like to know if the following "compactness at many inaccessibles" phenomenon is consistent:

${\bf (CMI) } \quad$ For every structure $\mathcal{A}$ and every cardinal $\kappa_0$ there are cardinals $\kappa_0\le \kappa<\lambda$ such that $\lambda$ is inaccessible and $\mathcal{A}$ is $(\kappa,\lambda)$-compact.

The inaccessibility requirement on $\lambda$ ensures that $\kappa$ is "vanishingly small" compared to $\lambda$, in which case $(\kappa,\lambda)$-compactness seems implausibly strong, and I don't offhand know of any nontrivial example even of $(\kappa,\kappa^{++})$-compactness of a structure. However, at the moment I can't rule (CMI) out. In fact, at the moment I can't even prove that the failure of (CMI) is consistent with $\mathsf{ZFC}$ + a proper class of inaccessibles.

A: To move this off the unanswered queue, I'm turning Harry West's comment above into an answer. If he posts an answer of his own, I'll delete this one and accept it instead; meanwhile, I've made this CW to avoid reputation gain.
The answer is yes, at least if we're willing to accept rather strong large cardinal axioms as consistent with $\mathsf{ZFC}$: the principle CMI follows for example from the existence of a proper class of strongly compact cardinals. This is because every structure can be described up to isomorphism by a single $\mathcal{L}_{\mu,\mu}$-sentence for some sufficiently large $\mu$ (the successor of the cardinality of the structure is always enough, but sometimes we can do better).
So suppose $\mathcal{A}$ is a $\Sigma$-structure and $\kappa_0$ is a cardinal. Let $\theta$ be a strongly compact cardinal $>\vert\mathcal{A}\vert+\kappa_0$ and suppose $T$ is a theory of arbitrary cardinality, in an expansion $\Sigma'$ of $\Sigma$ by constant symbols, every size-$<\theta$ subtheory of which has a model with $\Sigma$-reduct $\mathcal{A}$. Let $\varphi$ be a $\mathcal{L}_{\mu,\mu}$-sentence characterizing $\mathcal{A}$ up to isomorphism, with $\mu<\theta$; this exists since $\vert\mathcal{A}\vert<\theta$. Now just apply the strong compactness of $\theta$ to the theory $T\cup\{\varphi\}$.


text:
Q: What's faster, referencing a property in an outer table or comparing against a parameter? I realize this example is entirely contrived, but I'm looking for a general rule of thumb here; is there any difference from a performance standpoint between these two queries?
Example 1: Reference outer table:
select o.id, o.name,
(select count(*) from inner_table i1 where i1.outerid = o.id),
(select sum(i2.amount) from other_inner_table i2 where i2.outerid = o.id)
from outer_table o
where o.id = @outerid

Example 2: Compare directly against parameter:
select o.id, o.name,
(select count(*) from inner_table i1 where i1.outerid = @outerid),
(select sum(i2.amount) from other_inner_table i2 where i2.outerid = @outerid)
from outer_table o
where o.id = @outerid

I primarily use Sql Server 2008 R2, but I'd be interested in answers specific to any RDMS.
Update:
I realize this is hightly contextual; I guess I was just curious if this was only a stylistic choice or if there were circumstances where this would actual make a difference. I realize I could just "test it and see" for specific cases - but that's not really the answer I'm after.

A: One of the pluses and minuses of SQL is that it's high level so you can only be sure by getting the explain plan and testing a specific case to be sure of the outcome. It's no uncommon to answer most database question with...it depends.

A: I created some completely empty tables, with only the required columns to allow your queries to run:
CREATE TABLE [dbo].[inner_table](
    [outerid] [int] NOT NULL
)
CREATE TABLE [dbo].[other_inner_table](
    [outerid] [int] NOT NULL,
    [amount] [int] NOT NULL
)
CREATE TABLE [dbo].[outer_table](
    [id] [int] NOT NULL,
    [name] [varchar](30) NOT NULL
)

I then turned on Execution plans, and executed both queries. In both cases, this showed that all 3 tables were being scanned (as expected, with no/low rows). In particular, the scan against inner_table has a predicate of:
[DBName].[dbo].[inner_table].[outerid] as [i1].[outerid]=[@outerid]

and the scan against other_inner_table has a predicate of:
[DBName].[dbo].[other_inner_table].[outerid] as [i2].[outerid]=[@outerid]

That is, in the first example, the optimizer has identified that the outer where clauses condition of where o.id = @outerid implies that, within the subqueries, o.id is always equal to @outerid, and has performed that substitution.
In general, unless there is a performance issue, you shouldn't try to "help" SQL by transforming the queries by hand. There are something like 300 different optimizations that the optimizer has available to it - you might not pick the best one(s).

A: There's no easy way to answer this; what do yor indexes look like? constraints? statistics?  What's the distribution of data on i2.outerid?  How much RAM do you have on your server?
Sometime performance tuning is a science; usually it's voodoo. :)


text:
Q: tomcat published two projects under path "webapps/" I modified the file conf/server.xml like this below
  <Context path="AA" docBase="BB" reloadable="true" />

when I start tomcat  from a shell file publish.sh:
#!/bin/bash
#defined
TOMCAT_HOME="/root/software/apache-tomcat-7.0.29"

#start tomcat
cd "$TOMCAT_HOME"/bin
sh startup.sh
echo "tomcat is starting,please try to access $PROJECT console url"

tomcat publish two projects under path "webapps/",AA and BB。And I tracked that BB  was published after AA.
If you logged on the  terminal , and start tomcat directly in the directory  "$TOMCAT_HOME"/bin with command:
>./startup.sh

Only one project "BB" under path "webapps/"。
Who can tell me Why?  Thanks!

A: You have double-deployed your web application.
How? Well, you put BB.war into webapps/ (which will be auto-deployed to /BB) and then you put <Context path="AA" docbase="BB"> into server.xml which deployed BB.war to /AA. What did you expect?
If you just want your application to be deployed to /AA, then just re-name the WAR file to AA.war and be done with it: take-out the <Context> in server.xml because it's just making your job harder. This is why it's explicitly recommended not to do that.


text:
Q: error: SharePoint integration with Yammer After configuring yammer app whith sharepoint the link becomes available in sharepoint,  but on clicking on the link instead of showing the yammer feed , the following error is displayed -

Unable to connect to remote webserver.
URL app-3cd776b7433029.s-1507/Yammer%20App%20for%20SharePoint/Pages/StartPage.aspx?SPHostUrl=http%3A%2F%2Fs%2D1507%3A4444&SPLanguage=en%2DUS&SPClientTag=2&SPProductNumber=15%2E0%2E4420%2E1017&SPAppWebUrl=http%3A%2F%2Fapp%2D3cd776b7433029%

A: Is your farm configured for Apps?  You need to ensure you have DNS configured correctly so that Apps will redirect back to a SharePoint web application.  Also, ensure that the web application you are directing too does not have HostHeaders assigned to it.

A: I am not to familiar with Yammer, but do your SharePoint credentials match the Yammer credentials?  Whenever you try to access anything outside of SharePoint, like connecting to an external database for example, SharePoint uses the current credentials to gain access.  If these do not match, you of course will not get in.  You might have to configure a new BDC Service.  Go to Central Admin => Application Management => Manage Service Applications and set up a new trusted BDC connection.
Like I said, I am not sure if you need this for Yammer, but I do know you have to set up external connections for SharePoint to be able to allow access. Here is an artical on how to set it up.


text:
Q: Посчитать количество знаков препинания в строке По условию задачи нужно ввести строку и посчитать в ней количество знаков препинания.
Код который получился у меня:
#include <iostream>

using namespace std;

int main()
    {
        char s[50];
        const char *mas[] = {".", ",", "!", "?", ";", ":", "-"};
        cout << "Ввод строки не более 50 символов" << endl;
        gets(s);
        int count = 0;
        for (int i = 0; s[i] != '\0'; i++) {
            for(int k = 0; k < sizeof(mas); k++) {
                if(s[i] == mas[k]) {
                    count++;
                }
            }
        }
        cout << "\nВ строке было " << count << "знаков препинания.";
        return 0;
    }

На s[i] == mas[k] компилятор выдает ошибку:

Comparison between pointer and integer ('int' and 'const char *')

Но разве s[i] это не char, как решить эту проблему?

A: Нет const char *mas[] это массив указателей на char или проще говоря - массив строк. И инициализируете вы его строками (символами в двойных кавычках).
Должно быть так
const char mas[] = {'.', ',', '!', '?', ';', ':', '-'};

A: *

*const char *mas = { ".!?;:-" }; - вместо твоей записи

*cin >> s - ты же iostream подключил, пользуйся

*sizeof() - возвращает не размер массива, заведи const int N = 6 и все

A: Я немного переделал
 const int sz = 50;
    char s[sz + 1];
           char mas[] = {'.', ',', '!', '?', ';', ':', '-'};
           cin.getline(s, sz + 1); // введет не более sz символов плюс '\0'
           cout << s << endl;
           int count = 0;
           for (int i = 0; i < sz; ++i) {
               for(size_t k = 0; k < sizeof(mas); ++k) {
                   if(s[i] == mas[k]) {
                       ++count;
                   }
               }
           }
           cout  << count ;


text:
Q: How to retrive an item ID from Sharepoint when user clicks on the item in the List? I have a SharePoint list that has many items in it. How can I find out which item the user clicked on? I need to pass that value to getItemByID() so that I can access the data within the form. I am also trying to do this in the Page_load method.

A: Try getSelectedItems
var items = SP.ListOperation.Selection.getSelectedItems(ctx);

            if (items.length > 0) {
                var itemids = [];
                for (i = 0; i < items.length; i++) {
                    itemids.push(items[i].id);
                }


text:
Q: Easy way to add images to an Android ListView I have a lisview that I want to add images to. The examples that I found early on showed using simple_list_item_1, but it doesn't seem to allow what I want.
If possible, I would also like to be able to change the color of items indepentantly of each other. So the text of One would be red, Two blue, etc.
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:orientation="vertical">

    <TextView android:id="@+id/textHeader"
         android:textSize="24px"
         android:textColor="#006699"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:gravity="center_horizontal"
         />
    <ListView
         android:id="@android:id/list"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         />
     <TextView android:id="@android:id/empty"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="Empty set"
         />
<TextView
    android:id="@+id/status_text"
    android:layout_width="fill_parent"
    android:layout_height="0dip"
    android:layout_weight="1"
    />
</LinearLayout>

main.java
public class sGuide extends ListActivity {
    private String[] mBooks = new String[]{ "One", "Two", "Three" };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ArrayAdapter<String> booksAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mBooks);

        this.setListAdapter(booksAdapter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //mChecker.onDestroy();
    }
}

Edit: here is my new row layout. I would like to make it so that tapping anywhere on the row selects it, instead of having to tap the image or label.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <ImageView
        android:id="@+id/icon"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="4dp"
        android:src="@drawable/icon"
         >
    </ImageView>

    <TextView
        android:id="@+id/label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="11dp"
        android:layout_marginBottom="9dp"
        android:text="@+id/label"
        android:textSize="22dp" >
    </TextView>

</LinearLayout>

Edit 2: Changed the linear layout to fill parent instead of wrap text. Now it works.

A: For this kind of behaviour you need to implement your own adapter. As you are using an Arrayadapter you should extend Arrayadapter and overwrite the getView method to change the view of the ListItem in the way you want it to. Have a look at this ListView Tutorial for more information on this topic.

A: In this case you need to use CustomAdapters, do the stuff you needed in getView() method, refer the link below for listview http://www.vogella.de/articles/AndroidListView/article.html


text:
Q: Showing data from database 15 mnute earlier and stop showing it 15 minute late from the time set for it $query = "SELECT title,time_strt,ampmstrt,time_end,ampmend
          FROM addfunction
          WHERE (NOW() + INTERVAL 15 MINUTE) BETWEEN time_strt AND time_end AND location = 'MAWAR ROOM'";

A: topo,
i hope i understand it correctly...
select title,time_strt,ampmstrt,time_end,ampmend
FROM addfunction
where UNIX_TIMESTAMP(time_strt) >= (UNIX_TIMESTAMP(NOW()) - 15 * 60)
and UNIX_TIMESTAMP(time_end) >= (UNIX_TIMESTAMP(NOW()) + 15 * 60)
AND location = 'MAWAR ROOM';

This will found all rows start 15 minutes before time_strt and ends 15 minutes after time_end.

A: Ended doing it like this which show the data from database 15 minute earlier than time_strt and stop Showing after 15 minute have elapsed from the time_end. I changed the data type from DATETIME to TIME.  Thanks to evryone and mostly @harley81!

WHERE date = CURDATE() AND time_strt <= (CURTIME() + INTERVAL 15 MINUTE) AND time_end >= (CURTIME() - INTERVAL 15 MINUTE) AND location = 'MAWAR ROOM'";


text:
Q: How to create a polygon feature class from polylines in Python ArcGIS? I am trying to create a polygon from polylines.  I've created this script but it gives errors of Arrays.
import arcpy
polyline=r'C:\temp\temp_lines.shp'
Output_polygon=r'C:\temp\temp_polygon.shp'
polygonArray = arcpy.Array()
polygonArray.add(polyline)
cursor = arcpy.InsertCursor(Output_polygon)
row = cursor.newRow()
polygon = arcpy.Polygon(polygonArray, "")
row.SHAPE = polygon
cursor.insertRow(row)
del row
del cursor

A: You need to break it down to points if they're good points and reconstruct. Polylines are made from paths, polygons are made from rings. Although they are created in a similar way they are not compatable, hence your error.
Go through each point on the line adding a point to your output array and then insert.
here's a post that might help Get all the points of a polyline
This should work, though it's only a fragment... you have to set your own FeatureClass and make an insert cursor to accept the polygon:
rows = arcpy.da.SearchCursor(FeatureClass)
desc = arcpy.Describe(FeatureClass)
shapefieldname = desc.ShapeFieldName

for row in rows:
    feat = row.getValue(shapefieldname) # input line
    PArray = arcpy.Array() # new polygon
    partnum = 0
    for part in feat:
        for pnt in feat.getPart(partnum):
            PArray.add(arcpy.Point(pnt.X,pnt.Y))
        # you will need to check that the first and last point are the same
        partnum += 1
    OutPoly = arcpy.Polygon(PArray) # now it's a polygon

Have a read of these:
Reading Geometries http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//002z0000001t000000
Writing Geometries http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#/Writing_geometries/002z0000001v000000/


text:
Q: How to represent extraneous Swagger parameters Our business is looking to create a Swagger document to represent an internal server.
For various reasons, each request is required to include a series of extraneous header parameters:
parameters:
    - name: device_id
      in: header
      required: false
      type: string
    - name: ip_address
      in: header
      required: true
      type: string
    - name: client_id
      in: header
      required: true
      type: string
    - name: request_id
      in: header
      required: true
      type: string

The server will reject the request if the parameters are not included but the parameters themselves are unrelated to the request being made.
The primary purpose of the Swagger document is to generate a small number of client applications (all of which we control) to interact with the server.
We could add each parameter explicitly on every request but this would result in repetition within the document and additional handling within the clients. Alternatively, we could regard these parameters as metadata and exclude them from the document, relying on the clients to add them to each request appropriately.
Is there a recommended approach for such parameters?

A: An OpenAPI definition serves as a contract between the API provider and the clients. It can be used, among other things, to generate client SDKs. So it's expected that an OpenAPI definition describes your API precisely, including the request body format, required parameters, authentication, etc.
All required parameters should be defined explicitly.
To reduce the code duplication, you can define reusable parameters in the global parameters section (for OpenAPI 2.0) or components/parameters section (for OpenAPI 3.0), and then $ref them from individual paths or operations, as shown here:
Swagger/OpenAPI - use $ref to pass a reusable defined parameter
Note that there's currently no way to $ref a group of parameters. The corresponding feature requests are tracked here:
Group multiple parameter definitions for better maintainability
Global/common parameters (this one is closed for some reason, even though it's not implemented)


text:
Q: Remote Debuggging in Visual Studio 2012 I was trying to remotely debug a ASP .net application installed in the client's windows server 2012. I installed Remote debugger in the remote machine and ran it in administrator mode. (Even After) Following the Microsoft instructions, I was hit by serious of errors - most of which are configuration error which was not detailed (or overlooked) in the instructions.
After all the setup hurdles, I managed to attach the process W3WP.EXE but I was not not able to debug the remote application.
Debugger gave the standard warning - No Symbols have been loaded for this document
(I tried copying .Pdb file to the remote machine - making sure that the versions in local copy and in remote copy are same).
Am I missing any steps ? A detailed walk through would help.

A: One step that is not clearly documented is that in the remote applications web.config file, compilation debug must be set to true:
<system.web>
    <compilation targetFramework="4.5" debug="true">
    ...

A: Consider the following situation:
We have deployed a web application on a client machine and the client reports a bug. Then we try to replicate the problem in our local environment (where the code exists), but could not succeed. Now there are two ways to debug the client installation – either through log files or through visual studio debug mode. If our logging is not detailed, we will have nightmares in troubleshooting. The other option is installing visual studio in a server machine (which is not a great idea).
To solve this remote debug problem, we can use a tiny tool called Remote Debugging Monitor (MSVSMON.EXE). It lets you run, debug, and test an application that is running on one device (client machine) from another computer (local development environment) that is running Visual Studio.
Pre-Requisites:

*

*The remote device and the Visual Studio computer must be connected over a network or connected directly through an Ethernet cable. Debugging over the internet is not supported.

*The remote device must be running the remote debugging components.

*You must be an administrator to install the remote debugger on the remote device. To communicate with the remote debugger, you must have user access to the remote device.
Installation:

*

*Download the Visual Studio Remote Debugger setup program from the Microsoft download center. Run the setup program that matches the operating system (x86, x64, ARM) on the remote device (client machine – Remember you need administrator access to install this).

*Once you install and start the remote debugger for the first time – Configure Remote Debugging dialog box appears

*If the Windows Service API is not installed, choose the Install button.

*Select the type of networks that you want the remote debugger to communicate with. At least one network type must be selected.

*To change the Authentication mode or to specify a timeout value for the remote debugger, choose Options on the Remote Debugging Monitor Tools menu.
(You can choose to run the remote debugger in No Authentication mode, but this mode is strongly discouraged. There is no network security when you run in this mode. Choose the No Authentication mode only if you are sure that the network is not at risk of from malicious or hostile traffic.)

*By default, Administrators of the remote device can connect to the remote debugger. To grant or deny other users permission to use the remote debugger, choose Permissions on the Tools menu.

Instructions:

*

*Before connecting to the client machine, first initiate a worker process on the client PC. To initiate a worker process you need to run the application, the IIS will do the rest.

*Once started, open the instance of visual studio where the original code was developed and navigate to Debug -> Attach to Process

*By default this lists the process running in the local machine.

*To connect to the remote server's process, enter the machine name in the Qualifier field (Editable field). This detail can be obtained from the Remote Debugging Monitor. It displays the machine name with the port number once Remote Debugging Monitor (MSVSMON.EXE) is started.

*If you are accessing the Remote Debugging Monitor outside the domain, it will prompt for authentication. Authorization is based on the permission as configured in the Remote Debugging Monitor (under permission settings as discussed earlier).

*Once connected, we can attach to the required process to debug the application. In this instance, to debug the ASP .Net application we have attached to W3WP.exe of the remote machine (Client installation).

*Now the Visual Studio debug will work as expected from the local machine (development environment). For process requiring higher permissions, you need to run the Remote Debugging Monitor (MSVSMON.EXE) as admin in remote machine.
Troubleshooting:
Sometimes even if you attach the correct process, the VS Debug mode does not detect the process. It might be due to one of the below reasons:
•   Make sure you copy the .PDB file that is generated with your assembly into the same folder on the remote machine. This will allow the debugger to pick up the debug symbols.
•   Make sure that you are using the correct version of MSVSMON.exe – 64 bit version is for debugging 64 bit C# application – Which cannot be used with x86 application instance.
References:
Part of this procedure was taken from Microsoft instructions, blog post and from stack overflow discussion.

A: I had the problem that i created an ASP.NET application with latest .NET-framework (4.8).
After changing to 4.6.1 (which made a lot of problems) i was able to debug the remote application finally.


text:
Q: My python perfect number function returns invalid data I finally got the perfect number program that I am writing in Python to work...just not correctly.
I have run the code 3 times and it keeps returning 24 as a perfect number.
def printPerfectNumbers(firstNum, lastNum):

   for i in range(firstNum, lastNum +1):
       totalFactors = 0
       for x in range(1, i):
       # Checks if x is a divisor, if true, adds x to totalFactors.
         if(i % x == 0):
             totalFactors = totalFactors + x
             if (totalFactors == i):
                print(i, end = " ")

printPerfectNumbers(1, 1000)

Any advice would be welcome.

A:          if (totalFactors == i):
            print(i, end = " ")

needs to be 2 levels less since you want to check the sum totalFactors only after all possible candidate divisors have been looked at:
def printPerfectNumbers(firstNum, lastNum):

   for i in range(firstNum, lastNum +1):
       totalFactors = 0
       for x in range(1, i):
       # Checks if x is a divisor, if true, adds x to totalFactors.
           if(i % x == 0):
               totalFactors = totalFactors + x
       if (totalFactors == i):
           print(i, end = " ")

printPerfectNumbers(1, 1000)

A: That's simple.
1+2+3+4+6+8=24
You should compare the sum and double of the original number after for.


text:
Q: Factors of a polynomial in several variables Fix an embedding of $\overline{\mathbb{Q}}$ into $\mathbb{C}$.
Suppose you have a polynomial in several variables, with algebraic coefficients: $P\in \overline{\mathbb{Q}}[z_1, \ldots, z_n]$.  Also suppose we find some factorization $P=QR$ for some $Q, R\in \mathbb{C}[z_1, \ldots, z_n]$ (with, a priori, just complex coefficients).
It seems intuitively clear to me that $Q$ and $R$ would need to have algebraic coefficients as well.  (Well, almost -- we might need to do some scaling first.  Let's say we pick some $\alpha\in\mathbb{C}^\times$ such that $\alpha Q$ has at least one nonzero, algebraic coefficient.  Then replace $Q$ and $R$ with $\alpha Q$ and $\frac{1}{\alpha} R$.)  Can anyone remind me how you would go about proving this?
(I'm sure this has nothing to do with the particulars of $\overline{\mathbb{Q}}$ and $\mathbb{C}$, really -- we could probably replace them with any pair of nested, algebraically closed fields.)


text:
Q: How to upgrade PostgreSQL with PostGIS? I was running PostgreSQL 9.1 and I am trying to upgrade to PostgreSQL 9.3:

$ /usr/lib/postgresql/9.3/bin/pg_upgrade -b
  /usr/lib/postgresql/9.1/bin -B /usr/lib/postgresql/9.3/bin -d
  /var/lib/postgresql/9.1/main/ -D /var/lib/postgresql/9.3/main/ -O "-c
  config_file=/etc/postgresql/9.3/main/postgresql.conf" -o "-c
  config_file=/etc/postgresql/9.1/main/postgresql.conf"

However it fails with:

Checking for presence of required libraries                 fatal
Your installation references loadable libraries that are missing from
  the new installation.  You can add these libraries to the new
  installation, or remove the functions using them from the old
  installation.  A list of problem libraries is in the file:
      loadable_libraries.txt

loadable_libraries.txt contains:

Could not load library "$libdir/postgis-1.5" ERROR:  could not access
  file "$libdir/postgis-1.5": No such file or directory

It is similar to Missing libraries when upgrading to PostGIS 2.1 and PostgreSQL 9.3.1 using homebrew.
I am running Ubuntu and I have install PostgreSQL with PostGIS using apt-get.
Anyone managed that?

A: Since PostGIS 1.5 is not supported with PostgreSQL 9.3, you are also upgrading PostGIS versions. Since pg_upgrade cannot be used for this, you will need to follow the hard upgrade procedure, which utilises logic in a postgis_restore.pl script that comes with PostGIS. If you have any further questions with the procedure, amend them to this question.


text:
Q: Compare BASH variable to string I am very new to BASH scripting and am trying to write a program that will compare a command the user inputs, to a list of options. Here is my program so far:
echo "enter command"
read command
if ["$command" = "quit"]
then
    exit
fi

when I run this, I get the following error:
./script.sh: line 3: [quit: command not found

Thanks in advance :)


text:
Q: How can I make the following C++ program faster? Link to the problem - https://www.hackerrank.com/contests/freshers-challenge-2/challenges/counting-the-steps
The question is as follows - Find the number of prime numbers between a and b(including a and b,in case they are prime.)
I used the sieve of Eratosthenes to solve the problem, but I am getting timeout on two test cases.
Especially for one test case, where there are 10,000 numbers, my C++ program took around 10 seconds in CodeBLocks. I am inserting the code snippet below-
for(int i=2;i<=upperbound;i++)
{
    prime[i-2]=i;
}
int sq=sqrt(upperbound);
for(int i=0;prime[i]<=sq;i++)
{
    if(prime[i]!=0)
    {
        int j=i+prime[i];
        for(;j<m;j+=prime[i])
        {
            prime[j]=0;
        }
    }
}

This is the code snippet for the sieve. My outputs are all correct, but how can I make this program faster.
EDIT : The segmentation fault was solved after replacing upperbound with sq

A: You are using sqrt, which can be time consuming, especially as it finds the double root. You don't even use sq afterwards.
Edit: Try replacing upperbound by sq in your loop. It'll solve some speed concerns, but not the segfault which probably is the result from allocating too big a chunk of memory.

The problem with the sieve algorithm is that it allocates the full array, for all numbers.
Another way of finding primes is to check all number by dividing them by primes up until their square root. A simple optimisation to that algorithm is avoiding even numbers. And storing only the prime numbers in a structure.
int lastBound = 0; //avoids doing too many multiplications
vector<int> primes;

primes.push_back(2);

for (int i = 3; i <= upperbound; i+= 2) {
    bool prime = true;
    for(int j : primes) {
         if (j > lastBound && j * j > i) {
             lastBound = j;
             break;
         }

         if (i%j == 0) {
             prime = false;
             break;
         }
    }

    if (prime) {
        primes.push_back(i);
    }
}

Then you have the primes in the list, you can convert it to an array like you had, a set, or whatever.
There are some dynamic allocations that could cause some delay, but for a vector of size n there are only O(log(n)) allocations. There could probably be further optimisations, but for your purpose it should be enough.

A: The only time swallower I see in your code is the use of sqrt.
You can use the digit by digit method in base 2.
But it is a minor improvement.
You have to change your algorithm to achieve better results.
Search of prime numbers is a difficult problem and there is a lot of least worst solutions (for example you can use pseudo-prime filters...)

A: You're effectively storing the prime numbers twice in your array. prime[i] == i+2, so you can replace int j=i+prime[i]; with int j=i+(i+2);.
Now, if you don't need the actual values anymore, you can store just a single bit: std::vector<bool> prime(upperbound, true);. This reduces the memory needed by 95% (probably), which makes it likely that your sieve fits in the CPU cache.
Saving 2 bits in the beginning of prime is a bad idea. A single i-2 instruction elsewhere is going to take up at least a whole byte, and cost you actual runtime as well.


text:
Q: Get parent key in UITableview with firebase I have my firebase database structured like this:
Snap (-KWLSAIh5WJvNJOkxBEr) {
  beschrijving = "description";
  image = "link to image";
  title = "title";
}
Snap (-KWLSTak0H20X_2Qnanv) {
  beschrijving = "description";
  image = "link to image";
  title = "title";
}

This is the code I am using to display this in a TableView:
import UIKit
import Firebase

class NieuwsTableViewController: UITableViewController {

var users = [UsersII]()
let cellId = "IdCell"

override func viewDidLoad() {
    super.viewDidLoad()

    fetchUser()
}
func fetchUser() {
    Database.database().reference().child("Blog").observe(.childAdded, with: { (snapshot) in

        if let dictionary = snapshot.value as? [String: AnyObject] {
            let user = UsersII(dictionary: dictionary)
            self.users.append(user)

            print(snapshot)

            DispatchQueue.main.async(execute: {
                self.tableView.reloadData()
            })

        }

    }, withCancel: nil)
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return users.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> lllTableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)

    let user = users.reversed()[indexPath.row]
    cell.textLabel?.text = user.name

    return cell as! lllTableViewCell
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let message = users.reversed()[indexPath.row]

    guard let beschrijving = message.beschrijving else {
        return
    }
    guard let image = message.plaatje else {
        return
    }
    guard let titel = message.name else {
        return
    }

    UserDefaults.standard.set(beschrijving, forKey: "nieuwsBeschrijving")
    UserDefaults.standard.set(image,forKey: "nieuwsPlaatje")
    UserDefaults.standard.set(titel, forKey: "nieuwsTitel")

    self.performSegue(withIdentifier: "gotonews", sender: nil)
}

}

And I don't know if you will need this to answer this question but I'll also post the "UsersII" (defined as users just above the viewDidLoad method) in case this is needed to answer the question.
 import UIKit

class UsersII: NSObject {
 var name: String?
 var beschrijving: String?
 var plaatje: String?
 init(dictionary: [String: Any]) {
    self.name = dictionary["title"] as? String ?? ""
    self.beschrijving = dictionary["beschrijving"] as? String ?? ""
    self.plaatje = dictionary["image"] as? String ?? ""
 }
}

so what I want to achieve is that if you click on one of the cells, you get the parent id of the article, so in this case that would be the "-KWLSAIh5WJvNJOkxBEr or -KWLSTak0H20X_2Qnanv" I mentioned above in my firebase database structure.

A: Here is what i was saying you to do:
Your model class:
class UsersII: NSObject {
var parentId: String?
var name: String?
var beschrijving: String?
var plaatje: String?
init(dictionary: [String: Any],parentId:String) {
 self.name = dictionary["title"] as? String ?? ""
 self.beschrijving = dictionary["beschrijving"] as? String ?? ""
 self.plaatje = dictionary["image"] as? String ?? ""
 self.parentId = parentId
 }
}

Fetch user method:
  func fetchUser() {
   Database.database().reference().child("Blog").observe(.childAdded,        with: { (snapshot) in

    if let dictionary = snapshot.value as? [String: AnyObject] {
        let user = UsersII(dictionary: dictionary,parentId:snapshot.key)
        self.users.append(user)

        print(snapshot)

        DispatchQueue.main.async(execute: {
            self.tableView.reloadData()
        })

    }

 }, withCancel: nil)
}

And finaly you didSelect:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let message = users.reversed()[indexPath.row]

guard let beschrijving = message.beschrijving else {
    return
}
guard let image = message.plaatje else {
    return
}
guard let titel = message.name else {
    return
}

guard let parentId = message.name else
{
   return
 }

UserDefaults.standard.set(beschrijving, forKey: "nieuwsBeschrijving")
UserDefaults.standard.set(image,forKey: "nieuwsPlaatje")
UserDefaults.standard.set(titel, forKey: "nieuwsTitel")
UserDefaults.standard.set(parentId,forKey: "nieuwsParentId")

self.performSegue(withIdentifier: "gotonews", sender: nil)
 }

}


text:
Q: Where exactly to place "...[UIApplication sharedApplication] openURL..."? I am trying to make a table cell that when tapped calls a phone number and I think the code I must use is;

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel:thenumber"]];

But what happens is that the call gets placed automatically, as soon as the app is opened and therefore I think the problem is the location of the code.
Where does it need to be placed in order to achieve the desired cell functionality?

A: In
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

A: It should be placed in the
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
method in the tableview's delegate.

A: Thank You all for Your kind answers that are correct but (with Your help) I have found a simpler solution;
- (void)didTap_tableViewCell2:(UIView *)cell {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel:thenumber"]]; }


text:
Q: Getting FileNotFoundException while unzipping a zip file though Java I have a method that unzips zip files through Java.
This method works fine.
But recently I was trying to unzip a certain file(final output.zip) using this method but got a runtime exception.
Below is the code for that method:
public static List<String> unzipFiles(File zipFile, File targetDirectory) {
    List<String> files = new ArrayList<String>();
    try (FileInputStream fileInputStream = new FileInputStream(zipFile); ZipArchiveInputStream zipInputStream = new ZipArchiveInputStream(new BufferedInputStream(fileInputStream));){
        ZipEntry zipEntry;
        while ((zipEntry = zipInputStream.getNextZipEntry()) != null) {
            int length;
            byte data[] = new byte[bufferGlb];
            String fileName = zipEntry.getName();
            File opFile = new File(targetDirectory, fileName);
            FileOutputStream fileOutputStream = new FileOutputStream(opFile);//This is the line where the exception is thrown
            BufferedOutputStream dest = new BufferedOutputStream(fileOutputStream, bufferGlb);
            while ((length = zipInputStream.read(data, 0, bufferGlb)) != -1) {
                dest.write(data, 0, length);
            }
            dest.flush();
            files.add(fileName);
            fileOutputStream.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return files;
}
//library import used:
//import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;

It is important to note that I am able to successfully unzip this file using WinRar.
The line at which I am getting the exception is marked with comments in the above code.
The stack trace of the exception that I got is below :
java.io.FileNotFoundException: final output/0123450.pdf (No such file or directory)
    at java.io.FileOutputStream.open0(Native Method) ~[?:1.8.0_191]
    at java.io.FileOutputStream.open(FileOutputStream.java:270) ~[?:1.8.0_191]
    at java.io.FileOutputStream.<init>(FileOutputStream.java:213) ~[?:1.8.0_191]
    at java.io.FileOutputStream.<init>(FileOutputStream.java:162) ~[?:1.8.0_191]
    at ZipUtility.unzipFiles(ZipUtility.java:281)

Also the file mentioned in the exception, 0123450.pdf is actually there inside the zip file.
Please help.

A: I had faced a similar issue before.
The file mentioned in the exception:
java.io.FileNotFoundException: final output/0123450.pdf (No such file or directory)
    at java.io.FileOutputStream.open0(Native Method) ~[?:1.8.0_191]
    at java.io.FileOutputStream.open(FileOutputStream.java:270) ~[?:1.8.0_191]
    at java.io.FileOutputStream.<init>(FileOutputStream.java:213) ~[?:1.8.0_191]
    at java.io.FileOutputStream.<init>(FileOutputStream.java:162) ~[?:1.8.0_191]
    at ZipUtility.unzipFiles(ZipUtility.java:281)

i.e 0123450.pdf is actually inside a folder final output and not directly inside the zip file.
Try using a zip file that contains the files directly inside it


text:
Q: android push server instance to application I am new to android and I have a small doubt. Like
Is it possible to push a server instance to application ? Can do it with gcm notification. At that time is it possible to do some actions if the application is live / currently using and if doesn't make a notification .
In first case no need to show any notification.
Please advise
Thanks

A:
At that time is it possible to do some actions if the application is live / currently using and if doesn't make a notification .

You can accomplish this using an event bus, where your GCM receiving code publishes the event on the event bus, then detects if nothing picked up that event and displays the Notification.
The following projects demonstrate this basic pattern (though triggered by AlarmManager instead of GCM), using:

*

*LocalBroadcastManager

*Square's Otto

*greenrobot's EventBus


text:
Q: Casting, Assignability and custom conversions Consider the following code, simply a class with a custom widening conversion from Long (Int64).
Public Class CharacterArgs
    Private _CharacterID As Long

    Public ReadOnly Property CharacterID() As Long
        Get
            Return _CharacterID
        End Get
    End Property

    Public Sub New(ByVal characterID As Long)
        _CharacterID = characterID
    End Sub

    Public Sub New()

    End Sub

    Overloads Shared Widening Operator CType(ByVal source As Long) As CharacterArgs
        Return New CharacterArgs(source)
    End Operator

End Class

The following code works:
Dim test As CharacterArgs
test = 10

But:
Dim canAssign = GetType(CharacterArgs).IsAssignableFrom(GetType(Long)) 'False
Dim convertTest = Convert.ChangeType(10L, GetType(CharacterArgs))
'Throws InvalidCastException

So my questions:

*

*Is there a casting/conversion method that supports the custom conversion, but also accepts the destination type as a System.Type object (as opposed to CType)?

*Is there a reflection or casting "test" method, similar to IsAssignableFrom, that will account for the custom conversion as well?

A: So far as I know, neither of the things you are looking for exist.  The closest I can think of for the first requirement would be a TypeConverter.  However, TypeConverters seem geared toward designer support and are specific to a single type that will always be either the source or destination type.
To find the conversion methods on a type, you could make a function to look for methods with the special names op_Implicit and op_Explicit (as per MSDN) on either the source or destination types with the appropriate arguments and return types.
As an aside, the reason IsAssignableFrom returns false in this case is that it checks if one type can be assigned a variable of another type directly without conversions.  Conversion operators add confusion to this issue because in the source code it appears that you are doing a simple assignment, but you are actually calling a method and assigning its result.

A: Depending on exactly what you are attempting to accomplish with your class, you may be better off using Extension Methods rather than Widening. You can get more information on Extension Methods in MSDN.


text:
Q: How do I get the "Finish Bonus" and how much is it actually worth? At the end of a battle sometimes I get a "Finish Bonus" on the win screen. It looks like an experience boost. Do I get this from winning on an All-Out Attack or just by winning in one turn? And what is the actual bonus?

A: You get a finish bonus if your battle is ended during the All-Out Attack.


text:
Q: Bash Find Files with zero size and delete files with different extensions This command will find files of zero size:
find . -size 0

A filename returned might be
filename.001

I am looking for a one liner that will delete files found with this, plus any that have the same filename with a different extension (which would be non-zero sized), so these files would be deleted too:
filename.txt
filename.bak
filename.ZZz

A: $> find . -size 0 | while read f; do rm "${f%.*}."* ; done

explanation:

*

*find all files with size 0

*pipe the names to the while loop

*cut of the suffix (extension) part ${f%.*} (read man bash)

*rm all other files with the same base


text:
Q: two image inside a scrollviewer here is my problem. i have two image inside a scrollviewer.
but i can't make it work because:
it says the property content can only be set once.

is there a workaround to make it work?
i need to overlay two image inside scrollviewer.
one of the image control opacity is set to 50%
one of the image control in on the top. in order to overlay
and i need the scrollviewer in order to view the picture when the image cotrol stretch property is set to none.

A: You can place a grid within the scroll viewer and then put both images inside the grid.


text:
Q: Querying a database within a PHP function I'm trying to load some data from a database using PHP, but for some reason it doesn't work when I put it inside a function. If I try the code without a function, it works fine:
//$dbc connection
$call1 = 0;
$output = '';
$query = "select * from artists order by lname limit $call1, 15";
$result = mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($result)){
    $output .= "
";
    $output .= "
" . $row['name'] . "
";
    $output .= "
";
}

However, when I change the code to be inside a function, I don't get anything from the database (or at least it won't return anything):
//$dbc connection
$call1 = 0;
$output = '';
function loadArtists($call){
    $query = "select * from artists order by lname limit $call, 15";
    $result = mysqli_query($dbc, $query);
    while($row = mysqli_fetch_array($result)){
        $output .= "
";
        $output .= "
" . $row['name'] . "
";
        $output .= "
";
    }
}
loadArtists($call1);

What am I doing wrong here?

A: You cannot use $dbc in your function, because it is a global variable.
You can use either
function loadArtists($call){
    global $dbc;
    ...
}

to make $dbc known to loadArtists() or pass it as a second parameter
function loadArtists($dbc, $call){
...
}

and call it as
loadArtists($dbc, $call1);

A: As I mentioned in one of my comments, using global to fix the scope of your connection is poor practice. The correct way to pass your connection is like so:
$dbc = mysqli_connect("localhost", "my_user", "my_password", "world");

$call1 = 0;
$output = '';
function loadArtists($call, $dbc){
    $query = "select * from artists order by lname limit $call, 15";
    $result = mysqli_query($dbc, $query);
    while($row = mysqli_fetch_array($result)){
        $output .= "
";
        $output .= "
" . $row['name'] . "
";
        $output .= "
";
    }
}
loadArtists($call1, $dbc);

A: Declaring your username and password on the same page as the code you're executing every time you want to make a DB connection is bad practice because:

*

*You could potentially have more than one page to edit if you move to a different host or a different environment than the dev environment.

*If you declare it outside of the root you can limit access to the DB password from FTP accounts.

I like to use a function for the connection so this way if the connection closes you can reopen it at will (reducing server overhead). Also you don't have to set it as a global var inside the function (not a good idea because of several reasons).
So for those reasons, this connection should be outside (below) the root.
/../safe/connection.php
function openSQL() {
  $conn = mysqli('localhost', 'my_user', 'my_password', 'my_db');
  return $conn;
}

functions.php
require_once($_SERVER['DOCUMENT_ROOT'].'/../safe/connection.php');
function loadArtists($call){
   $dbc = openSQL();
   $query = "select * from artists order by lname limit $call, 15";
   $result = mysqli_query($dbc, $query);
   while($row = mysqli_fetch_array($result)){
      $output .= "
";
      $output .= "
" . $row['name'] . "
";
      $output .= "
";
   }
   mysqli_close($dbc);
   return $output;
}

$myOutput = loadArtists(4);

A: The problem is variable scope. That variable does not exist within your function.
There are three ways to deal with that:

*

*Make it global, that means an outside variable is readible from within a function. (Note that using global variables is often considered a security concern.)
global $dbc;

*You can pass that variable into the function as an argument
function loadArtists($connection, $call) { ... }

*you can make a class and that class variable will now be useable inside of class functions:
class Artists {
    public $dbc;
    public function __construct() {
        $this->dbc = open_the_db_connection(); //etc?
    }
    public function loadArtists($call) {
        $query = "select * from artists order by lname limit $call, 15";
        $result = mysqli_query($this->dbc, $query);
        while($row = mysqli_fetch_array($result)){
            $output .= "
";
            $output .= "
" . $row['name'] . "
";
            $output .= "
";
        }
        return $output;
    }
}

A: It looks like a scoping issue to me. The $output you reference in the function isn't the same as the $output you defined outside the function.
You should change your function to the following:
function loadArtists($call){
$output = "";
$query = "select * from artists order by lname limit $call, 15";
$result = mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($result)){
    $output .= "
";
    $output .= "
" . $row['name'] . "
";
    $output .= "
";
}

return $output;

}
$output = loadArtists($call1);


text:
Q: Is using a hash table valid in counting sort (in place of an array)? The classic counting sort example requires you to build an array of size equal to the greatest integer of your input array.
For example, if your array is [1, 6, 3, 10000, 8] you would need an array 10000 long for the counting sort.
Could this not be done in the same linear time using a hash table on the integers?  Just a simple map?
In python, it'd be something like:
counting_map = {n: 0 for n in input_array}  # start by mapping all to 0
for num in input_array:
    counting_map[n] += 1

I know this really only works well for integers, but in that case is the mapping solution not superior?
Time-complexity wise, you initialize the map in O(n) time, then iterate through the array in O(n) time, then perform hashing functions on input in O(1) time.  (Obviously big-O notation isn't the final determining factor of whether an algorithm is good, I just want to make sure I have the theory correct here).
Is this a good solution, or does the "original" counting sort still do something superior that I don't see?  I'm also curious why a "hashmap-based counting sort" hardly returns any Google search results, making it seem like it's hardly ever used.  Is the overhead of the hashing enough to outweigh its smaller memory footprint?

A: You can do that, and the construction would be O(n) with the obvious memory benefit.
With one little problem.
To output the sorted array, you'll still need to sort the hash table keys. And that problem is exactly what you were trying to solve in the first place.

A: you need not sort the key ,just traverse from min to max as key


text:
Q: Problems installing express using npm. Im trying to install express using npm, running this code:
npm install express mongoose jade less expresso
But i keep getting this error,
> make deps/jscoverage/node-jscoverage

sh: make: command not found

npm ERR! expresso@0.9.2 preinstall: `make deps/jscoverage/node-jscoverage`
npm ERR! `sh "-c" "make deps/jscoverage/node-jscoverage"` failed with 127
npm ERR! Failed at the expresso@0.9.2 preinstall script.
npm ERR! This is most likely a problem with the expresso package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     make deps/jscoverage/node-jscoverage

I searched a lot and can't seem to find the answer. Cheers.

A: You don't have make, you must install it (it's a part of gcc).
If you're on a Debian-based linux distribution:
sudo apt-get install build-essential

If you're on Mac OS X you must install XCode and then install its Command Line Tools:
Install XCode 4 then open it, Got to Preferences -> Downloads -> Components -> Click on Command Line Tools and then click on its Install button.

And I just hope you're not on Windows, because I won't be able to help you hehe :-P
Hope this helps!

A: What TomShreds said, and you may also want to swap "expresso" for "mocha", which kind of replaced expresso (from expresso's GitHub readme: "Be sure to check out Expresso's successor Mocha.")


text:
Q: Rufus scheduler implementation in rails 3 I have an app running with apache + passenger in production. Currently I initialize the rufus scheduler in a initializer and register jobs reading from a db in that initializer. Way apache/passenger works is that it creates multiple process/instance of the app which causes the scheduler to get initialized multiple times and will schedule duplicate jobs.
What is the correct of implementing this so that the scheduler is a singleton object?

A: You probably want to implement Rufus Scheduler as a separate worker process outside your application.
Instead of putting it as an initializer, I would implement a Rake task that starts it.
# Rakefile
desc "Starts the Scheduler worker"
task :scheduler do
  require 'path/to/your/scheduler/file'

  scheduler.join
end

Then just run rake scheduler to start it in the background.

Bonus: Since your app now needs 2 processes side by side, use Foreman to manage the multiple processes of your application. You can do this by creating a file called Procfile:
# Procfile
web:       thin start -p 4242
scheduler: rake scheduler

Then start your app with Foreman: (be sure to gem install foreman first)
$ foreman start

This will invoke both processes simultaneously.