text:
Q: Plugin registered on Delete : Unable to deserialize the serialized value I've registered my plugin on Create, Update and Delete. It's working fine on the Create and Update messages but for the Delete I debugged the plugin code using visual studio and it's throwing exceptions even before the plugin code executes in Visual Studio.

Unhandled Exception: System.InvalidOperationException: Unable to deserialize the serialized value.
     at PluginProfiler.Plugins.ServiceWrappers.ExecutionContextWrapper.Deserialize(OperationType operation, String serializedValue)
     at PluginProfiler.Library.AppDomainProxy.Execute(ProfilerExecutionConfiguration configuration, ProfilerExecutionReport report)
     at PluginProfiler.Library.AppDomainProxy.Execute(ProfilerExecutionConfiguration configuration, ProfilerExecutionReport report)
     at PluginProfiler.Library.ProfilerExecutionEngine.Execute(ProfilerExecutionConfiguration configuration)
     at PluginProfiler.Library.ProfilerExecutionUtility.Execute(PluginPermissions permissions, ProfilerExecutionConfiguration configuration)
     at PluginProfiler.Library.ProfilerExecutionUtility.Execute(PluginPermissions permissions, OperationConfiguration operation, ProfilerReportingConfiguration reporting, CrmServiceClient administratorProxy, ITracingService tracing)
     at Microsoft.Crm.Tools.DebugPlugin.DebugPluginViewModel.btnExecutionClicked()
  Inner Exception: System.Runtime.Serialization.SerializationException: Error in line 1 position 485. Element 'http://schemas.datacontract.org/2004/07/System.Collections.Generic:value' contains data from a type that maps to the name 'http://schemas.microsoft.com/xrm/7.1/Contracts:ConcurrencyBehavior'. The deserializer has no knowledge of any type that maps to this name. Consider changing the implementation of the ResolveName method on your DataContractResolver to return a non-null value for name 'ConcurrencyBehavior' and namespace 'http://schemas.microsoft.com/xrm/7.1/Contracts'.
     at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, Type declaredType, DataContract& dataContract)
     at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserializeWithSurrogate(XmlReaderDelegator xmlReader, Type declaredType, DataContract surrogateDataContract, String name, String ns)
     at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
     at ReadKeyValuePairFromXml(XmlReaderDelegator , XmlObjectSerializerReadContext , XmlDictionaryString[] , XmlDictionaryString[] )
     at System.Runtime.Serialization.ClassDataContract.ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
     at System.Runtime.Serialization.XmlObjectSerializerReadContext.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
     at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, Type declaredType, DataContract& dataContract)
     at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserializeWithSurrogate(XmlReaderDelegator xmlReader, Type declaredType, DataContract surrogateDataContract, String name, String ns)
     at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
     at ReadParameterCollectionFromXml(XmlReaderDelegator , XmlObjectSerializerReadContext , XmlDictionaryString , XmlDictionaryString , CollectionDataContract )
     at System.Runtime.Serialization.CollectionDataContract.ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
     at System.Runtime.Serialization.XmlObjectSerializerReadContext.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
     at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, Type declaredType, DataContract& dataContract)
     at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserializeWithSurrogate(XmlReaderDelegator xmlReader, Type declaredType, DataContract surrogateDataContract, String name, String ns)
     at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
     at ReadPluginExecutionContextFromXml(XmlReaderDelegator , XmlObjectSerializerReadContext , XmlDictionaryString[] , XmlDictionaryString[] )
     at System.Runtime.Serialization.ClassDataContract.ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
     at System.Runtime.Serialization.XmlObjectSerializerReadContext.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
     at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, Type declaredType, DataContract& dataContract)
     at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserializeWithSurrogate(XmlReaderDelegator xmlReader, Type declaredType, DataContract surrogateDataContract, String name, String ns)
     at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
     at ReadPluginExecutionContextFromXml(XmlReaderDelegator , XmlObjectSerializerReadContext , XmlDictionaryString[] , XmlDictionaryString[] )
     at System.Runtime.Serialization.ClassDataContract.ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
     at System.Runtime.Serialization.XmlObjectSerializerReadContext.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
     at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, Type declaredType, DataContract& dataContract)
     at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserializeWithSurrogate(XmlReaderDelegator xmlReader, Type declaredType, DataContract surrogateDataContract, String name, String ns)
     at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, String name, String ns)
     at System.Runtime.Serialization.DataContractSerializer.InternalReadObject(XmlReaderDelegator xmlReader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
     at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
     at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName)
     at System.Runtime.Serialization.XmlObjectSerializer.ReadObject(XmlDictionaryReader reader)
     at System.Runtime.Serialization.XmlObjectSerializer.ReadObject(Stream stream)
     at PluginProfiler.Plugins.PartialTrustSerializer.Deserialize(Type type, Byte[] value, Assembly proxyTypesAssembly)
     at PluginProfiler.Plugins.PartialTrustSerializer.Deserialize(Type type, String value, Assembly proxyTypesAssembly)
     at PluginProfiler.Plugins.ServiceWrappers.ExecutionContextWrapper.Deserialize(OperationType operation, String serializedValue)


text:
Q: How to notify adapter of a specific view change instead of an entire ViewHolder change? I have the following code -
dashboardViewModel.getChatReadersForMessageId(it.messageId).observe(this@ConversationActivity, Observer { readersCount ->
   if (readersCount == groupMembers.size) {
       it.messageWasReadByAllMembers = true
       conversationAdapter.notifyItemChanged(messagesList.indexOf(it))
   }
})

The issue is that messageWasReadByAllMembers effects a single ImageView inside the viewholder, causing an unnecessary re-rendering of the entire VH rather then that single imageview
How do I re-render only specific elements?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Move Element Up the Y-axis When Mouse is Over an iframe Objective:

*

*Moving a div element up and down the Y-axis relative to the page (top window).

Issue:

*

*This functionality partially breaks when the element is set on top of an iframe. I can still move the element down the Y-axis but cannot move it up the Y-axis unless if the mouse is positioned outside of the iframe.

Please see this JSFiddel Example.
Steps to reproduce:

*

*Move the red box up and down the Y-axis.

*Remove the iframe and notice the red box can be moved swiftly along the Y-axis.

A: When over the iframe you're no longer in the parent document. If you want this to work you'll need to put a transparent overlay at the same size and position of the iframe, in the parent document.


text:
Q: Nest Learning thermostat API "OFF" mode When using the API to communicate with a Nest Learning Thermostat (in this case using the nest home assistant integration), when a request is made to change the nest thermostat to the "OFF" mode, I can see the mode show as "OFF" on the home.nest.com website, however the thermostat doesn't register it at all and just stays in whatever mode it was already in.  Curiously, when I select "OFF" on the home.nest.com site the OFF mode that's displayed on the site has a leaf icon under it, while when I do it via the API it does not.  When selecting it on the site the thermostat does switch to "OFF" with a leaf icon displayed under that on the thermostat as well.  It seems like the API is sending an "OFF" state that the home.nest.com site can see but that the thermostat itself just doesn't respond to at all for whatever reason.  It's like there are two different off commands here and only one of them (whatever the nest.home.com site is using) is working, and whatever the API is using is not.  Seems like a bug but I wasn't sure if I'm just doing something wrong here or what.  Just wanted to mention it here so that it will hopefully have some visibility from the devs.  Thanks.

A: If you see the leaf icon on the home.nest.com site, then the thermostat is in Eco, and the ThermostatMode.SetMode command doesn't work when the thermostat is in Eco: https://developers.google.com/nest/device-access/traits/device/thermostat-mode#setmode. You have to use the ThermostatEco trait instead.

A: API bug confirmed, seems to be fixed here: https://github.com/home-assistant/core/issues/60941


text:
Q: Vercel / Nextjs middleware request object is just a string I have a nextjs / vercel middleware that looks like this:
import { NextResponse, type NextRequest } from "next/server";

export function middleware(req: NextRequest) {
    console.log('test----> ', req)
  return NextResponse.next();
}

I expect this to log some info about the request,  but instead it just logs this string,
test---->  { sourcePage: '/src/middleware' }

what is going on here?


text:
Q: MDN example (of Math.random()): could it be parseInt() instead of Math.floor()? I was reading a JavaScript tutorial and searching for functions on MDN website when I stumbled across this example of Math.random():
function getRandomIntInclusive(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

While I understand that Math.floor chooses the biggest number and with that erases all numbers that have decimal values, I already learnt another function called parseInt() which just deletes all of the numbers after point. So, what's the difference between those two? Couldn't I just use
function getRandomInclusive(min, max) {
return parseInt(Math.random() * (max - min + 1)) + min;
}

instead?
I got idea while writing this question that Math.floor() might write 5 when it's 4,5 and parseInt() would write 4, but it's not really important for random number generator as I understand (if you know any examples of when it would be important, please tell me!) So, there's still not much of a difference in this case?

A: parseInt parses a string into an integer, reading only digits at the beginning of that string. It is not appropriate to use to round a number to an integer. The number will be converted to a string first, sometimes with unexpected results:
var num = 1000000000000000000000;
parseInt(num) // 1, because the string representation is 1e+21

I got idea while writing this question that Math.floor() might write 5 when it's 4,5 and parseInt() would write 4

You're thinking of rounding to the nearest whole number, which is what Math.round does. Math.floor always rounds down.

A: Here's an example where their behaviour differs drastically: negative numbers.
Math.floor(-2.5) -> -3
parseInt(-2.5) -> -2

The semantic difference pointed out in other answers, however, is probably more important. Even if it does work for your particular and specific use-case, it's best to pick the one with the correct semantics. (There are countless other ways to return a seemingly random integer from a function, you should pick the one that's the least likely to make your code hard to maintain.)

A: The clear difference is that Math.floor is a function that works on numbers while parseInt is a function that takes a string. You don't want to use the latter here as we deal with random numbers.
If you are unsure about the rounding mode, compare Math.floor, Math.round and Math.ceil.


text:
Q: Sharepoint 2013 Site Template with publishing feature and inherit master page I got a on-premise Sharepoint 2013 15.0.4569.1506 site collection with a custom master page. All the sites inherit master page, theme and CSS. They also inherit Navigation, which is a simple termset. All of this work very well if I create out of the box sites.
But... now we want to create over 300 documentation sites with some apps, enabled features and a customized default page. And I want to make this as a template. A simple request, but how?
As far as I can see custom master page don't work without Publishing feature, and the Publishing feature are not supported if you want to make a template of a site.
Anyone got a tip?
/Steinar

