text:
Q: gRPC based microservice architecture for inter-service communication I am trying to comprehend how does the inter-service communication works when implementing these services using gRPC. While there are lot of articles out there covering the basics about getting started with gRPC and how it can be compiled to multiple different languages. I am still kind of missing some guidelines on how best should each service in microservice architecture communicate.
My general understanding, after following through something like this : https://www.oreilly.com/library/view/practical-grpc/9781939902580/
That if I need to use gRPC in microservice architecture where inter-service communication will be gRPC based each service will essentially (and as needed) should do server and client stub implementation to talk to other services.
So for me it would look something like this

And if above is the case, then getting each of these services deployed in K8s environment seems like quite some effort esp. with making each service discoverable in the entire cluster.
Some additional notes
I am developing with Go primarily and using protobuf for defining proto files.
It'll be greatly helpful if someone could comment on this or has a resource that I can go through to better my understanding.
Thanks!

A: Your understanding is correct. If you want to have separate services that talk to each other remotely in kubernetes, you will have to deploy them (helm could help here) and you have to create services for cluster discovery.


text:
Q: What does this probability exercise imply? i've been studying probability from George C. Canavos' Applied Probability and Statistical Methods, preparing for the course i'll start next month. I've reached an exercise from the third chapter(random variables and probability distributions) that i can't comprehend what does it want me to do. It's the next one:
3.8. An insurance company must determine the annual fee to collect from a $50 thousands insurance for men between the age of 30 and 35 years. According to research, the annual number of deaths of this age group is 5 per each 1000 men. If X is the random variable representing the company's profits, determine the amount of the annual fee so the company won't suffer losses, even though the great number of said insurances.
I must say i'm at a loss here, the entire chapter and the other exercises didn't represent as much of a struggle as this one. I understand it's fairly easily solved so i wouldn't really be seeking its actual solution rather than the right way it must be interpreted. Thanks beforehand for anyone who can help me.

A: You are told that, out of a 1000 people, on average, 5 will die within the year.  Your company will have to pay out \$50,000*5= \$250,000.  Your company will need to charge each of the 1000 people \$250,000/1000=\$250 per year to cover that.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do i do Flex Grid in bootstrap So I have a little problem with grid system. I want to make grid like McDonalds site did.
So if I zoom out on this site, the grid is not changing! I mean the height and widht is the same, just the content is changing. I don't know how to do it. Please for help
McDonald site http://mcdonalds.pl/
My example:

A: I am not sure if that is exactly what you are looking for, but I gave it a shot
Run the snipped below, activate "Full Page" and zoom in and out:

html, body {
  height: 100%;
}

