text:
Q: Laravel excel passing varable to exporter I am working with Laravel Excel 3.1 trying to export file using two parameter
web.php {route file}
Route::post('/Download', 'Controller@Download');

and my controller
public function Download(Request $request)
{
$StartDate  =  Input::get('StartDate');
$EndDate = Input::get('EndDate');
$exporter = app()->makeWith(UsersExport::class, compact('StartDate','EndDate'));
return $exporter->download('Summary Detail.xlsx');
}

userExporter.php
class UsersExport implements FromQuery, WithHeadings,ShouldAutoSize
{
use Exportable;
protected $StartDate,$EndDate;
public function __construct(String  $StartDate,String $EndDate)
{
$this->StartDate = $StartDate;
$this->EndDate = $EndDate;
}
public function query()
{
return databaseReceipt::query()
->whereDate('created_at', '>=', $this->StartDate)
->whereDate('created_at', '<=', $this->EndDate)
->select('id','servicename',"created_at");
}
}

when I use static variable like "00:00 01/04/2017" and "00:00 01/01/2018" for start date & end date it works fine which lead me that passing variables doesn't work

A: sorry guys I figured out what was the problem << I think, I was tired that day be cause the solution is easy
in function Download
$S = date('Y-m-d H:i:s', strtotime(strtr($request->StartDate, '/', '-')));
$E = date('Y-m-d H:i:s', strtotime(strtr($request->EndDate, '/', '-')));
return (new UsersExport($S,$E))->download('invoices.xlsx');

just to make it clear my mistake was because of different format date type.
and by the way you can pass as much as you need of variable and any type

A: public function Download(Request $request) { $StartDate = Input::get('StartDate'); $EndDate = Input::get('EndDate'); $exporter = new UsersExport('StartDate','EndDate'); return $exporter->download('Summary Detail.xlsx'); }


text:
Q: Minimum Required SDK - Percentages Does anyone know what percentage of consumers use each operating system for Android?
When choosing the minimum required SDK, you of course want to target the largest audience possible, but lose as few of the programming updates as possible.  For example, while v2.2 may have a wide audience, there are certain features that cannot be used in the program.  But using v4.2 will give you every feature available, but who knows how many people actually have the most up to date version.

A:
Does anyone know what percentage of consumers use each operating system for Android?

This is shown on the Device Dashboards and is reported by damn near every Android blog in existence.
Here, for example, is the just-updated May pie chart:

Note, though, that these dashboards are based on Play Store accesses, and therefore do not count devices that lack the Play Store (e.g., Kindle Fire).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python Selenium - Clicking a button inside an iframe that is inside an iframe, x2 so I'm trying to click a button, but it's inside an iframe, that is inside another iframe, that is inside another iframe..
I can get into the first iframe but I can't seem to be able to get into the third to press the button..
first iframe:

selector: body > div:nth-child(2) > iframe
js path: document.querySelector("body > div:nth-child(2) > iframe")
xpath: /html/body/div[2]/iframe
full xpath: /html/body/div[2]/iframe

second iframe:

selector: #fc-iframe-wrap
js path: document.querySelector("#fc-iframe-wrap")
xpath: //*[@id="fc-iframe-wrap"]
full xpath: /html/body/div/div[1]/div/iframe

third frame:

selector: #CaptchaFrame
js path: document.querySelector("#CaptchaFrame")
xpath: //*[@id="CaptchaFrame"]
full xpath: /html/body/div[2]/div[2]/div[1]/iframe

verify BUTTON:
<button aria-describedby="descriptionVerify" id="home_children_button" class="sc-bdnxRM dboBXq sc-kEqXSa iibXvF">Verify</button>
selector: #home_children_button
js path: document.querySelector("#home_children_button")
xpath: //*[@id="home_children_button"]
full xpath: /html/body/div/div/div[1]/button

And excuse my messy python code, I'm still learning..
print("trying to switch to iframe1")
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"body > div:nth-child(2) > iframe")))
print("im now in frame1")
print("trying to make token slot visible")
driver.execute_script('var element=document.getElementById("Token"); element.style.display="block";')
print("token slot is visible")
print("switching to captcha frame")
###The line below is where it's failing, it is timing out so not finding the correct captcha
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"#CaptchaFrame")))
print("im now in captcha frame")
print("trying to click verify button")
driver.find_element(By.CSS_SELECTOR, '#home_children_button').click()
#WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"#home_children_button"))).click()
print("i clicked verify button..")


text:
Q: Calculating percentage from row vuejs I have a table that has 4 rows: Item Name, Item Cost Price, Item Sell Price & Item Percent. What I am trying to do is calculate the percentage from the Item Cost Price and Item Sell Price and display in in the 'Item Percent' Column.
Please see my current code below:
    <b-col sm="6" lg="9">
  <b-card no-body>
    <b-tabs pills card>
      <b-tab title="Standard" active>
        <template>
          <b-table class="mb-0" responsive="sm" hover striped :items="filtered.products" :fields="columns"></b-table>
        </template>
      </b-tab>
      <b-tab title="Standard w. %">
        <template>
          <b-table class="mb-0" responsive="sm" hover striped :items="filtered.products">
            <template slot="percentage" slot-scope="data">
              {{(products.sellPrice - products.costPrice / product.sellPrice).toFixed(2) + '%'}}
            </template>
          </b-table>
        </template>
    </b-tabs>
  </b-card>
</b-col>

Please let me know if you require more of my code


text:
Q: Leaflet R shiny: select & zoom I'm working on a tool with shiny and leaflet:
I want that when a customer click on the vars (see UI code for exemple NE), the map go to another view for exemple like this in pure leaflet:
  L.easyButton( 'NE', function(){
  //zoomTo.setView([55, -2], 4);
  map.setView([46.95, 6.85], 12);
  }).addTo(map);

Here my R_code (thank you in advance for your answer and support;)

 #UI:
 library(leaflet)

Choices for drop-downs
vars <- c(
"NE" = "NE",
"VD" = "VD",
"VS" = "VS",
"JU" = "JU",
"BE" = "BE",
"GE" = "GE")

navbarPage("Près de chez toi ciao.ch", id="nav",

tabPanel("Interactive map",
div(class="outer",

  tags$head(
    # Include our custom CSS
    includeCSS("styles.css"),
    includeScript("gomap.js")
  ),

  leafletOutput("map", width="100%", height="100%"),

  # Shiny versions prior to 0.11 should use class="modal" instead.
  absolutePanel(id = "controls", class = "panel panel-default", fixed =             TRUE,
    draggable = TRUE, top = 60, left = "auto", right = 20, bottom = "auto",
    width = 330, height = "auto",

    h2("Rechercher "),

    selectInput("canton", "Canton", data$canton,selected = "" )

  ),

  tags$div(id="cite",
    "sddssd"
  )
  )
 ),

tabPanel("Adresses",
                  dataTableOutput('mytable')
)
)

   #SERVER:
         data <- read_csv("~/Desktop/superzip r/Sans titre 2.csv")
    function(input, output, session) {

 ## Interactive Map ###########################################

 # Create the map
 output$map <- renderLeaflet({
 leaflet() %>%
  addTiles(
 urlTemplate = "//{s}.tiles.mapbox.com/v3/jcheng.map-        5ebohr46/{z}/{x}/{y}.png",
    attribution = 'Maps by Mapbox'
  ) %>%
  setView(lng =  6.6328200, lat = 46.5160000, zoom = 12)%>%
  addMarkers(data,lng=data$Longitude,lat=data$Latitude,label =    data$nom)

 })

 ###observation
observe({
canton<-input$canton
 })
output$mytable = renderDataTable({
       data
      },options = list(
        autoWidth = TRUE,
        columnDefs = list(list(width = '200px', targets = "_all"))))}

 #data
 1           Genève     GE 022 329 11 69                                                          www.fegpa.ch  6.164722 46.19853
 2 Chavannes-près-Renens     VD 021 633 44 32                                                        croix-bleue.ch  6.575761 46.53280
 3              Lausanne     VD 021 623 84 84                                                            www.fva.ch  6.611342 46.52284
 4             Neuchâtel     NE 032 889 62 10                                                  http://www.cenea.ch/  6.909872 46.98825
 5              Delémont     JU 032 421 80 80 http://www.addiction-jura.ch  6.411595 46.94195
 6              Lausanne     VD 021 321 29 11                                                www.addictionsuisse.ch  6.626040 46.51873

A: To update a leafletMap you should use leafletProxy, you can read about that here.
The idea is that you need to have a reactive value that is updated when you change the selection, that reactive value is observed by the leafletProxy and its values used to perform the update.
It should look like this:
output$map <- renderLeaflet({
        leaflet(data) %>%
            addTiles(urlTemplate = "//{s}.tiles.mapbox.com/v3/jcheng.map-5ebohr46/{z}/{x}/{y}.png",
                     attribution = 'Maps by Mapbox'
            ) %>%
            setView(lng = 6.6328200, lat = 46.5160000, zoom = 12) %>%
            addMarkers(data$long, data$lat, label = data$nom)
    })

    center <- reactive({
        subset(data, nom == input$canton)
        # or whatever operation is needed to transform the selection
        # to an object that contains lat and long
    })

    observe({
        leafletProxy('map') %>%
            setView(lng =  center()$long, lat = center()$lat, zoom = 12)
    })


text:
Q: What is the convention for Lisp filename extension? ".el" is the convention for filename ending with Emacs Lisp programs. What is the convention when writing Common Lisp programs, please?

A: Wikipedia and the Google Common Lisp Style guide both suggest .lisp.
Practical Common Lisp suggests .lisp or .cl.
Note, I'm not a Common Lisp programmer by any measure, so I have no idea if .lisp is actually used in practice.

A: Common Lisp pathname types for source code:

*

*lisp is the default. Use this if possible.

*lsp if the pathname type allows only three characters

*l if the pathname type should be one character (rare).

The pathname type cl is mostly not used. You can see it sometimes in older code or projects which use several different Lisp dialects.
For compiled code the pathname type can be computed in Common Lisp using the function COMPILE-FILE-PATHNAME (here 64bit LispWorks on a Mac):
CL-USER > (pathname-type (compile-file-pathname "foo.lisp"))
"64xfasl"


text:
Q: BOOTSTRAP - How to remove table border while printing? I can remove while browsing, but when I put the code under the @media print section, nothing happens (I have code inside this block, works perfectly).
Seems like a Chrome default behaviour. Any solutions?


text:
Q: How to Update Ember Model to Show JSON Search Response I feel like this answer to this question is trivial, but I am having a difficult time figuring out how to do this the 'Ember way'.
Quick problem background: I am creating a recipe app with Ember frontend and a Rails API backend. I am implementing a search feature to find recipes based on ingredients. I have already configured my Rails API endpoint which sends back the correct records as JSON.
    Ember.$.get('/recipes_query', {query: query})
    .then(function(reponse) {
        // Do something here
    });

Now all I need to do is display these. What I am confused about is how to handle the data when it is retrieved (or in other words, how to push these to the store, and then ONLY show the most recently retrieved results). I could push these results to the store and then use a filter to display the correct results, but this seems like an extra step - the JSON response already contains everything I need to display. What is the Ember convention for performing this simple task?

A: It would be trivial answer if you would use query instead of jQuery.get, so if possible, refactor to:
this.store.query('recipe', {query: query})
.then(records => {
  // you have everything you need as records
});


text:
Q: Automapper- Map and add elements to list conditionally I have a unique requirement when mapping some elements using Automapper.
I am not finding any effective solution with built scenarios:

