text:
Q: Отобразить элемент title с помощью selenium web-driver на скриншоте Имеется веб страничка.
На веб страничке есть элемент Name
После наведения на элемент, всплывает подробная информация об элементе. К самому элементу добавляется title Name .
Для наведения на элемент использую:
element = driver.find_element_by_css_selector('css')
    hover = ActionChains(driver).move_to_element(element).move_by_offset(9, 9)
    hover.perform()
    time.sleep(10)

get_attribute("title") после move_to_element(element) - выдает названия Title.
Требуется сделать скрин вмест со всплывающей подсказкой, но окно не появляется.
При постановке брекпоинта, и самостоятельном наведении на элемент, появляется.
Подскажите, как по человечески вывести это всплывающее окошко.

A: Решение таково.
Дело в том, что selenium не умеет работать с элементами, которые являются частью системы. Т.е. при наведении на элемент title появлялся, в другом слое.
Если наводить курсор средствами системы, то всплывающее окно отображается.
Следовательно нужно наводить курсор средствами системы, а не селениума.
Остается скрестить селениум и наведение системы.
Вот функция.
import pyautogui

def mouse_move_to_element(driver, value, isCss):
    if not isCss:
        e = driver.find_element_by_xpath(value)
    else:
        e = driver.find_element_by_css_selector(value)

    location_x = e.location.get('x', 0)
    location_y = e.location.get('y', 0)
    size_x = e.size.get('width', 0)
    size_y = e.size.get ('height', 0)

    pyautogui.moveTo(10, 133)
    pyautogui.moveRel(location_x+size_x/2, location_y+size_y/2)
    pyautogui.moveRel(-1, -1, 0.1)

pyautogui.moveTo(10, 133) - верхний левый угол нашего окна браузера. (пожно поиграться с опциями и настроить под себя или вовсе избавиться от зависимости)


text:
Q: How to write a unit test for an async method? I have the following test code:
import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing';
import {inject, TestBed} from '@angular/core/testing';
import {AviorBackendService} from './avior-backend.service';

describe('AviorBackendService', () => {
  beforeEach(() => TestBed.configureTestingModule({
    imports: [HttpClientTestingModule],
    providers: [AviorBackendService],
  }));

  it('should be created', () => {
    const service: AviorBackendService = TestBed.get(AviorBackendService);
    expect(service).toBeTruthy();
  });

  // Inject the `done` method. This will tell the test suite that asynchronous methods are being called
  // and it will mark the test as failed if within a specific timeout (usually 5s) the `done` is not called
  it('expects service to fetch data with proper sorting', (done) => {
    const service: AviorBackendService = TestBed.get(AviorBackendService);
    // tslint:disable-next-line: prefer-const
    let httpMock: HttpTestingController;
    service.getUserCollection().subscribe(data => {
      expect(data.length).toBe(7);
      const req = httpMock.expectOne('http://localhost:3000/users');
      expect(req.request.method).toEqual('GET');      // Then we set the fake data to be returned by the mock
      req.flush({firstname: 'Chad'});
      done(); // Mark the test as done
    }, done.fail); // Mark the test as failed if something goes wrong
  });
});