.cover-img {
  color: gray;
  font-weight: bold;
  width: 100%;
  height: 100%;
  background: url("https://s-media-cache-ak0.pinimg.com/originals/82/64/7e/82647eca04687361c6d515f335d4c08a.jpg") no-repeat center center fixed;
  background-size: cover;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        Toggle navigation

      </button>
      Brand

Link1

Link2

Link3

Some content here

Hope it helps

A: Here is another try. You can use vieport hight and width in your CSS (i.e. height: 50vh):
It is not a perfect example:

html, body {
  height: 100%;
}

.cover-img {
  color: gray;
  font-weight: bold;
  width: 100%;
  height: 100%;
  background: url("https://s-media-cache-ak0.pinimg.com/originals/82/64/7e/82647eca04687361c6d515f335d4c08a.jpg") no-repeat center center fixed;
  background-size: cover;
}

.some-box {
  display: flex;
  margin-top: 75px;
  height: 50vh;
  line-height: 10vh;
  font-size: 6vh;
  background: rgba(255,255,255,0.2);
}

.col-xs-6 {
  width: 38vw !important;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        Toggle navigation

      </button>
      Brand

Link1

Link2

Link3

        Stay the same size

        Stay the same size

NOTE: Viewport works like percentages
A little closer on what you want?


text:
Q: including html tag in state of vuex I have some data that includes html tags in the state of vuex, but I want the html tags can be parsed as normal html tags, not to escape them. How can I achieve this task.
For example,
export default {
  state: {
    someHtml: 'This is a a tag.'
  }
}

this.$store.state.someHtml can be displayed as a html link.

A: If you want to display unescapted HTML using Vue, use the v-html directive like so :


text:
Q: Renaming XML nodes using E4X in AS3 I have an XML object in AS3 that is formatted as follows:
<data>
  <nodes>
    <item></item>
    <item></item>
    ...
  </nodes>
  <nodes>
    <item></item>
    <item></item>
    ...
  </nodes>
  ...
</data>

My problem is I want to rename the node names("nodes" and "item") to something more relevant e.g. "nodes" could be "author", and "item" could be "book".
So what would be the best way to do this with E4X in AS3?

A: you can use the setName() method of XML Object in AS3.
example:
   //extract all nodes named "nodes"

    var l:XMLList=data..nodes;
    for each(var n:XML in l){
       n.setName("new_node_name");
    }

    //extract all nodes named "item"

    var l2:XMLList=data..item;
    for each(var n2:XML in l2){
       n2.setName("new_item_name");
    }

A: As far as I know there is no way to do this natively within ActionScript, however here is a simple function that will accomplish just that. First I am converting it to a string, then using a simple regular expression to find and replace all instances.
function replaceAll(findTag:String, replaceWith:String, source:XML):XML
    {
        var xmls:String = source.toXMLString();
        var findPattern:RegExp = new RegExp(findTag, "g");
        xmls = xmls.replace(findPattern, replaceWith);
        return new XML(xmls);
    }

Hope it helps.


text:
Q: Calculated column increase date column by one day I want to create acalculated column that takes a date field and sets the value to the date, increased by one day. How can this be done?
For ex:
If date field value: 20/10/2015
calculated result will be: 21/10/2015
Suggest some formula to use.

A: Date columns are essentially numbers starting at 30/12/1899
So besides adding one day, you have to display it as a date again (when using it in a Calculated Column datatype=Text)
=TEXT( [Due Date]+1 , "dd/mm/yyyy" )

Or set the datatype of the Calculated Column to Date
=[Due Date]+1

Adding one day correctly counts the new date
=TEXT(DATE(2015,12,31+1),"dd/mm/yyyy")

outputs january 1st 2016
More Date functions: https://www.365csi.nl/vm365com/365coach/#/Calculated_Column_Functions_List


text:
Q: How to use a regex without raising a RuboCop warning This is a regex pattern:
(@location =~ /\A#[a-zA-Z0-9]*\Z/) == 0

RuboCop suggests to use .zero? instead of  == 0. But when the regex does not match, it will return nil. Then nil.zero? will throw an "undefined method .zero? for nil" error. Any better way to do regex in ruby?

A: Not every tip from rubocop is a good tip.
In Ruby 2.4 :
@location.match? /\A#[a-zA-Z0-9]*\Z/

By the way, do you want /\Z/ (a line ending at the end of the string) or /\z/ (end of the string)?

A: Assuming you run ruby 2.3.0+:
(@location =~ /\A#[a-zA-Z0-9]*\Z/)&.zero?

Also as per your specific case, you seem to want to check that you have an exact match. Hence you don't need to check that the starting position is exactly 0 at all:
do_something if @location =~ /\A#[a-zA-Z0-9]*\Z/

A: You are trying to solve a problem that does not exist. Because of anchor \A there are exactly two possible returns: 0 and nil. That said:
!(@location =~ /\A#[a-zA-Z0-9]*\Z/).nil?

or even
!!(@location =~ /\A#[a-zA-Z0-9]*\Z/)

or even better:
@location[/\A#[a-zA-Z0-9]*\Z/]

A: This is a known false positive that happens because #=~ does not adhere to the principle of duck typing, i.e. it has incompatible return value signatures.
There are some good answers already regarding how you can rewrite your code, and this is really what RuboCop is all about, but sometimes rewriting will result in code that is worse. For those cases, the generic way of marking false positives is to use a disable:
(@location =~ /\A#[a-zA-Z0-9]*\Z/) == 0 # rubocop:disable Style/NumericPredicate

A: I'd propose the following solution:
/\A#[a-zA-Z0-9]*\Z/.match?(@location)
This will safeguard the case when @location is nil and will make rubocop happy.


text:
Q: If a standard or VF page action causes a trigger to fire, does the trigger execute in the system context? Assuming that the trigger only instantiates classes that are marked as without sharing does that trigger fire in the system context for:

*

*A standard object page

*A VF page with a controller or extension marked as with sharing

A: The trigger runs in system context for both cases, the with sharing only impacts record visibility, i.e. FLS etc will be ignored in both cases

If a class is not declared as either with or without sharing, the
  current sharing rules remain in effect. This means that if the class
  is called by a class that has sharing enforced, then sharing is
  enforced for the called class.

I believe StandardController references are still an exception and still operate in user mode
so stdController.save() in a without sharing controller extension would still error, if the user did not having Edit access on the record.


text:
Q: jQuery remove all list items from an unordered list I forgot the jQuery command that will clear all list elements from a list. I did a bit of searching, done it a bunch of times before, but just simply forgot the command.
$("ul").clear()
$("ul").empty()

both didn't seem to accomplish this.. which command is it again?
UPDATE:
Thanks guys, I must have some syntax error on my selector.

A: If you have multiple ul and want to empty specific ul then use id eg:

1

2

3

$('input').click(function() {
  $('#randomName').empty()
})

1

2

3

4

5

<input type="button" value="click me" />

A: $("ul").empty() works fine. Is there some other error?

$('input').click(function() {
  $('ul').empty()
});

test

test

<input type="button" value="click me" />

http://jsfiddle.net/infernalbadger/D5ss8/

A: $("ul").empty() should work and clear the childrens.
you can see it here:
http://jsfiddle.net/ZKFA5/

A:    var ul = document.getElementById("yourElementId");

     while (ul.firstChild)
         ul.removeChild(ul.firstChild);

A: As noted by others, $('ul').empty() works fine, as does:
$('ul li').remove();

JS Fiddle demo.

A: This should work:
$("ul").html('')

A: Look your class or id. Perhaps Like This
$("#resi_result").html(''); This should work:

A: An example using .remove():

Remove LI's from list

Test

Test

Test

Test

Test

END

setTimeout(function(){$('ul li').remove();},1000);

http://jsfiddle.net/userdude/ZAd2Y/
Also, .empty() should have worked.

A: this worked for me with minimal code
$(my_list).remove('li');


text:
Q: Django save in two models with onetoone filed I m beginner in Django and I have a problem and i can t resolve it
I want to save address to every person in a different model
I tried in this way but doesn t work
Sorry for my english
models.py
class Person(models.Model):
user - models.OneToOneField(User, on_delete=models.CASCADE)
name =  models.CharField(max_length=50)
email = models.EmailField("E-mail", max_length=50, blank=True)
address = models.OneToOneField(AddressPerson, on_delete=models.CASCADE)

class AddressPerson(models.Model)
domicile = models.CharField(max_length=100)
county = models.ForeignKey(County, on_delete=models.PROTECT)
locality = models.ForeignKey(Locality, on_delete=models.PROTECT)

views.py
def add_person(request):
address = AddressForm(request.POST or None)
person = PersonForm(request.POST or None)
if address.is_valid() and person.is_valid():
address.save()
person.save()
return redirect('myapp:add_person'
else:
address = AddressForm()
person = PersonForm()
context = {
'form_p': pacient,
'form_a': adresa
}
return render(request, 'person/add.html',context)


text:
Q: Using the if statement in a loop to create a class in a data.set in R I have seen several questions that are similar to mine, but none of those answers is helping me get this code straight.
I want to classify a data set according to a set of a statement using if() statement, making a loop so it can be applied to the whole dataset. Here is my code:
x100 <- c(100,100,85,90,100,75,65,55,95,90)
x20 <- c(100, 95, 60,52,45,36,47,50,90,85)
index <- x100 + x20
code <- data.frame(x100, x20, index)
code$class <-for (i in code){
                 if (x100 < 100 & x20 < 50) { "3"}
                 else if (x100 ==100 & x20 >=50){"2"}
                 else (x100 == 100 & x20 == 100) "1"
                 }

I just recently started to work with R, sorry if this is a basic question.

A: The code
for(i in code) { ... }

iterates over the columns in your dataframe, not the rows.  Use ifelse
with(code, ifelse(x100 < 100 & x20 < 50, '3', ifelse(x100 ==100 & x20 >=50, '2', '1')))


text:
Q: Microsoft Chart control not working on hosted server but working fine on local iis Dear members I am facing an issue
I am using chart control by Microsoft the issue is chart is displaying fine when hosted on local machine. But when I host it on deploy server chart doesn't come.
I had done all the possible changes available on internet spent almost 3-4 days on it at last have to write it over here please help.
I am pasting my web.config as well as my .aspx page for chart control over here..
Kindly help..
my web.config file
    <?xml version="1.0"?>

<configuration>
  <configSections>
    <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">

        <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">

        </sectionGroup>
      </sectionGroup>
    </sectionGroup>
  </configSections>
  <appSettings>

    <add key="ChartImageHandler" value="Storage=file;Timeout=20;Url=~/Images/;"/>

  </appSettings>
  <connectionStrings>

  </connectionStrings>

  <system.web>

    <globalization uiCulture="en" culture="en-gb"/>
    <anonymousIdentification enabled="true"/>
    <sessionState mode="InProc" cookieless="false" timeout="15"/>
    <httpRuntime maxRequestLength="15360" requestLengthDiskThreshold="15360"/>
    <httpCookies httpOnlyCookies="true" lockItem="true"/>

  <authorization>

  <deny users="?" />
  </authorization>

    <compilation debug="true" strict="false" explicit="true">
      <assemblies>

        <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

      </assemblies>
      <buildProviders>

      </buildProviders>

    </compilation>
    <pages enableEventValidation="false" validateRequest="true" viewStateEncryptionMode="Always"
      maintainScrollPositionOnPostBack="true">
      <namespaces>
        <clear />
        <add namespace="System" />
        <add namespace="System.Collections" />
        <add namespace="System.Collections.Specialized" />
        <add namespace="System.Configuration" />
        <add namespace="System.Text" />
        <add namespace="System.Text.RegularExpressions" />
        <add namespace="System.Web" />
        <add namespace="System.Web.Caching" />
        <add namespace="System.Web.SessionState" />
        <add namespace="System.Web.Security" />
        <add namespace="System.Web.Profile" />
        <add namespace="System.Web.UI" />
        <add namespace="System.Web.UI.WebControls" />
        <add namespace="System.Web.UI.WebControls.WebParts" />
        <add namespace="System.Web.UI.HtmlControls" />
      </namespaces>
      <controls>
        <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add tagPrefix="ajaxToolkit" namespace="AjaxControlToolkit" assembly="AjaxControlToolkit" />
        <add tagPrefix="asp" namespace="System.Web.UI.DataVisualization.Charting"
          assembly="System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
      </controls>
    </pages>
    <customErrors mode="Off"/>

    <httpHandlers>
      <remove path="*.asmx" verb="*" />
      <add path="*.asmx" verb="*" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
        validate="false" />
      <add path="CaptchaImage.axd" verb="GET" type="MSCaptcha.CaptchaImageHandler, MSCaptcha" />
      <add path="Reserved.ReportViewerWebControl.axd" verb="*" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
        validate="false" />
      <add path="*_AppService.axd" verb="*" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
        validate="false" />
      <add path="ScriptResource.axd" verb="GET,HEAD" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
        validate="false" />
      <add path="ChartImg.axd" verb="GET,HEAD,POST" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        validate="false" />
    </httpHandlers>
    <httpModules>
      <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    </httpModules>
  </system.web>

  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider,System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4">
        <providerOption name="CompilerVersion" value="v3.5"/>
        <providerOption name="WarnAsError" value="false"/>
      </compiler>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4">
        <providerOption name="CompilerVersion" value="v3.5"/>
        <providerOption name="OptionInfer" value="true"/>
        <providerOption name="WarnAsError" value="false"/>
      </compiler>
    </compilers>
  </system.codedom>
  <system.webServer>

    <modules runAllManagedModulesForAllRequests="true" />
    <directoryBrowse enabled="false" />

    <validation validateIntegratedModeConfiguration="false" />
    <modules>
      <remove name="ScriptModule" />
      <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    </modules>
    <handlers>
      <remove name="WebServiceHandlerFactory-Integrated" />
      <remove name="ScriptHandlerFactory" />
      <remove name="ScriptHandlerFactoryAppServices" />
      <remove name="ScriptResource" />
      <remove name="ChartImageHandler" />
      <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode"
        type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd"
        preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      <add name="ScriptResource" verb="GET,HEAD" path="ScriptResource.axd"
        preCondition="integratedMode" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      <add name="ChartImageHandler" preCondition="integratedMode" verb="GET,HEAD,POST"
        path="ChartImg.axd" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    </handlers>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

my Chart.aspx code.
<%--<asp:Chart ID="Chart1" runat="server" ImageLocation="Images/1.png" ImageStorageMode="UseImageLocation" ImageType="Png"
                                Height="500px">
                                <Series>
                                    <asp:Series ChartType="Pie" Name="Series1" Legend="Legend1" IsValueShownAsLabel="true">
                                    </asp:Series>
                                </Series>
                                <ChartAreas>
                                    <asp:ChartArea Name="ChartArea1">
                                    </asp:ChartArea>
                                </ChartAreas>
                                <Legends>
                                    <asp:Legend Name="Legend1" Docking="Bottom" LegendStyle="Column">
                                    </asp:Legend>
                                </Legends>
                            </asp:Chart>--%>
                           <%--<asp:Chart ID="Chart1" runat="server" ImageLocation="\\demotemp384\Images\1.png" ImageStorageMode="UseImageLocation" ImageType="Png"
                                Height="500px">
                                <Series>
                                    <asp:Series ChartType="Pie" Name="Series1" Legend="Legend1" IsValueShownAsLabel="true">
                                    </asp:Series>
                                </Series>
                                <ChartAreas>
                                    <asp:ChartArea Name="ChartArea1">
                                    </asp:ChartArea>
                                </ChartAreas>
                                <Legends>
                                    <asp:Legend Name="Legend1" Docking="Bottom" LegendStyle="Column">
                                    </asp:Legend>
                                </Legends>
                            </asp:Chart>--%>
                            <asp:Chart ID="Chart1" runat="server" ImageLocation="~/Images/1.png" ImageStorageMode="UseImageLocation" ImageType="Png"
                                Height="500px">
                                <Series>
                                    <asp:Series ChartType="Pie" Name="Series1" Legend="Legend1" IsValueShownAsLabel="true">
                                    </asp:Series>
                                </Series>
                                <ChartAreas>
                                    <asp:ChartArea Name="ChartArea1">
                                    </asp:ChartArea>
                                </ChartAreas>
                                <Legends>
                                    <asp:Legend Name="Legend1" Docking="Bottom" LegendStyle="Column">
                                    </asp:Legend>
                                </Legends>
                            </asp:Chart>
                            <%--<asp:Chart ID="Chart1" runat="server" ImageLocation="~/1.png" ImageStorageMode="UseImageLocation" ImageType="Png"
                                Height="500px">
                             <%--<asp:Chart ID="Chart1" runat="server" ImageStorageMode="UseImageLocation" ImageType="Png"
                                Height="500px">
                                <Series>
                                    <asp:Series ChartType="Pie" Name="Series1" Legend="Legend1" IsValueShownAsLabel="true">
                                    </asp:Series>
                                </Series>
                                <ChartAreas>
                                    <asp:ChartArea Name="ChartArea1">
                                    </asp:ChartArea>
                                </ChartAreas>
                                <Legends>
                                    <asp:Legend Name="Legend1" Docking="Bottom" LegendStyle="Column">
                                    </asp:Legend>
                                </Legends>
                            </asp:Chart>--%>

                            <%--<asp:Chart ID="Chart2" runat="server" ImageLocation="Images/2.png" ImageStorageMode="UseImageLocation" ImageType="Png"
                                Height="500px">
                                <Series>
                                    <asp:Series ChartType="Pie" Name="Series1" XValueMember="CompHeadName" YValueMembers="Expenditure"
                                        Legend="Legend1" IsValueShownAsLabel="true">
                                    </asp:Series>
                                </Series>
                                <ChartAreas>
                                    <asp:ChartArea Name="ChartArea1">
                                    </asp:ChartArea>
                                </ChartAreas>
                                <Legends>
                                    <asp:Legend Name="Legend1" Docking="Bottom" LegendStyle="Column">
                                    </asp:Legend>
                                </Legends>
                            </asp:Chart>--%>
                               <%--<asp:Chart ID="Chart2" runat="server" ImageLocation="\\demotemp384\Images\2.png" ImageStorageMode="UseImageLocation" ImageType="Png"
                                Height="500px">
                                <Series>
                                    <asp:Series ChartType="Pie" Name="Series1" XValueMember="CompHeadName" YValueMembers="Expenditure"
                                        Legend="Legend1" IsValueShownAsLabel="true">
                                    </asp:Series>
                                </Series>
                                <ChartAreas>
                                    <asp:ChartArea Name="ChartArea1">
                                    </asp:ChartArea>
                                </ChartAreas>
                                <Legends>
                                    <asp:Legend Name="Legend1" Docking="Bottom" LegendStyle="Column">
                                    </asp:Legend>
                                </Legends>
                            </asp:Chart>--%>
                            <asp:Chart ID="Chart2" runat="server" ImageLocation="~/Images/2.png" ImageStorageMode="UseImageLocation" ImageType="Png"
                                Height="500px">
                                <Series>
                                    <asp:Series ChartType="Pie" Name="Series1" XValueMember="CompHeadName" YValueMembers="Expenditure"
                                        Legend="Legend1" IsValueShownAsLabel="true">
                                    </asp:Series>
                                </Series>
                                <ChartAreas>
                                    <asp:ChartArea Name="ChartArea1">
                                    </asp:ChartArea>
                                </ChartAreas>
                                <Legends>
                                    <asp:Legend Name="Legend1" Docking="Bottom" LegendStyle="Column">
                                    </asp:Legend>
                                </Legends>
                            </asp:Chart>
                            <%--<asp:Chart ID="Chart2" runat="server" ImageLocation="~/2.png" ImageStorageMode="UseImageLocation" ImageType="Png"
                                Height="500px">
                                <Series>
                                    <asp:Series ChartType="Pie" Name="Series1" XValueMember="CompHeadName" YValueMembers="Expenditure"
                                        Legend="Legend1" IsValueShownAsLabel="true">
                                    </asp:Series>
                                </Series>
                                <ChartAreas>
                                    <asp:ChartArea Name="ChartArea1">
                                    </asp:ChartArea>
                                </ChartAreas>
                                <Legends>
                                    <asp:Legend Name="Legend1" Docking="Bottom" LegendStyle="Column">
                                    </asp:Legend>
                                </Legends>
                            </asp:Chart>--%>

                            <asp:Chart ID="Chart3" runat="server" ImageLocation="~/Images/3.png" ImageStorageMode="UseImageLocation"
                                Height="500px" Width="500px">
                                <Legends>
                                    <asp:Legend Name="Legend1">
                                    </asp:Legend>
                                </Legends>
                                <Series>
                                    <asp:Series Name="Series1" Legend="Legend1" LegendText="Budget">
                                    </asp:Series>
                                    <asp:Series Name="Series2" XValueMember="CompHeadName" YValueMembers="Expenditure"
                                        Legend="Legend1" LegendText="Expenditure">
                                    </asp:Series>
                                </Series>
                                <ChartAreas>
                                    <asp:ChartArea Name="ChartArea1">
                                    </asp:ChartArea>
                                </ChartAreas>
                            </asp:Chart>

A: I had the same problem. For my ASP.NET application running on a VPS, I used a domain name relocation service in 'Frame' mode to replace the ugly IP address with an elegant site name. I verified that the graph was produced in the c:\Temp directory specified in web.config, but somehow the ChartImageHander was denied permission to load it using IE. Chrome proved to be more tolerant. The thing is: the graph DID get displayed when the site was approached using the raw IP-address, but NOT when using the domain name. Running the domain name relocation service in '301' mode solved the problem, but unfortunately, the ugly IP address is now visible again in the browser...
Hope this helps.


text:
Q: Spring Boot Security XML vs WebSecurityConfigurerAdapter for CSRF I am migrating my Spring Application to Spring Boot.
I have an extensive security.xml file which maps all my controller code to the different Authentication Providers.
I know I can create a WebSecurityConfigurerAdapter and convert them to code, however, its not possible in the short term.
I can use the security.xml with ImportResource and works but all my controllers return back a CSRF Error
I tried making a class as this:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
    }
}

And Spring Boot Application
@ImportResource(locations = {"classpath:security.xml"})
public class MyApplication extends SpringBootServletInitializer

Now when I remove the ImportResource, the CSRF disable in WebSecurityConfig works, but if I have it doesn't work.
I tried adding the csrf disabled = true tag under <http> tag in my xml file but it is not working.
Any way to disable CSRF in Spring Boot using XML or somehow get it to consider both the XML and WebSecurityConfigurerAdapter class?

A: You may try to add the tag
[sec:csrf disabled="true"][/sec:csrf]

in your xml config


text:
Q: Create date ranges list I have a start date 01/jan and end date 22/jan
My employees work 5 days consecutively and they stay at home 5 days to start to work again after these last 5 days. These 5 days are defined as policy in our company.
How can I get the working days in ranges in SQL Server? Like this
Bob starts to work from 01/jan
John starts to work from 06/jan
Alex starts to work from 20/jan
Period: January from 01/jan to 22/jan

Bob 01/jan - 05/jan
Bob 11/jan - 15/jan
Bob 21/jan - 22/jan
John 06/jan - 10/jan
John 16/jan - 20/jan
Alex 20/jan - 22/jan

I found this answer from this article but I don't understand the code.
How to generate a range of dates in SQL Server

A: Here you go!  Have fun.   If you need any more help just ask.
--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--This is a table that holds all the people who work for you and when they started
--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
DECLARE @People TABLE
(
    Name        NVARCHAR(64),
    FirstDate   DATE
)

INSERT INTO @People
(
    Name,
    FirstDate
)
VALUES
    ('Bob','01/jan/2015'),
    ('Alex','20/jan/2015'),
    ('John','6/jan/2015')

--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--This is where the magic happens
--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

--This is the date range you want the results for
DECLARE @StartDate  DATE = '1/JAN/2015'
DECLARE @EndDate    DATE = '22/JAN/2015'

--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Using the above dates we can make a temporary table with all the dates for this date range
--This table could be a permanent table (with all reasonable dates in) if you wanted it to be,
--but for this example we will make it from scratch each time
--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

DECLARE @DateTable TABLE (Date DATE)

DECLARE @Date DATE = @StartDate

--This is just a loop that inserts all the dates in the range
WHILE @Date <= @EndDate
BEGIN
    INSERT INTO @DateTable(Date) VALUES (@Date)
    SET @Date = DATEADD(D,1,@Date)
END

--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Now this is the bit you will be interested in
--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

SELECT          Name,                       --Name
                MIN(Date) AS [From],        --First date
                MAX(Date) AS [To]           --Last date
FROM            @People AS P                --All people
CROSS JOIN      @DateTable AS D             --All dates
WHERE           DATEDIFF(D,FirstDate,Date) / 5 % 2 = 0      --Turn dates into groups each with 5 dates in (/5) Then pick only the even groups (%2 = 0) so one on one off
AND             FirstDate <= Date                                   --The date must be after they started
GROUP BY        Name,DATEDIFF(D,FirstDate,Date) / 5             --Group by each group so we can work out the first and last date of each group
ORDER BY        Name                                                        --Make it look nice

-----------------------------------------
If you want to change the number of days on and off, then it gets a bit more complex.
here is how you could do it
--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--This is a table that holds all the people who work for you and when they started
--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
DECLARE @People TABLE
(
    Name        NVARCHAR(64),
    FirstDate   DATE
)

INSERT INTO @People
(
    Name,
    FirstDate
)
VALUES
    ('Bob','01/jan/2015'),
    ('Alex','20/jan/2015'),
    ('John','6/jan/2015')

--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--This is where the magic happens
--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

--This is the date range you want the results for
DECLARE @StartDate  DATE = '1/JAN/2015'
DECLARE @EndDate    DATE = '22/JAN/2015'

--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Using the above dates we can make a temporary table with all the dates for this date range
--This table could be a permanent table (with all reasonable dates in) if you wanted it to be,
--but for this example we will make it from scratch each time
--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

DECLARE @DateTable TABLE (Date DATE)

DECLARE @Date DATE = @StartDate

--This is just a loop that inserts all the dates in the range
WHILE @Date <= @EndDate
BEGIN
    INSERT INTO @DateTable(Date) VALUES (@Date)
    SET @Date = DATEADD(D,1,@Date)
END

--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Used for changing the number of days each perosn works vs not works
--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

DECLARE  @DaysOn  INT
DECLARE  @DaysOff INT

SET @DaysOn = 5         --Days working
SET @DaysOff = 1        --Days not working

--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Now this is the bit you will be interested in
--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

SELECT   Name,
         MIN(Date) AS [From],     --First date
         MAX(Date) AS [To]        --Last date
FROM
(
   SELECT          Name,                        --Name
                   Date,                        --Date
                   ROW_NUMBER() OVER (PARTITION BY Name,DATEDIFF(D,FirstDate,Date) / (@DaysOn + @DaysOff) ORDER BY Date) AS Day,    --Day of cycle
                   DATEDIFF(D,FirstDate,Date) / (@DaysOn + @DaysOff) AS Cycle                                                       --Cycle
   FROM            @People AS P                --All people
   CROSS JOIN      @DateTable AS D             --All dates
   WHERE          FirstDate <= Date                                   --The date must be after they started
) AS Cycle
WHERE Day <= @DaysOn    --Only total up working days
GROUP BY Name,Cycle     --For each person and cycle
ORDER BY Name           --Make it looks nice


text:
Q: babel-node gives import error when only when writing to file The purpose of this whole exercise is to run ES2015 javascript in the browser. I have a test setup like this:
foo.js:
export class Foo {}

main.js:
import {Foo} from './foo';
console.log('ready')

Finally I have also a .babelrc file:
{
    "presets": [
        "es2015",
        "stage-0"
    ]
}

This code runs fine
$> ./node_modules/.bin/babel-node main.js
ready

The first step (and please correct me if I'm wrong) is to transpile this from ES2015 to ES5
$> ./node_modules/.bin/babel-node main.js -o main-es5.js
/Users/dev/test/main.js:1
(function (exports, require, module, __filename, __dirname) { import {Foo} from './foo';
                                                              ^^^^^^
SyntaxError: Unexpected token import

Just for completeness, my last step would be
$> ./node_modules/.bin/browserify main-es5.js bundle.js

Any help why on this matter would be appreciated

A: babel-node is just an interactive repl which precompiles input source.
To compile es6 and emit es5, do this:
babel main.js > main-es5.js
Incidentally, you would also need to export the class in foo.js to make it available in main.js. In your example, Foo is undefined.


text:
Q: Simplifying $9^{3/4}$, I get $3\sqrt[4]{9}$, but that's not the answer. Why? I am trying to simplify:
$9^\frac{3}{4}$
So this is what I did:
$9^\frac{3}{4} = \sqrt[4]{9^3}$
$\sqrt[4]{3*3*3*3*3*3}$
$3\sqrt[4]{3*3}$
$3\sqrt[4]{9}$
$3\sqrt[4]{3^2}$
I don't see how I can simplify this even more, however the answer I provided is incorrect. How can I simplify this even more?

A: We know that $9=3^2$ .So, $$\sqrt [4]{9^3} =\sqrt [4]{(3^2)^3} =\sqrt [4]{3^2*3^2*3^2} =\sqrt {3*3*3*3*3*3} $$ After this you have proceeded correctly. You can simplify the last step as: $$ 3\sqrt [4]{3^2} =3\times 3^{2/4} =3\times 3^{1/2} =3\sqrt {3} $$ Hope it helps.

A: Your answer is correct, but I would leave it as $3\sqrt[4]{9}$.
EDIT: In the spirit of other answers, I might try this instead:
$$9^{3/4}=(3^2)^{3/4}=3^{(2)(3/4)}=3^{6/4}=3^{3/2}=3^{1+1/2}=3\cdot3^{1/2}=3\sqrt{3}
$$

A: Simplify it this way:
$
9^\frac{3}{4} \\
= (3^2)^\frac{3}{4}\\
= 3^\frac{2\times 3}{4}\\
= 3^\frac{3}{2}\\
= 3^{\left(1 + \frac{1}{2}\right)}\\
= 3 \times 3^\frac{1}{2}\\
= 3 \sqrt{3}
$


text:
Q: Запись битов из массива vector в файл (C++) Как записать биты из vector типа bool в файл. Пробовал всячески, ничего не помогло. Пишет что должен быть типа char, но мне необходимо именно bool.

A: Байт - минимальный независимо адресуемый набор данных. Бит может существовать только в составе какого-то байта. Соответственно, в языке невозможна адресация одного бита. vector<bool> - прокси, который просто делает вид, что работает с отдельными битами, но на самом деле биты, с которыми он работает, входят в состав байтов.
Так что вопрос так, как он сформулирован, просто бессмысленен. Вы можете записывать биты в составе байтов, - от 1 до 8 (не будем вдаваться в экзотику) бит в одном байте.
Если же вас интересует вопрос, как записать весь вектор сразу, не деля его на отдельные биты, то спрашивать надо несколько иначе, так что я даже не уверен, что именно вас интересует. Но отвечу и на это.
В этом случае проблема в том, что стандарт, насколько я знаю, не требует того или иного конкретного решения от реализации, а значит, нет и переносимого способа достучаться до байтов с интересующими вас битами. В VC++ это, например, тип unsigned int, а не char или что-то еще однобайтное. В лучшем случае надо лезть внутрь исходников и докапываться, где именно и как они там хранятся. Причем не факт, что этот "лучший" случай на самом деле не худший :( Плюс - с очень высокой вероятностью - вас просто никто не допустит непосредственно к этим данным в силу того, что они и их интерфейс будут private.


text:
Q: Why doesn't the Templar Order care about the 2nd disaster? The templars know that the 2nd disaster is coming - they surely must after accessing the ancestral memories of Desmond, Clay Kazmercik and Daniel Cross, and observing the interactions between the ancestors and the First Civilization. A comic even tells us that Daniel Cross read Minerva's prophecy from the Prophet's Codex to Vidic himself.
So why do they not care at all that a world-changing event is about to destroy what they care about most - order?
Could it be possible that in addition to controlling the world, the Templar Satellite also was designed to prevent the 2012 coronal mass ejection?

A: Well I had the same question has you, but after thinking about it I came to this conclusion:
The Templars did not know about the incoming tragedy.

So why do they not care at all that a world-changing event is about to
destroy what they care about most - order?

We can't say for sure that they didn't try, because the satellite was probably their idea to prevent the tragedy.

The Templars set about gathering the remaining Pieces to ensure
"absolute peace", although they soon found themselves in a race
against the Assassin Order to obtain the Pieces first.
They planned to send a satellite with a Piece mounted on it into
orbit, with the launch scheduled on 21 December 2012. Ultimately,
Abstergo cancelled the launch of the satellite as they were unable to
obtain the required Piece of Eden in time.

So maybe this was their try to save the planet. Even the Minerva says that they wasted away their time (to save the planet) fighting each other (Assassins vs Templars).

"I had hoped you might find this place – and finish our work. But it
is too late. You and the Templars have squabbled over our refuse. You
have wasted centuries. And so you have lost your chance. You cannot
hope to stop the end now, Desmond. Only to survive it."
―Minerva, to  Desmond Miles.

But the satellite was an Abstergo Project called Eye-Abstergo.

This satellite was planned to ensure that a New World Order would be
enforced on Earth with the Piece of Eden's powers.
"If we were to place just one Piece of Eden within a satellite and
angle it toward the Earth... well, utopia would be within our grasp."
―Warren Vidic.
Upon entering low Earth orbit, the Eye would amplify the Apple of
Eden's power, as well as boost Abstergo's observational capabilities,
and locate "individuals with potential."
Though highly uncertain, preliminary analysis suggested that the
satellite would allow the harvesting of raw data, and would "awaken in
humans what should have been ours from the moment of our creation."

But it doesn't make sense since Abstergo planned to launch it December 21, 2012
So honestly, my answer is: The Templars did not know about the incoming tragedy.
Their plans just don't add up and Ubisoft isn't stupid not to notice that big of a plot hole.
The Templars interpretation of Minervas Speech must have been off.


text:
Q: PowerBuilder 12.5 tutorials I am new to PowerBuilder Classic 12.5. I have created ado.net database profile. How can I now connect to it and create a login window to read username and password, validate and let the user access to the program.
Please help with a sample code and where do I put the codes?
Thanks.

A: Making the database connection was one of the things that took me the longest to learn, not because it's difficult, but because you do it once and don't have to look at it again.
In your code, you'll need to set the properties of the SQLCA global transaction object. If you have the connection defined in your database painter, then you can right-click on it, choose "Properties", and see what the syntax needs to be from the "Preview" tab.
This syntax will (probably) include your security credentials for the connection. You'll need to build your own userid/password prompt and parse the results into the connection string. I don't have ADO.NET installed, but here's a sample of an ODBC connection... straight copy and paste:
// Profile CINEMA3
SQLCA.DBMS = "ODBC"
SQLCA.AutoCommit = False
SQLCA.DBParm = "ConnectString='DSN=cinema;UID=UserName;PWD=SuperSecurePassword'"


text:
Q: Image zoom in scrollview in iOS I have a scroll view with an image view. And I want to zoom the image in all direction equally. But when I am trying to do it's not happening.
But its zooming image only in vertical direction not in horizontal direction. I have done  this:
[monthView setImage:[monthArray objectForKey:dateString] ];
 scrollView1.contentSize=CGSizeMake(1280, 960);
#pragma scrollview delegates
-(UIView *) viewForZoomingInScrollView:(UIScrollView *)scrollView
 {

return monthView;
}

A: Write minimumZoomScale and maximumZoomScale value of scrollView in viewDidLoad
 _scrollview.minimumZoomScale=1.0;
 _scrollview.maximumZoomScale=2.0;

A: Set zooming scale for scrollview. Like:
self.myScrollView.minimumZoomScale = 1.0;
self.myScrollView.maximumZoomScale = 5.0f;

And Make sure monthView is a subview of scroll view.
Hope this helps. :)

A: 1 Set your view controller up as a .
2 Draw your UIScrollView the size you want for the rectangle at the center of the view. Set the max zoom in the inspector to something bigger than 1. Like 4 or 10.
3 Right click on the scroll view and connect the delegate to your view controller.
4 Draw your UIImageView in the UIScrollView and set it up with whatever image you want. Make it the same size as the UIScrollView.
5 Ctrl + drag form you UIImageView to the .h of your View controller to create an IBOutlet for the UIImageView, call it something clever like imageView.
6 add this code.
-(UIView *) viewForZoomingInScrollView:(UIScrollView *)scrollView {return self.imageView;}
7 Run project.


text:
Q: Validation rule on Rich Text Area field Using LEN() function, we are able to validate if a rich text area is blank, but when a rich text area with image is added, LEN() still say 0.
How to validate whether rich text area field contains image or not ?

A: Wrote a trigger to validate rich text area to check for image or not
trigger JobTrigger on Job__c (before update) {

       for(Job__c j: Trigger.newMap.keySet()){

        if((Trigger.oldMap.get(j).Status__c != Trigger.newMap.get(j).Status__c)
                 && (Trigger.newMap.get(j).Status__c == 'Completed'))
         {

          if(j.Picture__c != null){

             String picString = j.Picture__c.substringBetween('<img', 'img>');

              if(picString == null ){
               j.addError('Picture is required to move Status to Completed');
              }
          }

       else {

         if(picture__c == null ){
              j.addError('Picture is required to move Status to Completed');
           }

          }
        }
      }
    }

A: You can use isEmpty(). If it's length is 0 and it's not empty, it must contain something which could be an image.


text:
Q: Change the size of a JTextField inside a JBorderLayout When I use the code below it doesn't alter the size at all, it still fills the area in the grid.
JPanel displayPanel = new JPanel(new GridLayout(4, 2));

JTextField titleText = new JTextField("title");

displayPanel.add(titleText);

titleText.setSize(200, 24);

A: With a BorderLayout you need to use setPreferredSize instead of setSize

A: From the api on GridLayout:

The container is divided into
  equal-sized rectangles, and one
  component is placed in each rectangle.

Try using FlowLayout or GridBagLayout for your set size to be meaningful. Also, @Serplat is correct. You need to use setPreferredSize( Dimension ) instead of setSize( int, int ).
    JPanel displayPanel = new JPanel();
    // JPanel displayPanel = new JPanel( new GridLayout( 4, 2 ) );
    // JPanel displayPanel = new JPanel( new BorderLayout() );
    // JPanel displayPanel = new JPanel( new GridBagLayout() );

    JTextField titleText = new JTextField( "title" );

    titleText.setPreferredSize( new Dimension( 200, 24 ) );

    // For FlowLayout and GridLayout, uncomment:
    displayPanel.add( titleText );

    // For BorderLayout, uncomment:
    // displayPanel.add( titleText, BorderLayout.NORTH );

    // For GridBagLayout, uncomment:
    // displayPanel.add( titleText, new GridBagConstraints( 0, 0, 1, 1, 1.0,
    // 1.0, GridBagConstraints.CENTER, GridBagConstraints.NONE,
    // new Insets( 0, 0, 0, 0 ), 0, 0 ) );

A: Try to play with
setMinSize()
setMaxSize()
setPreferredSize()

These method are used by layout when it decide what should be the size of current element. The layout manager calls setSize() and actually overrides your values.

A: Any component added to the GridLayout will be resized to the same size as the largest component added. If you want a component to remain at its preferred size, then wrap that component in a JPanel and then the panel will be resized:
JPanel displayPanel = new JPanel(new GridLayout(4, 2));
JTextField titleText = new JTextField("title");
JPanel wrapper = new JPanel( new FlowLayout(0, 0, FlowLayout.LEADING) );
wrapper.add( titleText );
displayPanel.add(wrapper);
//displayPanel.add(titleText);


text:
Q: How to get feature importance in predicting something for every each year using different index? I have these two datasets, one of these is various index for long long period and the second one is the total number of typhoons for same period as the former one.
First dataset (dimension : (22, 30) )
            A  B   C    D   E    F  G   H   I  J  \
Unnamed: 0
1979         1803.0  1.1  0.16 -0.15 -0.29 -0.24    -0.08  0.42  0.10 -0.81
1980         1932.0 -0.0 -0.36  0.08  0.21  0.16     0.64  0.47 -0.08  1.21
1981         1569.0  2.0 -0.63 -0.43 -0.46 -0.59    -0.47  0.18 -0.22 -0.80
1982         1719.0 -1.7  0.13  0.54  0.53  0.45     1.74 -0.15 -0.45 -0.14
1983         1386.0  0.1  4.24  1.52  0.54 -0.00     0.82  0.35 -0.45  4.82
1984         1003.0 -0.6 -0.95 -1.17 -0.90 -0.78    -0.28 -0.37  0.46 -2.62
1985          761.0 -0.6 -1.27 -1.02 -0.91 -0.95    -0.11 -0.30  0.04 -1.59

Second dataset (dimension : (30, ))
Unnamed: 0
1979        0.68
1980        0.45
1981        0.20
1982        1.14
1983        1.38
1984       -1.89
1985        0.25
1986       -0.17
1987        0.58

I want to make ANN model which can predict the total number (like first dataset) for future while using various index (like second dataset), so I tried to make a model for it.
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split

# upload dataset
X = pd.read_csv('index.csv')
X.set_index('Unnamed: 0', inplace=True)
X = X.T
X = X.values

raw_data = pd.read_csv('sum.csv')
y = raw_data.iloc[30:60, -1]
y = y.values

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

But I got an error:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-50-5f25f916c229> in <module>
     16 y = y.values
     17
---> 18 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

2 frames
/usr/local/lib/python3.7/dist-packages/sklearn/utils/validation.py in check_consistent_length(*arrays)
    332         raise ValueError(
    333             "Found input variables with inconsistent numbers of samples: %r"
--> 334             % [int(l) for l in lengths]
    335         )
    336

ValueError: Found input variables with inconsistent numbers of samples: [22, 30]

How can I deal with this new ANN problem and more essential problem (dimension stuff)?


text:
Q: how to update row I hv a table like this:-
ID    Model     Value
DAX   FAB01
DAZ   FAB01
DAA   FAB01
DAX   FAB02
DAZ   FAB02
DAA   FAB02

I need to update the table so that the final output will be like this:-
ID    Model     Value
DAX   FAB01     123
DAZ   FAB01     789
DAA   FAB01     963
DAX   FAB02     456
DAZ   FAB02     951
DAA   FAB02     753

I tried the below:-
UPDATE [TABLE]
SET VALUE = CASE
              WHEN MODEL='FAB01' AND ID='DAX' THEN '123'
              WHEN MODEL='FAB01' AND ID='DAZ' THEN '789'
              WHEN MODEL='FAB01' AND ID='DAA' THEN '963'
              WHEN MODEL='FAB02' AND ID='DAX' THEN '456'
              WHEN MODEL='FAB02' AND ID='DAX' THEN '951'
              WHEN MODEL='FAB02' AND ID='DAX' THEN '753'
              ELSE VALUE
            END

Re-run the above & it works now.
Thanks.

A:    UPDATE [TABLENAME]
   SET VALUE = 123

   WHERE ID = "DAX" AND MODEL = "FAB01"

Etc..repeat for each row

A: Extending from the bAN's answer. The update should be -
UPDATE [TABLENAME]
SET [VALUE] = 123
WHERE ID = 'DAX'
AND Model = 'FAB01'

The uniqueness is on two columns in the table (ID and Model).

A: All statements:
UPDATE YourTableName SET [Value] = 123 WHERE [ID] = 'DAX' AND [model] = 'FAB01'
GO

UPDATE YourTableName SET [Value] = 789 WHERE [ID] = 'DAZ' AND [model] = 'FAB01'
GO

UPDATE YourTableName SET [Value] = 963 WHERE [ID] = 'DAA' AND [model] = 'FAB01'
GO

UPDATE YourTableName SET [Value] = 456 WHERE [ID] = 'DAX' AND [model] = 'FAB02'
GO

UPDATE YourTableName SET [Value] = 951 WHERE [ID] = 'DAZ' AND [model] = 'FAB02'
GO

UPDATE YourTableName SET [Value] = 753 WHERE [ID] = 'DAA' AND [model] = 'FAB02'
GO

A: Alternatively you might try to use OPENROWSET(). Here's an example:
UPDATE YourTable
SET Value = xls.ExcelColumnValue
FROM OPENROWSET(...) xls
WHERE YourTable.ID    = xls.ExcelColumnID
  AND YourTable.Model = xls.ExcelColumnModel

All column names after xls. are arbitrary here, you should replace them with the actual column names. Basically, you can find them out simply with SELECT * FROM OPENROWSET(...). (You can also know them in advance following the information below.)
Now for the ... part. Here you define the source, in particular you specify the file format, the file name, the sheet name, and also you specify the middle tier software to be used, whatever that means, and some properties of the source. Depending on what Excel version is used you can try the following variants:

*

*for Excel 97-2003:

OPENROWSET (
  'Microsoft.Jet.OLEDB.4.0',
  'Excel 8.0;HDR=YES;Database=C:\path\file.xls',
  'SELECT * FROM [sheet name$]'
)

*

*for Excel 2007+:

OPENROWSET (
  'Microsoft.ACE.OLEDB.12.0',
  'Excel 12.0;HDR=YES;Database=C:\path\file.xls',
  'SELECT * FROM [sheet name$]'
)

Replace the italics accordingly with the actual file name and sheet name.
The HDR=YES; option specifies that the first row defines the column names. If in your case the first row contains data like all the other rows, simply drop this option.


text:
Q: How to implement a check for update on Mac OS X I'm trying to create an internal app for my company. I want to provide some kind of "automatic update" feature that give the user a message (with install option) once a new version is available. I know that for windows there is a technology named ClickOnce. Is there some kind of standard implementation for mac os x? Should I write it from scratch? If so, how can I start the install process directly from my application? Should I provide a mpkg?

A: Sparkle is probably what you want.  It's used in many apps and is probably the "norm" of actual automatic update nowadays in mac apps other than the app store itself.


text:
Q: Download content to the app when it starts for first time? I have a doubt related with my app. My app takes like 5-10 seconds to download all the data from my web service and also from twitter using STTwitterAPI, and I download all this content when the app just starts. The question is: What you  would do during this 5-10 secs? Show an UIAlertView saying that the app is downloading content? Load an Image to a UIImageView and once the data is downloaded delete the UIImageView (I don´t know how to check that)? Is there any method that Apple provides to give a solution to this question?
I just thought about setting a NSTimer for the UIImageview or the NSAlertView, the problem is that if I keep adding data to the server, or depending the connection of the user that is downloading the data, maybe the UIImageView goes away before all the data is already download.
What would be the best solution? Does STTwitter have a method to check if all the data is downloaded?

A: Have a look at this fantastic HUD display singleton framework:
SVProgressHUD by Sam Vermette, all you do is drag the folder into your xcode project. Then import the .h file where ever you want to display your message and then you can start displaying a heads up display which is what the overlay is called by simply calling a method from the singleton class like so [SVProgressHUD showWithStatus:@"Doing Stuff"];. It's as simple as that!

Then download a project called AFNetworking. AFNetworking from github.
in AFNetworking there are is a selector method that you can set to the  will be of interest to you. So with this framework its easy to establish a connection to your server, download the data and the framework gives you the option to set a SUCCESS method which will then call your success method as soon as the data has finished downloading from your server.
Here's what your code may look like.
-(void)startDownloadingData{
    [SVProgressHUD showWithStatus:@"Downloading data"];
    //add your AFNetworking connection here that downloads the data
    //...
    [serverRequest setDidFinishSelector:@selector(requestSucceeded:)];
    //...
}
-(void)requestSucceeded:(ASIHTTPRequest*)request{
switch (statusCode) {
    case 400:
    case 401:
    {

        [SVProgressHUD showErrorWithStatus:@"An error occurred";
        break;
    }
    case 200:{
        NSLog(@"Request Successful");
        [SVProgressHUD dismissWithSuccess:@"Done"];
    }
    default:{
    }
}


text:
Q: Problem when installing the cover package for golang I have some code.
But when
I try run cover test and have response:
'go get -u github.com/gregoryv/uncover/...
go test -coverprofile /tmp/c.out
uncover /tmp/c.out'

I try install cover package:
go get code.google.com/p/go.tools/cmd/cover

but get error
package code.google.com/p/go.tools/cmd/cover: unrecognized import path "code.google.com/p/go.tools/cmd/cover" (parse https://code.google.com/p/go.tools/cmd/cover?go-get=1: no go-import meta tags (meta tag github.com/golang/go did not match import path code.google.com/p/go.tools/cmd/cover))

System: Ubuntu 18.04

A: The correct path is:
go get golang.org/x/tools/cmd/cover


text:
Q: onMouseDown/onClick event on  inside  I am new to Javascript.
There is a big
 as a bar with three
 inside. One of those 3 divs contains an input, which is a field the user can type things in. The input normally let the user click on it and type.
However, the default behavior of the bar is to close when the user clicks out of it, which won't let the user type because it just closes. I try to use preventDefault() on the big
 when the mouse goes down, so that the bar won't close, and that works. But then it does not let the user type inside the input, which was possible if I don't preventDefault(). Can anyone explain this behavior and how to handle these events?

 {
  event.preventDefault();
}}
>

    <Input placeholder="default size" />

A: I believe you have to use "stopPropagation" on the input, so the click does not propagate to the div.
<input onMouseDown="{event => { event.stopPropagation(); }}" placeholder... />


text:
Q: how to replace the starting with minus value in a file with zero I am having the text file as below. that file contains some negative data. so I want to replace that data with zero.
1,2,3
4,5,-6
7,-8,9

I have tried with below command.
sed 's/-*/0/g' 1.txt

but am not getting the reqired output. so can any one please help me on this.

A: Try this:
sed 's/-[0-9]\+/0/g' 1.txt

The way this works is, sed will find all sequences of characters that match the pattern -[0-9]\+ and replace them with a 0. Now, they meaning of the -[0-9]\+ pattern is as follows: it will find a - character followed by a nonempty sequence of characters (this is the meaning of \+) that consists entirely of characters in the set between 0 and 9.

A: You have to better understand regular expression for sed.
The expression -* in s /-*/0/g will match zero or more '-' characters. * in regular expression means zero or more duplicates, not wild character match, . does all character set match for a single character. See http://www.grymoire.com/Unix/Regular.html
To your question, you have to build a RE to match any negative number (maybe you need also consider float numbers). I would suggest:
-[0-9]*\.?[0-9]+

This is an extended regular expression for sed program, meaning that starts with -, can with or without pre-dot numbers or dot, and must contain at least one number.
So
sed -r s/-[0-9]*\.?[0-9]+/0/g 1.txt >2.txt

is what you need. -r option means use extended regular expression.
Some tests:
echo '12, 0.12, -2' | sed -r s/-[0-9]*\.?[0-9]+/0/g
      12, 0.12, 0
echo '12, -234, -2' | sed -r s/-[0-9]*\.?[0-9]+/0/g
      12, 0, 0
echo '-0.98, 2.34, -2' | sed -r s/-[0-9]*\.?[0-9]+/0/g
          0, 2.34, 0
echo '-9.8, 0.34, -2' | sed -r s/-[0-9]*\.?[0-9]+/0/g
         0, 0.34, 0
echo '-9.8, 1.34, -2' | sed -r s/-[0-9]*\.?[0-9]+/0/g
         0, 1.34, 0

Hope this would be helpful, check tutors on http://www.grymoire.com/Unix/Sed.html.
Thanks

A: awk:
$ awk 'gsub(/-[0-9]+/,0)1' 1.txt
Identical to @redneb's sed solution but in awk. Replace all - starting number strings ([0-9]+) with a 0 in record $0 and print it nevertheless (1in the end).

A: awk 'sub(/-./,"0")1' file
1,2,3
4,5,0
7,0,9

A: With awk, you would write
awk -F, -v OFS=, '{for (i=1; i<=NF; i++) if ($i < 0) $i = 0; print}' file

My sed would be
sed -r 's/(^|,)-[^,]+/\10/g' file


text:
Q: jQuery data attribute click event I have made a quick fiddle to outline my problem: http://jsfiddle.net/mYdxw/
I'm trying to click on a div, grab its data attribute and show its corresponding set of divs.
Can anyone spot why it isn't doing this currently?
JS
$(document).ready(function() {

    $('.categoryItems').click(function() {
        $('.itemLinks').hide();
        var target_category = $(this).attr('data-target_category');
        $('.itemLinks [data-category=' + target_category + ']').show();
    });
});

HTML

HTML Site Templates

jQuery Plugins

Tumblr Themes

WordPress Themes

    Mini Tumblr Theme
    Randomr jQuery Plugin
    Redux WP Theme

A: Just to improve on the code, jQuery provides .data() to retrieve the value of the dataset so instead of using attr() use data()
 var target_category = $(this).data('target_category');

DEMO: http://jsfiddle.net/mYdxw/28/

A: This...
$('.itemLinks [data-category=' + target_category + ']').show();

should be this...
$('.itemLinks[data-category="' + target_category + '"]').show();

The space is interpreted as a descendant selector, but the data-category is directly on the itemLinks element, not on a descendant.
I also added quotes around the value of the attribute selector. The API requires it.
DEMO: http://jsfiddle.net/mYdxw/11/


text:
Q: How do I check which shell I am using? I read that terminal is nothing but shell, and Unix provides different flavors of shells:

*

*Bourne shell (sh)

*C shell (csh)

*TC shell (tcsh)

*Korn shell (ksh)

*Bourne Again shell (bash)

Questions:

*

*When I open a terminal window, which shell is opened by default?

*How do I check how many shells are installed?

*How do I change the shell used from my account?

A: You can type the following command in your terminal to see which shell you are using:
echo $0

The result will look something similar to the below if you are using the bash (Bourne Again Shell) terminal:
-bash

A: $SHELL gives you the default shell.
$0 gives you the current shell.
For example: I have bash as my default shell, which I use for my Terminal App. But for my iTerm2 app, I use the command as the window opens: /bin/ksh.
So my
$0 gives me /bin/ksh on iTerm2.
$SHELL gives me /bin/bash on iTerm2.
$0,$SHELL gives me /bin/bash on Terminal

A: The other answers tend to be using shell specific features, but we are trying to discover which shell we are using, so they assume the answer to the problem. For example none of the answers will work on fish.
sh -c 'ps -p $$ -o ppid=' | xargs ps -o comm= -p

Instead use the $$ syntax in an invocation of sh, but then we are looking for the PPID not the PID. Use the PPID to find the cmd.
sh -c 'ps -p $$ -o ppid=' | xargs -I'{}' readlink -f '/proc/{}/exe'

Thanks for improvement @muru

A: To address your third question, "How do I change the shell used from my account?", the answer is to use chsh.
There are two modes:

*

*interactive, and;

*non-interactive.

From Changing Shells - Changing your login shell which is permanent, and paraphrasing it slightly:

You will use a program called chsh. There is a interactive method
and non-interactive method. Type the following into your terminal:
INTERACTIVE METHOD
$ chsh

This results in a brief dialog in which the user is prompted first for
their password and then for the full path of the desired new shell.
Caution should be exercised when changing one's default shell because
it is possible to make an error that only the root user (i.e., system
administrator) can repair (although it should be easy for a skilled
user to repair it on a home system). In particular, it is important to
first test the shell temporarily in the current session and then to
make certain that a valid shell name is being entered when making the
permanent change.
NON-INTERACTIVE METHOD
I will use csh as again an example.
$ chsh -s /bin/csh

The -s sets it for you without having to go into the editor to do
it.
Once this is executed successfully, then echo $SHELL will still say
that you are in the same shell as before. However, you need to log out
and back in for the change to take effect. Now do echo $SHELL. You
should see it shows the new shell.

A: You may not want to know the current shell's name (e.g. -bash, bash, zsh, etc., from echo $0), nor default shell's executable path (from echo $SHELL), but rather the current shell's executable path (especially useful e.g. if you have more than one version of Bash installed).
To do this you can use lsof -p "$$" or with some extra coding to extract just the required info:
lsof -p "$$" | grep -m 1 txt | xargs -n 1 | tail -n 1

Example output for Bash installed via Homebrew:
/usr/local/Cellar/bash/5.1.8/bin/bash

or for Zsh:
/bin/zsh

The above is different from echo $SHELL, both because the above is for the shell which is currently running rather than the user's default shell, and also because the above gives the executable after any symlinks have been expanded. E.g. for the same Bash install as above, echo $SHELL gives /usr/local/bin/bash.
EDIT: If you need to allow for possible space characters in the shell's path, use lsof -p "$$" | grep -m 1 txt | xargs -n 1 | tail -n +9 | xargs instead.

A: To find the shell you have on the default environment you can check the value of the SHELL environment variable:
echo $SHELL

To find the current shell instance, look for the process (shell) having the PID of the current shell instance.
To find the PID of the current instance of shell:
echo "$$"

Now to find the process having the PID:
ps -p <PID>

Putting it together:
ps -p "$$"

A: The original post asked three questions. The answers given do cover the first question, "When I open a terminal window, which shell is opened by default?" They also answer a question which was NOT asked, namely "How can I find out which shell is currently running in the terminal?" However, as far as I can see nobody has answered either the second or third questions originally asked, namely "How do I check how many shells are installed?" and "How do I change the shell used from my account?"

*

*To answer "How do I check how many shells are installed?" the following command will list all the available shells:
cat /etc/shells

For example, on a default installation of Ubuntu 18.10 this gives:
# /etc/shells: valid login shells
/bin/sh
/bin/dash
/bin/bash
/bin/rbash

However, by default sh is a symbolic link to dash, while rbash links to bash with the option -r ("restricted bash") so there are actually only two shells, not four as the above list suggests. The following command will show you whether any of the listed shells are in fact symbolic links, and if so where they link to:
ls -l /bin

*Now for the question "How do I change the shell used from my account?" Assuming this means "How do I permanently change the default shell that a terminal will use", there is an answer here.

A: To know which is the default shell for your user, you can run:
echo "$SHELL"

For example if you're using Bash you should get the following output:
/bin/bash

If you didn't change any configuration it should be Bash since Bash it's the default shell on Ubuntu.

A: In one of the servers I connect to, the login shell is /bin/sh which is a symlink to /bin/bash
Most answers here will give sh, which would make the OP consider it's Bourne shell and not GNU bash, except this one that gives /bin/bash
Another option that works for this case is:
$ echo $SHELL
/bin/sh

$ ls -l /bin/sh
lrwxrwxrwx 1 root root 4 May 31 16:15 /bin/sh -> bash

$ /bin/sh --help
GNU bash, version 4.2.10(1)
Usage:  /bin/sh [GNU long option] [option] ...
        /bin/sh [GNU long option] [option] script-file ...


text:
Q: TypeError: unsupported operand type(s) for <<: 'int' and 'float' There's this open source code I was trying out to play checkers, the code works just fine till the taking a piece part, and the following error appears:
line 73, in make_move
    taken_piece = int(1 << sum(i for (i, b) in enumerate(bin(move)[::-1]) if b == '1')/2)
TypeError: unsupported operand type(s) for <<: 'int' and 'float'

any help regarding how to fix this issue?

A: You can't shift bits by a float/decimal, the error is pretty clear. sum(...)/2 gives a float in the current operation.
What you can do, however, is perform an integer division using //, in Python 3. For Python 2, / does an integer division (for int operands) except you've overridden the default behavior.


text:
Q: converting a string to a date in C# I was wondering how I would convert a string of four to six digits to a date in C#?
111110 would be 11 11 10
111 10 would be 11 1 10
1 1 10 would be 1 1 10
The pattern being mmddyy mmd yy m d yy
and the spaces are either ' ' or '\0' (the input I am given is not very clean)
This what I have so far and it works for all above cases, its just not very pretty:
Is there a more efficient solution to the above cases?
//Converts the given input string into a valid Date
private DateTime convertToDateFromString(string dateString)
{
  int length = dateString.Length;
  int month = 1;
  int day = 1;
  int year = 1;
  bool gotMonth = false;
  bool gotDay = false;
  bool gotYear = false;
  char c = ' ';
  char peek = ' ';
  string buffer = "";
  DateTime bufferDate;
  int count = 0;

  try
  {
    //loop character by character through the string
    for (int i = 0; i < dateString.Length; i++)
    {
      c = dateString[i];
      if ((i + 1) < dateString.Length)
        peek = dateString[i + 1];
      else
        peek = '\0';

      if (c != ' ' && c != '\0')
      {
        buffer += c;
        count++;
        //Check if the month is done
        if ((peek == ' ' || peek == '\0' || count == 2) && gotMonth == false)
        {
          count = 0;
          gotMonth = true;
          month = int.Parse(buffer);
          buffer = null;
        }
        //Check if the day is done
        else if ((peek == ' ' || peek == '\0' || count == 2) && gotDay == false && gotMonth == true)
        {
          count = 0;
          gotDay = true;
          day = int.Parse(buffer);
          buffer = null;
        }
        //Check if the year is done
        else if ((peek == ' ' || peek == '\0' || count == 2) && gotYear == false && gotMonth == true && gotDay == true)
        {
          count = 0;
          gotYear = true;
          year = int.Parse(buffer);
          buffer = null;

          if (year >= 80 && year <= 99)
            year += 1900;
          else if (year >= 0 && year <= 79)
            year += 2000;
        }
      }
    }
    bufferDate = new DateTime(year, month, day);
  }
  catch (System.Exception ex)
  {
    bufferDate = new DateTime(1, 1, 1);
  }
  return bufferDate;
}

A: You should use one of the many Parse methods defined on DateTime.
These will take the string, an optional format string (describing the format of the datetime string) and an optional culture.
Take a look at Parse, ParseExact, TryParse and TryParseExact, some of which will take a string[] of the formats to try.
Additionally, here available string formats - standard and custom date and time format strings.

A: Try using
DateTime.TryParseExact(dateString, new string[] { "MMddyy", "MMd yy", "M d yy" }, CultureInfo.CurrentCulture, DateTimeStyles.AssumeLocal, out result);

if you need to you can
dateString = dateString.Replace('\0', ' ');

before you begin

A: You discriminator here is the number of spaces. First get that:
string source = "....";
int spaceCount = source.Count(c => c == ' ');

Then create formatstrings for the expected range 0..2 . You can use the strings from the question except that you have to use M for the months:
var formats = new string[] { "MMddyy", "MMd yy", "M d yy" };

and then you can get your date :
DateTime r = DateTime.ParseExact(source, formats[spaceCount], null);

Add validations as required.


text:
Q: How to remove character encoding for apache axis 2 message response We use Axis2 to generate web service response of which the body is a xml message that generated from a system using windows 1252 as encoding.  Our Axis2 system, will wrapped this body inside a soap message using utf8. The message is then send to the caller.  However, the caller keep reject the message with "Invalid byte 1 of 1-byte UTF-8"
The caller system suggest me to take out the encoding attribute in the xml declare of the response.  I do not know how to tell axis not to put this setting.  Any one know how?

A: It's probably best to keep the Axis response as UTF-8, and instead try to alter the encoding of the payload from 1252 to UTF-8. How are you assembling the SOAP response from the payload?

A: Is the original XML's encoding correctly declared as Windows-1252 in the XML header? If not, it's not really XML and that system is broken; if it is declared and Axis2 just relabels it as UTF-8 without actually converting the data, then Axis2 is (very badly) broken.
In either case, fix the broken system. Do NOT remove the encoding - that's the worst thing you can do. As indicated above: XML without a declared encoding is not XML, it's random data that might look vaguely like XML.


text: Q: How can I check the response of MQTT when doing testing through Tsung I am trying to connect to IOTF platform which is based on MQTT for load testing through Tsung, want to know is it possible in Tsung to check the server response when we are configuring xml for mqtt req. I have tried match tag but nothing seems to worked yet.


text:
Q: AVPlayerItem addobserver issue in iOS8 Hi I am playing video on my UITableViewCells using AVPlayer, It was working fine on iOS 7, but in iOS8 it crashing with following error.
       'An instance 0x7c01b000 of class AVPlayerItem was deallocated while key value observers were still registered with it.

Here is my code
      - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
         {

          .........
          .........

        if(cell.videoPlayer!= nil && cell.videoPlayer.currentItem != nil)

           {
              [cell.videoItem removeObserver:self forKeyPath:@"playbackBufferEmpty" context:nil];
               [cell.videoItem removeObserver:self forKeyPath:@"playbackLikelyToKeepUp" context:nil];

               }
     cell.videoPlayer = [AVPlayer playerWithPlayerItem:cell.videoItem];
     cell.avLayer = [AVPlayerLayer playerLayerWithPlayer:cell.videoPlayer];
     cell.videoPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;

     [cell.videoItem addObserver:self forKeyPath:@"playbackBufferEmpty" options:NSKeyValueObservingOptionInitial context:nil];
     [cell.videoItem addObserver:self forKeyPath:@"playbackLikelyToKeepUp" options:NSKeyValueObservingOptionInitial context:nil];

     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(itemDidBufferPlaying:) name:AVPlayerItemPlaybackStalledNotification object:nil];

     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(itemDidFinishPlaying:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];

    cell.avLayer.frame = CGRectMake(5, 9, 310, 310);
   [cell.contentView.layer addSublayer:  cell.avLayer];
   [ cell.videoPlayer play];
   [cell.contentView addSubview:cell.videoActivity];

     return cell;
    }

   -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
               change:(NSDictionary *)change context:(void *)context {

      NSArray* cells = homeTabl.visibleCells;

      for (HomeCell* cell in cells) {

        if (object == cell.videoItem && [keyPath isEqualToString:@"playbackBufferEmpty"])                 {

   if (cell.videoItem.playbackBufferEmpty) {

        NSLog(@"buffering");
        cell.videoActivity.hidden = NO;

       }
    }

       else if (object == cell.videoItem && [keyPath isEqualToString:@"playbackLikelyToKeepUp"])
    {
         if (cell.videoItem.playbackLikelyToKeepUp)
        {

        cell.videoActivity.hidden = YES;
        [cell.videoPlayer play];

           }
        }

      }

    }

 -(void)scrollViewDidScroll:(UIScrollView *)aScrollView {

    NSArray* cells = homeTabl.visibleCells;

    for (HomeCell* cell in cells) {

    [cell.videoPlayer pause];
    [cell.avLayer removeFromSuperlayer];
    cell.videoPlayer = nil;
    cell.videoItem = nil;

   }

What could be the reason ? I have gone through this SO question, but I could not implement this in my codes. Please help me to fix this.

A: Removing observers is one of the flakiest areas in iOS in my experience. You need to balance calls for AddObserver with a RemoveObserver very carefully. I have found a failsafe way to do this is to put any AddObserver calls into an object's Init method and then balance these with RemoveObserver calls in its Dealloc method. In your case this would be in your 'videoItem' subclass. (this code is not checked)
- (id) initWithOwner:(id)owner
{
    self = [super init];
    if( self ) {
        _owner = owner;
        [self addObserver:_owner forKeyPath:@"playbackBufferEmpty" options:NSKeyValueObservingOptionInitial context:nil];
    }
    return self;
}

- (void) dealloc
{
    [self removeObserver:_owner forKeyPath:@"playbackBufferEmpty" context:nil];
}

I'm not sure where videoItem is declared but basically you create a new class called VideoItem and in it create a new initialiser called initWithOwner:. In your cellForRowAtIndexPath: method when you create your new cell you also create an instance of VideoItem and pass in self as the owner
self.videoItem = [[VideoItem alloc] initWithOwner:self];

Without more of your code I can't really specify this in more detail. You might also think of formatting your code first in xcode then cutting and pasting it into SO to keep it tidier.


text:
Q: How to get the Android TextView to scroll down to the end automatically? I have a TextView whose contents are copied from a text file. Now each time the contents of the text file is loaded into the TextView, I want it to scroll down automatically to the end.
This is what that portion of my layout XML file has :
    <ScrollView
        android:id="@+id/scroller"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/command"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/header"
        android:fillViewport="true" >

        <TextView
            android:id="@+id/output"
            android:layout_width="fill_parent"
            android:layout_height="132dp"
            android:bufferType="spannable"
            android:editable="false"
            android:enabled="false"
            android:focusable="true"
            android:focusableInTouchMode="false"
            android:freezesText="true"
            android:inputType="textMultiLine"
            android:isScrollContainer="true"
            android:scrollbars="vertical"
            android:text="@string/output" >

            <requestFocus />
        </TextView>
    </ScrollView>

And this is what the function looks like :
public void displayOutput()
{
    File sdcard = Environment.getExternalStorageDirectory();
    File file = new File(sdcard,"/Android/data/terminalemulatorlog.txt");
    StringBuilder text = new StringBuilder();
    try
    {
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;

        while ((line = br.readLine()) != null)
        {
            text.append(line);
            text.append('\n');
        }
    }
    catch (IOException e)
    {
        Toast.makeText(getApplicationContext(),"Error reading file!",Toast.LENGTH_LONG).show();
    }
    TextView output=(TextView) findViewById(R.id.output);
    output.setText(text);
    ((ScrollView) findViewById(R.id.scroller)).post(new Runnable()
    {
        public void run()
        {
            ((ScrollView) findViewById(R.id.scroller)).fullScroll(View.FOCUS_DOWN);
        }
    });
}

Now I found a partial solution over here.
Hence the last line bit of code that says :
((ScrollView) findViewById(R.id.scroller)).post(new Runnable()
{
    public void run()
    {
        ((ScrollView) findViewById(R.id.scroller)).fullScroll(View.FOCUS_DOWN);
    }
});

But this works only the first time the text file is loaded. How do I always make the TextView scroll down to the end?

A: Just add to your TextView:
android:gravity="bottom"
android:scrollbars = "vertical"
and set movement method:
myTextView.setMovementMethod(new ScrollingMovementMethod());

A: EDIT:
Use this:
    final ScrollView scroller = (ScrollView) findViewById(R.id.scroller);
    scroller.setOnFocusChangeListener(new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                scroller.fullScroll(View.FOCUS_DOWN);
            }
        }
    });


text:
Q: "no main manifest attribute" maven project So we got the jmjrst project from our prof.
My problem is that whatever I do in my pom.xml there will be no main manifest attribute. This is the last thing I have to do now but I can't get it working.
pom.xml:(whole build part)
<build>
    <plugins>
        <plugin>
            <groupId>a1</groupId>
            <artifactId>1800</artifactId>
            <version>0.0.1-SNAPSHOT</version>
            <dependencies>
                <dependency>
                    <groupId>com.puppycrawl.tools</groupId>
                    <artifactId>checkstyle</artifactId>
                    <version>6.4.1</version>
                </dependency>
            </dependencies>
            <configuration>
                <consoleOutput>true</consoleOutput>
                <configLocation>${basedir}/src/test/resources/checkstyle_swt1.xml</configLocation>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>2.4</version>
            <configuration>
                <descriptor>src/assembly/src.xml</descriptor>
            </configuration>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

    </plugins>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>a1</groupId>
                <artifactId>1800</artifactId>
                <version>0.0.1-SNAPSHOT</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <archive>
                        <manifest>
                            <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                            <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>lib/</classpathPrefix>
                            <mainClass>${basedir}src/main/java/jis/Main.java</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>
</build>


text:
Q: Memory Stick Controller is not compatible with this version of Windows I'm getting this error message in the Action Center on Windows 7, and I can't seem to solve it through Windows or through searches on Google:

RICOH R5C592 PCI-CardBus/IEEE-1394/SD Card/Memory Stick Controller is not compatible with this version of Windows.

Thanks for any help
PS. I wasn't sure if you're allowed to post questions like this, about proprietary software, but I checked the FAQ and it seemed ok.
Response:
The URL I am told to visit it this but I can't tell which I should choose that I am originally presented with, or what to put in to select, as I am not sure what input it is referring to.

A: Your only way forward here is to check the manufacturer's website to see if they have release Windows 7 compatible drivers for the device. Otherwise you will either need to remove it, or just ignore the message and simply not use it.

A: In the link that you provide in your edit, there is a link to "Card Reader Application." I'd say that's a pretty safe bet to try first.


text:
Q: Midlet crashes when calling bluetooth API When I run following code on my phone I get black screen saying there was uncaught exception but whole block is wrapped in try/catch block so it is weird, anyway when I proceed with execution code just gets to "Getting device.." so it obviously fails on this line:
   LocalDevice local = LocalDevice.getLocalDevice();

Here is whole method:
 public void startBT()
            {
            try
                    {
                        f.append("Getting device..");
                        LocalDevice local = LocalDevice.getLocalDevice();
                        f.append("Got local device..");
                        DiscoveryAgent agent = local.getDiscoveryAgent();
                        f.append("Got local discovery agent..");
                        connString = agent.selectService(new UUID(
                                "86b4d249fb8844d6a756ec265dd1f6a3", false),
                                ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
                        f.append("Got connection string - >" + connString);
            }
                    catch (Exception ex)
                    {
                        Alert message = new Alert("info");
                        message.setString(ex.getMessage());
                        Display.getDisplay(this).setCurrent(message);
            }
}

Any ideas?

A: It looks like device I used doesn't support JSR-82 which is J2ME Bluetooth API(this is built into phone, no way of "installing" it) required to use Bluetooth from J2ME Midlets,here is snippet which should check for JSR-82 support:
 public static boolean IsBtJsrComaptible() {
        try {
            Class.forName("javax.bluetooth.LocalDevice");
            return true;
        } catch (Exception e) {
            return false;
        }
    }

Please note that I got uncaught exception trying to run above snippet, but maybe it would work on some other device.


text:
Q: Bootstrap modal opening only with the button I have HTML template which have injected bootsrap modal, but modal opening only with the button. I want that modal open automatically when page load, without button.
So this is the button code:
<button type="button" class="btn btn-success" data-toggle="modal" data-target=".bs-example-modal-sm">Small modal</button>

This is the modal code HTML:

                                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Modal title

                                                        Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo.

                                                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                                                        <button type="button" class="btn btn-success">Save changes</button>

A: You could load the modal on document.ready
After the document loads you can either trigger the click event on the button as
   <button type="button" id="smallModalButton" class="btn btn-success" data-toggle="modal" data-target=".bs-example-modal-sm">Small modal</button>

 $( document ).ready(function() {
         $('#smallModalButton').click();
});

or you could simply toggle the modal as
     $( document ).ready(function() {
             $('.bs-example-modal-sm').modal('toggle');
    });

A: I found a solution. Change the class from fade to show, and add onclick to close button. Code:

Button:
 <button type="button" onclick = "$('.modal').removeClass('show').addClass('fade');"  class="btn btn-default" data-dismiss="modal">Close</button>


text:
Q: Linux script to kill process listening on a particular port I have a process that listens on a TCP port (?0003). From time to time it crashes - badly. It stops working, but continues hogging the port for some time, so I can't even restart it. I'm looking to automate this.
What I do right now is:
netstat -ntlp |grep -P "\*\:\d0003"

To see what the PID is and then:
kill -9 <pid>

Does anyone have a script (or EXE for that matter) that would link the two steps together, ie. parse the PID from the first command and pass it to the second?

A: kill $(netstat -ntpl 2>/dev/null | egrep "^tcp  .*:[0-9]0003"|awk '{print $7}'|cut -d / -f 1 )

You may do kill -9 instead of you think the -9 is required. I redirect the netstat stderr because it omits a message when run as non-root which is unimportant for this purpose. I include tcp in the regex to filter out tcp6.

A: You also can do by that way :
kill -9 $( lsof -i:?0003 -t )

A: there you go, one line for you
netstat -ntlp | awk '$4~/:*0003$/{gsub(/\/.*/,"",$NF);cmd="kill -9 "$NF;system(cmd)}'

A: I take it that the python command is just the first term in the full command, right?
If you have the name of the script being run you can look at something like pgrep -f
If you are sure of uniqueness, you can also use the related pkill -f

A: What about killall <command> are there more than one of these processes?
If that don't work try:
PID=`netstat -ntlp |grep -P "\*\:\d0003"`; kill -9 $PID

That should do the trick.

A: Maybe the fuser command with the -k and -n options may help. Say "man fuser" for more info.