*

*I want to add phone number details to the contacts list if the phone number is not null

*I want to add email address details to the contacts list if the email is not null

  CreateMap<UserModel, UserDefinition>()
                .ForMember(d => d.Id, o => o.Ignore())
                .ForMember(d => d.UserName, o => o.MapFrom(s => s.Username))
                .ForMember(d => d.Contacts, o =>
                    new List<UserContactDefinition>()
                    {
                        o.MapFrom(s => !string.IsNullOrWhiteSpace(s.PhoneNumber) ?
                        new UserContactDefinition
                        {
                            Type = ContactType.Phone,
                            IsPrimary = true,
                            Label = s.PhoneType,
                            Value = s.PhoneNumber
                        }: null,
                        o.MapFrom(s => !string.IsNullOrWhiteSpace(s.ContactEmail) ?
                         new UserContactDefinition
                        {
                            Type = ContactType.Email,
                            IsPrimary = true,
                            Label = s.EmailType,
                            Value = s.Email
                        }: null
                    }
                );

This code is not working and I don't want to add empty elements if there is no value.
Any leads to this?

A: For your scenario, you need the Custom Value Resolver to map the destination member for the Contacts property.

*

*Implement UserContactDefinitionListResolver custom value resolver.

public class UserContactDefinitionListResolver : IValueResolver<UserModel, UserDefinition, List<UserContactDefinition>>
{
    public List<UserContactDefinition> Resolve(UserModel src, UserDefinition dst, List<UserContactDefinition> dstMember, ResolutionContext ctx)
    {
        dstMember = new List<UserContactDefinition>();

        if (!string.IsNullOrWhiteSpace(src.PhoneNumber))
            dstMember.Add(new UserContactDefinition
            {
                Type = ContactType.Phone,
                IsPrimary = true,
                Label = src.PhoneType,
                Value = src.PhoneNumber
            });

        if (!string.IsNullOrWhiteSpace(src.ContactEmail))
            dstMember.Add(new UserContactDefinition
            {
                Type = ContactType.Email,
                IsPrimary = true,
                Label = src.EmailType,
                Value = src.ContactEmail
            });

        return dstMember;
    }
}

*Add mapping configuration/profile for the member Contacts to use the UserContactDefinitionListResolver.

CreateMap<UserModel, UserDefinition>()
    .ForMember(d => d.Id, o => o.Ignore())
    .ForMember(d => d.UserName, o => o.MapFrom(s => s.Username))
    .ForMember(d => d.Contacts, o => o.MapFrom(new UserContactDefinitionListResolver()));

Demo @ .NET Fiddle


text:
Q: Can Qt signals can be safely emitted from another QThread I'm using some QThread in my application.
My objects "live" in different threads (their owner threads as Qt means it are different) and use signal/slots with queued connections to communicate.
Now, I have this problem :

*

*Object "A" lives in QThread "A"

*Object "B" lives in QThread "B"

*Gui lives in the "main thread"

then :

*

*Object "A" calls a method B::foo on "B" instance, from its own thread "A"

*the ressources shared by this B::foo method are protected using a mutex, no problem here to execute B::foo from the thread "A"

*inside the B::foo method, object "B" emit the signal barSignal
And I have some questions about his configuration :

*

*Is it safe to emit a signal of object "B" from a thread which is not the "B" owner's QThread ?

*Is it safe to use Qt::AutoConnection to receive this signal in a GUI object who lives in the "Qt main thread" ?

*Is it safe to use a Qt::AutoConnection to receive this signal in a object  "C" who lives in it's own QThread "C" ?
My test tends to say "yes" to everything.
By reading the Qt emit code, it seems to be ok.
But it didn't find anything in the Qt documentation about "emitting signal from a thread which is not the emitter's owner thread".

A: It's safe to emit signals from other threads, if you use auto or queued connections. Auto is deduced to be queued in situations where the signal is emitted in a thread in which the receiving QObject do not have affinity. Direct connections are not thread safe.
There is a "Signals and Slots Across Threads" section in the documentation that deals with emitting signals to objects in different threads.

Queued Connection - The slot is invoked when control returns to the event loop of the receiver's thread. The slot is executed in the receiver's thread.

also

The connection type can be specified by passing an additional argument to connect(). Be aware that using direct connections when the sender and receiver live in different threads is unsafe if an event loop is running in the receiver's thread, for the same reason that calling any function on an object living in another thread is unsafe.
QObject::connect() itself is thread-safe.


text:
Q: Possible reason of different results if adding () in the mysql query SELECT ddlcno,max(id) pq FROM `employee` group by ddlcno having count(ddlcno)>1

Running the above in mysql gives 25 rows. But when I run the same query within() i.e.
(SELECT ddlcno,max(id) pq FROM `employee` group by ddlcno having count(ddlcno)>1 )

It gives me 391 rows. Possible reason for the same?


text:
Q: Javascript to return numbers in href link click How would i return the value '170236' when clicking 'Enquire' in this example?
Enquire

I need it for a variable in Google Tag Manager

A:

function getLastSegment()
{
  var links = document.getElementsByClassName('mylink');
  var link = links[0].href;
  alert(link.substr(link.lastIndexOf('/') + 1));
}
Enquire

A: Got it!
function() {

var links = document.getElementsByClassName('mylink test tester');
var link = links[0].href;
var element = link.substr(link.lastIndexOf('/') + 1);

return element;

}


text:
Q: In java, while using the acm library, how do I set the size of a JTextField? I found that JTextFields can be manipulated easily with acm functions such as setLocation(), as in:
    textfield.setLocation(x,y);

However I cannot seem to be able to find a method that can set the default size of a JTextField.  I tried using setPreferedSize() but it didn't change the size of the JTextField.
Any help would be fantastic.

A:
I cannot seem to be able to find a method that can set the default size of a JTextField.

I don't know that the ACM library has any special methods to do this. I would just look at the API for the JTextField:
JTextField textField = new JTextField(10);

Will make the text field larger enough to hold a minimum of 10 characters.

I found that JTextFields can be manipulated easily with acm functions such as setLocation()

Not sure what the ACM functions are, but you should not be using methods like setLocation(). That is the job of the layout manager to set the location of a component based on the rules of the layout manager that you are using.


text:
Q: Non-greedy capturing parenthesis I have the string mysql://user:pw@host/db?reconnect=true and the following (incorrect) regex: /^mysql:\/\/(.+):(.+)@(.+)\/(.+)\??.*$/
These are the matches I get:
["user", "pw", "host", "db?reconnect=true"]

The only problematic match is "db?reconnect=true", which I intend to be "db"
I have tried non-greedy qualifiers for both the "?" after "db" and after the last capturing parenthesis with no success. It seems like the last capturing parenthesis is greedy no matter what. Is there even a solution for this?
Cheers!

A: You can use a negated character class [^?] to match anything except a question mark ?.
Try this:
^mysql:\/\/(.+?):(.+?)@(.+?)\/([^?]+)

Regex101
Group 1.    `user`
Group 2.    `pw`
Group 3.    `host`
Group 4.    `db`

A: All of your quantifiers are greedy; you need to add ? to make them non-greedy. In this specific case, you need to be careful, because if you don't ensure it must match the GET query separately, non-greediness will omit the b in db too. There are two decent options here:

*

*Explicitly non-greedy: /^mysql:\/\/(.+):(.+)@(.+)\/(.+?)(?:\?.*)?$/ (You need to group the ? with the rest of GET query; if it's optional by itself, the non-greedy code will stop early, ignore the optional ?, and just shove everything into the match on the greedy .*)

*Greedy, but excluding ? from the things it's willing to match: /^mysql:\/\/(.+):(.+)@(.+)\/([^?]+)(?:\?.*)?$/ Since a ? can't occur in a legal URL except when splitting the GET query, we swap from .+ to [^?]+ to keep everything until the ?


text:
Q: Can't detect hard drive partitions? I am trying to install Ubuntu 14.04.4 alongside windows 7 but I can't figure out how to detect all the disk partitions I have already built in Windows. I have done a primary NTFS 30GB disk partition reserved to install ubuntu. But when I try to install Ubuntu from my pendrive it only detects a big 500GB partition. So I'd like to detect all of them so as to install Ubuntu in the place I want. I leave you some screenshots that might be useful.

I'd really appreciate any comment or help!


text:
Q: Save data from custom sql query bound to a DataGrid in C# So I have this problem - I want to allow users of my app to run select queries against a PostgreSql database and I want the data returned by those queries to be bound to a DataSet -> DataGrid. Problem is the "custom" part :). Of course when I try to edit data coming from a query with join clause, then the trouble starts. I'm getting an error saying that UpdateCommand couldn't be automatically generated because of lacking primary key column, which is expected (well, at least I was expecting it)... Solution I came up with is primitive, but good enough for me - I have a list of table names, and when one of those table names is found in custom query, then I want to generate my own UpdateCommand on the fly. So:

*

*I'm having trouble writing regular expression that would get table names from query, so any help would be much appreciated :). Thing is tricky - you've got to remember that table name may also be found as a column name, so the regular expression should be able to filter out that cases.

*Is it generally a good idea in my scenario? Maybe there's a simpler and/or more elegant solution to my problem?

Something like a pseudo code:
string[] names = new string[] { "table1", "table2" };
string customQuery = GetWhateverUserWroteInATextBox();

//what I want to do is to find name coming from names array in the customQuery

I'm calling it a custom query, because the user writes it, and I can't predict what the user input will be.

A: First Question:
As you said the regex is a little tricky ...
        string[] tableNames = new string[] { "table1", "table2" };
        List<string> fields = new List<string>();
        Regex rgx = new Regex(@"\w+(?=\s?,?)");
        MatchCollection matches = rgx.Matches(textBox1.Text);
        foreach (Match m in matches)
        {
            if (!tableNames.Contains(m.Value))
            {
                fields.Add(m.Value);
            }
        }

If U can convince your users that separate fields with , this works fine ;)
If my pattern does not match with your name styles you can make your own patterns and here is some instructions:

*

*MSDN: Regular Expression Language

*MSDN: Regex Class

*MSDN: How to: Search Strings Using Regular Expressions

*Stackoverflow Reference
Second Question:

*

*The way that users enter their own query is not good, because:

*

*For this kind of queries you have to inform users about table and field names. this means you let your guard down and accept some security risks.

*It's not user friendly. Filling a text box with bunch of names and some hard rules is not simple for users. Note that for being a good developer you have to imagine all users are lazy and idiot.

*You can not prevent users's access. If user can make their own query so they can simply make all queries for all of your records and tables. In that case maybe some information have to stay in shadows and you can't guaranty.

*You can not convince users to fallow rules in making new queries and it will cause errors for you and users.

*You can simply make your own interface.

*

*A new interface is a new experience for users so they will loved that.


text:
Q: Making the matrix raining html canvas animation ascend instead of descend So I've been messing around the Matrix raining canvas animation here and was wondering if it was possible to make it rain upwards instead of downwards. I've tried using the rotate() method and it basically skews and sort of stretches the canvas. Any advice?
code:
 var numberOfColumns = 50;
 var pixelsPerColumn = width / numberOfColumns;

 var columnY = [];
 for (var i=0; i<numberOfColumns; i++) {
      columnY[i] = randomInt(0, height);
 }

 var characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*";
 c.font = "12px Courier";

 function step() {
     c.fillStyle = "rgba(0,0,0,0.05)";
     c.fillRect(0, 0, width, height);
     c.fillStyle = "#0f0";
 for (var i=0; i<numberOfColumns; i++) {
     var r = randomInt(0, characters.length);
     var char = characters.substring(r, r+1);
     c.fillText(char, i*pixelsPerColumn, columnY[i]);
     columnY[i] += pixelsPerColumn;
    if (columnY[i] > height) {
     columnY[i] -= height;
    }
 }
}
loop(step, 100);;

A: Easy.
columnY[i] -= pixelsPerColumn; //subtract instead of add
if (columnY[i] < 0) { //if less than zero (the top)
  columnY[i] += height; //add height instead of removing it
}


text:
Q: Data Refresh Error after upgrade PowerPivot from 2008R2 to 2012 after upgrading PowerPivot for SharePoint I cannot refresh the data in all the workbooks. Error appears when opening a workbook in the gallery or in the Scheduled-Data-Refresh.
1. Gallery / SharePoint Integrated
"There was an error....blah blah blah"
and in the Windows Event Log:
"Activation context generation failed for "\Program Files\Microsoft Analysis Services\AS OLEDB\110\msolap110.dll". Dependent Assembly Microsoft.AnalysisServices.ChannelTransport,processorArchitecture="MSIL",publicKeyToken="89845dcd8080cc91",version="11.0.0.0" could not be found. Please use sxstrace.exe for detailed diagnosis."
2. Scheduled Data Refresh
"Microsoft.AnalysisServices.XmlSerializationException: Deserialization failed: The 'FormatString' element in the 'htt://schemas.microsoft.com/analysisservices/2011/engine/300/300' namespace is unexpected. ---> Microsoft.AnalysisServices.XmlSerializationException: The 'FormatString' element in the 'htt://schemas.microsoft.com/analysisservices/2011/engine/300/300' namespace is unexpected.     at Microsoft.AnalysisServices.DesignXmlReader.ReadStructContent(Object obj, StructMapping mapping)     at Microsoft.AnalysisServices.DesignXmlReader.ReadObjectContent(Object value, Type type, TypeMapping mapping)     at Microsoft.AnalysisServices.DesignXmlReader.ReadClassObject(Type type, MemberMapping mm)     at Microsoft.AnalysisServices.DesignXmlReader.ReadArrayContent(Object array, Array..."
3. Installation Files
I cannot start the SQL Server PowerPivot Configuration Tool (via Installation Center), it is greyed out! But the Version of my PowerPivot Instance is 11.XXXX!
It seems that the "Microsoft.AnalysisServices.SharePoint.Integration" dll files in the Windows-Assembly folder were not updated as they still show the version 10.0.0.0!
What I've done:
I followed this instruction:
htt://technet.microsoft.com/en-us/library/ee210646(v=sql.110).aspx
The only thing is: It says I need to install CummUpdate for August 2010 even after I installed SP1 for SharePoint! That is not possible as the built for SP1 is higher than the Aug2010CummUpdate...
Any Ideas?
Thanks a lot


text:
Q: How to bulk transfer reports from one .org to another .org? My task is to upload all of the reports of an old .org to a completely new .org
I found that it is possible to retrieve reports via .xml-files from an old .org and upload it to a new org via workbench. Like this
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
<types>
   <members>FOLDERA/REPORTA</members>
   <members>FOLDERB/REPORTB</members>
   <name>Report</name>
</types>
<version>43.0</version>

I've tested this way and it does work fine
BUT
the old .org contains thousands of reports and it would be quite tiresome to go through each folder at a time, customizing the .xml files each time.
Is there a way to mass download, transfer and upload all the reports and files at once, so that I have the exact same structure in the new and yet "clean" .org?
I'd appreciate any feedback!
Thank you already in advance!
UPDATE:
The suggestion from @Badbuxx, just retrieved an empty folder called "unpacked" cotaining the .xml file called "packaged" but unfortunately nothing more.
<?xml version="1.0" encoding="UTF-8"?>
<Package
xmlns="http://soap.sforce.com/2006/04/metadata">
<types>
    <members>*</members>
    <name>Report</name>
</types>
<version>43.0</version>


text:
Q: Java 8 DateTimeFormatter's symbol "F" In java.time.format.DateTimeFormatterBuilder:
/** Map of letters to fields. */
private static final Map<Character, TemporalField> FIELD_MAP = new HashMap<>();

static {
    // SDF = SimpleDateFormat
    // ...
    FIELD_MAP.put('F', ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH);  // SDF, LDML
    // ...
}

It shows that the symbol "F" may have the same meaning in SimpleDateFormatter(SDF).
In SDF, the symbol "F" means the ordinal of designated day of week, such as "the second Sunday in May" , Mother's Day (US).
With SDF, I can define Mother's Day (US) in 2021 by "2021-05-2-Sun" with pattern "yyyy-MM-F-EEE".
But any pattern with the symbol "F" with DateTimeFormatter may cause a DateTimeParseException.
I found an issue that is already "fixed":
[JDK-8169482]java.time.DateTimeFormatter javadoc: F is not week-of-month
But it only "fixed" the javadoc! Σ(っ °Д °;)っ
The symbol "F" is still with an undefined behavior.
The confusing description in SDF "F: Day of week in month" may be the reason.

A: Since the resolution of the bug was to fix the documentation, rather than to fix the DateTimeFormatter's implementation, it seems like F meaning ALIGNED_DAY_OF_WEEK_IN_MONTH is actually intended, and it's only that the // SDF comment hasn't been corrected.
And because it means ALIGNED_DAY_OF_WEEK_IN_MONTH, a date such as "2021-05-2-Sun" doesn't make much sense. You've only given a month and a year, and the day of the week. That's not enough information to figure out which day of month it is. It doesn't happen with "2021-05-2-Sun", but in cases like "2021-05-2-Mon", the day of week (Mon), and the aligned day of week (2) can even say different things about which day of week it should be. :)
To parse an "nth day-of-week", you need ALIGNED_WEEK_OF_MONTH, which DateFormatter doesn't have a symbol for. (Note that W is the non-aligned week of month.) But don't worry, you can append any TemporalField into the pattern with appendValue:
DateTimeFormatter formatter =
    new DateTimeFormatterBuilder()
        .appendPattern("yyyy-MM-")
        .appendValue(ChronoField.ALIGNED_WEEK_OF_MONTH)
        .appendPattern("-EEE").toFormatter(Locale.ENGLISH);

Usage:
System.out.println(LocalDate.parse("2021-05-2-Sun", formatter));
// 2021-05-09


text:
Q: CS50 valid triangle — incorrect code output The code below compiles, runs, and takes input, but it does not output true or false as intended. I'm not sure what I am doing wrong.
#include <stdio.h>
#include <cs50.h>

//int add_two_ints(int a, int b);
bool valid_triangle (float a, float b, float c);
int main (void)
{

        float a = get_float("Enter Side 1:");
        float b = get_float("Enter Side 2:");
        float c = get_float("Enter Side 3:");
}

bool valid_triangle (float a, float b, float c)
{   //checks if two sides are greater than one
    if ((a + b <= c) || (a + c <= b) || (b + c <= a))
    {
        return false;
    }

    //checks for positive sides
    if (a <= 0 || b <= 0 || c <= 0 )
    {
        return false;
    }
     //if conditions are met print true
    else
        return true;
}

A: Nothing in your code will run unless it is called in the main function. main is what runs when you start your code.
Your valid_triangle function has only been defined, telling the rest of the code how it works and what kinds of values it accepts, but it will not run unless called. Add a call to your valid_triangle function within main, and it will execute the function based on its definition.
int main (void)
{

        float a = get_float("Enter Side 1:");
        float b = get_float("Enter Side 2:");
        float c = get_float("Enter Side 3:");
        bool isValid = valid_triangle(a, b, c);
}

By adding this final line into main, the program will run your function with the three triangle sides and collect the output in a boolean value. How you use the value is up to you. Just make sure it is written in main, or is called by main.

EDIT: Your printf function is using the %d identifier, which means take the next argument (result) and treat it like an integer (0 for false, 1 for true). C does not have a similar identifier for boolean values because they are typically used to control portions of the code, and not be the direct output.
There are many ways to print out true or false, but here is a more beginner-friendly version:
// Check if result is true
if (result)
{
    printf("%s", "true");
}
else
{
    printf("%s", "false");
}

Depending on the boolean value of result, the code will print a different string to correspond to that value. To see the most condensed form that accomplishes this, see What is the printf format specifier for bool?.

A: I think from what i see in your code that you didn't call the function " valid_triangle " to consulte the output of it ..


text:
Q: How to solve differential equation of this type? So, I tried so solve the first equation, where I am looking for $p_2$, in Mathematica with next command:
x:=DSolve[Derivative[p2,z]==-p1*p1der/p0-8*p1/p0-8*p0der/p0^2-
p0der*p2/p0,p2,z]

but i got The function p2 appears with no arguments. I also before that defined:
p0:=(1+64*(1-z))^0.5
p1:=8*(1/p0-1)
p0der:=z derivative(p0) !this is not code, just command
p1der:=z derivative(p1) !this is not code, just command

What should i do to solve first $p_2$, after that $p_3$ symbolic in Mathematica, i am beginner I have no idea what could be mistake and how big is it?

A: p0[z_] := Sqrt[1 + 64 (1 - z)];
p1[z_] := 8 (1/p0[z] - 1);

eqns = {p2'[z] == (-p1[z] p1'[z] + 8 (-p1'[z] - p0'[z]/p0[z]) - p0'[z] p2[z])/p0[z],
        p3'[z] == (-p1'[z] p2[z] - p1[z] p2'[z] - 8 p2'[z] - 8 p1'[z]/p0[z] +
        8 p1[z] p0'[z]/p0[z]^2 - p0'[z] p3[z])/p0[z]} // Simplify;