A: It is true that you need to deactivate the publishing feature to save site as template but if you are going to use the template using the code than after creating the site you can activate publishing feature programmatically.
You can get a reference from below mentioned code.
public class Feature1EventReceiver : SPFeatureReceiver
{
    public override void FeatureActivated(SPFeatureReceiverProperties properties)
    {
        SPSite siteCollection = properties.Feature.Parent as SPSite;
        if (siteCollection != null)
        {
            SPWeb topLevelSite = siteCollection.RootWeb;

            ActivateSharePointServerPublishingInfrastructureFeature(topLevelSite);
        }
    }

    private static void ActivateSharePointServerPublishingInfrastructureFeature(SPWeb topLevelSite)
    {
        // activating the Sharepoint Server publishing Infrastructure feature at the site collection
        string pubFeatureID = "F6924D36-2FA8-4f0b-B16D-06B7250180FA";
        Guid PublishingInfraFeatureID = new Guid(pubFeatureID);
        topLevelSite.Features.Add(PublishingInfraFeatureID, true, SPFeatureDefinitionScope.Site);
    }
}


text:
Q: How to access files outside /var/www/html I'm using wordpress+apache2 and deploy it myself. I have created a custom mechanism to sync wordpress to git so that on the server itself I have to have symlinks between the synced wp-content folder and /var/www/html.
For example, on my server:
wp-content -> /temp/storefront-cms/wp-content

And in turn:
/temp/storefront-cms -> ff2cbcaf328b17f100f9446b1a49acf3b2e85b0c

It all worked well, but we need to change the theme now and the new theme seems to be using WP customizer in a way that makes the site crash. This is an example from the logs:
[21/Feb/2023:12:14:09 +0000] "GET /temp/ff2cbcaf328b17f100f9446b1a49acf3b2e85b0c/wp-content/plugins/kirki/kirki-packages/module-webfonts/src/assets/scripts/vendor-typekit/webfontloader.js?ver=3.0.28 HTTP/1.1" 404 114258 "https://mydomain/wp-admin/options-general.php" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36"

I'm not good at PHP, so not sure how to proceed. I tried to just enable /temp access in apache, but it didn't help and I'm still getting 404:
<Directory /temp>
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

I understand that it fails because GET request should go to mydomain/wp-content... instead of calling full path(/temp...), but I can't figure out the easiest way to fix it. Whether it should be on apache level or WP or both.
UPDATE
In general I don't understand why some WP components try to call other components by their full path. Even if I remove the symlink and just use /var/www/html, it doesn't seem right that the calls are made to https://domain/var/www/html/..... I don't think that server folder structure should be exposed directly. That's the whole point of having a server, like apache, after all.
What I see in network traffic:


text:
Q: Setting AWS region programmatically for SQS I just started working on AWS SDK for Java and .net.
currently i am creating a AWS SQS Queue. I was able to Create a QUEUE, List the existing queues, and talk to the queues with .net SDK.
When i tried the same with the java i m getting following error.

Unable to find a region via the region provider chain. Must provide an
  explicit region in the builder or setup environment to supply a
  region.
   I have set all the necessary access keys, Region and credentials in the aws preferences in eclipse.

This is how i am initializing SQS client in a Java maven project
  AmazonSQS sqs = AmazonSQSClientBuilder.defaultClient();

I have googled and found that there is a key word called withregion() for S3 where i can specify the region but its not there for SQS.
I also tried setting region as
  sqs.setRegion(Region.AP_Mumbai);

This shows up following exception

The method setRegion(com.amazonaws.regions.Region) in the type
  AmazonSQS is not applicable for the arguments
  (com.amazonaws.services.s3.model.Region)

i tried setting the same using com.amazonaws.regions.Region but there is no provision as such.
Please Suggest

A: I setup the aws sqs client this way:
BasicAWSCredentials bAWSc = new BasicAWSCredentials(accessKey, secretKey);
return AmazonSQSClientBuilder.standard().withRegion(region).withCredentials(new AWSStaticCredentialsProvider(bAWSc)).build();

A: based on what @Francesco put, I created a more intuitive version
BasicAWSCredentials bAWSc = new BasicAWSCredentials(accessKey, secretKey);
final AmazonSQS sqs = AmazonSQSClientBuilder.standard()
        .withRegion(Regions.US_EAST_1)
        .withCredentials(new AWSStaticCredentialsProvider(bAWSc ))
        .build();


text:
Q: What's wrong with my wire connections? (LED strips only getting ~1 V) I'm trying to make an LED strip work, with these parts:

*

*A WS2812B LED strip (60 LEDs/m), 5V

*An Alitov 5V 15A power supply

*An Arduino Nano

My issue is that the strip isn't getting the 5v it requires. The arduino is just running simple code to show all white LEDs. See below pictures for my wiring:

As you can see, it's measuring around 1 volt across the 5v and GND terminals at the start of the strip. This seems... very wrong. When I rotate the barrel plug adapter, the LEDs flicker red a bit, and I've measured up to 1.6V in brief moments. I don't know if it's my barrel adapter, or the power supply, or even the way I'm inserting the wires into the barrel adapter? The weird part is this used to (mostly) work fine.
edit: as per comments, I measured the voltage on the barrel adapter and it's 5.19V so that seems fine. However, when the wires are inserted, it drops to ~1V. Here's how I'm putting the wires into the adapter:

I fold them back so there's no exposed wire hanging out of the adapter. I screw down the adapter's screws and it's plenty tight; the wires won't come out, but still not enough voltage. I've also tried un-folding the wires and sticking them in straight, same result.

A: You either have a bad connection, high resistance, or a short/faulty component. Or a bad power supply.
Replace the wires and or try with a different part. That's essentially the only troubleshooting. Longer explanation, check solder joints, make sure the wire is the right guage for the adapter or it won't  connect/squish down correctly.


text:
Q: Apps won't restore from backup I backed up my iPhone 5s, and when I try to restore my new iPhone 6s from that same backup, the apps won't transfer over. How do I fix this?

A: The same thing happened to me and my iPhone 5S yesterday when I tried to restore that backup onto my iPhone 6S. You just have to install all of the apps again from the App Store. They will function just as you left them, will all game saves and app data in place, as all your app data was restored, just not the apps themselves.


text:
Q: How to automatically run cocoa application after install via installer I have a built a cocoa application that I have packaged using package maker so that the app is installed using the installer.
After install is finished I want to run the installed application. In the package maker I can see postinstall actions, but I don't find an appropriate action to execute the application.
Any ideas what should I do ? my app is install in the /Applications/my.app
Should I write a script file of some sort or should the package maker help me run the app?
Thanks,
Ahmed

A: You need to add a postflight (assuming you want this for both installs and upgrades. If you just want it for installs, use postinstall).
Just call open "$3/Applications/my.app" to launch.
$3 is the install target. It's usually going to be /, but if you're being installed onto another volume, it could be something different like /Volumes/Other_Drive.


text:
Q: Opening index.html without running localserver in webpack dist folder I have created the output files/folder after webpack build. The index.html has been generated in dist folder with scripts and styles folder.
The configuration in package.json is as follow
"build": "rimraf dist && cross-env NODE_ENV=production webpack --colors",

But when I open index.html it is simply showing a blank page. It works only after running in local server. As I want to run it through electron desktop app, I want it to run as a standalone without starting any server.
UPDATE:
here is how I am opening the electron window


text: Q: Access denied while accessing _api/web/webinfos for a user with 'Full Control' permission to the Sharepoint Online site When a user with 'Full Control' access is trying to access a subsite using '_api/web/webinfos' the system is showing 'Access Denied'. Please note that the issue is existing for this user alone. Could any one please help me to resolve this issue.


text:
Q: How to initiate bias node in a restricted Boltzman machine I am new to Neural Networks and trying to implement RBM. I am stuck on initializing the visible layer's bias value. Is it supposed to initialize to some random number or there is some probabilistic distribution by which it should be initialized. In python I am seeing:
> "vbias = theano.shared(value =numpy.zeros(n_visible,
>                               dtype = theano.config.floatX), name='vbias') "

but don't know what is happening here in this line.

A: That line of code is initializing the visible biases to zero. In Hinton's RBM guide (available here) he recommends initializing the bias of the $i^{th}$ visible to
$$
b_i = \log\left(\frac{p_i}{1 - p_i}\right)
$$
where $p_i$ the proportion of training instances where the $i^{th}$ binary feature is 1. The reasoning behind this is if you were to then sample from the visible units using just the biases as input you would have that the probability that the $i^{th}$ unit is on is given by
$$
\begin{align*}
P(v_i = 1)
&= \frac{1}{1 + e^{-b_i}}\\
&= \frac{1}{1 + e^{-\log(p_i / (1 - p_i))}}\\
&= \frac{1}{1 + \frac{1 - p_i}{p_i}}\\
&= p_i.
\end{align*}
$$


text:
Q: ssl certificate installation - wp 8.1 SL I've installed ssl certificate (which I downloaded from a webbrowser) via email on the device. Unfortunately, after the installation I still can't open the page in IE without warning ('It looks like the security certificate wasn't issued by a trusted certificate authority...').
I have to install my custom certificate properly, because without it I can't provide https connection between my wp 8.1 silverlight app and my web service. I tried .p7b, .peb, .cer and .cert certificates.
Any suggestions?

A: Untrusted certificates only work for email inboxes, not for apps. Either use HTTP or a paid cert.


text:
Q: PHP extract specific DIV from target URL I'm using Simple HTML DOM to try and extract a div and all of it's contents from a target URL, here is my code:
<?php
  require 'simple_html_dom.php';
  $html = file_get_html('http://mozilla.org');
  foreach($html->find('.accordion') as $element)
      echo $element . '<br>';
?>

The problem I have is that the above code only extracts the plain text of the div. There are also images in the div that I need to extract. If I use this following code, then all images are extracted but so is everything else in the page.
<?php
  require 'simple_html_dom.php';
  $html = file_get_html('http://mozilla.org');
  echo $html;
?>

So my question is, how can I use the first bit of code to extract the contents + images from .accordion?
Thanks

A: You could always try;
$imgs = array();
foreach($html->find('.accordion',0)->find('img') as $img){
    $imgs[] = $img->src;
}

print_r($imgs);

This should populate the $imgs variable with all of the image links from the .accordion div.
:)