I need to write a prototype test for the supplied function (then I'll write the rest for the other similar functions). I am still learning how to write tests and as far I as I understand I need to use a mock, but I don't understand how.
My code to test is:
  getUserCollection() {
    // withCredentials is very important as it passes the JWT cookie needed to authenticate
    return this.client.get<User[]>(SERVICE_URL + 'users', { withCredentials: true });
  }

My test code gives out an error Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
UPDATE
My user-collection.model.ts:
import { User } from './user.model';

export interface UserCollection {

    user: User[];

}

My user.model.ts:
import { Role } from './role';

// was class and not interface!
export interface User {
    _id: number;
    mandator?: number;
    loginId: string;
    lastname: string;
    firstname: string;
    password: string;
    eMail: string;
    group?: string;
    role?: Role;
    active?: boolean;
    token?: string;
}

A: You're doing the flush in a wrong location (a place that will never be traversed).
Try the following:
describe('AviorBackendService', () => {
  let httpTestingController: HttpTestingController;
  let service: AviorBackendService;

  beforeEach(() => {
   TestBed.configureTestingModule({
     imports: [HttpClientTestingModule],
     providers: [AviorBackendService],
   });

   httpTestingController = TestBed.get(HttpTestingController);
   service = TestBed.get(AviorBackendService);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  it('expects the service to fetch data with proper sorting', () => {
    const mockReponse = { firstName: 'Chad' };

    service.getUserCollection().subscribe(data => {
      expect(data.firstName).toEqual('Chad');
    });
    const req = httpTestingController.expectOne('IN HERE PUT WHATEVER SERVICE_URL + 'users' EQUALS TO');
    expect(req.request.method).toEqual('POST');
    // send the response to the subscribe.
    req.flush(mockResponse);
  });
});

A good link on how to test HTTP Service in Angular (https://medium.com/better-programming/testing-http-requests-in-angular-with-httpclienttestingmodule-3880ceac74cf)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sharing Excel Spreadsheet Is there a file format that saves everything in your workbook to data? I basically want to remove all formulas quickly.
This is because I regularly have to share the updated version of a report I run with others via email, but when others try and open the spreadsheet on their PCs their version of the workbook data always gets messed up. This is because the workbook in question uses external workbooks and updates every time you open it.
I know I could C&P all the data as values, but this would take a long time as there are multiple sheets with huge amounts of data and I have to share this report regularly.
Any ideas?

A: I missed that you already know about Pasting Value.
Another option is, save the file in "csv" format. It preserve the values. But you have to do it for every sheet.

*

*Press Ctrl+A to select whole excel sheet

*Right click and select "Paste Special"

*Then click on second option "Values"

This will convert the formula to values and you can share without worrying.


text:
Q: Does FindFit use symbolic differentiation? Does FindFit use symbolic differentiation when optimizing by least squares a non-linear function?

A: FindFit does perform symbolic differentiation by default. It has the option to use finite differences instead via the option Gradient -> "FiniteDifference".
There is worked example in the documentation here.

A: Yes it does. You can see this by using a function that prints the argument passed to the function evaluated in the FindFit procedure.
For example you could use this little setup:
data = Table[{x, 2.5*Exp[x]}, {x, 0, 1, 0.1}];
f[a_, x_] := Block[{}, Print[x]; a*Exp[x]]
FindFit[data, f[a, x], {a}, x]

What you will notice, when you execute the code, is that in addition to the correct result a = 2.5 the Print routine yields the output x. This means that the function f has been evaluated symbolically by Mathematica, otherwise you would have gotten a list of numerical values, which would correspond to points where  f would have been evaluated numerically.


text:
Q: OnClick event to select and display a chart by clicking on a cell containing text I want an Excel worksheet that displays the progress of Performance Indicators in the form of a dynamic report.
The structure of the report will be Grouped Lists of Performance Indicator Descriptions under their respective Headings and for a chart, based on that description to be displayed detailing the relevant month-by-month performance.
The main build has been done, however, it's the dynamic part of calling charts based on clicking on a cell that is stumping me.
I want the end-user to click on one of the listed descriptions and the relevant chart based on that description to be displayed on the right-hand side.
Is there a way to do this via VBA? The charts and tables will be stored on a separate hidden worksheet in the same document.

A: You can use hyperlinks to trigger some specific action by using the Worksheet_FollowHyperlink event.
In the worksheet code module for the sheet where the user will be clicking cells:
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)

    Debug.Print Target.TextToDisplay   'Text of the clicked cell
    Debug.Print Target.Range.Address   'the actual cell which was clicked

    'Process either of the above to figure out what action to take...

End Sub

And in a regular module:
'Sets up your links: select one or more cells and run this to turn the cell
'  contents into hyperlinks which will trigger the event handler.
Sub MakeLinks()
    Dim c As Range
    For Each c In Selection.Cells
        c.Hyperlinks.Delete 'remove any existing link
        c.Worksheet.Hyperlinks.Add Anchor:=c, Address:="#LinkTarget()", _
                                   TextToDisplay:=c.Text
        'you can re-style the cells if you don't want the blue/underlined font
    Next c
End Sub

'This serves as a "dummy" destination for the hyperlinks
'  Just returns the clicked-on cell, so the selection doesn't jump around
Function LinkTarget() As Range
    Set LinkTarget = Selection
End Function

Once this is set up, clicking any of the links will trigger the event handler in the sheet module, and you can decide what action to take based on the text of the clicked link.
This is a useful alternative to having a bunch of buttons in a table-like structure, since you don't have to worry about tying buttons to specific rows (eg. when sorting)
Notes

*

*If you need to respond to clicks on multiple sheets then there's also the Workbook_SheetFollowHyperlink event (in the ThisWorkbook code module)

*This doesn't work with links created using the HYPERLINK() worksheet formula, since those type of links don't trigger the event handler.

*If your cell text is short then clicking the cell may "miss" the link - in that case you can pad the text with spaces on either side so it fits the cell better

A: You can run a macro when a certain cell is selected by using the Worksheet.SelectionChange event.
I would start by putting the event handler into the sheet in question and test what the selected range is compared to the range you care about.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Target.row = row_of_kpi_desc And Target.Column = col_of_kpi_desc Then
        Call Other_Macro
    End If
End Sub

Other_Macro could copy the chart from this other hidden sheet and paste it to a specific location. There are ample examples of how to do this. Best of luck.

A: Assuming the charts are on a worksheet names Charts, and each chart object has been named with a useful name (my code uses "KPI 1", "KPI 2", "KPI 3", but feel free to use something descriptive).
This code goes in the code module behind the sheet the user will click on. To access it easily, right-click on the sheet tab and select View Code.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  If Target.Cells.Count = 1 Then
    Select Case True
      Case Not Intersect(Target, Me.Range("A2")) Is Nothing
        Dim ChartName As String
        ChartName = "KPI 1"
      Case Not Intersect(Target, Me.Range("A3")) Is Nothing
        ChartName = "KPI 2"
      Case Not Intersect(Target, Me.Range("A4")) Is Nothing
        ChartName = "KPI 3"
    End Select

    If Len(ChartName) > 0 Then
      Application.ScreenUpdating = False
      Dim shp As Shape
      For Each shp In Me.Shapes
        If shp.Name = "KPI Chart" Then
          shp.Delete
        End If
      Next
      Worksheets("Charts").ChartObjects(ChartName).Copy
      Me.Paste
      With Me.Shapes(Me.Shapes.Count)
        .Top = Target.Top
        .Left = Target.Left + Target.Width
        .Name = "KPI Chart"
      End With
      ActiveCell.Select
      Application.ScreenUpdating = True
    End If
  End If
End Sub


text:
Q: When I access Jenkins trough an EC2 I get an error I got an issue. I created a Jenkins AMI that i snapshoted it and created an image from a running ec2 instance with an already configured Jenkins Master on port 8443 with an https certificate. But when I curl to the jenkins instance i get the following:
[1]: https://i.stack.imgur.com/K2tz0.png
I checked Jenkins logs and everything was normal. And my Elatic Load balancer is healthy which means the security groups and other things are working just fine. Does anybody have a clue why is it giving a 403 Forbidden? Another point is that I can even access the GUI

A: By using curl you're making your life harder but look at some of what comes back:
<meta http-equiv='refresh' content='1;url=/login?from=%2F'/>

If you've done HTML programming, this is one way of having the browser execute a redirect.  Why Jenkins doesn't do some sort of HTTP redirect I don't know but the code is telling you that, after 1 second, redirect to the url /login.
curl isn't going to interpret the HTML for you, unlike the browser.  Jenkins is working fine - you just need to follow what the HTML and JavaScript code is telling you to do through curl.

A: The 403 error is the Jenkins application specifically saying your current user is not allowed access to the current action.
It appears you're not logged in so your action is treated as an anonymous user. If the anonymous user should have the permissions to access this action you will need to add them.


text:
Q: Call external javascript in the default administration page in Django How can I call external javascript in my default admin html page in Django.
I know that using MEDIA class I can do this in admin.py file.
Here is the my try:
  class PlayerAdmin(admin.ModelAdmin):
      class Media:
        js = ('/static_files/js/adminsettings.js')

But I am not getting data written in the JavaScript file.

A: You need to use a path relative to STATIC_URL (or MEDIA_URL), in your example this may work:
  class PlayerAdmin(admin.ModelAdmin):
      class Media:
        js = ('js/adminsettings.js',)

Also, not that the js attribute is a tuple in my example (it can be any iterable, a list, set, etc.)
An alternative is overriding admin templates, which can give you more flexibility, and allow you to apply the same javascript to many models easily.


text:
Q: How can I increase spacing between nodes in dot graph with pygraphviz? I'm having trouble trying to increase the spacing between nodes in a hierarchical graph I'm making. I expect to put labels on this graph, so the spacing between nodes has to be fairly large, but I'm unsure how the "args" parameter  of pygraphvis_layout works, or if I'm using it properly.
It seems as if the spacing between nodes of the same rank should be at least 2 inches, but this doesn't reflect in the actual images. Varying the number provided to nodesep has no effect on spacing as far as I've tested.
I've already looked over other solutions: pydot hasn't worked and seems to output png files I can't open, and I already am using NetworkX for graphing something else related.
(Replication will require graphviz in addition to the indicated imports.)
import networkx as nx
import matplotlib.pyplot as plt
from networkx.drawing.nx_agraph import pygraphviz_layout

plt.figure(figsize=(10, 7))
graph = nx.DiGraph([(0, 1), (0, 2),
                    (1, 3), (1,4), (2,5), (2,6),
                    (3, 7), (3, 8), (4, 9), (4, 10), (5, 11), (5, 12), (6, 13), (6, 14)])
pos = pygraphviz_layout(graph, prog="dot", args='-Gnodesep=2')
nx.draw_networkx_nodes(
    graph, pos, nodelist=graph.nodes, node_size=1000, node_color="r", alpha=0.8
)
nx.draw_networkx_edges(graph, pos, edgelist=graph.edges, width=1, edge_color="k")
plt.axis("off")
plt.savefig("test.svg")
plt.show()

A: The space for plotting the graph is limited by the plot's figure size. Try to play with the size, for example:
pos = pygraphviz_layout(graph, prog="dot", args='-Gnodesep=2')
nx.draw_networkx_nodes(...)
nx.draw_networkx_edges(...)
plt.figure(figsize=(20,20))
plt.show()

Once the size is large enough the Gnodesep argument should work.


text:
Q: Unbinding Masonry Scenario:
I'm currently working with KnockoutJS, jQuery UI's sortable and Masonry. I use Knockout to display a list of cards, Masonry to arrange the cards properly, and sortable for sorting the cards.
The cards are of similar size, but I'll be introducing different sizes later on so I surely need Masonry to help me arrange them.
I'm using a customized bindingHandler function for the sortable so that when the user sorts the cards, the item's position gets updated in the knockout observableArray.
Problem:
Since the knockout sortable function removes the item from the last position and puts it back to a new position, Masonry messes up and somehow sortable also not functions properly. What I discovered was if I simply float left all the cards without using Masonry, sortable works fine.
I plan to undo Masonry at the start of the sortable, and put it back at the stop of the sortable. However I don't know how to unbind Masonry. Is there a way? Or at least a way to get it working.
Here's a prototype of what I'm trying to do:
http://jsbin.com/avujom/9/edit

A: you could use masonry's destroy to remove masonry. so it removes the Masonry functionality completely. This will return the element back to its pre-initialized state. and you could create masonry element when you needed by msnry = new Masonry( container );. Also you could use layout method.


text:
Q: NotApplicable Response is XACML policy Why am i getting NotApplicable response in XACML policy ? Please find my XACML policy, request and response below. In my policy, i have main target element which matches username. I am using wso2is-5.1.0 for my testing.
XACML policy
<Policy xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17"  PolicyId="TestPolicyWithTarget" RuleCombiningAlgId="urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:first-applicable" Version="1.0">
       <Target>
          <AnyOf>
             <AllOf>
                <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
                   <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">abhishek</AttributeValue>
                   <AttributeDesignator AttributeId="urn:oasis:names:tc:xacml:1.0:subject:subject-id" Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="true"></AttributeDesignator>
                </Match>
             </AllOf>
          </AnyOf>
       </Target>
       <Rule Effect="Permit" RuleId="TestRule">
          <Target>
             <AnyOf>
                <AllOf>
                   <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
                      <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">foo1</AttributeValue>
                      <AttributeDesignator AttributeId="urn:oasis:names:tc:xacml:1.0:resource:resource-id" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="true"></AttributeDesignator>
                   </Match>
                </AllOf>
             </AnyOf>
             <AnyOf>
                <AllOf>
                   <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
                      <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">read</AttributeValue>
                      <AttributeDesignator AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="true"></AttributeDesignator>
                   </Match>
                </AllOf>
             </AnyOf>
          </Target>
          <Condition>
             <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:not">
                <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:any-of">
                   <Function FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-equal"></Function>
                   <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">abhishek</AttributeValue>
                   <AttributeDesignator AttributeId="urn:oasis:names:tc:xacml:1.0:subject:subject-id" Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="true"></AttributeDesignator>
                </Apply>
             </Apply>
          </Condition>
       </Rule>
    </Policy>

XACML Request
<Request xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17" CombinedDecision="false" ReturnPolicyIdList="false">
    <Attributes Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource">
        <Attribute AttributeId="urn:oasis:names:tc:xacml:1.0:resource:resource-id" IncludeInResult="false">
            <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">foo1</AttributeValue>
        </Attribute>
    </Attributes>
    <Attributes Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject">
        <Attribute AttributeId="urn:oasis:names:tc:xacml:1.0:subject:subject-id" IncludeInResult="false">
            <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">abhishek</AttributeValue>
        </Attribute>
    </Attributes>
    <Attributes Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action">
        <Attribute AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id" IncludeInResult="false">
            <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">read</AttributeValue>
        </Attribute>
    </Attributes>
</Request>

XACML Response
<Response xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17">
    <Result>
        <Decision>NotApplicable</Decision>
        <Status>
            <StatusCode Value="urn:oasis:names:tc:xacml:1.0:status:ok"/>
        </Status>
    </Result>
</Response>

A: I tested your policy in the Axiomatics Policy Server and I also get NotApplicable. What effect were you expecting? The policy behaves correctly. The Policy target and the Rule target are both matched.
The condition is also matched but given you use a not() function, it becomes false and therefore the rule does not apply which leads to NotApplicable.

If you want Deny back, then you need to have a catch all Deny rule after the Permit rule.

And here is the code.
<xacml3:Policy xmlns:xacml3="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17" PolicyId="TestPolicyWithTarget" Version="1.0" RuleCombiningAlgId="urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:first-applicable">
    <xacml3:Description/>
    <xacml3:PolicyDefaults>
        <xacml3:XPathVersion>http://www.w3.org/TR/1999/REC-xpath-19991116</xacml3:XPathVersion>
    </xacml3:PolicyDefaults>
    <xacml3:Target>
        <xacml3:AnyOf>
            <xacml3:AllOf>
                <xacml3:Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
                    <xacml3:AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">abhishek</xacml3:AttributeValue>
                    <xacml3:AttributeDesignator Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"  AttributeId="urn:oasis:names:tc:xacml:1.0:subject:subject-id" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="true"/>
                </xacml3:Match>
            </xacml3:AllOf>
        </xacml3:AnyOf>
    </xacml3:Target>
    <xacml3:Rule RuleId="TestRule" Effect="Permit">
        <xacml3:Target>
            <xacml3:AnyOf>
                <xacml3:AllOf>
                    <xacml3:Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
                        <xacml3:AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">foo1</xacml3:AttributeValue>
                        <xacml3:AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource"  AttributeId="urn:oasis:names:tc:xacml:1.0:resource:resource-id" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="true"/>
                    </xacml3:Match>
                </xacml3:AllOf>
            </xacml3:AnyOf>
            <xacml3:AnyOf>
                <xacml3:AllOf>
                    <xacml3:Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
                        <xacml3:AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">read</xacml3:AttributeValue>
                        <xacml3:AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action"  AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="true"/>
                    </xacml3:Match>
                </xacml3:AllOf>
            </xacml3:AnyOf>
        </xacml3:Target>
        <xacml3:Condition >
            <xacml3:Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:not">
                <xacml3:Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:any-of">
                    <xacml3:Function FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-equal"/>
                    <xacml3:AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">abhishek</xacml3:AttributeValue>
                    <xacml3:AttributeDesignator Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"  AttributeId="urn:oasis:names:tc:xacml:1.0:subject:subject-id" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="true"/>
                </xacml3:Apply>
            </xacml3:Apply>
        </xacml3:Condition>
    </xacml3:Rule>
    <xacml3:Rule RuleId="0e96abf0-e2f5-495b-8df1-bb3f2987e949" Effect="Deny">
        <xacml3:Description>Catch all</xacml3:Description>
        <xacml3:Target/>
    </xacml3:Rule>
</xacml3:Policy>


text:
Q: Jquery array loop I am attempting to loop through the contents of an array in Jquery, the array contains a list of Place Names, followed by a URL ([0]name, [1]url, [2]name [3]url, etc.). The data for place names has been pulled through an API and as such some are undefined. Below is my loop in its current iteration.

      for (var i=0; i<albums.length; i++){
            if ((albums[i] != "undefined") && (albums[i+1].indexOf("http") !== 1)){
                $("#thumbnail").css("overflow:", "auto");
                $("#thumbnail").css("max-height:", "100px");
                $("#thumbview").append('

');
            }
            i++;
        };

Below is the array as it is structured currently

Array[14]
[0]:"location name"[1]:"https:/..."[2]:"location name"[3]:"https:/..."[4]:"location name"[5]:"https:/..."[6]:"location name"[7]:"https:/..."[8]:undefined[9]:"https:/..."[10]:undefined[11]:"https:/..."[12]:"location name"[13]:"https:/..."

My goal for the loop is to check [i], if [i] is NOT undefined,  then check [i+1] to see if it contains "http", if both conditions are true > build the image with the source from the array, and set the name and caption as location name.
in its current iteration it doesn't seem to be working correctly, it just iterates through and builds the div regardless of whether the name is undefined or not.
Any help would be much appreciated.

A: You are actually checking if the content of albums[i] equals the string undefined.
You should check if the content of albums[i] is undefined.
You should also use the ===/!== operators. If you want to check if the variable is null you should then check if albums[i] === null or albums[i] !== null
albums[i] != "undefined" => albums[i] !== undefined
Here is your for loop :
for (var i = 0; i < albums.length; i++){
    if ((albums[i] !== undefined) && (albums[i+1].indexOf("http") !== 1)){
        $("#thumbnail").css("overflow:", "auto");
        $("#thumbnail").css("max-height:", "100px");
        $("#thumbview").append('

');
    };
};


text:
Q: How to fix error in google sheet custom script I have a script that is executed in google sheet to automate the extraction of landing performance data with pageSpeed, the problem I have is that it throws me an error:

This would be the function to execute the function below and to send the corresponding url
function runTool() {
var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Results");
var rows = activeSheet.getLastRow();

for (var i = 6; i <= rows; i++) {
    var workingCell = activeSheet.getRange(i, 2).getValue();
    var stuff = "=runCheck"

    if (workingCell != "") {
        activeSheet.getRange(i, 3).setFormulaR1C1(stuff + "(R[0]C[-1])");
    }
}
}

Key would be the google key
strategy would be the device, either desktop or mobile
this is the script
function runCheck(Url) {
var settingsSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Settings");
var key = settingsSheet.getRange("C7:C7").getValue();
var strategy = settingsSheet.getRange("C19").getValue();

var serviceUrl = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=" + Url + "&key=" + key + "&strategy=" + strategy + "";

var array = [];

if (key == "YOUR_API_KEY")
    return "Please enter your API key to the script";

var response = UrlFetchApp.fetch(serviceUrl);

if (response.getResponseCode() == 200) {
    var content = JSON.parse(response.getContentText());

    if ((content != null) && (content["lighthouseResult"] != null)) {

        if (content["captchaResult"]) {
            var score = content["lighthouseResult"]["categories"]["performance"]["score"];
            var timetointeractive = content["lighthouseResult"]["audits"]["interactive"]["displayValue"].slice(0, -2);
            var largestcontentfulpaint = content["lighthouseResult"]["audits"]["largest-contentful-paint"]["displayValue"].slice(0, -2);
            var firstcontentfulpaint = content["lighthouseResult"]["audits"]["first-contentful-paint"]["displayValue"].slice(0, -2);
            var serverresponsetime = content["lighthouseResult"]["audits"]["server-response-time"]["displayValue"].slice(19, -3);
            var speedindex = content["lighthouseResult"]["audits"]["speed-index"]["displayValue"].slice(0, -2);
            var device = strategy;
        } else {
            var score = "An error occured";
            var timetointeractive = "An error occured";
            var largestcontentfulpaint = "An error occured";
            var firstcontentfulpaint = "An error occured";
            var serverresponsetime = "An error occured";
            var speedindex = "An error occured";
            var device = "An error occured";

        }
    }

    var currentDate = new Date().toJSON().slice(0, 10).replace(/-/g, '/');

    array.push([score, timetointeractive, largestcontentfulpaint, firstcontentfulpaint, serverresponsetime, speedindex, currentDate, "complete", device]);
    Utilities.sleep(1000);
    return array;
}
}


text:
Q: How to print / console log props in constructor method in react native Folks,
Please help me in a way to print/console props in the constructor. I have tried console.log(this.props) but not sure where it is getting printed.
I am using the android simulator for react-native development.
Please help.

A: You can see the console using the "Debug JS remotely" option on the emulator menu, but I strongly recommend the standalone app called "React native debugger"
https://github.com/jhen0409/react-native-debugger
You can see not only the console logs but also the components information, their props, styles, the network tab, the redux actions, states, etc.

A: Not sure, if you're asking how to bring up the console?
On Android emulator, Once your app has started, press
CMD + M to bring up the options and select "Debug JS remotely" which will automatically start the debugger on chrome

A: The output of console.log is getting printed here for Android simulator and devices
Open Terminal and run the following command :-
 $ react-native log-android

Now run the app on simulator or device, you will see the logs.
You will see the logs inside the terminal.
Similarly can do for iOS as follows:-
$ react-native log-ios

Thanks

A: A Pure React Component can be declared as follows:
class MyComp extends React.Component {
   constructor(props) {
       super(props)
       console.log(props)
       ...
    }
    ...
}

In the code above it will show you the props object being passed to the component.
In your case you must be using object/function approach to define a component, which results in a scope confusion of this.


text:
Q: I want to write a function that takes a list and returns a count of total number of duplicate elements in the list I have tried this, for some unknown reason when it prints h, it prints None, so i thought if it counts the number of None printed then divided by 2 it will give the number of duplicates, but i cant use function count here
a= [1,4,"hii",2,4,"hello","hii"]
def duplicate(L):
    li=[]
    lii=[]
    h=""
    for i in L:
        y= L.count(i)
        if y>1:
            h=y
            print h
            print h.count(None)

duplicate(a)

A: Use the Counter container:
from collections import Counter
c = Counter(['a', 'b', 'a'])

c is now a dictionary with the data: Counter({'a': 2, 'b': 1})
If you want to get a list with all duplicated elements (with no repetition), you can do as follows:
duplicates = filter(lambda k: c[k] > 1, c.iterkeys())

If you want to only count the duplicates, you can then just set
duplicates_len = len(duplicates)

A: You can use a set to get the count of unique elements, and then compare the sizes - something like that:
def duplicates(l):
    uniques = set(l)
    return len(l) - len(uniques)

A: the answer by egualo is much better, but here is another way using a dictionary.
def find_duplicates(arr):
    duplicates = {}
    duplicate_elements = []

    for element in arr:
        if element not in duplicates:
            duplicates[element] = False
        else:
            if duplicates[element] == False:
                duplicate_elements.append(element)
            duplicates[element] = True

        return duplicate_elements

It's pretty simple and doesn't go through the lists twice which is kind of nice.
>> test = [1,2,3,1,1,2,2,4]
>> find_duplicates(test)
[1, 2]

A: i found an answer which is
a= [1,4,"hii",2,4,"hello",7,"hii"]
def duplicate(L):
    li=[]
    for i in L:
        y= L.count(i)
        if y>1:
            li.append(i)
    print len(li)/2

duplicate(a)


text:
Q: setting up and maintaining summary collection this post from official mongodb blog advises to set up a summary collection as a part of a retail DB model.
I'm wondering about the ideal way of setting up and maintaining such a collection.
Is this supposed to be done through some kind of a cronjob?
Is there some convenient mongodb feature allowing to do this painlessly?


text:
Q: Typescript generic with constraint doesn't have key I'm trying to create a set of functions that operate on a generic T that must implement and interface IDocument. While this generally seems to work, it seems like TypeScript doesn't recognize that T must have the keys of IDocument.
Here is a minimal example:
interface IDocument
{
    _id: number;
}

function testGeneric<T>(v: { [P in keyof T]?: T[P] })
{ }

function testConstraint<T extends IDocument>(doc: T)
{
    // this works
    console.log(doc._id);

    // this works
    testGeneric<IDocument>({ _id: doc._id });

    // this fails
    // Argument of type '{ _id: number; }' is not assignable to parameter of type '{ [P in keyof T]?: T[P] | undefined; }'.
    testGeneric<T>({ _id: doc._id });
}

You can see this live on the TypeScript playground here.
I am confused as to why this doesn't work since it seems like in my testConstraint function that T will always have an _id key since it must implement IDocument. And in fact if I take a T parameter and access the _id property it works fine.
Note that the testGeneric function is in a library that I don't own, so I can't change that signature.
What am I doing wrong here? Do I need to use a different constraint to express that T must have each key that IDocument has?

A: The original example had a value like {_id: 10} assigned to a generic type like Partial<T> where T extends IDocument.  In such cases you can show that the compiler is correct to complain, since there are some types T that extend IDocument where 10 is not a valid property.  This is essentially the same issue as in this question.

The new example where you assign {_id: doc._id} to the generic type Partial<T> where T extends IDocument still yields an error, even though it should definitely be safe.  The compiler is unable to verify that Pick<T, "_id"> is assignable to Partial<T>.  This is (related to) an open issue; the compiler currently can't do the sort of type analysis necessary to ensure this.  In situations where you are sure something is safe (and you've double and triple checked) but the compiler isn't, you might want to use a type assertion:
testGeneric<T>({ _id: doc._id } as Partial<T>); // okay now

So inside the implementation of testConstraint() you may need to use a type assertion or the equivalent (such as a single call-signature overload with a looser implementation signature).

Finally, you said you wanted to actually prevent someone from calling testConstraint<T>() with a T whose properties are narrower than those on IDocument.  This is more restrictive than T extends IDocument, and is more cumbersome to represent in TypeScript where property narrowing is a natural part of subtyping.  You can do it by making the generic constraint include a conditional mapped type, like this:
function testConstraint<
    T extends IDocument &
    { [K in keyof IDocument]: IDocument[K] extends T[K] ? T[K] : never }>(doc: T): void;
function testConstraint(doc: IDocument) {
    testGeneric({ _id: doc._id });
}

Here we have T constrained to both IDocument and a type where each property of IDocument is compared to the corresponding property of T.  If the one on T is no narrower than the one on IDocument, great.  Otherwise, the property in the constraint is narrowed all the way to never, to which T likely will not match.
The call signature is complicated enough that the types inside the implementation would really confuse the compiler.  That's why I made it an overload, and loosened the implementation signature to be entirely non-generic.  You might be able to do something generic for the implementation, but the point is that you should probably treat the call side and the implementation separately in terms of types.
Let's see that function in action:
interface TheVeryFirstDocument extends IDocument {
    _id: 1
}
declare const tv1d: TheVeryFirstDocument;
testConstraint(tv1d); // error!
// --------->  ~~~~~
//  Types of property '_id' are incompatible.
//    Type '1' is not assignable to type 'never'.(

That gives an error, as we desire, while the following works without error:
declare const doc: IDocument;
testConstraint(doc); // okay

interface ExtendedDocument extends IDocument {
    title: string;
    numPages: number;
}
declare const xDoc: ExtendedDocument;
testConstraint(xDoc); // okay

Okay, hope that helps; good luck!  Link to code


text:
Q: does a list of all devices exist where google blacklisted webgl? I would like to know on which devices google blacklisted webgl, if such a list exists it would  be nice to get a link.

A: The list for Chrome browser appears to be here (https://code.google.com/p/chromium/codesearch#chromium/src/gpu/config/software_rendering_list_json.cc), thanks to @PaulIrish.
Note that, Google has several different rendering engines, and several browsers. So you need to be specific about the rendering engine and the browser itself.


text:
Q: How to avoid text highlighting of a string in a line starting with a specific symbol [java] I'm making a text editor which finds a string in the first line of a text and highlights it and its occurrences throughout the text. The problem is that it also highlights the occurrences located in the comment lines (started with "#").
This is my code so far:
    import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;

import java.awt.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class TextArea {

    public static void main(String[] args) {
        JFrame frame = new JFrame("textArea");
        frame.setSize(500,500);

        final JTextArea textArea = new JTextArea() ;
        frame.add(textArea);

        frame.setVisible(true);

        textArea.getDocument().addDocumentListener(new DocumentListener(){

            @Override
            public void changedUpdate(DocumentEvent e) {
                try {
                    String keyWords = findKeyWord();
                    findOccurrences(keyWords);
                } catch (BadLocationException ex) {
                    Logger.getLogger(TextArea.class.getName()).log(Level.SEVERE, null, ex);
                }

            }

            @Override
            public void insertUpdate(DocumentEvent e) {
                try {
                    String keyWords = findKeyWord();
                    findOccurrences(keyWords);
                } catch (BadLocationException ex) {
                    Logger.getLogger(TextArea.class.getName()).log(Level.SEVERE, null, ex);
                }

            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                try {
                    String keyWords = findKeyWord();
                    findOccurrences(keyWords);
                } catch (BadLocationException ex) {
                    Logger.getLogger(TextArea.class.getName()).log(Level.SEVERE, null, ex);
                }

            }

            public String findKeyWord() throws BadLocationException {
                String keyWord = "";

                for( String line : textArea.getText().split("\n")){
                    if (line.trim().length() > 0) {
                        if( !line.startsWith("#") ){
                            int keywordEndPosition = line.indexOf("#");
                            keyWord = line.substring(0, keywordEndPosition == -1 ? line.length() : keywordEndPosition);
                            keyWord = keyWord.trim();
                            break;
                        }
                    }

                }
            return keyWord;
            }

            public void findOccurrences(String keyWords) throws BadLocationException {
                Highlighter highlighter = textArea.getHighlighter();
                DefaultHighlighter.DefaultHighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(Color.CYAN);
                String[] keyArray;
                highlighter.removeAllHighlights();

                keyArray = keyWords.split("[(,)]");
                for (int i=0; i<keyArray.length; i++) {
                    keyArray[i] = keyArray[i].trim();                }

                for (String keyWord : keyArray) {
                    if (keyWord.isEmpty())
                        return;

                    Pattern pattern = Pattern.compile( Pattern.quote(keyWord) );
                    Matcher matcher = pattern.matcher(textArea.getText());

                    while(matcher.find()) {
                        highlighter.addHighlight(matcher.start(), matcher.end(), painter);
                    }
                }
            }

        });
    }
}

How can I edit this code to avoid highlighting of occurrences situated after a "#" symbol in a line?
Thanks for your help!

A: Replace the pattern with:
Pattern pattern = Pattern.compile("(?<!#.{0,1000})" + Pattern.quote(keyWord));

i am using a regular expression with negative lookbehind and a length of up to 1000 characters between # and the keyword.


text:
Q: Javascript wait for Promise to complete inside for-loop before returning response I am trying to respond after a Promise within a for-loop is complete.
I have looked at these questions, but they don't address my situation.
The methodGetOrders and methodGetLines are part of an external library that I have to use. They both make network calls, so there is some expected lag. The function always returns a '0', since it doesn't wait for the inner promise to complete. I realize there is no way to 'wait' for the promise to complete, but how do I get the correct value of counter in the response?
doWorkMainFunction() {
  methodGetOrders()
    .then(orderList =>  {
       var counter=0;
       for (var i=0; i< orderList.length; i++) {
         methodGetLines()
           .then (lineData => {
              if (someCondition) { counter++; }
            } // end of inner THEN
       } // end FOR loop
       return counter; // This always returns '0'
   } // end of outer THEN
}

A: Create an array of all the promises in the loop and then use Promise.all() to return counter after all those promises have resolved
methodGetOrders()
  .then(orderList => {
    var counter = 0;

    var promises = orderList.map(order => {
      return methodGetLines()
        .then(lineData => {
          if (someCondition) {
            counter++;
          }
        }) // end of inner THEN
    }) // end promise map
    return Promise.all(promises).then(_ => counter);
  }) // end of outer THEN
})


text:
Q: Forwarding linux terminal from serial port to TCP with socat I'm working on embedded ARM platform, Slackware. I'm using G24 Java modem which is configured to forward data between ports /dev/ttyS1 and /dev/ttyACM0, so anything that goes onto any of these ports is then visible on the other. I want to set terminal on one of these ports, /dev/ttyS1 and forward the other port, /dev/ACM0 to the TCP port, so it can be accessed from other machine via LAN.
First of all, I configured /etc/inittab:
s2:12345:respawn:/sbin/agetty -L ttyS1 115200 vt100

Then I'm trying to use socat with following command:
socat -d -d -d TCP-l:2020,reuseaddr,fork /dev/ttyACM0,raw,nonblock,waitlock="/var/run/ttyACM0.lock",b115200,echo=1,icanon=1,crnl
Then I'm trying to connect with telnet 192.168.1.222 2020 from other machine, the result is not quite good, I see from the client side that terminal is asking for login, but then there is an immediate answer which I haven't typed in: ^M^M^M... etc., the terminal is answering that the login is incorrect and then again and again the same thing.
I know that ^M means carriage return sign, but I'm not quite sure how to fix that problem.
I have tried different configurations of socat, but none of them worked correctly.

A: After few more hours of intensive research and testing many different options I came with a solution.
First of all, I had to enable terminal by adding line:
ttyS1
in file /etc/securetty.
Without this you cannot login to terminal at /dev/ttyS1.
Secondly, I tested many different socat configurations and the following command works:
/usr/local/bin/socat tcp-l:2020,reuseaddr,fork,crlf file:/dev/ttyACM0,echo=0,b115200,raw,crnl,icanon=1
However, this solution isn't perfect. Terminal breaks line after every command prompt so the user input is typed in the next line. Furthermore, after executing each command appears an empty command prompt (like I had entered empty command immediately after the one I had really entered).
I suppose that I should configure /dev/ttyACM0 properly with stty, but I'm still researching the topic.


text:
Q: Recursive merge sort - sorts coordinates in ascending order from an origin I have an assignment where I need to implement merge sort to sort some coordinates in ascending order from the origin. I have my program's coordinates as follows (cannot edit this; it is required for the assignment):
// stores the origin (does not change).
struct origin
{
  int x_naught;
  int y_naught;
};

// Individual coordinate to be sorted.
struct coordinate
{
  int x;
  int y;
};

I have an unsorted array of struct coordinates: struct coordinate **coordArray; that holds n amount of coordinate struct pointers.
My question is, what is the most efficient way to sort these coordinates in ascending order from the origin using merge sort? I originally planned to have helper function that declares a separate array and stores the magnitude (distance formula) of each coordinate in the coordArray array, and then pass that array, as well as its length to a recursive merge sort function.
This, I believe, is the easiest and most straight forward way to do this. However, I do not like the fact that this helper function will take an extra n (length) steps of work to sort coordArray before even calling merge_sort.. Is it possible to somehow sort these coordinates by just passing the two struct pointers into a recursive merge_sort function?
Possible function signature:
void merge_sort(struct origin *origin_coord, struct coordinate **coordArray, int length);

One problem I see with the approach I am trying to implement here is how to deal with sorting the x and y components separately (i.e., coordArray[I]->x, coordArray[I]->y) for the x and y in struct origin (i.e., origin_coord->x_naught, origin_coord->y_naught).
I understand that O(2n log(n)) (or maybe even O(3nlogn) to convert the sorted magnitude array back into its original form: (x, y)) for the merge_sort and helper function really isn't that big of a deal, but if I'm sorting 1 billion coordinates, that extra 2 billion steps of work might matter.

A: If you cannot store the distance or its square in the coordinate structure, I would suggest you pass the origin structure as an argument to your mergesort_coords function and recompute the square of both distances in the comparison function.  This computation is quite cheap as simple compared to the overhead of allocating and handling ancillary structures. Furthermore, the time complexity is unchanged at O(N.log(N)).
Regarding the x and y ordering, you should specify how to order coordinates that have the same distance to the origin. There are many options for this but the comparison function must be transitive and the order should be complete.
Suggested prototypes:
void merge_sort(struct coordinate **coordArray, size_t count,
                int cmp(const struct coordinate *a,
                        const struct coordinate *b,
                        const struct origin *origin_coord),
                struct origin *origin_coord);

int cmpdistance(const struct coordinate *a,
                const struct coordinate *b,
                const struct origin *o)
{
    long long dxa = (long long)a->x - o->x_naught;
    long long dya = (long long)a->y - o->y_naught;
    long long dxb = (long long)b->x - o->x_naught;
    long long dyb = (long long)b->y - o->y_naught;
    long long da = dxa * dxa + dya * dya;
    long long db = dxb * dxb + dyb * dyb;
    if (da < db) return -1;
    if (da > db) return +1;
    // if points are at the same distance, order by x, then by y
    if (a->x < b->x) return -1;
    if (a->x > b->x) return +1;
    if (a->y < b->y) return -1;
    if (a->y > b->y) return +1;
    return 0;
}


text:
Q: How to select first-n/top-n rows from a query's resultant if its count is more than a given number? I have a query that returns more than 1000 rows.
Step1:
with total_res as (
select table1.col1, table1.col2, table2.col3,... table2.coln
from table1 join table2
    on table1.keycol=table2.keycol
where table1.col4='ABCD' and table2.col5 <= '02-02-2022'
   order by table1.col1 desc)

In my requirement, I have to return the first 350rows by ordering col3 in desc if the output of the above query contain more than 1000rows.
So I added a row number column like below to add sequential numbers to the resulset from above.
Step2:
select col1, col2, col2...coln, ROW_NUMBER() OVER (ORDER BY col3 desc) as number from total_res;

What I don't understand now is how can I check if the output from step2 contains more than 350 rows and if so, select the first 350 rows.
Could anyone let me know how can I achieve this ? Or is there a better way to do it than using row_number ?

A: try like below in 2nd step check highest number>350 and then limit the value 350
with cte as
(
select col1, col2, col2...coln, ROW_NUMBER() OVER (ORDER BY col3  as number from total_res

) select * from cte
  where 350 < ( select max(number) from cte)
order by number
limit 350


text:
Q: Problema para mostrar datos de manera correcta en consulta SQL en Access Buen día. Tengo una tabla en Access llamada Cartera compuesta de la siguiente manera
idCartera, codigo, nombre, categoria, mes, idAnio

(El campo mes se llena del 1 al 12 representando a cada mes).. Y por ejemplo tengo estos registros
1, 123, "Juan", "A1", 1, 12
2, 456, "Maria", "B", 1, 12
3, 789, "Pepe", "A2", 1, 12

4, 123, "Juan", "A1", 2, 12
5, 456, "Maria", "A1", 2, 12
6, 789, "Pepe", "A2", 2, 12

Lo que necesito es mostrar los registros que cumplan con un rango de categorias Pero hay un caso especial: En el caso de la categoria A1. Si en el mes anterior la categoria es A1 y en el mes actual sigue siendo A1, no debo mostrarla. Pero si en el mes anterior es cualquier categoria diferente de A1 y en el mes actual la categoria es A1, si debo mostrala
Por ejemplo, Ubicándonos en la consulta del mes de Febrero, los resultados que deseo obtener son
5, 456, "Maria", "A1", 2, 12
6, 456, "Pepe", "A2", 2, 12

Por el momento la consulta que tengo es:
SELECT c.idCartera, c.codigo, c.nombre, [c].[mes]-1 AS mes_anterior
FROM cartera AS c INNER JOIN cartera AS d ON (c.codigo = d.codigo) AND (d.mes = c.mes-1) AND (c.idAnio = d.idAnio)
WHERE c.mes = 2 AND c.categoria IN ('A1','A2','B')

(Para aclarar: Lo de "mes_anterior" lo utilizo para hacer una resta en
  otra consulta)

Pero esta consulta no cumple con el caso especial que tengo, en vez de eso me muestra todos los registros con categoria A1 sin importar que en el mes anterior la categoria es la misma. O sea que me devuelve:
4, 123, "Juan", "A1", 2, 12
5, 456, "Maria", "A1", 2, 12
6, 789, "Pepe", "A2", 2, 12

Entonces mi pregunta es de que manera puedo poner ese caso especial o "condicion" en mi consulta.
De antemano, gracias.

A: SELECT c.idCartera, c.codigo, c.nombre, [c].[mes]-1 AS mes_anterior
FROM #cartera AS c
    INNER JOIN #cartera AS d ON (c.codigo = d.codigo) AND (d.mes = c.mes-1) AND (c.idAnio = d.idAnio)
WHERE c.mes = 2 AND ((d.categoria <> 'A1' and c.categoria = 'A1') or c.categoria <> 'A1') AND c.categoria IN ('A1','A2','B')

Diria que esta es la consulta que pides, en esta consulta tiene que tener que si la categoria del "mes en curso" es A1 el anterior es distinto de A1 o que directamente este mes sea distinto de A1, revisalo a ver que tal


text:
Q: Btrieve file only shows partial data Almost ready to throw up the white flag but thought I'd throw it out there. I have an OLD program from 1994 that uses a btrieve dB and renders basic membership info for a gym. The btr file that holds the data will open in notepad and I can search and find all records although the formatting is nearly unreadable. When it opens in the program there is a huge chunk of records missing. It seems to stop on specific records up and down when scrolling.
I know almost nothing about btrieve as it predates my IT career by many years and I've honestly never seen it. Any suggestions on where I should troubleshoot or tools that may help would be much appreciated.

A: This sounds like the file may be corrupted although I would expect errors if it was corrupted.  One way to rebuild the file is to use BUTIL (and a couple of OS commands).
The steps to rebuild are:

*

*Make a backup of the original file to another directory.

*Rename the original file.  I like to use change the extension to .OLD.

*Delete the original file.  It will be recreated in the next step.

*Issue the BUTIL -CLONE command (BUTIL -CLONE

*Issue the BUTIL -COPY command (BUTIL -COPY

The rebuild is complete.
I've use the commands below in the past (changing 'filename' and the extensions to match my files).
copy filename.btr someother\location\filename.btr
ren filename.btr filename.old
del filename.btr
butil -clone filename.btr filename.old
butil -copy filename.old filename.btr


text:
Q: Como pegar o 2 valor de um indice e mostrar? No meu programa eu faço a pesquisa dos dados da tabela e adiciono num array v_patr e depois eu adiciono esse array na var w_a:
<html>
            <select multiple size="7" name="cb_Patr" style="width:300">
                <?
                $w_querybusca="SELECT * FROM public.sai_cad_patr_seri WHERE
                                sai_cad_patr_seri.fk_seq_cara_peri = '$arr_w_param[17]'";
                $w_queryresultado=f_class_conecta_bd($w_querybusca);
                $w_indice = 0;
                while($w_registro = pg_fetch_object($w_queryresultado))
                {
                    print('<option value="'.$w_registro->tx_num_patr.'">'.trim($w_registro->tx_num_patr).'</option>'."\n");

                    print("<SCRIPT language=javascript>
                               v_patr[$w_indice] = \"$w_registro->tx_num_patr,$w_registro->tx_num_seri\";
                           w_a = v_patr[$w_indice];
                           </SCRIPT>");

                    $w_indice++;
                }
                ?>
               </select>

Mas eu tenho uma segunda pesquisa depois. Assim eu vou reaproveitar o v_patr que foi adicionado em w_a para pegar o elemento 1 do array.
            <select multiple size="7" name="cb_Seri" style="width:300">
            <?
                for($i=0;$i<=$w_indice;$i++)
                {

                    //print('<option value="'.$i.'">'._[$i].'</option>'."\n");
                }
                ?>
                </select>

Mas eu não sei como pegar os elemento do w_a que foi criado em um JS dentro do php e atribuir ele ao: print('<option value="'.$i.'">'.w_a[$i].'</option>'."\n");

A: O transporte da variável de uma linguagem para outra deve ser feita sobre uma nova requisição. Não só vai te incomodar tentar trafegar essa informação sobre as duas linguagens, como este é o jeito errado de fazer.
Para não reinventar a roda, sugiro você fazer a leitura desta minha resposta que dá um resumo sobre requisições $.ajax – que é a solução para os seus problemas.


text:
Q: Chat crashes mobile chrome I just recently started using stack overflow chat. I tried to access it from my iPhone with chrome web browser, but it causes it to crash sometimes. I have never had it crash this consistently on any other site. I tried to figure out how to reproduce the problem, but it is seemingly random. No specific operations or amount of time cause it, as far as I can tell
Edit: it is on iOS 7.0.4 and chrome v33.0.1750.15


text:
Q: app.config / program.cs expected by TFS but not in solution explorer I added a new project to a solution as a class library. I worked on it for several days and now the time has come to check in my changes to TFS.
However, the following two files are expected by TFS:
Program.cs and app.config. The check-in fails because they don't exist.
Furthermore, when I go to the solution explorer and try to browse to find the files they aren't there either.
I can check in the project by just excluding them, but I'm afraid this may be breaking something, as well as it's just annoying. (I can't see them to remove them in the solution explorer so they'll show up every time I do a check-in.)
I have edited the myproject.csproj file in a text editor and can't find any reference to either file there either.

A: OK I saw that when I tried to check in that project individually it wouldn't give me that option (the rest of the project was already checked in.) It was only when I clicked on the Solution and tried to check in from there that it expected the files, but in the directory of this project.
So I went into the Source Control Explorer and browsed to that directory, and sure enough there they were. I was able to delete them from there and problem solved.

A:  I think you have created a console project instead of a class library, suddenly when you want to archive, it also expects a app.config and a class contains the Main() method.
The solution I propose you is to change the output type to calss library.


text:
Q: Android gradle error(30.0) : gradle DSL method not found : compile() There is some error in compile error in build.gradle file. when i am synchronise the code there is something missing in the compile() method and mention an error (30,0).
build.gradle(project) :

dependencies {
        classpath 'com.android.tools.build:gradle:2.1.2'
        //classpath 'com.google.gms:google-services:3.0.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

AND build.gradle(module) CODE IS :
buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
}

//add library
compile 'com.android.support:design:25.0.1'
compile 'com.firebaseui:firebase-ui:0.6.2'


text:
Q: Would interrupting a partitioning process cause my Hard Drive to become bad? Can I fix it with a full format? I was trying to partition my hard drive to install windows 7 without losing data, but I thought the process had locked up so I stopped it and restarted my computer. I tried again and it worked, but when I went to install win7, the computer started saying my hard drive was bad, and so did diagnostic tools. I wasn't having this problem just earlier that same day.
Been using the drive like this just fine for a month now, with the partitions remerged, but everything still says the drive is bad. I'm thinking about reformatting before I decide to just buy a new hard drive. Is this likely to work? My hard drive is a spinpoint F3 1TB.
Note: when I was partitioning, this drive had been my secondary storage drive. I was partitioning because I was making it my primary drive in a new build that day, but didn't want to lose data as I had no external to hold 350 gigs of data.
I've tried Seatools and CrystalDiskInfo. Here is the screenshot from CrystalDiskInfo:

A: No, interrupting the partitioning process probably didn't cause the hard drive to become bad. However, if you were using a utility to resize the partitions, a lot of data would have gotten shuffled around, and in the process some previously-unreported bad sectors could have been discovered.
It may be the case that the hard drive was failing already and that's why it originally seemed like the repartitioning process had locked up.
You should try running SMART diagnostics on the drive. If you don't have another computer you can plug it into, you can boot off an Ubuntu Live CD. First, unplug any other hard drives, then open a terminal and type the following:
sudo bash
apt-get install smartmontools
smartctl -a /dev/sda

Check the Reallocated Sector Count. If the raw value is greater than zero, the hard drive has already started failing and would be a ticking timebomb if you were to continue using it. If this is the case, you should replace it, especially if it's still under warranty.
Hard drives do have a certain number of "spare" sectors which will be used to automatically replace bad sectors, and once the spare sectors run out, chkdsk (on Windows) or badblocks (on Linux) will start to report bad sectors. Although it has generally been considered okay to have a few reallocated sectors, you may also notice increasingly worse disk performance as more and more sectors are reallocated.
Update: based on your SMART diagnostics, I'd recommend replacing the drive. If you want to use it anyway, I'd at least recommend checking the power supply and the power and data cables. Then I'd image the drive, do a full read/write test, and run the SMART diagnostics again before putting it back in service. But even then, I still wouldn't trust it.
To do a thorough disk surface test, follow the instructions below. (WARNING: this will destroy all data on the drive!) Alternatively, you can do a chkdsk /r in Windows, but that won't be quite as thorough. Note that this will not reset the drive's SMART data. You will have to check with the drive manufacturer to see whether they have made any tools available to consumers which will do this. (My guess would be no, since unscrupulous fellows could then sell defective hard drives that look like new, perfect drives, according to the SMART data.)

*

*Remove all other hard drives, flash drives, etc. (So you only have the goofy hard drive and the CD/DVD drive)

*Boot off an Ubuntu Live CD

*Open a terminal and type this command (you'll probably want to let it run overnight):
badblocks -wvs /dev/sda

*After badblocks finishes, run your SMART diagnostics again and compare with the previous values.

The badblocks command listed above will make four passes, writing and reading each of the following patterns: 10101010, 01010101, 11111111, and 00000000--leaving it completely zeroed in the end. Afterward, you will need to partition and format the drive.
Again, because of the high read error rate reported by the SMART diagnostics, I still wouldn't trust the drive to reliably store anything that can't be easily restored or reproduced.

A: Stopping a partitioning process shouldn't (from my knowledge) actually make the disk unusable.   It may make the data on the disk hard to recover or lost forever.
The disk may be failing and if so check the SMART status with a 'Live CD' OS like Ubuntu or Fedora.
If the drive checks out then try partitioning and formatting the disk with fdisk and mke2fs in one of those Unix systems.  I have had problems with Windows complaining about disks and unable to do any kind of work (partition, format, etc) until I used outside system to bring the file-system to a usable state.  Windows seems particularly reluctant to recover from disk errors and then not provide easy tools to correct the issue.


text:
Q: MyQuery error: "null | Unknown column in 'where clause'" This is for my senior project. Please keep in mind that I'm still a beginner.
So I want to create a search app where the user will choose a 'speciality' from a JComboBox and once they click 'Search', the app will retrieve data from MySQL database and display it in a JTable.
Since I'm not a pro at programming I followed some tutorials and I'm stuck on this error:

Unknown column 'Architecture' in 'where clause'

'Architecture' is one of the options in the JComboBox but I think SQL reads it as a column although it is a row!
this is my Query:
public class MyQuery {

   public Connection getConnection(){
        Connection con = null;
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydata?autoReconnect=true&useSSL=false", "root", "1110");
        } catch (SQLException ex) {
            Logger.getLogger(Query.class.getName()).log(Level.SEVERE, null, ex);
        }
        return con;
    }

    public ArrayList<Applications> getData(String speciality){

   ArrayList<Applications> list = new ArrayList<Applications>();
   Connection con = getConnection();
   Statement st;
   ResultSet rows;

   try {
   st = con.createStatement();

   rows = st.executeQuery("SELECT * FROM mydb.applications WHERE speciality LIKE " + speciality);

   Applications applications;
   while(rows.next()){
   applications = new Applications(
   rows.getInt("id"),
   rows.getString("name"),
   rows.getString("nationality"),
   rows.getString("speciality"),
   rows.getString("experience")
   );

   list.add(applications);
   }

   } catch (SQLException ex) {
   Logger.getLogger(MyQuery.class.getName()).log(Level.SEVERE, null, ex);
   }
   return list;
   }
}

&
        JButton btnSearch = new JButton("Search...\n");
    btnSearch.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            MyQuery mq = new MyQuery();
            ArrayList<Applications> list = mq.getData((String)comboBox_searchSp.getSelectedItem());
            DefaultTableModel model = new DefaultTableModel();
            model.setColumnIdentifiers(new Object[]{"ID","Name","Nationality","Speciality","Experience"});
            Object[] row = new Object[5];
            for(int i = 0; i < list.size(); i++){
                row[0] = list.get(i).getName();
                row[1] = list.get(i).getNationality();
                row[2] = list.get(i).getSpeciality();
                row[3] = list.get(i).getExperience();
                model.addRow(row);
            }
            table.setModel(model);

        }

            public void BindCombo(){

            MyQuery mq = new MyQuery();
            Connection con =  mq.getConnection();
            Statement st;
            ResultSet rows;

            try {
                st = con.createStatement();
                rows = st.executeQuery("SELECT `id`, `name` FROM mydb.applications");
                while(rows.next()){
                    comboBox_searchSp.addItem(rows.getInt(1));
                }
            } catch (SQLException ex) {
                Logger.getLogger(AdminPage.class.getName()).log(Level.SEVERE, null, ex);
            }

            }

    });

A: An even better solution is to use a PreparedStatement -- then you won't get into trouble if one of your specialties was Being "cool", even though it contains a quote character.
Prepared statements also protect you against SQL injection attacks.
PreparedStatement ps = connection.prepareStatement(
    "SELECT * FROM mydb.applications WHERE speciality LIKE ?");
ps.setString(1, specialty);
ResultSet rs = ps.executeQuery();

A: Try to put quotes around the input:
rows = st.executeQuery("SELECT * FROM mydb.applications WHERE speciality LIKE '" + speciality + "'");

A: The issue here is in your SQL query syntax:
rows = st.executeQuery("SELECT * FROM mydb.applications WHERE speciality LIKE " + speciality);

should be:
rows = st.executeQuery("SELECT * FROM mydb.applications WHERE speciality LIKE '" + speciality+"'");


text:
Q: Is an HMM an appropriate model for a case like this? If not, what is? I hope to build a fully empirical model of Total Daily Energy Expenditure (TDEE), i.e. the number of calories an individual must eat in order to neither lose nor gain weight.
As data, I have individuals' weight (measured daily) and calorie intake (also daily).
As the TDEE is not directly observed, it occurred to me to use a Hidden Markov Model (HMM) for this. However, there are continuously many states that the system can be in -- one's TDEE could be any nonnegative real number. Does that mean an HMM is the wrong tool? If so, what might serve better here?

A: HMMs can be used with a continuous state space, in the sense that you can extend the concepts (Bayesian reasoning, hidden/observed random variables, ...) and the use that same framework with continuous hidden variables. Quoting Wikipedia:

Hidden Markov models can also be generalized to allow continuous state spaces. Examples of such models are those where the Markov process over hidden variables is a linear dynamical system, with a linear relationship among related variables and where all hidden and observed variables follow a Gaussian distribution. In simple cases, such as the linear dynamical system just mentioned, exact inference is tractable (in this case, using the Kalman filter); however, in general, exact inference in HMMs with continuous latent variables is infeasible, and approximate methods must be used, such as the extended Kalman filter or the particle filter.

This tutorial is a good introduction on the topic.
As for your precise application, I am not familiar with it and there is too few details for me to judge. But you might give HMMs a try!


text:
Q: When modifying a pre-trained model in pytorch, does the old weight get re-initialized? I'm modifying a pretrained efficient-net model in pytorch. I'm doing the following in order:

*

*Create the default model, load the imagenet weights.

*Then, change the number of channels in the first layer, and delete few layers while adding few.
from efficientnet_pytorch import EfficientNet
from efficientnet_pytorch.utils import Conv2dStaticSamePadding

PATH = "../input/efficientnet-pytorch/efficientnet-b0-08094119.pth"
model = EfficientNet.from_name('efficientnet-b0')
model.load_state_dict(torch.load(PATH))

# augment model with 4 channels

model._conv_stem = Conv2dStaticSamePadding(4, 32, kernel_size = (3,3), stride = (2,2),
                                                             bias = False, image_size = 512)

model._fc = torch.nn.Linear(in_features=1280, out_features=2, bias=True)

My question is: what will happen to the original weights that I loaded? Will it be there or all of the model will get randomly initialized?

A: If you are re-defining some of the layers, which you seem to be doing with model._conv_stem and model._fc. Then, yes those will be randomly initialized, thus meaning the loaded weights will no longer be used on those layers. The rest of the model will of course stay untouched and will use the loaded weights.


text:
Q: Parsing chain of greater than in Bison/Yacc I'm attempting to construct a linked list of comparisons using yacc/bison grammar.
In short I conceptually want to take:
3 < 4 < 5

And create a basic linked list of value, comparison, etc.  I've tried to simplify what I have now to the specific-ist test case
%{

#define LESS_THAN 1

typedef struct mylist {
    long num;
    int sym;
    mylist* next;
} mylist;

void destroy_mylist(mylist* l) {
    mylist* n = NULL;

    if (l->next != NULL) {
        n = l->next;
    }

    free(l);

    if (n != NULL) {
        destroy_mylist(n);
    }
}

mylist* create_list(long left, long right, int sym) {
    mylist* l = malloc(sizeof(mylist));
    mylist* r = malloc(sizeof(mylist));
    l->num = left;
    l->sym = sym;
    l->next = r;
    r->num = right;
    return l;
}

mylist* add_list(mylist* l, long num, int sym) {
    mylist* n = malloc(sizeof(mylist));
    mylist* t = l;
    n->num = num;

    while (t->next != NULL) {
        t = t->next;
    }

    t->sym = sym;
    t->next = n;
    return l;
}

%}
%destructor { destroy_mylist($$); } <list>

%union {
    long tmp;
}

%type <list> top_list expr compare_chain
%left '<'
%token <tmp> T_LONG "Long"
%start start

%% /* Rules */

start:
    top_list { $1; }
;

top_list:
    expr { $$ = $1; }
|   { $$ = NULL; }
;

expr:
    compare_chain { $$ = $1; }
|   T_LONG { $$ = $1; }
;

compare_chain:
    compare_chain '<' expr { $$ = add_list($1, $3, LESS_THAN); }
|   expr '<' expr { $$ = create_list($1, $3, LESS_THAN); }
;

%%

FWIW, this probably won't compile, it's an attempt to be a close example of what i'm trying to attempt here.  The goal of this being that the result would be a mylist struct that would look like:
1 = {num = 3, sym = 1, next = 2}
2 = {num = 4, sym = 1, next = 3}
3 = {num = 5, sym = -, next = null}

A: Your add_list function adds to the end of the list, but since your yacc rule is right recursive it builds the list from right to left, which means you want to add on to the front of the list.  Change it to:
mylist* add_list(mylist* l, long num, int sym) {
    mylist* n = malloc(sizeof(mylist));
    n->num = num;
    n->sym = sym;
    n->next = l;
    return n;
}

You also have a broken grammar, defining expr in terms of compare_chain and compare_chain in terms of expr.  Get rid of the expr: compare_chain rule, and change top_list to be top_list: compare_chain.


text:
Q: System Verilog fork confusion, statements executed between fork and begin See the simplified example code here:
    process job[num_objs];
    // assume also, arr_obj1s (array of type obj1) and
    // arr_obj2s (array of type obj2) are arrays of size
    // num_objs, and the objects define a run() function
    foreach (arr_obj1s[i]) begin
        fork
            automatic int j = i;
            arr_obj1s[j].run(); // these run forever loops
            begin
                job[j] = process::self();
                arr_obj2s[j].run(); // these run finite logic
            end
        join_none
    end

    foreach (job[i]) begin
        wait (job[i] != null);
        job[i].await();
    end

    // How do we ever reach here?

My confusion is that the calls to arr_obj1s[j].run() will never return (they run forever loops) and I don't quite follow the meaning of that call's placement outside the begin/end block. Which process is that forever run() executed on, and how can it be that each call to await() will return if some process is running a run() which won't return?
EDIT: Here is some more information. Posting the full code would be pages and pages, but I hope this extra bit helps.
obj1's run() function looks like this:
virtual task run;
  fork
    run_a(); // different logically separated tasks
    run_b();
    run_c();
  join
endtask: run

And as an example, run_a looks basically like this (they are all similar):
virtual task run_a;
  // declare some local variables
  forever begin
    @(posedge clk)
    // ...
  end
endtask: run_a

But obj2's run() function looks basically like this:
virtual task run;
  fork
    run_d(); // different logically separated tasks
    run_e();
  join
endtask: run

And as an example run_d() looks like this:
virtual task run_d;
  while ((data_que.size() > 0)) begin
    // process a pre-loaded queue,
    // data will not be pushed on during the simulation
  end
endtask:run_d

A: This code fragment looks like it is demonstrating process control so here's my guess as to what's going on. There is a group of processes in arr_obj1s and arr_obj2s:

*

*Those in arr_obj1s run forever so they only need to be spawned once and forgotten about.

*Those in arr_obj2s accomplish some task and return, so the parent process needs to know when this happens.

*All processes have the same parent

My confusion is that the calls to arr_obj1s[j].run() will never return
  (they run forever loops) and I don't quite follow the meaning of that
  call's placement outside the begin/end block

So all that's needed to spawn all processes are three lines of code in the fork..join_none block.
foreach (arr_obj1s[i]) begin
  fork
    automatic int j = i; // Spawns process
    arr_obj1s[j].run();  // Spawns process
    arr_obj2s[j].run();  // Spawns process
  join_none
end

The join_none keyword indicates that execution will continue after the parallel block completes, thus the entire foreach loop will execute and then the parent process will continue on to the next foreach loop. Further, the join_none also means that the child processes will not start until the parent process reaches a blocking statement.
However this won't allow us to detect when the child processes complete, unless they have some sort of shared variable they modify. To get around having to code that, SystemVerilog allows a handle to a process so it can schedule an event when the process completes. It doesn't, however, provide the ability to get the handle of a single statement. You must use process::self() inside a procedural context to get the process handle. Thus this won't work right if added directly to the fork-join block.
foreach (arr_obj1s[i]) begin
  fork
    automatic int j = i;
    arr_obj1s[j].run();
    job[j] = process::self(); // Will return parent process
    arr_obj2s[j].run();
  join_none
end

To fix this we need to create a new sequential procedural context that we can get the process handle of, then run the function from there:
foreach (arr_obj1s[i]) begin
  fork
    automatic int j = i;
    arr_obj1s[j].run(); // Spawns a new process for those that don't complete
    begin               // Spawns a new process for those that complete
      job[j] = process::self(); // Saves handle to this begin..end process
      arr_obj2s[j].run();       // Process continues though here
    end
  join_none
end

The final foreach loop only waits on processes for which we have a handle of. The processes that run forever are ignored.

A: First off, the way fork/join works in Verilog, each statement in the fork/join block executes concurrently.  Absent a begin/end, each line is a statement in itself.
So your example is forking off at least two processes for each iteration of the loop.
    fork
        automatic int j = i;                               <= Statement 1 ??
        arr_obj1s[j].run(); // these run forever loops     <= Statement 2
        begin                                              \
            job[j] = process::self();                      |  <= Statement 3
            arr_obj2s[j].run(); // these run finite logic  |
        end                                                /
    join_none

I say at least, because I don't fully understand how the automatic int j is treated in this case.
So here is what happens.
For each iteration of the loop:

*

*arr_obj1s[j].run() is started. (This runs a forever loop and will never end.)

*arr_obj2s[j].run() is started. (This will end after running for some finite time.)  The process ID for the process that started this is stored in job[j].

The code which is calling await is only waiting on the processes which started the calls to arr_obj2s[j].run().  They will complete since they are running a finite task.
The forever loops will still be running, even after the await calls have all completed.


text:
Q: Unable to send array with post method and to query multiple items to DB I am creating an array with a while for each item that I have saved on my DB and is being displayed with checkboxes to allow the user to select which ones they'll be using, but I am not able to send those items..
this is what I am using to display each item and is being displayed on my screen with each id of the table and the exercise assigned to that id
<?php while ($row7 = mysqli_fetch_array($result7)):;?>
<input type="checkbox" name="array[]" value="<?php $row7['id_detalle_plan'];?>"><?php echo $row7['ejercicio'];?>
<?php endwhile;?>

and this is what I am using to save the array but I guess something is missing on my code
foreach ($_POST["array"] as $elementos){
    $sql = "INSERT INTO usuario_detalle_plan(id_detalle_plan,id_usuario)
            values('$elementos','$idusuario');INSERT INTO detalle_plan_has_dia(id_detalle_plan,id_dia)
            values('$elementos','$id_dia')";
    mysqli_multi_query($db,$sql);
}

I just want to save the selected items from the checkboxes but those checkboxes are created with the WHILE that I used to display them


text:
Q: How to pass HTML META tags from inside a Google App SANDBOX to the parent window? Using Google App Script UI creating a simple file upload script, it works, but there is a Catch 22. Google wraps your HTML code in an IFRAME SANDBOX and any/all meta-tags in your HTML page are not passed to the parent wrapper.
I do realize security is the reason Goggle uses IFRAME/SANDBOX, however, one should be able to set some common tags such as, title and viewport, as that would pose no security risk to the sandBox.
Here is a snippet of what I tried, but did not work in a Google App Script, Yes I tried just regular meta tags, but they don't pass to the parent.
function setParentMetaTag() {
    var viewPortTag=document.createElement('meta');
    viewPortTag.id="viewport";
    viewPortTag.name = "viewport";
    viewPortTag.content = "width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;";
    window.parent.document.getElementsByTagName('head')[0].appendChild(viewPortTag);
}
setParentMetaTag();


text:
Q: Find the asymptotic behavior of solutions of the equation Find the asymptotic behavior of solutions $y$ of the equation
$$x^5 + x^2y^2=y^6,$$
which tends to $0$ when $x$ tends to $0$.
My solution: if $y=Ax^n$, then
$$x^5 + A^2x^{2+2n}=A^6x^{6n}.$$
If $2+2n\ge 5$, we should have $5=6n$, but $2+2\cdot5/6 \not> 5$.
If $2+2n< 5$, we have $2+2n=6n$, $n=1/2$; $A^2=A^6\Longrightarrow A=1$, and $y\sim \sqrt x$ when $x\to 0$.
Am I right? How to find the next terms of the expansion of $y$?

A: Now lets use a correction term
$$y=\sqrt x + f$$
Insert and use only the first two terms in the binomial expansion
$$x^5+x^2(x+2x^{0.5} f)=x^3+6x^{2.5}f$$
$$x^5=4x^{2.5}f$$
$$f=\frac{x^{2.5}}{4}$$
Now, you may want to insert $y=\sqrt x +\frac{x^{2.5}}{4}+f$
Adding (or multiplying) a correction term and inserting into the equation usually works well.
The order of the colors are blue orange green red
Beware, I simply guessed the 0.0275


text:
Q: Trigger Animations I have a usercontrol that when I double click on it, I want it to zoom in, if it's not already. If it is, then the double click will zoom out on it. I can get it to work with code behind, but I can't get it to work in xaml.
Here is the code behind that handle's the double click event.
void MyObjectMouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        if (IsZoomedIn)
        {
            IsZoomedIn = false;
            //ZoomOutAnimation();
        }
        else
        {
            IsZoomedIn = true;
            //ZoomInAnimation();
        }
    }

then in my xaml:
<UserControl.RenderTransform>
    <TransformGroup>
        <RotateTransform />
        <ScaleTransform />
        <TranslateTransform />
    </TransformGroup>
</UserControl.RenderTransform>

<UserControl.Style>
    <Style>
        <Style.Triggers>
            <Trigger Property="local:MyObject.IsZoomedIn" Value="False">
                <Trigger.EnterActions>
                    <BeginStoryboard>
                        <Storyboard>
                            <DoubleAnimation Storyboard.TargetProperty="(UserControl.
                            RenderTransform).(TransformGroup.Children)[1].
                            (ScaleTransform.ScaleX)" To="1" Duration="0:0:.3" />
                            <DoubleAnimation Storyboard.TargetProperty="(UserControl.
                            RenderTransform).(TransformGroup.Children)[1].
                            (ScaleTransform.ScaleY)" To="1" Duration="0:0:.3" />
                        </Storyboard>
                    </BeginStoryboard>
                </Trigger.EnterActions>
            </Trigger>
            <Trigger Property="local:MyObject.IsZoomedIn" Value="True">
                <Trigger.EnterActions>
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetProperty="(UserControl.
                        RenderTransform).(TransformGroup.Children)[1].
                        (ScaleTransform.ScaleX)" To="2" Duration="0:0:.3" />
                        <DoubleAnimation Storyboard.TargetProperty="(UserControl.
                        RenderTransform).(TransformGroup.Children)[1].
                        (ScaleTransform.ScaleY)" To="2" Duration="0:0:.3" />
                    </Storyboard>
                </BeginStoryboard>
                </Trigger.EnterActions>
            </Trigger>
        </Style.Triggers>
    </Style>
</UserControl.Style>

Once it zooms in on my usercontrol, the zoom out animation doesn't work. Any help appreciated.
Thanks.

A: Your animations are holding the values, and so the second animation isn't appearing even though the trigger is firing. Instead of having two separate triggers, you can use the Trigger.ExitActions like you are using the EnterActions.
<Trigger Property="IsZoomedIn"
         Value="True">
    <Trigger.EnterActions>
        <BeginStoryboard>
            <Storyboard >
                <DoubleAnimation Storyboard.TargetProperty="(UserControl.RenderTransform).(TransformGroup.Children)[1].(ScaleTransform.ScaleX)"
                                 To="2"
                                 Duration="0:0:.3" />
                <DoubleAnimation Storyboard.TargetProperty="(UserControl.RenderTransform).(TransformGroup.Children)[1].(ScaleTransform.ScaleY)"
                                 To="2"
                                 Duration="0:0:.3" />
            </Storyboard>
        </BeginStoryboard>
    </Trigger.EnterActions>
    <Trigger.ExitActions>
        <BeginStoryboard>
            <Storyboard>
                <DoubleAnimation Storyboard.TargetProperty="(UserControl.RenderTransform).(TransformGroup.Children)[1].(ScaleTransform.ScaleX)"
                                 To="1"
                                 Duration="0:0:.3" />
                <DoubleAnimation Storyboard.TargetProperty="(UserControl.RenderTransform).(TransformGroup.Children)[1].(ScaleTransform.ScaleY)"
                                 To="1"
                                 Duration="0:0:.3" />
            </Storyboard>
        </BeginStoryboard>
    </Trigger.ExitActions>
</Trigger>


text:
Q: Troubleshooting openDialog() Extendscript code I'm trying to write an openDialog() extendscript code that filters the selectable file types to only csv files on a mac. I was directed to the code here which does what I'm asking:  Link
I've written mostly the same thing, and the panel opens and allows me to select a file, but for some reason the filter doesn't work.
Here's what I have written:
// target the active Premiere Pro project
var activeSequence = app.project.activeSequence;

// import the CSV file
var file = File.openDialog("Select a CSV file to import.", fileFilter);
if (file) {
file.open("r");
var data = file.read();
file.close();
}

//This is the filter used by the openDialog function
function fileFilter(file){

index = file.name.lastIndexOf(".");
ext = file.name.substring(index + 1);

if(ext == "xml" || ext == "XML"){
return true;
}
return false;
}

Can anyone see what the issue might be?

A: I just tried the code from the link and it works fine for me.
Here is my a bit shortened version of the same code:
var file = File.openDialog("Select a CSV file to import", fileFilter);

function fileFilter(file) {
    if (!file instanceof Folder) return true;
    if (file.name.split('.').pop().toLowerCase() == 'csv') return true;
    return false;
}

Just in case, on Windows it works much simplier:
var file = File.openDialog("Select a CSV file to import.", "*.csv");


text:
Q: Function for converting comma-separated input parameter into rows of int in MySQL I have a stored procedure where I am passing a CSV list of my values to be inserted into a table by the procedure.
My sp is
DELIMITER $$
USE `btwa`$$
DROP PROCEDURE IF EXISTS `sp_AddRole`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_AddRole`(IN _rolename VARCHAR(50) , IN _permissionList VARCHAR(255))
BEGIN

        DECLARE _roleId INT;
        INSERT INTO roles(RoleName, CreatedOn)
            VALUES    (_rolename,CURDATE());
        SET _roleId = LAST_INSERT_ID();
        /*INSERT INTO role_permissions(FkRoleId,FKPermissionId)
        VALUES (_roleId, ...);*/here I want to insert values of _permissionList

END$$
DELIMITER ;

How can I get rows of int from permissionList which I might pass like '1,2,3,4'
I have done development in SQL Server but not much in MySQL.

A: I were able to done it via help of a forum post at http://www.slickdev.com/2008/09/15/mysql-query-real-values-from-delimiter-separated-string-ids/
My query looks like following
INSERT INTO role_permissions(FkRoleId,FKPermissionId)
        SELECT _roleId, permissionID FROM permissions WHERE FIND_IN_SET(permissionID, _permissionList);


text:
Q: Streaming to a variable instead of a file when using the requests library in Python I am using Python's requests package to download data from a remote server. Previously I was just downloading the whole response in one go like this:
response = requests.get(url=endpoint,
                        headers={'Authorization': 'Bearer ' + access_token,
                                 'Content-type': 'application/json'}
                        )

and then accessing the data by using the response.json() method:
reports = response.json()['data']['report']

however since some of the requests send back quite a lot of data that takes up to several minutes to download, I've been asked to implement a progress bar for each request so the user can monitor what's going on. The key here seems to be using the stream=True option when sending the GET request:
response = requests.get(url=endpoint,
                        headers={'Authorization': 'Bearer ' + access_token,
                                 'Content-type': 'application/json'},
                        stream=True)

then downloading the data in chunks like this:
with open('output_file', 'wb') as f:
    for chunk in response.iter_content(chunk_size=4096):
        f.write(chunk)
        # print download progress based on chunk size and response.headers.get('content-length')

The bit where I'm stuck is that all the examples I've found using response.iter_content() write each chunk directly to a file when downloaded (as in the example above). Really I need to download the JSON data to a local variable so that I can do some manipulation/filtering of it before writing to disk, but I'm unsure how to achieve this when downloading the response in chunks.
Can anyone suggest how it could be done? Thanks.

A: response.iter_content gives you chunks. You can do whatever you want with them. You don't have to write them to a file.
For example, you could stick them in a list, and put them together and parse the result at the end:
import json

chunks = []
for chunk in response.iter_content(chunk_size=4096):
    chunks.append(chunk)
    do_progress_bar_stuff()

full_content = b''.join(chunks)
parsed_data = json.loads(full_content)
do_stuff_with(parsed_data)

(I've avoided concatenating the chunks with + because that would cause quadratic runtime.)


text:
Q: In C#, is there any more elegant way to take a DateTime and calculate how many months until the "next" Quarter? I want a function in C#, where I

*

*Take a date and get the month

*Determine how many months until the next quarter of the year BUT if the number is 1, then it looks to get the number to the following quarter (basically adds 3 to it)

Here are some examples:

*

*If the current date is in the month of Jan, I want the function to return 3. (as Apr would be the first month of the next quarter)

*If its Feb i would want it to return 2;

*If its March then I would return 4 (as it would be 1 but then 3 is added to get to the next quarter)

right now i literally have a switch statement with 12 cases (from 1 to 12) which works but i was looking to see if there was a more elegant way to write this function

A: This should do it:
int untilNextQuarter = 4 - (currentMonth % 3);

Or a slightly clearer but slightly less efficient approach:
int[] remainingMonths = new[] { 3, 2, 4 };
int untilNextQuarter = remainingMonths[(currentMonth - 1) % 3];

A: DateTime.Now.Month

Returns the month number.
Just use simple if-else:
public int GetMonthsToQuater(){
    if(1<date.Month<3)
        return 4-date.Month;
    else...
}


text:
Q: Why is jQuery syntax used here? As in this screencast ( http://www.youtube.com/watch?v=h0uZIljjElo ), I think I often see jQuery syntax being used to wrap and define functions that don't benefit from jQuery.  E.g.:
<script>
  $(function() {
    // some code to run at load time
  });
</script>

It would be shorter to write the code without the 2nd and 4th lines.  Is there some value in writing after this fashion?

A: The code is "benefiting from jQuery" by asking the library not to run it until the entire DOM is ready. For example, if that code is in the <head>, references to the DOM (by "id" or "class" or anything else) generally won't work because the body has not been loaded, and so there are no elements to find.

A: Even if the function is not using JQuery explicitly, it will be executed on the ready event of the document. The same effect could be achieved by using window.onload = function() {} but JQuery's version is better IMHO, because it allows for an arbitrary amount of functions to listen to the ready event.

A: This statement is a document ready statement, which is basically saying "Please don't run any of the code inside this block until the DOM is ready to be manipulated."

A: Well nothing wrong with that only in certain cases you might want to use functions as soon as DOM object you are looking for is there so we leave function outside and use "on*" events asap. But wrapping it in jquery all DOM ready function is just a safer way to write.


text:
Q: Using local function parameter inside a while loop - SQL Server My inline table function basically prints out numbers, from 1 to the number that is input in the function. Since I'm new to SQL Server I am not sure how to implement a while loop inside a function. My implementation is below. As expected i get a lot compiler errors at WHILE, BEGIN, THEN. Can anyone suggest how can i improve the code. Thanks!
CREATE FUNCTION num_F(@nnn INT)
RETURNS TABLE
AS
RETURN (SELECT CASE
                WHEN @nnn = 0
                    THEN NULL
                    ELSE WHILE dbo.num_F(@nnn) > 0
                          BEGIN
                          THEN dbo.num_F(@nnn)
                          SET dbo.num_F(@nnn) = dbo.num_F(@nnn)-1
                         END
                         GO
                END as First_Col
        ORDER BY First_Col ASC)

A: simplest ways is by using a common table expression (CTE)
CREATE FUNCTION Numfunctn1 (@num INT)
RETURNS TABLE
AS
    RETURN(
      WITH cte
           AS (SELECT 1 id
               UNION ALL
               SELECT id + 1
               FROM   cte
               WHERE  id < @num)
      SELECT *
       FROM   cte)

SELECT *
FROM   Numfunctn1(10)