sol = DSolve[eqns, {p2, p3}, z][[1]]

(* {p2 -> Function[{z},
   C[1]/Sqrt[65 - 64 z] - (4 (8 + (65 - 64 z) Log[65 - 64 z]))/(65 - 64 z)^(3/2)],
    p3 -> Function[{z}, -((512 C[1])/((4160 - 4096 z) Sqrt[65 - 64 z])) +
      C[2]/Sqrt[65 - 64 z] - (1/((65 - 64 z)^(5/2)))
    32 (2 (61 - 65 Sqrt[65 - 64 z] + 64 (-1 + Sqrt[65 - 64 z]) z) + (-65 + 64 z)
         Log[65 - 64 z])]} *)

Verifying that the solutions satisfy the equations,
eqns /. sol // Simplify

(* {True, True} *)

The functions are real when
FunctionDomain[#, z] & /@ ({p2[z], p3[z]} /. sol)

(* {z < 65/64, z < 65/64} *)

The asymptotic values as z -> -Infinity are
Limit[#[z] /. sol, z -> -Infinity] & /@ {p2, p3}

(* {0, 0} *)

Setting the arbitrary constants (C[1] and C[2]) to zero and plotting
Plot[
 Evaluate[{p2[z], p3[z]} /. sol /. {C[1] -> 0, C[2] -> 0}],
 {z, -5, 65/64},
 PlotLegends -> Placed[{p2, p3}, {0.25, 0.75}]]


text:
Q: proof of uniform convergence of sequence of functions
Let be $f_n$ a sequence of functions with $f_n:\mathbb{R}\supset[\alpha, \beta] \to \mathbb{R}$ and $f_n$ continuous and bounded for all $n\in \mathbb{N}$. Further, $f_n$ converges point-wisely: $\lim\limits_{n\to\infty}f_n(x) = f(x)$, where $f(x)$ is also continuous and bounded for all $x\in[\alpha, \beta]$.

Can I conclude that $f_n$ converges uniformly?
I tried to construct a finite covering of $[\alpha,\beta]$ which should have delivered a $n_0$ such that for all $n>n_0$ the condition of uniform convergence holds. However, it didn't work...
May be it is not possible with further assumptions. In that case I would be interested in which further assumptions I need to prove uniform convergence?

A: No, that is not true. Take, for instance, $f_n\colon[0,1]\longrightarrow\Bbb R$ defined by $f_n(x)=nx(1-x)^n$. Each $f_n$ is continuous and bounded and $(f_n)_{n\in\Bbb N}$ converges uniflmly to the null function. But the convergence is not uniform, since$$(\forall n\in\Bbb N):f\left(\frac1{n+1}\right)=\left(\frac n{n+1}\right)^{n+1}\text{ and }\lim_{n\to\infty}\left(\frac n{n+1}\right)^{n+1}=\frac1e\ne0.$$However, if, for each $x\in[\alpha,\beta]$, the sequence $(f_n(x))_{n\in\Bbb N}$ is increasing (or if, for each $x\in[\alpha,\beta]$, the sequence $(f_n(x))_{n\in\Bbb N}$ is decreasing), then, yes, the convergence is uniform; that's Dini's theorem.

A: The statement is not true. For instance, $f_n(x)=n x (1-x^2)^n$ is pointwize convergent to $f = 0$, but the corresponding integrals satisfy
$$
\int_0^1 f_n(x)dx= \frac{n}{2+2n} \to \frac 12 \ne 0.
$$


text:
Q: Expression with IIF conditional showing only "ERROR" in corresponding textboxes I am trying to run a conditional function in an SSRS expression, that conditionally renders a "-" if any of the fields are empty, and otherwise performs some arithmetic.
The problem is that the control doesn't seem to go to the second condition at all. I am getting the fields in the Report filled with "ERROR".
=IIf(IsNothing(Fields!sales_overall.Value Or Fields!current.Value) = false,
     "-" ,
     Fields!sales_ overall.Value/Fields!current.Value)

Can anyone point out what I'am doing wrong here?

A: There are two issues, I am seeing.

*

*You don't need to compare isNothing output to false.

*SSRS gives  #Error because of data type mismatch.
Make sure Sales_Overall and Current value doesn't have commas or anything that makes them text instead of a number.
Try this first
=IIf(IsNothing(Fields!sales_overall.Value) Or ISNothing(Fields!current.Value),
     "-" ,
     Fields!sales_overall.Value/Fields!current.Value)

If this doesn't work, do the explicit conversion
=IIf(IsNothing(Fields!sales_overall.Value) Or ISNothing(Fields!current.Value) ,
     "-" ,
     CDBL(Fields!sales_overall.Value)/CDBL(Fields!current.Value))

OR
=IIf(IsNothing(Fields!sales_overall.Value) Or ISNothing(Fields!current.Value),
     "-" ,
     CDEC(Fields!sales_overall.Value)/CDEC(Fields!current.Value))


text:
Q: Rel: le_antisymmetric comprehension Rel chapter from Logical foundations. I was given a solution to the excersize that I'm trying to comprehend:
Definition antisymmetric {X: Type} (R: relation X) :=
  forall a b : X, (R a b) -> (R b a) -> a = b.

Theorem le_antisymmetric :
  antisymmetric le.
Proof.
  unfold antisymmetric. intros a b [| b' H1] H2.
  - reflexivity.
  - absurd (S b' <= b').
    + apply le_Sn_n.
    + etransitivity ; eassumption.

I don't understand, how does intro pattern [| b' H1] work? After intros it shows:
2 subgoals (ID 43)

  a, b : nat
  H2 : a <= a
  ============================
  a = a

subgoal 2 (ID 46) is:
 a = S b'

2-nd subgoal:
a, b, b' : nat
H1 : a <= b'
H2 : S b' <= a
============================
a = S b'

I understand that it is equivalent to destruct, but what sort of destruct? It's definitely not a simple destruct b.
Also I'm trying to understand the logics behind using absurd (S b' <= b') tactics. Does it mean that if we prove that a = S b' in this context, it would imply that after we rewrite a to S b' in H1, we get: S b' <= b', which is a universally false statement (absurd)?

A: intros a b [| b' H1] H2 is equivalent to
intros a b H H2.
destruct H as [| b' H1].

destruct patterns generally follow the rules that if an inductive type has a single constructor (e.g. products) then for x in that inductive type, destruct x as [a b c...] does (non-recursive) induction and renames the new variables to a, b, c, etc. When the inductive type has more than one constructor, there are multiple cases. For that, you use destruct x as [a b c ... | d e f ... | ...]. These destruction patterns can be nested if needed, e.g. destruct x as [[a b] | [c [d | e]]]. Note that if a constructor takes no arguments, there is nothing to rename, so you can leave the pattern empty.
In particular, something like a natural number can be destructed with destruct n as [ | n']. This divides into the cases where n is zero (and the constructor has no arguments, so there's nothing to the left of the |) or n is the successor of n'. Similarly, a list could be destructed as destruct li as [ | a li'] to divide into the cases where the list is nil and where it is cons a li'. The space to the left of the | is unnecessary, so you could do destruct li as [| a li'].
What's happening in your case specifically is that le is defined as an inductive type something along the lines of
Inductive le (n : nat) : nat -> Prop :=
| le_n : le n n
| le_S : forall m : nat, le n m -> le n (S m).

So there are two cases: one with no arguments, and the successor case where the arguments are m: nat and H: le n m. Hence, the destruct pattern is [| m H].

To answer your second question, absurd (S b' <= b'). means that (we think) we're able to prove S b' <= b' in the current context. We can also prove (in the same context) that S b' <= b' is absurd, i.e. leads to a witness of False (more precisely, S b' <= b' -> False). Using the induction principle for False, this allows us to generate a witness for any type, and in particular for a = S b'.
You can see what kind of proof term absurd produces with a minimal experiment.
Goal forall A B: Type, A.
Proof.
  intros A B.
  absurd B.
  Show Proof.

This should print (fun A B : Type => False_rect A (?Goal ?Goal0)). The first goal (?Goal) has type ~B (i.e. B -> False). The second goal (?Goal0) has type B. If we can provide both, then ?Goal ?Goal0 has type False, so False_rect A (?Goal ?Goal0) produces a witness of type A.


text:
Q: Android MapView - Custom Polygon Overlays not resetting properly on a pan or Zomm I am writing an app that requires polygons to be shown on a map.  I researched and found the best way to do it was to subclass the Overlay Class and override the draw method. It works fine--but when I scroll or pan, the shape and canvas location of the original polygon(s) do not go away - so as I pan I keep getting more and more polygons of the same shape - same when I zoom.  Here is the code for my custom Overlay.  Once I get my coordinates for the polygon shape, I call the setOverlayType method - so that the draw method has the data it needs to figure out where to draw the polygon.
It's probably something stupid!!
public class myOverLay extends Overlay {

public final int OVERLAY_TYPE_NORMAL = 0;
public final int OVERLAY_TYPE_SCALED = 1;

private GeoPoint pVerts[];
private GeoPoint pCenter;
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private Path path = new Path();
private Context mContext;
private int overlayType;
private String pName = "";

public myOverLay(Context context) {
    super();
    this.mContext=context;
}

public void setOverlayType(GeoPoint[] polyVerts, GeoPoint polyCenter, int overlayT, String pn) {
    this.pVerts = polyVerts;
    this.pCenter = polyCenter;
    this.overlayType = overlayT;
    this.pName = pn;
}
@Override
public void draw(Canvas canvas, MapView mapview, boolean shadow)
{
super.draw(canvas,mapview,false);
Projection projection = mapview.getProjection();
Point pVert = new Point(0,0);

if(this.overlayType==0)
    paint.setColor(android.graphics.Color.argb(50, 255, 0, 0));
else
    paint.setColor(android.graphics.Color.argb(50, 255, 255, 0));

paint.setStrokeWidth(2);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setAntiAlias(true);

path.setFillType(Path.FillType.EVEN_ODD);
projection.toPixels(this.pVerts[0],pVert);
path.moveTo(pVert.x, pVert.y);
for(int x=0;x<=5;x++)
{
    projection.toPixels(this.pVerts[x],pVert);
    path.lineTo(pVert.x, pVert.y);
}
path.close();

Log.v("OVERLAY", "Draw Method Called");
canvas.drawPath(path, paint);

if(this.overlayType==0) //Icon
{
    Point centerPt = new Point();
    projection.toPixels(this.pCenter, centerPt);
    Bitmap bmap=BitmapFactory.decodeResource(this.mContext.getResources(),     R.drawable.my_image);
    bmap = Bitmap.createScaledBitmap(bmap,20, 40, true);
    canvas.drawBitmap(bmap, centerPt.x-10, centerPt.y-50, null);
}
}

}

A: Answer to my own question - I moved the Paint and Path variables from class variables to local variables within the draw method - something stupid indeed - map now pans, zooms and scrolls nicely with the polygon.


text:
Q: Passing multiple arguments with SHELL_EXEC I've got a small c++ script on my raspberry pi which I want to execute from PHP on my small webserver, when I run the following command in my CLI the code executes : "/home/pi/kaku 1 a on". But when I run the following PHP code on my webserver shell_exec("/home/pi/kaku 1 a on"); the code that gets triggered by php simply doesn't run, When I don't give in any parameters by running shell_exec("/home/pi/kaku"); Than I simply get response that I need to fill in the parameters. The c++ code can be found overhere: https://github.com/chaanstra/raspKaku
The permissions of /home/pi/kaku has been set to 777 by using chmod for testing purposes. I am wondering why is my code not running?


text:
Q: Histogram Equalization of matplotlib color tables I'm new to python and matplotlib and I was wondering whether anyone knew if there were any utilities available to do the equavalent of histogram equalization but to a matplotlib color table? There is a function called matplotlib.colors.Normalize which, if given a image array, will automatically set the bottom and top levels but I want something more intelligent that this. I could always just apply histogram equalization to the data itself but I would rather not touch the data. Any thoughts?

A: You have to create your own image-specific colormap, but it's not too tricky:
import pylab
import matplotlib.colors
import numpy

im = pylab.imread('lena.png').sum(axis=2) # make grayscale
pylab.imshow(im, cmap=pylab.cm.gray)
pylab.title('orig')
imvals = numpy.sort(im.flatten())
lo = imvals[0]
hi = imvals[-1]
steps = (imvals[::len(imvals)/256] - lo) / (hi - lo)
num_steps = float(len(steps))
interps = [(s, idx/num_steps, idx/num_steps) for idx, s in enumerate(steps)]
interps.append((1, 1, 1))
cdict = {'red' : interps,
         'green' : interps,
         'blue' : interps}
histeq_cmap = matplotlib.colors.LinearSegmentedColormap('HistEq', cdict)
pylab.figure()
pylab.imshow(im, cmap=histeq_cmap)
pylab.title('histeq')
pylab.show()

A: Histogram equalization can be applied by modifying the palette (or LUT) of your image, so it would the definition of a palette that is equalized.
I searched a bit and couldn't find source code for computing an equalized palette, so unless something exitss you would have to code it yourself.
You should be started with the description of the algorithm on the Wikipedia article.
You could also ask for help on the matplotlib lists.


text:
Q: I decided not to ____
A: Did you play tennis last weekend?
B: No, I wasn't feeling so well, so I decided not to _____.

What CAN'T you say in the blank?
a. (nothing)
b. do
c. do so
d. do it
e. do that
f. play
g. play tennis
h. play tennis last weekend

Why do I ask this question?
Because I know that you can end the sentence with "to" as in (a). And I also know that you can add "do so/it/that" after "to". And I also know that you can repeat the verb phrase with or without "last weekend".
But I can't find a rule that you can omit the object and just use "play" as in (f), although somehow (f) does sound fine to my ears.
When can we end the sentence with a lexical verb (e.g., play) and omit its object (e.g., tennis)?
Could someone find me some authoritative source on this particular point?

A: If you put (b) "do" in the blank, the sentence would be incomplete.

*I wasn't feeling so well, so I decided not to do.

The other versions would be all correct, even (f) which omits the direct object because it is so obvious.


text:
Q: How to implement the concept of particles entering an open network according to a Poisson process with a rate different from the rate in the network [Poisson Process with different rates][1]
[Poisson Process with different rates][2]
! [1]: https://i.stack.imgur.com/LJ87x.png
![2]: https://i.stack.imgur.com/xJsB4.png
How do I choose if the next poisson clock a particle is going to enter the network or go through the network?


text:
Q: Create a map from existing variables (e.g. a Java equivalent to JavaScript's `{varA, varB, varC}`) I'm primarily a JavaScript developer, but am currently working on some Groovy code and haven't been able to figure out how to do something that's super-simple in JavaScript.
The JavaScript equivalent of what I'm trying to do follows.
I'm specifically trying to figure out the Java (or Groovy) equivalent of creating an object in JS (map in Java) out of just the existing variable names, e.g. {a, b, c} shorthand in the code snippet below.  Any guidance will be much appreciated!

javaScriptExample()

function javaScriptExample () {
  // the variables already exist in the program that I'm working in
  const a = 'a'
  const b = 'bee'
  const c = 'see'

  //                ➡ Here's where I'm stuck. ⬅
  // I simply want to be able to arbitrarily pass variable keys and values
  // as a map to another function, _using just the variable keys_,
  // e.g. the equivalent of JavaScript's `{a, b, c}` in the next call
  doOtherStuffWithVariables({a, b, c})
}

function doOtherStuffWithVariables (obj) {
  for (const key in obj) {
    console.log(`variable ${key} has a value of "${obj[key]}" and string length of ${obj[key].length}`)
  }
}

A: As stated, there is no shortcut in Groovy.  But if you want/need this
syntax, you can achieve this with Groovy
Macros.
E.g. a very straight forward attempt:
@Macro
static Expression map(MacroContext ctx, final Expression... exps) {
    return new MapExpression(
        exps.collect{
            new MapEntryExpression(GeneralUtils.constX(it.getText()), it)
        }
    )
}

Usage:
def a = 42
def b = 666

println(map(a,b))
// → [a:42, b:666]

A: Unfortunately there's no direct counterpart in Groovy or Java for object deconstruction in JS. Although you can use map literals to write a similar code:
def doStuff( Map obj ) {
  obj.each{ key, val ->
    println "variable $key has a value of '${val}' and string length of ${obj[key].size()}"
  }
}

def example(){
  def a = 'a'
  def b = 'bee'
  def c = 'see'

  doStuff( a:a, b:b, c:c )
}

A: I am not sure what you exactly want to do, but afaik, there is nothing similiar in java.
You could use tho the "new" methods in the java collections library:
    String a = "a";
    String b = "b";
    String c = "c";

    Map.of("a", a, "b", b, "c", c);
    List.of(a,b,c)

But you should keep in mind, those methods are returning unmodifiable objects.
JavaDoc: Returns an unmodifiable list containing three elements. See Unmodifiable Lists for details.

A: As already said, this is not possible in Groovy, because as soon as you use a variable a in your code, then the value of that variable is passed and the name is forgotten.
However, I have also a solution which involves an intermediate object holding the properties to be interrogated:
def toMap(obj) {
    obj.properties.collectEntries {
        [(it.key):it.value]
    }
}

def ex =
  new Expando().tap {
    a = 'A'
    b = 'B'
  }

assert toMap(ex) == [a:'A', b:'B']

The involves the dynamically expandable object feature.


text:
Q: iOS 11 custom back button Issue
I want back button at this position in iOS 11.
Code that I used on till now (iOS 10) doesn't work on iOS 11.
Here's a code:
let barBtnNeg = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace, target: self, action: nil)
barBtnNeg.width = -15.0
let btn: UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 27))
btn.setBackgroundImage(UIImage(named: "BackArrow"), for: UIControlState());
// Was CustomStatusViewController Changed to ChatThreadInfoViewController
btn.addTarget(self, action: #selector(ChatThreadInfoController.backButtonAction(_:)), for: UIControlEvents.touchUpInside)
let barBtnBack = UIBarButtonItem(customView: btn)
self.navigationItem.leftBarButtonItems = [barBtnNeg, barBtnBack]

Code that I use in iOS 11 for this:
let view = UIView()
view.frame = CGRect(x: 0, y: 0, width: 40, height: 27)
let btn: UIButton = UIButton(frame: CGRect(x:-14, y: 0, width: 30, height: 27))
btn.setBackgroundImage(UIImage(named: "BackArrow"), for: UIControlState());
btn.addTarget(self, action: #selector(RoomMessageController.leftNavBackButtonPressed(_:)), for: UIControlEvents.touchUpInside)
btn.center = CGPoint(x: btn.center.x,y :view.center.y)
let tap = UITapGestureRecognizer(target: self, action: #selector(RoomMessageController.leftNavBackButtonPressed(_:)))
view.addGestureRecognizer(tap)
view.isUserInteractionEnabled = true
view.addSubview(btn)
let leftButtonItem = UIBarButtonItem(customView: view)
//add view to nav bar
self.navigationItem.leftBarButtonItem = leftButtonItem

Issue is in iOS 11 sometimes by using above code I am not able to tap properly on button and I can't use default back button because I need custom action?

A: According to your question, you just need to display custom image instead of default back button. So I'd suggest you to use simple UIBarButtonItem initializer:
let backItem = UIBarButtonItem(image: UIImage(named: "BackArrow"),
                               style: .plain,
                               target: self,
                               action: #selector(ChatThreadInfoController.backButtonAction(_:)))
self.navigationItem.leftBarButtonItem = backItem

It will use correct frame for this button so you won't experience any problem with tapping.


text:
Q: perl6: Cannot unbox 65536 bit wide bigint into native integer I try some examples from Rosettacode and encounter an issue with the provided Ackermann example: When running it "unmodified" (I replaced the utf-8 variable names by latin-1 ones), I get (similar, but now copyable):
$ perl6 t/ackermann.p6
65533
19729 digits starting with 20035299304068464649790723515602557504478254755697...
Cannot unbox 65536 bit wide bigint into native integer
  in sub A at t/ackermann.p6 line 3
  in sub A at t/ackermann.p6 line 11
  in sub A at t/ackermann.p6 line 3
  in block <unit> at t/ackermann.p6 line 17

Removing the proto declaration in line 3 (by commenting out):
$ perl6 t/ackermann.p6
65533
19729 digits starting with 20035299304068464649790723515602557504478254755697...
Numeric overflow
  in sub A at t/ackermann.p6 line 8
  in sub A at t/ackermann.p6 line 11
  in block <unit> at t/ackermann.p6 line 17

What went wrong? The program doesn't allocate much memory. Is the natural integer kind-of limited?
I replaced in the code from Ackermann function the  with m and the  with n for better terminal interaction for copying errors and tried to comment out proto declaration. I also asked Liz ;)
use v6;

proto A(Int \m, Int \n) { (state @)[m][n] //= {*} }

multi A(0,      Int \n) { n + 1 }
multi A(1,      Int \n) { n + 2 }
multi A(2,      Int \n) { 3 + 2 * n }
multi A(3,      Int \n) { 5 + 8 * (2 ** n - 1) }

multi A(Int \m, 0     ) { A(m - 1, 1) }
multi A(Int \m, Int \n) { A(m - 1, A(m, n - 1)) }

# Testing:
say A(4,1);
say .chars, " digits starting with ", .substr(0,50), "..." given A(4,2);

A(4, 3).say;

A: Please read JJ's answer first. It's breezy and led to this answer which is effectively an elaboration of it.
TL;DR A(4,3) is a very big number, one that cannot be computed in this universe. But raku(do) will try. As it does you will blow past reasonable limits related to memory allocation and indexing if you use the caching version and limits related to numeric calculations if you don't.

I try some examples from Rosettacode and encounter an issue with the provided Ackermann example

Quoting the task description with some added emphasis:

Arbitrary precision is preferred (since the function grows so quickly)

raku's standard integer type Int is arbitrary precision. The raku solution uses them to compute the most advanced answer possible. It only fails when you make it try to do the impossible.

When running it "unmodified" (I replaced the utf-8 variable names by latin-1 ones)

Replacing the variable names is not a significant change.
But adding the A(4,3) line shifted the code from being computable in reality to not being computable in reality.
The example you modified has just one explanatory comment:

Here's a caching version of that ... to make A(4,2) possible

Note that the A(4,2) solution is nearly 20,000 digits long.
If you look at the other solutions on that page most don't even try to reach A(4,2). There are comments like this one on the Phix version:

optimised. still no bignum library, so ack(4,2), which is power(2,65536)-3, which is apparently 19729 digits, and any above, are beyond (the CPU/FPU hardware) and this [code].

A solution for A(4,2) is the most advanced possible.
A(4,3) is not computable in practice
To quote Academic Kids: Ackermann function:

Even for small inputs (4,3, say) the values of the Ackermann function become so large that they cannot be feasibly computed, and in fact their decimal expansions cannot even be stored in the entire physical universe.

So computing A(4,3).say is impossible (in this universe).
It must inevitably lead to an overflow of even arbitrary precision integer arithmetic. It's just a matter of when and how.
Cannot unbox 65536 bit wide bigint into native integer
The first error message mentions this line of code:
proto A(Int \m, Int \n) { (state @)[m][n] //= {*} }

The state @ is an anonymous state array variable.
By default @ variables use the default concrete type for raku's abstract array type. This default array type provides a balance between implementation complexity and decent performance.
While computing A(4,2) the indexes (m and n) remain small enough that the computation completes without overflowing the default array's indexing limit.
This limit is a "native" integer (note: not a "natural" integer). A "native" integer is what raku calls the fixed width integers supported by the hardware it's running on, typically a long long which in turn is typically 64 bits.
A 64 bit wide index can handle indices up to 9,223,372,036,854,775,807.
But in trying to compute A(4,3) the algorithm generates a 65536 bits (8192 bytes) wide integer index. Such an integer could be as big as 265536, a 20,032 decimal digit number. But the biggest index allowed is a 64 bit native integer. So unless you comment out the caching line that uses an array, then for A(4,3) the program ends up throwing the exception:

Cannot unbox 65536 bit wide bigint into native integer

Limits to allocations and indexing of the default array type
As already explained, there is no array that could be big enough to help fully compute A(4,3). In addition, a 64 bit integer is already a pretty big index (9,223,372,036,854,775,807).
That said, raku can accommodate other array implementations such as Array::Sparse so I'll discuss that briefly below because such possibilities might be of interest for other problems.
But before discussing bigger arrays, running the code below on tio.run shows the practical limits for the default array type on that platform:
my @array;
@array[2**29]++; # works
@array[2**30]++; # could not allocate 8589967360 bytes
@array[2**60]++; # Unable to allocate ... 1152921504606846977 elements
@array[2**63]++; # Cannot unbox 64 bit wide bigint into native integer

(Comment out error lines to see later/greater errors.)
The "could not allocate 8589967360 bytes" error is a MoarVM panic. It's a result of tio.run refusing a memory allocation request.
I think the "Unable to allocate ... elements" error is a raku level exception that's thrown as a result of exceeding some internal Rakudo implementation limit.
The last error message shows the indexing limit for the default array type even if vast amounts of memory were made available to programs.
What if someone wanted to do larger indexing?
It's possible to create/use other @ (does Positional) data types that support things like sparse arrays etc.
And, using this mechanism, it's possible that someone could write an array implementation that supports larger integer indexing than is supported by the default array type (presumably by layering logic on top of the underlying platform's instructions; perhaps the Array::Sparse I linked above does).
If such an alternative were called BigArray then the cache line could be replaced with:
my @array is BigArray;
proto A(Int \, Int \) { @array[][] //= {*} }

Again, this still wouldn't be enough to store interim results for fully computing A(4,3) but my point was to show use of custom array types.
Numeric overflow
When you comment out the caching you get:

Numeric overflow

Raku/Rakudo do arbitrary precision arithmetic. While this is sometimes called infinite precision it obviously isn't actually infinite but is instead, well, "arbitrary", which in this context also means "sane" for some definition of "sane".
This classically means running out of memory to store a number. But in Rakudo's case I think there's an attempt to keep things sane by switching from a truly vast Int to a Num (a floating point number) before completely running out of RAM. But then computing A(4,3) eventually overflows even a double float.
So while the caching blows up sooner, the code is bound to blow up later anyway, and then you'd get a numeric overflow that would either manifest as an out of memory error or a numeric overflow error as it is in this case.

A: Array subscripts use native ints; that's why you get the error in line 3, when you use the big ints as array subscripts. You might have to define a new BigArray that uses Ints as array subscripts.
The second problem arises in the ** operator: the result is a Real, and when the low-level operations returns a Num, it throws an exception.
https://github.com/rakudo/rakudo/blob/master/src/core/Int.pm6#L391-L401
So creating a BigArray might not be helpful anyway. You'll have to create your own ** too, that always works with Int, but you seem to have hit the (not so infinite) limit of the infinite precision Ints.


text:
Q: Visual Studio cannot connect to SQL Server database Getting a message "login failed for user [my_user]"
Of note is that I am capable of connecting to the server with freetds from linux using the same server, username and password and TDS protocol 7.4. The port is the default SQL Server port. Viz. $tsql -S [my_server] -U "my_user" -P "my_pass" succeeds and I am able to poke around in the server.
However, on my windows machine, it simply reports that my login has failed.

*

*Data Source: Microsoft SQL Server

*Server Name: [my_server]

*Use SQL Server Authentication: User name: [my_user] Password: [my_pass]

Any thoughts on what to try?
UPDATE:
I can connect via pymssql with
pymssql.connect(server=[my_server], user=[my_user], password=[my_pass])


text:
Q: Bootstrap tooltip makes element flicker In my application, I use the bootstrap tooltips but whenever I hover over a button that uses tooltips one of my elements starts flickering. What could cause this issue?
This is how I create the tooltip:
$('[data-toggle="tooltip"]').tooltip({placement:"auto"});

Here is an example https://jsfiddle.net/oLkuat84/10/

A: This seems to be a browser issue.  Your JS works with no flicker on OSX->Firefox and OSX->Chrome but has that horrible red/blue flicker in OSX->Safari (where does the blue come from?)
You can isolate the problem by removing the top and left attributes from the style-switcher-btn-3 class.
From what I can gather: it's that safari is re-rendering the two fixed-position items (the tooltip and the style-switcher-btn-3) and this cases the flicker.  Where the blue colouring comes from I have no idea.
If at all possible, try to make that button grouping not a position:fixed.


text:
Q: I don't understand C pointers I don't really understand the reason why I obtain a different address from what I'm expecting.
I've tried to build this small C code with -m32 flag option.
#include <stdio.h>
#include <stdlib.h>

char *Buffer[10];

int main (void){
 printf("%p\n", Buffer);
 char *Buffer2 = Buffer + 6;
 printf("%p\n", Buffer2);
}

Expected output:
Buffer = 0x56559040
Buffer2 = 0x56559046

Obtained output:
Buffer = 0x56559040
Buffer2 = 0x56559058

Why the obtained output is different from the expected one (0x56559040 + 6 = 0x56559046)?

A: The difference between these two values
Buffer = 0x56559040
Buffer2 = 0x56559058

is 0x18 or in decimal 24.
In this declaration
char *Buffer2 = Buffer + 6;

the array designator Buffer is converted to pointer to its first element. As the element type of the array Buffer is char * then the expression has the type char **.
There is no implicit conversion between types char * (the type of the variable Buffer2) and char ** (the type of the initializer)
So the compiler should issue at least a warning.
Nevertheless using the pointer arithmetic this expression
Buffer + 6

is evaluated like
the value of the address pointed to by Buffer + 6 * sizeof( char * )

as the size of a pointer of the type char * (the size of element of the array) in your system is equal to 4 then you get the value 0x56559058 that is
0x56559040 + 6 * sizeof( char * )
                 ^^^^^^^^^^^^^^^^
                       4

That is the expression
Buffer + 6

points to the sixth element of the array Buffer.


text:
Q: How to get integers from a specific string using regexp? I have some sample text
# HELP aaasd asdads
# TYPE ASDA dasdas
goodmetric_total{"camel-1"} 777.0
# HELP qqq www
# TYPE eee rrr
badmetric_total{"camel-1"} 888.0

I will need to get numbers from a specific string. Using String.format, I will substitute the values I need. For example goodmetric_total.
How do I write a regexp to get only a numerical value?
At the moment, I have solutions for searching string first.
^goodmetric.+\d+

And already in this line look for numbers.
I think you can do all this in one operation.
Thanks!

A: You can use a regex approach with
(?m)^goodmetric.*\h(\d+)(?:\.0+)?$

See the regex demo. Details:

*

*(?m)^ - start of a line

*goodmetric - a string

*.* - any zero or more chars other than line break chars, as many as possible

*\h - a horizontal whitespace

*(\d+) - Group 1: one or more digits

*(?:\.0+)? - an optional sequence of a . and one or more 0 chars

*$ - end of a line (due to (?m) modifier = Pattern.MULTILINE).

See the Java demo:
String s = "# HELP aaasd asdads\n# TYPE ASDA dasdas\ngoodmetric_total{\"camel-1\"} 777.0\n# HELP qqq www\n# TYPE eee rrr\nbadmetric_total{\"camel-1\"} 888.0";
Pattern pattern = Pattern.compile("^goodmetric.*\\h(\\d+)(?:\\.0+)?$", Pattern.MULTILINE);
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
    System.out.println(matcher.group(1));
}


text:
Q: ValueError: seek of closed file | pdfplumber I am writing a program that it will extract text from a PDF file using library pdfplumber and I am getting the following error in the last 3 iterations before the end of the for loop.
Do you have any ideas?
Thanks
def changePDF():
    numPages = int(input("how many pages does your pdf have? --> "))
    for i in range(numPages):
        with pdfplumber.open(r'test.pdf') as pdf:
            page = pdf.pages[i]
            print(f"working on page {i}")
    print(page.extract_text())

A: I'm not familiar with pdfplumber but I can make an educated guess that page does not hold all of the data from the file but instead references a location within an open file handle.  Once you leave your with block, that file handle is closed and you can no longer access the data.
What you can do is move the with line outside of your for loop and do all of your interaction with the PDF inside that block.  That is,
with pdfplumber.open(r'test.pdf') as pdf:
    for i in range(numPages):
        page = pdf.pages[i]
        print(f"working on page {i}")
        print(page.extract_text())


text:
Q: Should I unsubscribe from events? I have 3 questions concerning events:

*

*Should I always unsubscribe events that were subscribed?

*What happens if I do NOT?

*In the below examples, how would you unsubscribe from the subscribed events?

I have for example this code:
Ctor: Purpose: For database property updates
this.PropertyChanged += (o, e) =>
{
    switch (e.PropertyName)
    {
        case "FirstName": break;
        case "LastName": break;
    }
};

and this: Purpose: For GUI-binding wrap the model into viewmodels
ObservableCollection<Period> periods = _lpRepo.GetDailyLessonPlanner(data.DailyDate);
PeriodListViewModel = new ObservableCollection<PeriodViewModel>();

foreach (Period period in periods)
{
    PeriodViewModel periodViewModel = new PeriodViewModel(period,_lpRepo);
    foreach (DocumentListViewModel documentListViewModel in periodViewModel.DocumentViewModelList)
    {
        documentListViewModel.DeleteDocumentDelegate += new Action<List<Document>>(OnDeleteDocument);
        documentListViewModel.AddDocumentDelegate += new Action(OnAddDocument);
        documentListViewModel.OpenDocumentDelegate += new Action<int, string>(OnOpenDocument);
    }
    PeriodListViewModel.Add(periodViewModel);
}

A: You don't have to desubscribe from an event when the instance that is subscribing has the same scope as the instance that is being subscribed to.
Lets say you are a form and you are subscribing to a control, these two together form a group. However, if you have a central class that manages forms and you have subscribed to the Closed event of that form, these do not form a group together and you must desubscribe once the form is closed.
Subscribing to an event makes the subscribed instance create a reference to the instance being subscribed to. This prevents garbage collection. So, when you have a central class that manages form instances, this will keep all forms in memory.
WPF is an exception because it has a weak event model where events are subscribed to using weak references and it will not hold the form in memory. However, it is still best practice to desubscribe when you are not part of the form.

A: Well, let's take the last question first. You can't reliably unsubscribe from an event that you've subscribed to directly with a lambda expression. You either need to keep a variable around with the delegate in (so you can still use a lambda expression) or you need to use a method group conversion instead.
Now as for whether you actually need to unsubscribe, it depends on the relationship between the event producer and the event consumer. If the event producer should live for longer than the event consumer, you should unsubscribe - because otherwise the producer will have a reference to the consumer, keeping it alive for longer than it should be. The event handler will also keep getting called for as long as the producer produces it.
Now in many cases that's not a problem - for example, in a form the button that raises the Click event is likely to live for about as long as the form on which it's created, where the handler is typically subscribed... so there's no need to unsubscribe. This is very typical for a GUI.
Likewise if you create a WebClient solely for the purpose of a single asynchronous request, subscribe to the relevant event and start the asynchronous request, then the WebClient itself will be eligible for garbage collection when the request has finished (assuming you don't keep a reference elsewhere).
Basically, you should always consider the relationship between the producer and the consumer. If the producer is going to live longer than you want the consumer to, or it's going to continue raising the event after you're no longer interested in it, then you should unsubscribe.

A: You may take a look at this article on MSDN. Quote:

To prevent your event handler from
  being invoked when the event is
  raised, simply unsubscribe from the
  event. In order to prevent resource
  leaks, it is important to unsubscribe
  from events before you dispose of a
  subscriber object. Until you
  unsubscribe from an event, the
  multicast delegate that underlies the
  event in the publishing object has a
  reference to the delegate that
  encapsulates the subscriber's event
  handler. As long as the publishing
  object holds that reference, your
  subscriber object will not be garbage
  collected.

A: 1) It depends. Usually it's a good idea, but there are typical cases where you don't need to. Basically, if you are sure that the subscribing object is going to outlive the event source, you ought to unsubscribe, otherwise this would create an unnecessary reference.
If however your object is subscribing to its own events, like in the following:
<Window Loaded="self_Loaded" ...>...</Window>

--then you don't have to.
2) Subscribing to an event makes additional reference to the subscribing object. So if you don't unsubscribe, your object might be kept alive by this reference, making effectively a memory leak. By unsubscribing you are removing that reference. Note that in the case of self-subscription the problem doesn't arise.
3) You can do like that:
this.PropertyChanged += PropertyChangedHandler;
...
this.PropertyChanged -= PropertyChangedHandler;

where
void PropertyChangedHandler(object o, PropertyChangedEventArgs e)
{
    switch (e.PropertyName)
    {
        case "FirstName": break;
        case "LastName": break;
    }
}

A: 1.) Should I always desubscribe events that were subscribed?
Usually yes. The only exception is when the object on which you subscribed isn't referenced anymore and will be garbage collected soon.
2.) What happens if I do NOT?
The object on which you subscribed will hold a reference to the delegate, which in turn holds a reference to its this pointer, and thus you'll get a memory leak.
Or if the handler was a lamda it will hold onto whatever local variables it bound, which thus won't be collected either.