text:
Q: chartJS - How to customize x-axis scale / ticks I've recently been working on a project involving Chart.JS. I'm looking to scale the x-axis so that 50% width goes from values 0-100 while the other 50% width of the chart goes from 100 - 1000.
I'm using a horizontal stacked bar chart with 3 datasets. This can be seen here
What I'm trying to achieve is something like this here, except the 500 would be 100 and the 1000 would remain 1000. i.e. the graph wouldn't have a linear scale.
I'm attempting to do this as anything above around 150 is pretty much an outlier and I'm not worried about it going over 1000.
Here is my current config for the chart (I'm using react-chartjs and react)
I've react the documentation on chart.js and viewed some GitHub issue posts but can't find to find anyone with a similar problem. Maybe I'm misunderstanding one of the properties of the ticks object.
Anyway, thanks to everyone and anyone that replies! Will edit once I find a solution.
Chart Config Code Block
options= {{
    maintainAspectRatio: false,
    legend: {
        display: true,
    },
    scales: {
        xAxes: [{
            stacked: true,
            ticks: {
                min: 0,
                maxTicksLimit: 3
            }
        }],
        yAxes: [{
            stacked: true
        }]
    }
}}


text:
Q: Silverlight - Reflection - dynamic class - Inject code in the setter In Silverlight, I use a Dynamic class. I want to call boolean function before set property, for example :
Private _MyVar as Object
Public Property MyVar as Object
    Get
        return _MyVar
    End Get
    Set(value as Object)
        If IsUpdateProp(value,"MyVar") Then _myVar = value
    End Set
End Property

Private Function IsUpdateProp(value as Object, key as string) as Boolean
     If value Is Nothing AndAlso GetValueProperty(key) Is Nothing
                OrElse (value IsNot Nothing AndAlso
                   GetValueProperty(key) IsNot Nothing AndAlso
                          value.Equals(GetValueProperty(key))) Then
         Return False
     End If

     RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(key))
     Return True`
End Function

I want to make this with reflection, my code :
Dim dp As DynamicProperty = properties(i)
Dim fb As FieldBuilder = tb.DefineField("_" & dp.Name, dp.Type,
            FieldAttributes.Private)
Dim pb As PropertyBuilder = tb.DefineProperty(dp.Name,
             PropertyAttributes.HasDefault, dp.Type, Nothing)
Dim isModify = GetType(Dynamic.DynamicClass).GetMethod("SetModifyField",
                  New Type() {GetType(Object), GetType(String)})
Dim mbSet As MethodBuilder = tb.DefineMethod("set_" & dp.Name,
                    MethodAttributes.Public Or
                        MethodAttributes.SpecialName Or
                           MethodAttributes.HideBySig,
                                Nothing, New Type() {dp.Type})
Dim genSet As ILGenerator = mbSet.GetILGenerator()
Dim mLabel = genSet.DefineLabel

genSet.Emit(OpCodes.Nop)
genSet.Emit(OpCodes.Ldarg_0)
genSet.Emit(OpCodes.Ldarg_1)
genSet.Emit(OpCodes.Box, dp.Type)
genSet.Emit(OpCodes.Ldstr, dp.Name)
genSet.Emit(OpCodes.Call, isModify)
genSet.Emit(OpCodes.Call, GetType(Convert).GetMethod("ToBoolean",
                                    New   Type() {GetType(Object)}))
genSet.Emit(OpCodes.Stloc_0)
genSet.Emit(OpCodes.Ldloc_0)
genSet.Emit(OpCodes.Brfalse_S, mLabel)
genSet.Emit(OpCodes.Ldarg_0)
genSet.Emit(OpCodes.Ldarg_1)
genSet.Emit(OpCodes.Stfld, fb)
genSet.MarkLabel(mLabel)
genSet.Emit(OpCodes.Nop)
genSet.Emit(OpCodes.Nop)
genSet.Emit(OpCodes.Ret)

At runtime, when I call setvalue on my property I get this error message:

System.Security.VerificationException: Cette opération pourrait déstabiliser le runtime." & vbCrLf & "   à DynamicClass1.set_MyVar(Nullable`1 )

Thanks


text:
Q: Why does converting two images to black and white produce two different results? Im trying to do a small project on machine learning and in the process of doing so I have to convert a few images into black and white to classify the images. My problem is that the same method produces wildly different results with the same algorithm.
Here is the image before it is converted Image 1 and this is what it looks like after its been converted. Yeah that works fine looks okay.
This is the code that I used.
test_img=Image.open(str(idx) + '.png')
test_img=test_img.resize((100,100),Image.ANTIALIAS)
test_img.show()
test_img=test_img.convert('1')

Now I will ty to do the same with this image which produces this result. As you can see aster it is converted I have weird black spots all over the image.
This is the code that I used:
source_img=source_img.resize((100,100),Image.ANTIALIAS)
source_img=source_img.convert('1')
source_img.show()

Ive tried multiple methods to convert an image to black and white including the source_img.convert('L') method and with other methods I'm not able to flatten the image out into a 1D array.
Does anyone know why the conversion works for the first image but not the second?

A: The PIL method convert("1") converts to black and white using dithering, as the docs state:

The default method of converting a greyscale ("L") or "RGB" image into a bilevel (mode "1") image uses Floyd-Steinberg dither to approximate the original image luminosity levels.

Dithering replicates many colors with fewer by placing noise within the image to approximate the many colors. Check the Wikipedia article for dithering for more. For e.g., from that page, the following image is dithered---there's only black and white pixels, but the dithering makes it look grayscale somewhat. This is why your second image has some stippling---the color is not-quite-white, so it tries to approximate the gray with a few specks of black. Not particularly convincing there, though it is more impressive on other types of images:

If you want to binarize the image, the simplest way is to set a threshold, so that every pixel above that threshold is considered white, and everything below, black. As the docs for convert() state:

If dither is NONE, all non-zero values are set to 255 (white). To use other thresholds, use the point() method.

Which you can find the docs for here. If you want to use OpenCV, you can accomplish this through cv2.threshold(), docs here, tutorial here, and a related previous Stack Overflow answer I've given here.


text:
Q: how to call form_open Hello guys i have a problem with my code...
I can't call function form_open('administrator/login') from my view...
this is my view
<?php echo form_open('administrator/login'); ?>

Form Login

                     Username

                        <input type="text" name="username" />

                     Password

                        <input type="password" name="password" id="inputPassword" />

                         <button type="submit" class="btn">Sign in</button>

            <?php echo form_close(); ?>

A: i am guessing you have not loaded the form library.
autoload the form library
like this
go to this file
applications/config/autoload

look for the $autoload[helper] and replace that line with below one.
$autoload['helper'] = array('url', 'form');

OR use this in ur controller
$this->load->helper('form');

Hopefully this will solve your problem.

Edit:
I saw your Reply, and found your Problem as you have used the form in autoload function as well as you have loaded the form in controller function it self.
You only need to load the form only One Time, or it might will cause problem.
remove $this->load->helper('form') from your controller function as you have loaded the form through autoload already :)

A: this is my $autoload[helper]
$autoload['helper'] = array('url','text','form', 'file');
this is my controller administrator.php
    public function login(){
        $this->load->helper('form');
    $username =$this->input->post('username',TRUE);
    $password =$this->input->post('password',TRUE);
    $this->db->where('USERNAME', $username);
    $this->db->where('PASSWORD', md5($password));
    $query =$this->db->get('admin');

}
but it still can't call the function login from view..
404 Page Not Found
The page you requested was not found.
sorry if my english is bad :D


text:
Q: Will Lucene produce smaller files sizes if you index short one character Field names? Does Lucene produce smaller files sizes if you index short one character Field names?
For instance, will using "d" instead of "description" produce significantly smaller indexing files on disk?
Or does it map to shorter internal IDs anyway? :)

A: Field names are stored in the segment index. A segment is quite large. So as expected, using shorter field names would not save much on the file size.


text:
Q: How can i read cookies in rails that have been set by jquery I am setting a cookie in jquery like this(works fine and the cookie is generated):
$(document).ready(function() {
    var consp = $("input[home]").attr("home");
    $("input[name='commit']").click(function() {
        $.cookie('home', consp);
    });
});

In my controller i am trying to get hold of that cookies value. So i am using standard READing of cookies like this
def some_method
    @value = cookies[:home]
end

But when i output the value of @value, nothing is returned. This only happens if i set the cookie using jquery, however does not happen if i set the cookie directly through rails(no jquery). Any thoughts as to why this occurs? thanks

A: Ok, figured this one out:
I was creating this cookie when i was submitting a form and due to the mvc architecture, rails was submitting to a create action and the redirecting back to orginal page upon successfull redirect. So i needed this cookie to be valid across all pages so jquery.cookie plugin.
The solution was to pass the path parameter into the mix like this
$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });

This then allows the cookie to be read from all page routes.


text:
Q: Entity framework. Counting database hits When working with NHibernate I was able to count, in a test, how many times I hit the database which was great (guards from unintentional mistakes when rewriting queries).
Is it possible count/detect when a query is executed when using the Enitity Framerwork?
An example test would look like this:
int currentSqlCounter = EntityFrameWork.QueryCount();
MyMethodBeingTested();
Assert.AreEqual( 2, EntityFrameWork.QueryCount() - currentSqlCounter);

A: Support for logging in EntityFramework is quite weak and I don't know of any in-the-box solution for this.
I used the Tracing capabilities of the  EFProviderWrappers  http://code.msdn.microsoft.com/EFProviderWrappers to do something similar in a previous project.


text:
Q: Return specific array value in json format using php I want to display an output illustrated as json format but using PHP. I have an array for fruits and its color.
Array list
red = apple, strawberry
yellow = lemon, ripe mango
  <?php
  class FruitColor
  {
  private $fruitcolor;
  function FruitColor($fruitcolor)
  {
  $this->fruitcolor = $fruitcolor;
  }

  public function getFruits($color)
  {

  return NULL;
  }
  }

  $fruitcolor = new FruitColor(array(
"red" => array("apple", "strawberry"),
"yellow" => array("lemon", "ripe mango")
 ));

 echo $fruitcolor->getFruits("red");
 echo "\n";
 echo $fruitcolor->getFruits("violet");

 ?>