text:
Q: What's causing this ramp on a video signal? See this image, it's a composite video signal on my scope.

As can be seen the dc offset of the signal is varying with time; it also varies with brightness in the scene.
I am plugging the signal from a composite video signal directly into my scope, however the cable is also spliced and goes to my computer's TV card. Without the TV card attached I do not see this. Now I would like to be able to debug my signal using the TV card, but it seems to be interfering (maybe it's loading the signal too much) - what could be causing this? I have another card I'm going to try but I'm not hopeful. Apart from buffering the signal using expensive video buffer amps, what can I try?

A: I'm guessing that the source is AC coupled ( and shouldn't be)
you've got dc offset shifting with picture brightness. Video should be DC coupled and terminated into 75ohms. If that sounds like something that your wouldn't string across a room, congratulations; it was never designed to. I remember reading that in-studio distribution was never raw analog video. So check the source path for a cap.
Unless it's just a really bad ground connection (high resistance) ;and the ground is elevating with brightness, which is consistent with that. So check the return path resistance too.
Analog video; it's frustrating because it was never intended to go very far as a baseband signal.


text:
Q: How to use correctly several count(*) and select in a single table? I'm working with a single MySQL table called location. My columns are:

*

*idLocation: the location id.

*idParent: the direct parent location id.

*checked: a boolean indicating if the location has been checked or not.

I'm calling level 1 location each location who has no parents / level 2 each location who has a level 1 parent / level 3 each location who has a level 2 parent.
I'm trying to find all level 1 locations and to count their undirect children (i.e. all the level 3 locations who are undirectly related) and to count how many of them have been checked.
For example, if a lvl.1 location has 4 lvl.3 children and 1 has been checked, I would like to get 1/4 as result.
I've tried several queries, but I'm a beginner and so far I've only managed to obtain the number of children of each location (including the level 2 ones, but it's not what I'm looking for).
There is a query in order to create a reproducible example:
CREATE TABLE location (idLocation int, idParent int, checked tinyint(1));
INSERT INTO location (idLocation, idParent, checked)
VALUES (1, null, 0), (2, 1, 0), (3, 1, 0), (4, 3, 1), (5, 3, 0), (6, 3, 0),
(7, 3, 0), (8, 3, 0), (9, null, 0), (10, 9, 0), (11, 10, 0), (12, 10, 0);

In this situation, we should find has a result:

*

*idLocation 1 with 4 level 3 childrens. 1 of them is checked.

*idLocation 9 with 2 level 3 childrens. 1 of them is checked.

A: I finaly came to this query as an answer :
select idParent, count(*) as zone from location
where idParent is not null
and idParent not in (select idLocation from location where idParent is null)
and checked = 1
group by idParent;