As you can see, this line echo $fruitcolor->getFruits("red"); represents red
Where the output should be like this

{ "color":"red", "fruits": ["apple", "strawberry"]}

and if there's no color like violet in the array, the output should be like this

{ "color":"violet", "fruits":[] }

This way of coding like json is new to me. I guess i should use IF ELSE statement on this problem? But I dont know how can I implement it.

A: You can use json encode to do that. First you have to check if there is any fruits or not.
$fruits = isset($this->fruitcolor[$color]) ? $this->fruitcolor[$color] : array();

it's a shorthand version of if else statement which will return the fruits list if exists otherwise an empty array. Then you can encode that result using json_encode.
class FruitColor
{
    private $fruitcolor;

    function __construct($fruitcolor)
    {
        $this->fruitcolor = $fruitcolor;
    }

    public function getFruits($color)
    {
        $fruits = isset($this->fruitcolor[$color]) ? $this->fruitcolor[$color] : array();
        return array('color' => $color, 'fruits' => $fruits);
    }

    public function getFruitsJSON($color){
        return json_encode($this->getFruits($color));
    }
}

$fruitcolor = new FruitColor(array(
    "red" => array("apple", "strawberry"),
    "yellow" => array("lemon", "ripe mango")
));

echo $fruitcolor->getFruitsJSON("red");
echo "\n";
echo $fruitcolor->getFruitsJSON("violet");

Here getFruits will return the data as php array and getFruitsJSON will return that array as JSON encoded string.
WARNING: using same classname to declare constructor is deprecated, use __construct instead.

A: I'm not sure if I understand you. Normally what you do is going through serializer that serialize an object(in your case FruitColor) to some representation ex. JSON. What you want to do is that a method returns a json string which breaks SRP for sure but just for education let me help you with that.
  class FruitColor
  {
     private $fruitColors;

     public function __construct(array $fruitColors)
     {
         $this->fruitColors = $fruitColors;
     }

     public function getFruits(string $color): string
     {
         return json_encode([
             'color' => $color,
             'fruits' => $this->fruitColors[$color] ?? []
         ]);
     }
  }

  $fruitcolor = new FruitColor([
    "red"    => ["apple", "strawberry"],
    "yellow" => ["lemon", "ripe mango"],
  ]);

 echo $fruitcolor->getFruits("red");
 echo "\n";
 echo $fruitcolor->getFruits("violet");

The other better approach would be not to use json_encode in getFruits but use it on an array that is returned by this method.

A: Something like so....
<?php

class FruitColor
{
    private $fruitcolor = array ( );

    public function __construct ( $fruitcolor )
    {
        $this->fruitcolor = $fruitcolor;
    }

    public function getFruits ( $color )
    {
        return json_encode ( array ( 'color' => $color, 'fruits' => array ( ( ! empty ( $this->fruitcolor[$color] ) ? $this->fruitcolor[$color] : '' ) ) ) );
    }
}

  $fruitcolor = new FruitColor ( array ( 'red' => array ( 'apple', 'strawberry' ), 'yellow' => array ( 'lemon', 'ripe mango' ) ) );

 echo $fruitcolor->getFruits ( 'red' ) . "\r\n";

 echo $fruitcolor->getFruits ( 'violet' ) . "\r\n";

 ?>


text:
Q: Tensorflow-gpu use only CPU I have Cuda 9.0 with its respective cuDNN.
I have installed tensorflow-gpu with pip, I use the object-detection_tutorial.py example and it plays the video and everything, but it uses only CPU and nothing of GPU, the video plays very slow.


text:
Q: Anyone know of any parallelizing compilers following the approach of the Dragon Book? In Compilers: Principles, Techniques, & Tools, Aho et al describe an approach for optimizing for parallelism (chapter 11 in the second edition). Is anyone aware of any existing compilers which follow that approach?

A: I don't have any first-hand experience with it, nor do I know whether the techniques used are in the Dragon Book to the letter, but the Sun Studio C and C++ compilers can do automatic parallellization of for loops.

A: I can't answer directly that question, regarding parallelism or concurrency, but, the Dragon Book was written some decades ago, with some updates, maybe, and Compiler Techniques have change a lot.
I have read some compilers docs, on the internet, and some of them use different ideas.
Besides, there are other books & (online) publications about compilers, that try to "kill the dragon", each one in a different way.


text:
Q: dotnet core multiple auth schemes: authentication handler is not being triggered Dotnet Core 3.1. I have two custom authentication schemes and handlers. When controller action has an [Authorize] attribute then both handlers get triggered. When there is no [Authorize] attribute then only the default scheme gets triggered. I cannot put Authorize attribute on the controller action, but still need to get claims set by the second Auth scheme. How can I ensure that not only the default auth handler is triggered?
Here is my simplified setup.cs:
    services
        .AddAuthentication("Auth1")
        .AddScheme<AuthenticationSchemeOptions, Auth1>("Auth1", null)
        .AddScheme<AuthenticationSchemeOptions, Auth2>("Auth2", null);

    services
        .AddAuthorization(options =>
        {
            options.DefaultPolicy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .AddAuthenticationSchemes("Auth1", "Auth2")
                .Build();
        });

Auth1 and Auth2 handlers are like this (also just for demo):
public class Auth1 : AuthenticationHandler<AuthenticationSchemeOptions>
{
    ....
    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        return Task.FromResult(AuthenticateResult.NoResult());
    }
}

public class Auth2 : AuthenticationHandler<AuthenticationSchemeOptions>
{
    ....
    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        return Task.FromResult(AuthenticateResult.NoResult());
    }
}

A: I took your code and reproduced that in ASP.NET Core 3.1. I think that you forgot to register authentication middleware, so it's only triggering in the case of authorization.
My reproduced app behaved the same way as you described, but as soon I added the line from below into the startup.cs, breakpoints in the default authentication scheme Auth1 started being caught while debugging.
app.UseAuthentication();

Remember, to place this before UseAuthorization and keep in mind that only Auth1 will be invoked since you set it as the default authentication scheme.


text:
Q: console returns an error when npm run deploy I have problems with deploy.
gh-pages -d build
git-upload-pack '.': git-upload-pack: command not found
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! vkappcodesford@1.0.0 deploy: gh-pages -d build
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the vkappcodesford@1.0.0 deploy script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\yokum\AppData\Roaming\npm-cache_logs\2020-11-18T19_29_30_578Z-debug.log
screenshot console

A: If such a problem arises, then it is easier to deploy it with Bash. This could solve the problem.


text:
Q: i have problem with android studio key store Key was created with errors:
Warning:
The JKS keystore uses a proprietary format.
It is recommended to migrate to PKCS12 which is an industry standard format
using "keytool -importkeystore -srckeystore
C:\Users\Development\mykeystove.keystore -destkeystore
C:\Users\Development\mykeystove.keystore -deststoretype pkcs12".


text:
Q: Read Concern Majority when majority nodes are down I have a 6 node replica set (all of them data bearing) with 5 voting members. If I lose 3 voting members, I will not have a majority voting members and my replica set will become read-only.
In this scenario, if the application has a read concern of "majority", will the reads fail? I have read that this majority read concern introduces a "cache pressure" but will the reads fail?? Or do I need to disable the RC by the below options for basic reads (with majority) to work?

--enableMajorityReadConcern command line option to false.

replication.enableMajorityReadConcern configuration file setting to
false.

A: Using a read concern of "majority" does not cause the read operation to be submitted to multiple nodes.
When replication.enableMajorityReadConcern is true (default in MongoDB 3.6+) each node will note the most recent write operation that has been acknowledged by a majority of the voting nodes, and keep a snapshot of the data at that point in time.
A request using "majority" read concern instructs the mongod to read from that snapshot instead of the most recent write.
In your scenario, reads will continue normally with 3 nodes down.
In addition to keeping the snapshot at the latest majority commit, each node must also accept writes.  Keeping track of the not-yet-majority writes in addition to the majority snapshot requires some additional usage of cache.  If a cluster gets into a state where there is a primary and is able to accept writes, but is unable to replicate those writes to a majority of the voting nodes, this cache usage can increase to the point of causing system instability.
That can only occur when there is a voting member that does not contain data, i.e. an arbiter.
Since your scenario does not contain an arbiter, that cluster should not have the RCM-induced cache pressure issue.


text:
Q: Docker container in EC2 is unable to write data into AWS S3 through AWS SDK I have a docker machine running on AWS EC2 instance. It suppose to upload data to S3 via SDK client.

*

*The docker machine is created in EC2 instance and using following command

--driver amazonec2 \
--amazonec2-open-port ${open-port} \
--amazonec2-region ${region} \
--amazonec2-access-key ${access-key} \
--amazonec2-secret-key ${secret-key} \
--amazonec2-instance-type ${instance_type} \
--amazonec2-ami ${this.ami} \
--amazonec2-security-group ${security_group_name} \
--swarm \
--swarm-discovery token://${swarm_join_token} \
--swarm-addr ${ip_address};

*I created IAM user with S3fullAccess and also allowed public access
S3 full access screen shot
public access screen shot

*The S3 bucket policy is

    "Version": "2012-10-17",
    "Id": "Policyxxx",
    "Statement": [
        {
            "Sid": "Stmtxxx",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::xxx"
            },
            "Action": "s3:*",
            "Resource": [
                "arn:aws:s3:::xxx",
                "arn:aws:s3:::xxx/*"
            ]
        }
    ]
}

It keeps showing error: AccessDenied: Access Denied. Can someone help me?

A: The access to S3 from the container running on EC2 instance is not dictated by your IAM user credentials. Instead you should setup IAM role/profile for the instance with S3 permissions, and then provide the role/profile name using option for your docker-machine:
--amazonec2-iam-instance-profile

The permissions of the instance will be available inside the container if you use AWS CLI or SDK.
Instead of bucket policy, its easier to add S3 permissions to the instance role.