A: Well, I do not have 'mysql' installed, but with Postgresql it could be very similar:
SELECT a.idparent,count(a.idparent),sum(b.checked)
FROM location AS a LEFT JOIN location AS b ON b.idparent = a.idlocal
WHERE a.idparent IS NOT NULL AND b.checked IS NOT NULL
GROUP BY a.idparent ;

GROUP BY a.idparent  with count(a.idparent) gives number of all 3rd level childern, sum(b.checked) gives number of checked because you defined checked as 1 and unchecked as 0, hence the sumation is enough to collect the number of checked. The LEFT JOIN of the table itself with WHERE a.idparent IS NOT NULL condition choose all rows where the location has any parent, and because the locations of 3rd level do have no childern, the checked must be NULL, the b.checked IS NOT NULL condition kicks them out.


text:
Q: Jquery blur is not retaining highlighted textbox color I have below password control in my MVC3 view page and calling onblur function from the control itself,
@Html.PasswordFor(m => m.CurrentPass, new Dictionary<string, object> { { "id", "txtCurrentPass" }, { "name", "CurrentPass" }, { "Class", "textBoxPlacHold fieldLblMargin" }, { "onblur", "$(this).currPasswordBlur();" } })

below is the jquery function which i am calling,
$.fn.currPasswordBlur = function () {
        if ($('[id="txtCurrentPass"]').val() == '') {
            $('#PasswordChangeErr').html("Please enter current password.");
            $('[id="txtCurrentPass"]').addClass('outLineRed');
            $('#PasswordChangeErr').show();
            $('#MsgSucc').attr("style", "background-color:White;");
            $("html, body").animate({ scrollTop: 0 }, "slow");
            return false;
        }
        else {
            $('#PasswordChangeErr').hide();
            $('[id="txtCurrentPass"]').removeClass('outLineRed');
            $('#MsgSucc').attr("style", "background-color:#dfe5e6;");
        }

the below is highlighting the textbox in red color and when the execution reaches return false statement, the highlighted textbox is getting vanished.

$('[id="txtCurrentPass"]').addClass('outLineRed');

i need to retain the highlighted textbox even if i comeout of the textbox.

A: Firstly, you can provide an anonymous object to the htmlAttributes parameter in the PasswordFor declaration, which will shorten it quite a lot. Also, you should use jQuery to bind your events, not clunky on* attributes:
@Html.PasswordFor(m => m.CurrentPass, new { "id" = "txtCurrentPass", "name" = "CurrentPass", @"class" = "textBoxPlacHold fieldLblMargin" })

Your current jQuery creates the function as a plugin, however it only relates to a single element, defined by id, so there is no point having a plugin. You can put your code in a single blur event handler:
$('#txtCurrentPass').blur(function() {
    var $el = $(this);
    if ($el.val() == '') {
        $('#PasswordChangeErr').html("Please enter current password.").show();
        $el.addClass('outLineRed');
        $('#MsgSucc').css("background-color", "white");
        $("html, body").animate({ scrollTop: 0 }, "slow");
    }
    else {
        $('#PasswordChangeErr').hide();
        $el.removeClass('outLineRed');
        $('#MsgSucc').attr("style", "background-color:#dfe5e6;");
    }
});

Example fiddle
Note that when selecting by id you should use the # prefix on the id, as it is much quicker than the attribute selector.


text:
Q: inserting into postgresql decimal field fails with error "cannot convert {125.00} to Int2" I am fairly new to golang. I am trying to insert into a postgresql table which has a numeric field, using a web app gin-gonic.
postgres=# \d user_txns;
                       Table "public.user_txns"
   Column    |         Type          | Collation | Nullable | Default
-------------+-----------------------+-----------+----------+---------
 user_id     | character varying(15) |           | not null |
 txn_code    | smallint              |           | not null |
 description | character varying(64) |           | not null |
 txn_amount  | numeric(15,4)         |           | not null |
 txn_type    | smallint              |           | not null |
 voucher     | character varying(16) |           |          |

I am using jackc pgxpool to insert into the table as below.
109 ▏ sql := `INSERT INTO user_txns VALUES ($1,$2, $3, $4, $5)`
▎ 110 ▏ _, err = tx.Exec(context.Background(), sql,
▎ 111 ▏ ▏ ▏ ▏ ▏ ▏ claims["phone"],
▎ 112 ▏ ▏ ▏ ▏ ▏ ▏ recharge,
▎ 113 ▏ ▏ ▏ ▏ ▏ ▏ "User recharge",
▎ 114 ▏ ▏ ▏ ▏ ▏ ▏ recharge.Amount,
▎ 115 ▏ ▏ ▏ ▏ ▏ ▏ credit,
▎ 116 ▏ )
▎ 117 ▏ if err != nil {
▎ 118 ▏ ▏ c.JSON(http.StatusInternalServerError, gin.H{"msg": err.Error()})
▎ 119 ▏ ▏ return
▎ 120 ▏ },

The payload is a json request that has the following structure:
{
  "amount": 125.00
}

I unmarshal the request into a struct defined as below.
type Recharge struct {
  Amount string `json:"amount" binding:"required"`
}

The insert fails with error

"msg": "cannot convert {125} to Int2"

What is the right golang data type to use for inserting into a decimal field?
thanx

A: The easiest way to insert a value like 125.00 into a postgres column of type numeric would be to use a float type in Go. This works out of the box and so there's no need to implement any kind of custom interface.
For example:
CREATE TABLE t (
    id serial PRIMARY KEY
    , amount numeric(15,4) NOT NULL
    -- ...
);

data := []byte(`{"amount": 125.00}`)
var obj struct {
    Amount float64 `json:"amount"`
}
if err := json.Unmarshal(data, &obj); err != nil {
    panic(err)
}

_, err := db.Exec(`INSERT INTO t (amount) VALUES ($1)`, obj.Amount)

Float types are subject to rounding errors however, and because of that a common practice for storing monetary amounts is to use integers that represent the value in cents. E.g. 125.00 becomes 12500. This also works out of the box.
For example:
CREATE TABLE t (
    id serial PRIMARY KEY
    , amount int8 NOT NULL
    -- ...
);

data := []byte(`{"amount": 12500}`)
var obj struct {
    Amount int64 `json:"amount"`
}
if err := json.Unmarshal(data, &obj); err != nil {
    panic(err)
}

_, err := db.Exec(`INSERT INTO t (amount) VALUES ($1)`, obj.Amount)

If you want to use the pgtype.Numeric for storing and retrieving the amount to and from the database then you'll have to do some extra work because pgtype.Numeric doesn't know how to encode/decode JSON 125.00/"125.00" values.
One thing you can do is to declare a custom struct type, have it embed the pgtype.Numeric type, and then have the custom struct type implement the json.Marshaler and json.Unmarshaler interfaces.
For example:
CREATE TABLE t (
    id serial PRIMARY KEY
    , amount numeric(15,4) NOT NULL
    -- ...
);

type MyNumeric struct {
    pgtype.Numeric
}

func (n *MyNumeric) UnmarshalJSON(data []byte) error {
    var s json.Number
    if err := json.Unmarshal(data, &s); err != nil {
        return err
    }
    return n.Numeric.Set(s.String())
}

func (n MyNumeric) MarshalJSON() ([]byte, error) {
    var f float64
    if err := n.Numeric.AssignTo(&f); err != nil {
        return nil, err
    }
    return []byte(strconv.FormatFloat(f, 'f', -1, 64)), nil
}

data := []byte(`{"amount": 125.00}`)
var obj struct {
    Amount MyNumeric `json:"amount"`
}
if err := json.Unmarshal(data, &obj); err != nil {
    panic(err)
}

_, err := db.Exec(`INSERT INTO t (amount) VALUES ($1)`, obj.Amount)


text:
Q: How to measure length (in pixels) between multiple points on an image I have a fairly high resolution map, with a known scale. How to measure the length in pixels between multiple points on an image? Straight line is simple, but how to do it when there are multiple points / not straight line?
Example:
This can be reduced to 9 legs to get the total length in pixels.

I currently use the measure tool, which allows for a maximum of two legs only. This gets tedious quickly (write down the pixels, and then sum the total later), when there are a lot of curves in a road.


text:
Q: Generate error not working with AsyncBuilder I'm following https://recipes.tst.sh/docs/architecture/safe-async.html for the asyncBuilder package. I'm trying to generate the error method. For some reason, it's not working and on error the builder run...
AsyncBuilder(
        future: fetchData(),
        error: (context, error, stackTrace) {
          print('in error');
          return Text('some error');
        },
        builder: (_, snapshot) {
          print('in builder');
          print(snapshot); // prints out the error which the fetchData function returned in the catch statement
          return Container();
        });

Future<Response> fetchData() async {
    try {
      final responseJson = await _provider.get('data'); // throws error
      ...
      return Response.success(parsedData);
    } catch (e) {
      // This is called
      return Response.error(e.toString());
    }
  }

I tried throwing an error in the catch statement instead of returning one, but then the app crashed

A: You can copy paste run full code below
You can use throw Exception('Failed from fetchData ${e.toString()}');
code snippet
try {
  var response = await http
      .post("not exist", body: {'name': 'doodle', 'color': 'blue'});
  return http.Response("OK", 200);
} catch (e) {
  throw Exception('Failed from fetchData ${e.toString()}');
}

...
AsyncBuilder(
      future: fetchData(),
      error: (context, error, stackTrace) {
        print('in error');
        return Text('some error $error');
      },

working demo for success and error

full code
import 'package:async_builder/async_builder.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Future<http.Response> fetchData() async {
    try {
      var response = await http
          .post("not exist", body: {'name': 'doodle', 'color': 'blue'});
      return http.Response("OK", 200);
    } catch (e) {
      throw Exception('Failed from fetchData ${e.toString()}');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: AsyncBuilder(
          future: fetchData(),
          error: (context, error, stackTrace) {
            print('in error');
            return Text('some error $error');
          },
          builder: (_, snapshot) {
            print('in builder');
            print(snapshot);
            return Text("success ${(snapshot as http.Response)?.body}");
          }),
    );
  }
}


text:
Q: Create database project for PostgreSQL in Visual Studio 2015 I need to create a database project in Visual Studio 2015 for PostgreSQL databases. Then we can maintain version control of each database object in the form of SQL script file. So, is there any such provision (may be in the form of plug-in) in Visual Studio 2015?
EDITED:
We're already using Team Foundation System (TFS) as our version control system for all of our projects. So, we would like to use the same for Postgres scripts also. Our projects are developed in .Net on Windows OS, even the Postgres is now running on Windows Server. What we want is to use Visual Studio only for creating a database project for Postgres (similar .sqlproj for Microsoft SQL Server) so that we can maintain version history of table schemas in the form of SQL files, build the project and deploy whatever server we need. Hope I have provided enough information now.


text:
Q: Android - Fetching Data from URL issue i am trying to fetching data from url, its showing null.
here is my code
                try {
                URL urlA = new URL("http://www.domain.com/work123.html");
                BufferedReader in = new BufferedReader(new InputStreamReader(urlA.openStream()));

                String inputLineA;

                while ((inputLineA = in.readLine()) != null)
                    htmlCodeA += inputLineA;

                in.close();
                } catch (Exception e) {

                    //Log.d(LOG_TAG, "Error: " + e.toString());
                }

please let me know where i am doing mistake.
best regards,