text:
Q: How to change the Id of row dynamically in JQuery This is my simple HTML page. In this program when I press enter to create dynamic row, it creates a new row.
But the problem is that I want to change the id of every row like search1,search2,search3.
For checking this, I show id in alert, but only first row id show in alert box. When I inspect the page and check the id of second row, it changed the id.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link type="text/css" href="Bootstrap/bootstrap.css" rel="stylesheet"/>
        <title>JSP Page</title>

            No.
            Name
            Price

                1
                <input type="text" class="inputs searchName" name="pname_1" size="15" id="search1"/>
                <input type="text" class="inputs lst" size="15" />

This is the JQuery that are create dynamic rows:
 $(document).keypress(
    function(event){
     if (event.which == '13') {
        event.preventDefault();
      }
});

var i = $('table tr').length;
var count=0;
$(document).on('keyup', '.lst', function(e)
{
  var code = (e.keyCode ? e.keyCode : e.which);
  if (code == 13)
  {
    count = $('table tr').length;

    html = '
';
    html += ''+ i +'	';
    html += '<input type="text" class="inputs searchName"  size="15" name="pname_' + i + '" id="search'+i+'" />	';
    html += '<input type="text" class="inputs lst"  size="15" />	';

    html += '
';

    $('table').append(html);
    $(this).focus().select();
    i++;
  }
});

$(document).on('keydown', '.inputs', function(e) {
  var code = (e.keyCode ? e.keyCode : e.which);
  if (code==13) {
    var index = $('.inputs').index(this) + 1;
    $('.inputs').eq(index).focus();
  }
});

      $('.searchName').keyup(function()
      {
          var id=$(this).attr("id");
          alert(id);

      });

A: I think you need to use $(document).on instead of $('.searchName').keyup function
Try the following code
$(document).on('keyup', '.searchName', function() {
  var id=$(this).attr("id");
  alert(id);
});

Here is the working jsfiddle: https://jsfiddle.net/r9hpyabh/