A: Since you posted in the Android section, it's almost guaranteed that you will want to run this in an AsyncTask and not block the UIThread with that AsyncTask.
String htmlCodeA = "";
//
// A bunch of lines later...
try{
  HttpClient client = new DefaultHttpClient();
  HttpPost request = new HttpPost("http://www.domain.com/work123.html");
  HttpResponse response = client.execute(request);
  InputStreamReader isr = new InputStreamReader(response.getEntity().getContent());
  BufferedReader reader = new BufferedReader(isr);
  String line = "";
  while((line = reader.readLine())!=null)
  {
    htmlCodeA += line;
  }
}
catch(MalformedURLException e) { /* Do whatever you want here. */}
catch(IOException e) { /* Do whatever you want here. */}

A: URL connectURL = new URL(urlstring);

        HttpURLConnection hc = (HttpURLConnection) connectURL.openConnection();

hc.setConnectTimeout(20 * 1000);
                Enumeration kyes = header.keys();
                while (kyes.hasMoreElements()) {
                    String key = (String) kyes.nextElement();
                    String value = (String) header.get(key);
                    hc.setRequestProperty(key, value);
                }

InputStream is = hc.getInputStream();
                resMessage = new String(readFully(is),  "UTF-8")

public static byte[] readFully(InputStream input) throws IOException
{
    byte[] buffer = new byte[Constants.BUFFER_SIZE];
    int bytesRead;
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    while ((bytesRead = input.read(buffer)) != -1)
    {
        output.write(buffer, 0, bytesRead);
    }
    return output.toByteArray();
}


text:
Q: JQuery Colorbox in IE6 - missing border Colorbox is a jquery plugin that works like a lightbox, it has an automatic border already but this border doesn't seem to show up for me in IE6, this is their CSS as you can see near the bottom is where all the border ie6 styles are:
/*
  The following provides PNG transparency support for IE6
*/
.cboxIE6 #cboxTopLeft{background:url(/images/colorbox/ie6/borderTopLeft.png);}
.cboxIE6 #cboxTopCenter{background:url(/images/colorbox/ie6/borderTopCenter.png);}
.cboxIE6 #cboxTopRight{background:url(/images/colorbox/ie6/borderTopRight.png);}
.cboxIE6 #cboxBottomLeft{background:url(/images/colorbox/ie6/borderBottomLeft.png);}
.cboxIE6 #cboxBottomCenter{background:url(/images/colorbox/ie6/borderBottomCenter.png);}
.cboxIE6 #cboxBottomRight{background:url(/images/colorbox/ie6/borderBottomRight.png);}
.cboxIE6 #cboxMiddleLeft{background:url(/images/colorbox/ie6/borderMiddleLeft.png);}
.cboxIE6 #cboxMiddleRight{background:url(/images/colorbox/ie6/borderMiddleRight.png);}

.cboxIE6 #cboxTopLeft,
.cboxIE6 #cboxTopCenter,
.cboxIE6 #cboxTopRight,
.cboxIE6 #cboxBottomLeft,
.cboxIE6 #cboxBottomCenter,
.cboxIE6 #cboxBottomRight,
.cboxIE6 #cboxMiddleLeft,
.cboxIE6 #cboxMiddleRight {
_behavior: expression(this.src = this.src ? this.src : this.currentStyle.backgroundImage.split('"')[1], this.style.background = "none", this.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src=" + this.src + ", sizingMethod='scale')");
}

A: Works fine for me in IE6.  The problem you are having (I'm assuming with a site that you did not link to, and not the colorbox' examples page) is that the background images are not in the directory that the CSS expects them to be in.  Double check your file paths.

A: The png fix thing in the CSS I pasted above is what broke it in IE6, once I removed all the code above it worked! Weird huh?


text:
Q: C program running on my machine but not remote server? I'm a complete noob to C, and I'm having an issue. My program works on my machine, but fails on my schools remote machine where it will be graded. I have a suspicion that there is something corrupted on my school account, but also a good chance there is something wrong with my program.
This program takes in a CSV file of movie data with title, year, rating, and languages.
The function where I think there may be a problem effecting the memory is where I am supposed to print out the highest rated movie in each year. The best way to do this would be an array of hash maps for O(n) time, but since I'm new to C I took an easier approach. I did an O(n^2) loop through the movies (they are a linked list, which is required) and at each movie, I loop through the array to check if there is a higher rated movie for that year, then print it.
I also make a dynamic array that stores the "visited" years, so say if there are 2 2008 movies, it doesn't print both.
The program is fairly long, so I will just show the function I'm stuck on and then what one of the movie nodes looks like. I am passing in head of the linkedlist to the printHighestRated function.
struct movie
{
    /**
    * Node for each movie containing title, year, language, and release date.
    */
    char *title;
    char *year;
    char *languages;
    char *rating;
    struct movie *next;
};

bool ifIn(int curYear, int *p, int size)
    /**
    * Helper function to see if year has already been checked.
    */
{
    for (int i = 0; i < size; i ++)
    {
        if (*(p + i) == curYear)
        {
            return true;
        }
    }
    return false;
}

void printHighestRated(struct movie *list)
    /**
    * Prints the highest rated movie for each year.
    * Loops through linked list in O(n^2) time to find the max rated movie for each year being considered.
    * Keeps a 'visited' array so that the same year isn't checked/printed twice.
    */
{
    int *visited;
    int i = 0;
    int arrSize = 1;
    visited = calloc(arrSize, sizeof(int));     // Dynamic array to track visited years
    while (list != NULL)
    {
        int curYear = atoi(list->year);
        if (!ifIn(curYear, visited, i))         // If year has not been checked, find and print the highest rated movie
        {
            char *ptr;
            struct movie *cur = list;
            double maxRating = strtod(cur->rating, &ptr);
            struct movie *maxMovie = cur;
            while (cur != NULL)
            {
                if (strtod(cur->rating, &ptr) > maxRating && atoi(cur->year) == curYear)    // If higher rated movie is found
                {
                    maxMovie = cur;
                    maxRating = strtod(cur->rating, &ptr);
                }
                cur = cur->next;
            }
            printf("%s %s %s\n", maxMovie->year, maxMovie->rating, maxMovie->title);
        }
        *(visited + i) = curYear;
        i ++;
        if (i == arrSize - 1)
        {
            visited = realloc(visited, 2 * arrSize);  // Resize visited array if needed
        }
        list = list->next;
    }
    free(visited);
}

A: These three statements are problematic:
*(visited + i) = curYear;
i ++;
if (i == arrSize - 1)

If we start with i == 0 then
*(visited + i) = curYear;

will be okay since you access the first element of your one-element array.
Then you increase i so then i == 2.
Then you check if you need to increase the size of visited:
if (i == arrSize - 1)

But here's the problem, your comparison will be 2 == 1 - 1 which will be false and therefore you don't reallocate memory. So you will forever go out of bounds of the allocated memory for visited. Which of course leads to undefined behavior, and possible crashes.
The solution is to subtract from i instead of arrSize:
if (i - 1 == arrSize)

Or add one to arrSize:
if (i == arrSize + 1)

Also note that when you reallocate memory, you never increase arrSize, so no matter what you will only reallocate memory once.

Even on your local system where everything seems to work, this should have been quite easy to find out with a little debugging.
Take this as an opportunity to learn how to use a debugger to step through code statement by statement while monitoring variables and their values. Then you would have seen the code step over the reallocation, even though it was needed.