A: Had to change some of your code, found many errors , but I think I have you squared away.
First you needed to define your html var so I added var html;
Second your html var was duplicating your previous html so you need to blank it out with each new $(document).on('keyup', '.lst', function(e) { so I added html = '';
Third you needed to change your $('.searchName').keyup(function() { to $(document).on('keyup', '.searchName', function() { to account for your dynamic content.
Remember that whenever you are dealing with dynamic content you need to use $(document).on('event', 'class or id', function() { to be able to capture that dynamic content.

var i = $('table tr').length;
var count = 0;
var html;
$(document).on('keyup', '.lst', function(e) {
  html = '';
  var code = (e.keyCode ? e.keyCode : e.which);
  if (code == 13) {
    count = $('table tr').length;

    html += '
';
    html += '' + i + '	';
    html += '<input type="text" class="inputs searchName"  size="15" name="pname_' + i + '" id="search' + i + '" />	';
    html += '<input type="text" class="inputs lst"  size="15" />	';

    html += '
';

    $('tbody').append(html);
    $(this).focus().select();
    i++;
  }
});

$(document).on('keydown', '.inputs', function(e) {
  var code = (e.keyCode ? e.keyCode : e.which);
  if (code == 13) {
    var index = $('.inputs').index(this) + 1;
    $('.inputs').eq(index).focus();
  }
});

$(document).on('keyup', '.searchName', function() {
  var id = $(this).attr("id");
  alert(id);

});

<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>JSP Page</title>

                  No.
                  Name
                  Price

                  1
                  <input type="text" class="inputs searchName" name="pname_1" size="15" id="search1" />
                  <input type="text" class="inputs lst" size="15" />

A: I think you should learn how jquery works.  It's all about selectors. The selector which is applied on the id  selects a zero or one element. The selector which is applied on the class selects more elements. You should read the FAQ: How do I select an item using class or ID?.
After reading this article I came to idea what is wrong with your code.


text:
Q: Publishing website get error with resharper and subversion I'm using Resharper with Visual Studio 2010 also with TortoiseSVN and AnkhSVN as VS Client
I've a website (ASP.net) and when i try to publish it publish fails with this error message
i googled it a lot, with no hope.
Error   236 The process cannot access the file 'D:\Development\Project\_ReSharper.DotShoppingCart\PersistentCaches\LOCK' because it is being used by another process.

A: You need to make sure the _ReSharper.* folder is excluded from the publish process. If you're using ReSharper 8 or 7.1, you can also specify that the ReSharper caches are stored in the user local settings folder, rather than the solution folder - see ReSharper -> Options -> General.


text:
Q: How to select an element within a jquery dialog let me start by qualifying that I am very new to jquery. I've been using it for a month or so now with moderate success. I'm hoping my question is easily answered.
Basically, I have a dialog on a page that contains content that is generated within a DWR Ajax call. What I want to do is define a couple of divs in my content such that when a header div is clicked, the second div tag referenced by the first needs to be hidden / shown via the jquery slideToggle function on the referenced div. Try though I might however, I am unable to get this method to be called.
Here is the javascript method I am calling, please note that for testing purposes I have omitted the dwr ajax call and am manually setting the html in the showdialog method.
The dialog opens fine and displays my content as expected. However clicking the div containing the expansion-header class does not toggle the view of the referenced 'ELEMENT_ONE' div.
Any thoughts or comments would be most appreciated. I am sure I am doing something silly, but for the life of me I can't work it out.
Javascript
function showdialog() {

var data = '
'
        + 'Click to Toggle Element One
'
        + '
'
        + 'This is element ones text it contains a
few lines of gibberish.

'
        + 'This is the second paragraph to be hidden when the header is clicked
';

  $("#StatusDialog").html(data);
  $("#StatusDialog").dialog("open");
}

$(document).ready(function() {

  $(".expansion-header").click(function () {
    var reference = $(this).attr('reference');
    $("#" + reference).slideToggle(400);
  });

  $("body").append('

');
  $("#StatusDialog").dialog({
    autoOpen: false,
    resizable: true,
    width: 750,
    modal: false
  });
});

HTML

Click Me

A: You have defined the click event for .expansion-header before it exists!
should attach the click event in showdialog()
or consider binding it using .live()

A: I believe that when you display a dialog the html you are seeing is actually part of the page you are viewing. So you should be able to browse elements in the DOM just like any other jquery selector. For example you should be able to say:
$('#ELEMENT_ONE').Html('
New Content
');

A: this here works

$(document).ready(function() {
$(".expansion-header").live( 'click', function () {
var reference = $(this).attr('reference');
$("#" + reference).slideToggle(400);

});
$('#status').click(function(){
var data = ''
              + 'Click to Toggle Element One'
              + ''
              + 'This is element ones text it contains afew lines of gibberish.'
              + 'This is the second paragraph to be hidden when the header is clicked';
$("#StatusDialog").html(data);
$("#StatusDialog").dialog("open");

});
$("body").append('');
    $("#StatusDialog").dialog({
      autoOpen: false,
      resizable: true,
      width: 750,
      modal: false
    });
  });


text:
Q: Why am I not getting an error when I use PHPUnit + Selenium Server? Why am I not getting an error when I use PHPUnit + Selenium Server to log in with an email and password that doesn't exists?
This is the PHPUnit script.
public function testUserNotExists() {
    $this->open('https://dev.example.com/login');
    $this->type("id=email", "1d0ntex1s7@live.com");
    $this->type("id=password", "1d0n73x1s7");
    $this->click("name=login_user");

}

When I run it, it doesn't show an error
Terminal: phpunit ExampleTest.php
PHPUnit 3.6.12 by Sebastian Bergmann.
E...
Time: 29 seconds, Memory: 4.75Mb
There was 1 error:
1) ExampleTest::testTitle
Method assertTitleEquals not defined.
FAILURES!
Tests: 4, Assertions: 1, Errors: 1.

A: You have to write assertions to get some failure. Selenium doesn't know what should (or shouldn't) happen after sending some form.


text:
Q: Cakephp fetch data from database without refreshing the page i am working on a Cakephp 2.x ....actually what i want is i am showing a battery level on my view page and memory usage too... so the battery and memory is keeps on changing after some seconds or minutes ... so i dont want user to refresh or reload the page evry time and checks the status of these two ... so i want to get the data from db in ajax or jquery and show them to the user ... i know the syntax of sending form data and then return in ajax ... but here i am not sending anything .. there are other things too on my page in which i need a data in ajax ... help me ... if anyone has implemented this before then please share it

A: In the controller do your logic and then return an ajaxResponse.
  class FooController extends AppController{
    public $components = array("RequestHandler");
    //... Other actions here

    public function getSysParams(){
         if($this->RequestHandler->isAjax()){
             //Your logic here, example:
             $sysInfo = $this->Foo->find('first', array('fields'=>array('battery', 'cpu'));
             //Return the data to AJAX call using json_encode
             return new CakeResponse(array('type' => 'application/json',
                'body' => json_encode(array('battery' => $sysInfo['Foo']['battery'], 'cpuUsage'=>$sysInfo['Foo']['cpu']),
                JSON_FORCE_OBJECT),
                'charset' => 'UTF-8')
             );

         }
     }
   }

And then in the js it will come like this:
{'battery':"33%", 'cpuUsage':"80%"}

I've tested it on CakePHP 2.3 and it works. On previous versions I'm not sure.

EDIT
This is the JavaScript part using jQUery:
       $.ajax({
         url: '/Foo/getSysParams'
         data: {'foo': 'bar'}, //Any data you want to send
         success: function(dataReturned){
             $("div#update").text(dataReturned.battery);
             $("div#update2").text(dataReturned.cpuUsage);
         }
       });


text:
Q: How long does HP provide extended support for servers? Specifically a DL380 G5 We have 8 DL380 G5s in service as ESXi hosts.  The servers are currently under support until June of 2014.  How long does HP offer care packs after a product has been released?  I looked through all the documentation I could find but couldn't find anything saying something like HP will no longer support the DL380 G5 after a certain date in the future.

A: To my knowledge, HP will offer support for very long periods. It'll get insanely expensive the longer it gets, and anything past a certain point will be subject to a special contract between you and HP.
Like many vendors, they do structure their extended support costs so that buying new is attractive after a certain point, but if you really need this DL380 G5 right here for 10 years, they can probably accommodate you.


text: Q: How to read batch submit job payload in job? aws_stepfunctions_tasks.BatchSubmitJob takes a payload parameter - Is it possible to access the values from that payload within the job? The use case is that the original code specified payload={"count.$": "$.count"} and container_overrides=aws_stepfunctions_tasks.BatchContainerOverrides(command=["--count", "Ref::count"]), which forces the $.count output of the previous job to be a string. Since I need to use the count for another value which must be an integer I would like to avoid forcing the data type onto the previous job. Is this possible?


text:
Q: "Airfoil" - why it is called "foil" What is origin of word airfoil (e.g. wings of the airplane)? Why it has part "foil", which is a very thin metal sheet.
"Dictionary.com Unabridged" says only "Origin: 1920–25; air 1 + foil 2" (© Random House), and "foil 2" is defined by them exactly as thin metal, e.g. aluminium foil (http://en.wikipedia.org/wiki/Foil_(metal)).

A: It comes from the notion of a foil as a leaf shaped curve formed by the cusping of an arch or circle.  (See also the definition of a foil as a blade for fencing.)
An Airfoil is a similarly leaf-shaped curve or blade that is used to push/cut the air.  Look at the cross sections of common airfoil shapes, and you will see the similarity to the shape of a leaf.
Foil is derived from the latin folium meaning leaf.
Incidentally (and not directly related to the rest of the answer), that is the same etymology of the term gold leaf to mean a thin gold foil (leaf = foil).


text:
Q: Create a list by importing a .txt file I have the following code:
myList = {"later", "test"}
aList = [];
tagCount = {}

f = ["This is a test", "Call me later"]

 for line in f:
 #Get a separate line
    fields = line.split(' ')
    for word in fields:
       if word in myList:
          print(word)

It basically checks whether word for word in an array whether one word corresponds to words in the taglist. It works fine. However I would like to replace the myList list now with value I get from .txt file. So there I do:
  with open('taglist.txt') as f:
     myList = [line.rstrip('\n') for line in f]
     myList = set(myList)

 aList = [];
 tagCount = {}

 f = ["This is a test", "Call me later"]

 for line in f:
 #Get a separate line
 fields = line.split(' ')
  for word in fields:
   if word in myList:
     print(word)

Now it does not seem to work however. I assume something goes wrong with importing the list. Any thoughts on what goes wrong here?

A: Your code worked for me once I re-indented it :
with open('taglist.txt') as tl:
  myList = [line.rstrip('\n') for line in tl]
  myList = set(myList)

aList = [];
tagCount = {}

f = ["This is a test", "Call me later"]

for line in f:
#Get a separate line
  fields = line.split(' ')
  for word in fields:
    if word in myList:
      print(word)

taglist.txt
later
test


text:
Q: NetCut Alternative For Mac OS X Any NetCut like app available for Mac OS X?
I wonder if there are available alternative out there to scan and cut all devices that in our LAN connection.
Thank you.

A: JamWiFi is an open source project that allows you limit user sessions on your WiFi network.

JamWiFi allows you to select one or more nearby wireless networks, thereupon presenting a list of clients which are currently active on the network(s). Furthermore, JamWiFi allows you to disconnect clients of your choosing for as long as you wish.


text:
Q: How to make space between every two pixels in a pbm file(ASCII mode) I have a test.pbm file in ASCII mode containing the code as follows:
P1
# Comment
9 9
000000000
011000000
011000000
011000000
011000000
011000010
011111110
011111110
000000000

I want to make a new file "newFile.pbm" which will contain space between every two pixels. Like as follows:
P1
# Comment
9 9
0 0 0 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0
0 1 1 0 0 0 0 1 0
0 1 1 1 1 1 1 1 0
0 1 1 1 1 1 1 1 0
0 0 0 0 0 0 0 0 0

I have tried to open the file "test.pbm" with the following code to do the work, but I have faced many problems, firstly, it shows  'IOError: cannot identify image file' when opening .pbm, secondly, can not make the space between every two pixels. Actually I am new in Python. My os Linux Mint 17.3 cinamon 32bit  and Python2.7.6. Plese help. The code I have tried given below:
fo=open("test.pbm",'r')
columnSize, rowSize=fo.size
x=fo.readlines()
fn = open("newfile.pbm","w")
for i in range(columnSize):
     for j in range(rowSize):
      fn.write(x[i][j])
fn.close()

A: You could do something like this:
with open("test.pbm", 'r') as f:
    image = f.readlines()

with open("newfile.pbm", "w") as f:
    f.writelines(image[:3])   # rewrite the header with no change
    for line in image[3:]:    # expand the remaining lines
        f.write(' '.join(line))


text:
Q: NodeJS(express) How would i finish this .js file and .ejs file to query the objectiD within my browser? All i want to achieve is querying an objectID from my mongoDB into my nodeJS then retrieving it in my local host via
http://localhost:3000/objectSearch?objectid=
Ive google everything and i just cannot figure it out. If someone would finish the example so i can see how it works, thanks ! :D
**objectSearch.js**
    var express = require('express');
    var router = express.Router();
    var mongodb = require('mongodb');
    var MongoClient = mongodb.MongoClient;
    var objectID = require('mongodb')
    var url = 'mongodb://localhost:27017/WishList';

    router.get("/", function (err, db) {
        if (err) {
            console.log("unable to connect to server", err);
        } else {
            console.log("Connect to server");
            var collection = db.collection('orders');
            var _id = req.query.id
            collection.findOne({_id: mongodb.ObjectID(_id)}, function (err, result) {
                if (err || !result) {
                    res.render('error', {error: "No records found with that id"});
                } else {
                    res.render(
                        'objectSearch',
                        {
                            objectSearch: result,
                            title: result
                        })
                }
            })
        }
    })

    module.exports = router;

ObjectSearch.ejs
<!DOCTYPE html>

    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />

<%= title %>

Welcome to <%=objectSearch.name.f %>

A: Your parameter on the url it's not id, but objectid, so your line of code should be:
req.query.objectid


text:
Q: Phonetic understanding of tongue twisters I like tongue twisters.
Five fine vine weevils
(plays with W, F and V)
Six sick stick insects
(plays with S, ST, KT, K and T)
Gran crams clams into clean clam cans
(plays with R and L and also with M and N)
How many more English sounds can be played with in a tongue tripping way ?


text:
Q: Сохранение созданных виджетов с введенными данными, после выполнения функции add_row, Перезапись результатов Помогите решить две задачи
1)Сохранение созданных виджетов с введенными данными, после выполнения функции add_row

*

*При запуске программы в первом окне при нажатии кнопки- Параметры, открывается окно для введения параметров необходимых для расчета

*В открывшимся 2ом окне, выбирается количество строк и нажимается кнопка Добавить

*Появляется выбранное количество строк, которые нужно заполнить данными, и нажать кнопку Применить

*Здесь пользователь может закрыть окно, а может и не закрыть

*Далее в первом окне нужно нажать кнопку Расчет

*Появится третье окно с результатами.

рисунок 1

рисунок 3

Вопрос: как заморозить 2е окно в таком виде с такими данными которые ввел пользователь, если окно было закрыто? И, если пользователь захочет добавить строки, чтобы не происходило автоматическое очищение тех строк которые уже введены, а при выборе меньшего количества строк оставалось нужное количество с введенными данными, остальные строки удалялись.
2)Перезапись результатов
Эта задача связана с предыдущей

*

*При запуске программы в первом окне при нажатии кнопки- Параметры, открывается окно для введения параметров необходимых для расчета

*В открывшимся 2ом окне, выбирается количество строк и нажимается кнопка Добавить

*Появляется выбранное количество строк, которые нужно заполнить данными, и нажать кнопку Применить

*Здесь пользователь может закрыть окно, а может и не закрыть

*Далее в первом окне нужно нажать кнопку Расчет

*Появится третье окно с результатами.

*На этом этапе если пользователь не закрыл 2е окно где вводятся параметры и 3е окно с расчетами, и решил поменять данные, то после нажатия кнопок применить и расчет, происходит следующее: открывается новое окно с расчетами (4тое) в котором дублируется предыдущий расчет.
рисунок 1

рисунок 2

Вопрос: как избежать открытия нового окна с расчетами? Как убрать повтор предыдущего расчета?
import math
import  tkinter as tk
from tkinter import Frame, Spinbox
from tkinter import ttk

class FW:
    M_=[]
    P_=[]
    W_=[]
    PR_=[]

    m_ent=[]
    p_ent=[]
    w_ent=[]
    pr_ent=[]

    def f_p(self):
        self.win_f = tk.Toplevel(win)

        self.form_count = Spinbox(self.win_f, from_=1, to=10,)
        self.form_count.grid(row=0, column=0)  # +++

        ttk.Button(self.win_f, text="Добавить", command=self.add_row).grid(row=0, column=1)
        ttk.Button(self.win_f, text="Применить", command=self.get_data).grid(row=10, column=1)

    def add_row(self):
        for i in range (int(self.form_count.get())):
            label = ttk.Label(self.win_f, text="{}".format(i+1))
            label.grid(row=i+1, column=0)

            m = ttk.Entry(self.win_f)
            m.grid(row=i+1, column=1)

            p = ttk.Entry(self.win_f)
            p.grid(row=i+1, column=2)

            w = ttk.Entry(self.win_f)
            w.grid(row=i+1, column=3)

            pr = ttk.Entry(self.win_f)
            pr.grid(row=i+1, column=4)

            self.m_ent.append(m)
            self.p_ent.append(p)
            self.w_ent.append(w)
            self.pr_ent.append(pr)

    def get_data(self):
        for a,b,c,d in zip(self.m_ent,self.p_ent,self.w_ent,self.pr_ent):
            md=float(a.get())
            pd=float(b.get())
            wd=float(c.get())
            prd=float(d.get())
            self.M_.append(md)
            self.P_.append(pd)
            self.W_.append(wd)
            self.PR_.append(prd)

class LP:
    def l_p(self):
        PZ=[7.0, 6.5, 6.0, 5.5]
        ppl = 5
        rsk = 12.2
        mu1 = 0.578
        g =9.80665
        plot1 = 792.8
        dNKT = 168
        t2=480

        self.QN_LP_1=[]
        for h,m,s,k in zip(FW.M_, FW.P_, FW.W_, FW.PR_):
            tm=[]
            tmn=1
            while tmn<=t2:
                tm.append(tmn)
                tmn=tmn+10
            qn_1=[]
            for e in PZ:
                qn1=[]
                for l in tm:
                    qnn_1=float((2*math.pi*6.12*10**-2*k*h*(e-(e-ppl)*(l/t2)-ppl))/(mu1*math.log((100*0.7583*l**0.3698)/rsk))-(((math.pi*10**3/(4*g))*dNKT**2)/plot1)*((e-ppl)/t2))
                    qn1.append(qnn_1)
                qn_1.append(qn1)

            qn_1=[[i for i in j if i>0] for j in qn_1]
            self.QN_LP_1.append(qn_1)
        print ('QN',self.QN_LP_1)

    def r_w(self):
        self.l_p()
        win_result = tk.Toplevel(win)
        win_result.wm_title('Результаты')

        frame1 = Frame(win_result , width=300, height=150)
        frame1.grid(row=1, column=0)

        table1=ttk.Treeview(frame1)
        table1['show']='headings'
        table1['columns']=list(range(0,len(self.QN_LP_1)))

        for i in range(0,len(self.QN_LP_1)):
            table1.column(i, width=100)
            table1.heading(i,text="QN {}".format(i+1))

        for i in zip(*self.QN_LP_1):
            for j in zip(*i):
                table1.insert('', 'end', values=j)
        table1.grid()

win=tk.Tk()
LP=LP()
ttk.Button(win, text='Расчет',command = LP.r_w).grid(row=17,column=1,stick='we')
FW=FW()
ttk.Button(win, text='Параметры',command = FW.f_p).grid(row=3,column=4, columnspan=3,stick='we')

win.mainloop()```

  [1]: https://i.stack.imgur.com/lSaXN.jpg
  [2]: https://i.stack.imgur.com/xjYna.png
  [3]: https://i.stack.imgur.com/7HJhH.jpg


text:
Q: Getting different response From an API when tried from POSTMAN and Swift I am trying hit an GET API with a Authorization header but getting different response:
From swift:
  {
        error = "access_denied";
        "error_description" = "OAuth2 authentication required";
    }

swift:
var urlString = "http://exaple.com/ser/2521"
            urlString = urlString.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)!
            let url = URL(string: urlString)
            let headers: HTTPHeaders = [
                "Authorization": "Bearer " + self.oAuthToken.access_token!
                , "Accept": "application/json"
            ]
Alamofire.request(url!, method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: headers) .responseJSON { (response) in
                switch response.result {
                case .success(let data):
                    guard let response =  data as? [String: Any] else {
                        return
                    }
                    print(response)
                case .failure(let error):
                    print(error.localizedDescription)

                }
            }

From POSTMAN:
Response is:
{
    "code": 400,
    "message": "Reservation failed."
}


text:
Q: EF Core Create database row if not exists So I'm hitting my webservice to save a row in the database if the id doesn't already exist.  So I do this in two steps.  First I run a select on the context to bring back the entity with the given id.  If that returns null, I create a new entity and call saveChanges.  This works perfectly almost always.  However, when there are multiple requests hitting the webserver at the same time, there is a chance that 2 requests could run at pretty much the same time.  When this happens, there is the chance that they both create a row.  This is actually happening.
How would you handle this situation?
p.s. I'm using EntityFramework Core.


text:
Q: What type of padding do I need to use in Android studio to center my buttons on the screen? I'm trying to adjust the home screen on my app to move the buttons slightly to the right.
Here's a link to an image version of my current home screen.

Here's what I want it to look like:

All the icons I uploaded have extra room on them to adjust for the padding.I made the icons on sketch and uploaded them as entire buttons.
Here's a screenshot of one of them:

I know I need to do something with padding, but what should I write to ensure that icons and text are shifted to the right.
Here's the activity in question:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
tools:context="com.example.leoconnelly.connexus.MainActivity">

<LinearLayout
    android:id="@+id/ll_learn"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_gravity="center_vertical"
    android:layout_weight="1">

    <ImageButton
        android:id="@+id/learn"
        android:layout_width="match_parent"
        android:scaleType="centerCrop"
        android:src="@mipmap/learn_layer_long"
        android:layout_height="match_parent"
        android:layout_gravity="center_vertical"
        android:padding="0dp"
        android:layout_weight="1"
        android:text="@string/learn"
        android:textSize="22sp"
       />

</LinearLayout>

<LinearLayout
    android:id="@+id/ll_find_care"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:layout_gravity="center_vertical">

    <ImageButton
        android:id="@+id/find_care_button"
        android:layout_width="match_parent"
        android:padding = "0dp"
        android:scaleType="centerCrop"
        android:src="@mipmap/findcare_layer_long"
        android:layout_height="match_parent"
        android:layout_gravity="center_vertical"
        android:layout_weight="1"
        android:text="@string/learn"
        android:textSize="22sp" />

</LinearLayout>

<LinearLayout
    android:id="@+id/ll_talk_to_doctor"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:layout_gravity="center_vertical">

    <ImageButton
        android:id="@+id/TalkToADocButton"

        android:layout_width="match_parent"
        android:scaleType="centerCrop"
        android:src="@mipmap/talk_doc_layer_long"
        android:layout_height="match_parent"
        android:layout_gravity="center_vertical"
        android:padding="0dp"
        android:layout_weight="1"
        android:textSize="22sp" />

</LinearLayout>

<LinearLayout
    android:id="@+id/ll_visit_website"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:layout_gravity="center_vertical">

    <ImageButton
        android:id="@+id/VisitWeb"
        android:layout_width="match_parent"
        android:scaleType="centerCrop"

        android:src="@mipmap/visit_web_layer_long"

        android:layout_height="match_parent"
        android:layout_gravity="center_vertical"
        android:padding="0dp"
        android:layout_weight="1"
        android:textSize="22sp" />

</LinearLayout>

A: Try it:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/ll_learn"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <ImageView
            android:src="@mipmap/findcare_layer_long"
            android:scaleType="centerCrop"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"/>

        <TextView
            android:text="@android:string/untitled"
            android:gravity="center"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:textSize="22sp" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/ll_find_care"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <ImageView
            android:src="@mipmap/findcare_layer_long"
            android:scaleType="centerCrop"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"/>

        <TextView
            android:text="@android:string/untitled"
            android:gravity="center"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:textSize="22sp" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/ll_talk_to_doctor"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <ImageView
            android:src="@mipmap/talk_doc_layer_long"
            android:scaleType="centerCrop"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"/>

        <TextView
            android:text="@android:string/untitled"
            android:gravity="center"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:textSize="22sp" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/ll_visit_website"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <ImageView
            android:src="@mipmap/visit_web_layer_long"
            android:scaleType="centerCrop"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"/>

        <TextView
            android:text="@android:string/untitled"
            android:gravity="center"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:textSize="22sp" />

    </LinearLayout>

</LinearLayout>

A: Set your padding within your parent layout. So if you want a padding for all of your 4 sides of "5dp", you will do the following:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:paddingBottom="5dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="5dp"
tools:context="com.example.leoconnelly.connexus.MainActivity">

A: Here I have customized your layout file.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<LinearLayout
    android:id="@+id/ll_learn"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_gravity="center_vertical"
    android:layout_weight="1"
    android:background="@android:color/holo_blue_light">

    <TextView
        android:id="@+id/learn"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center_vertical"
        android:layout_marginStart="20dp"
        android:layout_marginEnd="20dp"
        android:drawablePadding="30dp"
        android:drawableStart="@drawable/ic_ico"
        android:gravity="center_vertical|center_horizontal"
        android:scaleType="centerCrop"
        android:text="learn"
        android:textStyle="bold"
        android:textColor="@color/white"
        android:textSize="30sp" />

</LinearLayout>

<LinearLayout
    android:id="@+id/ll_find_care"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_gravity="center_vertical"
    android:layout_weight="1"
    android:background="@android:color/holo_green_dark">

    <TextView
        android:id="@+id/find_care"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center_vertical"
        android:layout_marginStart="20dp"
        android:layout_marginEnd="20dp"
        android:drawablePadding="30dp"
        android:drawableStart="@drawable/ic_ico"
        android:gravity="center_vertical|center_horizontal"
        android:scaleType="centerCrop"
        android:text="Find Care"
        android:textStyle="bold"
        android:textColor="@color/white"
        android:textSize="30sp" />

</LinearLayout>

<LinearLayout
    android:id="@+id/ll_talk_to_doctor"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_gravity="center_vertical"
    android:layout_weight="1"
    android:background="@android:color/holo_orange_dark">

    <TextView
        android:id="@+id/TalkToADocButton"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center_vertical"
        android:layout_marginStart="20dp"
        android:layout_marginEnd="20dp"
        android:drawablePadding="30dp"
        android:drawableStart="@drawable/ic_ico"
        android:gravity="center_vertical|center_horizontal"
        android:scaleType="centerCrop"
        android:text="Emergency"
        android:textStyle="bold"
        android:textColor="@color/white"
        android:textSize="30sp" />

</LinearLayout>

<LinearLayout
    android:id="@+id/ll_visit_website"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_gravity="center_vertical"
    android:layout_weight="1"
    android:background="@android:color/holo_red_dark">

    <TextView
        android:id="@+id/VisitWeb"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center_vertical"
        android:layout_marginStart="20dp"
        android:layout_marginEnd="20dp"
        android:drawablePadding="30dp"
        android:drawableStart="@drawable/ic_ico"
        android:gravity="center_vertical|center_horizontal"
        android:scaleType="centerCrop"
        android:text="Message to a Doctor"
        android:textStyle="bold"
        android:textColor="@color/white"
        android:textSize="30sp" />

</LinearLayout>

Note: Change colors and icons as per your requirements. Because here I have used sample image and colors for testing purpose.
Output:


text:
Q: T-SQL: How can you create a table with SELECT? In oracle, you can issue:
 create table foo as select * from bar;

What is the equivalent T-SQL statement?

A: If you want to write to the tempdb
Select *
INTO #tmp
From bar

or to a SQL DB
Select *
INTO Temp
From bar

A: You can use SELECT INTO. From MSDN:

The SELECT INTO statement creates a new table and populates it with
  the result set of the SELECT statement. SELECT INTO can be used to
  combine data from several tables or views into one table. It can also
  be used to create a new table that contains data selected from a
  linked server.

So:
SELECT col1, col2, col3 INTO newTable FROM existingTable;

A: You can try like this:
select * into foo from bar


text:
Q: C# UseVisualStyleBackColor Is there a way in which I can change the button color and preserve the Windows VisualStyle? I want to create a button that looks like checkBox2 (color and style)

this.button2.BackColor = System.Drawing.SystemColors.GradientActiveCaption;
this.button2.UseVisualStyleBackColor = false;  //if true, BackColor gets ignored

A: No, not really.  This kind of button background is drawn by VisualStyleRenderer.DrawBackground().  Which in turns pinvokes DrawThemeBackground().  These methods don't take a color.  None is needed because the color is already specified in the theme.
Simulating the appearance with a LinearGradientBrush is your only real hope.  Note that custom drawing a button is quite difficult, all the code is internal and no owner-draw is provided.
Consider using an image.


text:
Q: Conditional transitive dependencies inclusion with maven My goal is to include one project into another while controlling the transitive dependencies that should be included.
Let's say that Project Y is based upon Project X.
Project X has two defined profiles, profile-a and profile-b:
<project>
  ...
  <profiles>
    <profile>
      <id>profile-a</id>
      <dependencies>
          // [A] depednencies
      </dependencies>
    </profile>
    <profile>
      <id>profile-b</id>
      <dependencies>
          // [B] depednencies
      </dependencies>
    </profile>
  <profiles>
</project>

Is there a way to include project X into project Y with the possibility of specifying the profile with which we want to import project X?
A sample way to control transitive dependencies should be the use of dependencies exclusion, but I'm looking for a more sophisticated method if ever it is possible to use one.

I have a second question that concerns the use of dependencies in profiles:
Naturally, project X may have many classes that depend on both dependencies of profile-a and profile-b.
If project X is built or imported (if ever it is possible) with one profile, this won't break the compilation of classes that use the dependencies of the other profile?
Thank you all for your feedback.

A: After my discussion with @khmarbaise I made an additional search in maven website, and I stumbled upon this article.
In this page, there is a paragraph that concerns Producing Multiple Unique JARs from a Single Source Directory, where it is specified:

As many people that complain about not being able to spread out their
  sources into multiple source directories seem to complain about not
  wanting to spread anything out, producing several unique artifacts
  from a single directory using includes and excludes.
Why isn't this recommended?
This practice can be confusing and risky.
You may end up building two JARs that include the same classes - this
  indicates that the common functionality should have been abstracted
  into a separate dependency. You may end up introducing a dependency
  between the two JARs that you didn't realise, and often a circular
  dependency. This indicates that the classes are in the wrong JAR, or
  perhaps that everything should just be a single JAR.
How do I do this?
You still should adhere to producing one artifact per POM, but this
  requires having multiple POMs, and hence multiple subdirectories. The
  positive to this is that these introduced directories won't change the
  layout of existing code, and will establish a future layout should you
  decide to separate.

At first, I was looking for a way to manage transitive dependencies from a project to another by creating many artifacts from the same source.
After this reading, it is clear that maven encourages the creation of one artifact per pom.
Creating separate modules of the project surely remains the most clean way to handle different cases of dependencies usage from one project to another.


text:
Q: Excel VBA extension DLL "Wrong number of agruments or invalid property assignment" I wrote an extension dll in C# which I'm calling in the VBA code.
Since the code in the DLL is somewhat more complex I decided to split the functionality into some classes.
This means that the Main entrypoint to my DLL is still the Main method but in there I can call the different other classes and methods.
All of this worked fine until today.
I changed the signature of one method a bit because I need one more variable coming from Excel VBA and suddenly I could not call the method anymore and its throwing me the following exception:

Wrong number of arguments or invalid property assignment

The code in VBA from which I call the DLL is as follows (the variable orig_value is the one I added)
Public Sub Worksheet_Change(ByVal Target As Range)
    If TlbMain Is Nothing Then
        Set TlbMain = New EstimationTypeLibrary.Main
    End If

    Call TlbMain.EstimationSheetChanged(ActiveWorkbook, Target, orig_value)
End Sub

The code in the C# DLL which I call from VBA is as follows (the variable originalValue is the one I added)
public void EstimationSheetChanged(Workbook activeWorkbook, Range range, string originalValue)
{
    PublicEstimationSheetProperties.OriginalValue = originalValue;
    EstimationOnChange.EstimationSheetChanged(activeWorkbook, range);
}


text:
Q: Python, tuple indices must be integers, not tuple? So, I'm not entirely sure what's going on here, but for whatever reason Python is throwing this at me. For reference, it's part of a small neural network I'm building for fun, but it uses a lot of np.array and such, so there's a lot of matrices being thrown around, so I think it's creating some sort of data type clash. Maybe somebody can help me figure this out, because I've been staring at this error for too long without being able to fix it.
#cross-entropy error
#y is a vector of size N and output is an Nx3 array
def CalculateError(self, output, y):

    #calculate total error against the vector y for the neurons where output = 1 (the rest are 0)
    totalError = 0
    for i in range(0,len(y)):
       totalError += -np.log(output[i, int(y[i])]) #error is thrown here

    #now account for regularizer
    totalError+=(self.regLambda/self.inputDim) * (np.sum(np.square(self.W1))+np.sum(np.square(self.W2)))

    error=totalError/len(y) #divide ny N
    return error

EDIT: Here's the function that returns the output so you know where that came from. y is a vector of length 150 that is taken directly from a text document. at each index of y it contains an index either 1,2, or 3:
#forward propogation algorithm takes a matrix "X" of size 150 x 3
def ForProp(self, X):
        #signal vector for hidden layer
        #tanh activation function
        S1 = X.dot(self.W1) + self.b1
        Z1 = np.tanh(S1)

        #vector for the final output layer
        S2 = Z1.dot(self.W2)+ self.b2
        #softmax for output layer activation
        expScores = np.exp(S2)
        output = expScores/(np.sum(expScores, axis=1, keepdims=True))
        return output,Z1

A: Your output variable is not a N x 4 matrix, at least not in python types sense. It is a tuple, which can only be indexed by a single number, and you try to index by tuple (2 numbers with coma in between), which works only for numpy matrices. Print your output, figure out if the problem is just a type (then just convert to np.array) or if you are passing something completely different (then fix whatever is producing output).
Example of what is happening:
import numpy as np
output = ((1,2,3,5), (1,2,1,1))

print output[1, 2] # your error
print output[(1, 2)] # your error as well - these are equivalent calls

print output[1][2] # ok
print np.array(output)[1, 2] # ok
print np.array(output)[(1, 2)] # ok
print np.array(output)[1][2] # ok


text:
Q: VBA: How to get page to update after filling in the select box I'm trying to use the full matchup table on this page https://stats.nba.com/player/2544/head-to-head/?Season=2018-19&SeasonType=Regular%20Season
So far this is what I have:
Option Explicit
Sub BrowsetoSite()

Dim IE As Object

Set IE = CreateObject("InternetExplorer.Application")

IE.Visible = True
IE.navigate "https://stats.nba.com/player/2544/head-to-head/?Season=2018-19&SeasonType=Regular%20Season"

Do While IE.ReadyState <> READYSTATE_COMPLETE
Loop

IE.Document.getElementsByClassName("stats-table-pagination__select")(0).Value = "string:All"
On Error Resume Next
IE.Document.getElementsByClassName("stats-table-pagination__select")(0).Focus.FireEvent ("onchange")

End Sub

That fills in the page selection as "All", but the page does not upload like it does if you were to click that option on the website. How do I fix this?
Here is the HTML code for the selection:
<select class="stats-table-pagination__select ng-valid ng-not-empty ng-touched ng-dirty ng-valid-parse" ng-model="vm.data.page" ng-options="p for p in vm.data.pages" aria-invalid="false">
<option label="All" value="string:All">All</option>
<option label="1" value="number:1" selected="selected">1</option>
<option label="2" value="number:2">2</option>
<option label="3" value="number:3">3</option>
<option label="4" value="number:4">4</option>
<option label="5" value="number:5">5</option>
<option label="6" value="number:6">6</option>
<option label="7" value="number:7">7</option>
</select>

A: You can use the following code. FireEvent don't work for the most of the modern pages. You must use dispatchEvent and you can only dispatch an event, if you set it before and initialize it via initEvent. For that I use the private sub TriggerEvent() below.
Please read the comments for more information.
Code in the head of the macro:
Option Explicit

'With the following Windows api function we can do breaks less than 1 second
'It works with Excel 32 bit and Excel 64 bit
#If Win64 Then
  'For 64 bit systems
  Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr)
#Else
  'For 32 bit systems
  Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#End If

The main macro:
Sub OpenAllPages()

Dim url As String
Dim browser As Object
Dim nodeDropdown As Object

  url = "https://stats.nba.com/player/2544/head-to-head/?Season=2018-19&SeasonType=Regular%20Season"

  'Initialize Internet Explorer, set visibility,
  'call URL and wait until page is fully loaded
  Set browser = CreateObject("internetexplorer.application")
  browser.Visible = True
  browser.navigate url
  Do Until browser.ReadyState = 4: DoEvents: Loop
  'Wait a little bit to load the table into the page from server
  '(I have scheduled the break conservatively. You can try fewer seconds)
  Sleep (5000)

  'You must save the DOM objekt of the dropdown to an object
  'variable to be able to trigger the change event later
  Set nodeDropdown = browser.document.getElementsByClassName("stats-table-pagination__select")(0)
  'Set the value to the object variable
  nodeDropdown.Value = "string:All"
  'Trigger the change event
  Call TriggerEvent(browser.document, nodeDropdown, "change")
  'Wait a little bit to open the table with all results
  Sleep (500)

  'Do here something you want with the whole table of results
End Sub

The macro to trigger an html event:
Private Sub TriggerEvent(htmlDocument As Object, htmlElementWithEvent As Object, eventType As String)

  Dim theEvent As Object

  htmlElementWithEvent.Focus
  Set theEvent = htmlDocument.createEvent("HTMLEvents")
  theEvent.initEvent eventType, True, False
  htmlElementWithEvent.dispatchEvent theEvent
End Sub