text:
Q: Run several small test within one 'it' in E2E test using Protractor I am working on a E2E test for a single-page web application in Angular2.
There are lots of clickable tags (not redirected to other pages but has some css effect when clicking) on the page, with some logic between them. What I am trying to do is,

*

*randomly click a tag,

*check to see the the response from the page is correct or not (need to grab many components from the web to do this),

*then unclick it.

I set two const as totalRound and ITER, which I would load the webpage totalRound times, then within each loading page, I would randomly choose and click button ITER times.
My code structure is like:
let totalRound: number = 10;
let ITER: number = 100;

describe('XX Test', () => {
    let page: AppPage;

    beforeEach(() => {
       page = new AppPage();
    });

    describe('Simulate User\'s Click & Unclick',() => {
        for(let round = 0; round < totalRound; round++){
            it('Click Simulation Round ' + round, () =>{
                page.navigateTo('');
                let allTagFinder = element.all(by.css('someCSS'));
                allTagFinder.getText().then(function(tags){
                let isMatched: boolean = True;
                let innerTurn = 0;

                for(let i = 0; i < ITER; i++){

                    /* Randomly select a button from allTagFinder,
                      using async func. eg. getText() to get more info
                      about the page, then check if the logic is correct or not.
                      If not correct, set isMatchTemp, a local variable to False*/

                    isMatched = isMatched && isMatchTemp;
                    innerTurn += 1;
                    if(innerTurn == ITER - 1){
                        expect(isMatched).toEqual(true);
                    }
                }

                });
            });
        }

    });
});

I want to get a result after every ITER button checks from a loading page. Inside the for loop, the code is nested for async functions like getText(), etc..
In most time, the code performs correctly (looks the button checkings are in sequential). But still sometimes, it seems 2 iterations' information were conflicted. I guess there is some problem with my code structure for the async.
I thought JS is single-thread. (didn't take OS, correct me if wrong) So in the for loop, after all async. function finish initialization, all nested async. function (one for each loop) still has to run one by one, as what I wish? So in the most, the code still perform as what I hope?
I tried to add a lock in the for loop,
like:
while(i > innerTurn){
    ;
}

I wish this could force the loop to be run sequentially. So for the async. func from index 1 to ITER-1, it has to wait the first async. finish its work and increment the innerTurn by 1. But it just cannot even get the first async. (i=0) back...

A: Finally I used promise to solve the problem.
Basically, I put every small sync/async function into separate promises then use chaining to make sure the later function will only be called after the previous was resolved.
For the ITER for loop problem, I used a recursion plus promise approach:
var clickTest = function(prefix, numLeft, ITER, tagList, tagGsLen){
  if(numLeft == 0){
    return Promise.resolve();
  }

  return singleClickTest(prefix, numLeft, ITER, tagList, tagGsLen).then(function(){
    clickTest(prefix, numLeft - 1, ITER, tagList, tagGsLen);
  }).catch((hasError) => { expect(hasError).toEqual(false); });
}

So, each single clicking test will return a resolve signal when finished. Only then, the next round will be run, and the numLeft will decrease by 1. The whole test will end when numLeft gets to 0.
Also, I tried to use Python to rewrite the whole program. It seems the code can run in sequential easily. I didn't met the problems in Protractor and everything works for my first try. The application I need to test has a relatively simple logic so native Selenium seemed to be a better choice for me since it does not require to run with Frond-end code(just visit the webapp url and grab data and do process) and I am more confident with Python.


text:
Q: React Draft.js Wysiwyg: How to programmatically insert text at the cursor location? I am using the React Draft Wysiwyg and I need to insert arbitrary text from one component of my application into the editor component. I am doing this via the clipboard as an intermediary for the transfer from one component to the other. But the document.execCommand('paste') fails.
Does anybody know how to do this?
My sample code is here; the third console log emits false for the paste result.
import React, { Component } from 'react';
import { EditorState, convertToRaw, Modifier } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import styled from 'styled-components';

class EditorConvertToHTML extends Component {
  constructor(props) {
    super(props);
    this.state = {editorState: EditorState.createEmpty()};
    this.onChange = (editorState) => this.setState({editorState});
    this.setEditor = (editor) => {
      this.editor = editor;
    };
    this.focusEditor = () => {
      if (this.editor) {
        this.editor.focusEditor();
        console.log("1. Editor has the focus now");
      }
    };
  }

  componentDidMount() {
    this.focusEditor();
  }

  onEditorStateChange = (editorState) => {
    this.setState({
      editorState,
    });
  };

  sendTextToEditor = (text) => {
    var input = document.createElement('input');
    input.setAttribute('value', text);
    document.body.appendChild(input);
    input.select();
    var result = document.execCommand('copy');
    document.body.removeChild(input);

    navigator.clipboard.readText()
    .then(text => {
      this.focusEditor();
      console.log('2. Retrieved pasted text from clipboard = ', text);
      result = document.execCommand('paste');
      console.log("3. Paste command's result = ", result);
    })
    .catch(err => {
      console.error('Failed to read clipboard contents: ', err);
    });

    return result;
  }

  render() {
    const { editorState } = this.state;
    return (
      <>
        <EditorStyled>
          <Editor
            ref={this.setEditor}
            editorState={editorState}
            wrapperClassName="demo-wrapper"
            editorClassName="demo-editor"
            onEditorStateChange={this.onEditorStateChange}
          />
        </EditorStyled>
        <button type="button" onClick={this.sendTextToEditor.bind(this, 'Sample text to put in editor')}>Copy sample text to editor</button>
      </>
    );
  }
}

export default EditorConvertToHTML;

const EditorStyled = styled.div`
  width: ${() => "calc(100% - 40px)"};
  min-height: 400px;
  margin: 20px;
  border: 1px solid black;
`;

Thank you in advance for your help!

A: Thanks to Rosemarie Robertson's explanations/article @ https://dev.to/rose/draft-js-simple-content-manipulation-b7a I got the sample working. Here is the code:
import React, { Component } from 'react';
import { EditorState, Modifier } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import styled from 'styled-components';

// Following sample is based the article https://dev.to/rose/draft-js-simple-content-manipulation-b7a

class EditorConvertToHTML extends Component {
  constructor(props) {
    super(props);
    this.state = {editorState: EditorState.createEmpty()};
  }

  componentDidMount() {
    this.focusEditor();
  }

  setEditor = (editor) => {
    this.editor = editor;
  };

  focusEditor = () => {
    if (this.editor) {
      this.editor.focusEditor();
      console.log("1. Editor has the focus now");
    }
  };

  onEditorStateChange = (editorState) => {
    this.setState({
      editorState,
    });
  };

  sendTextToEditor = (text) => {
    this.setState({editorState: this.insertText(text, this.state.editorState)});
    this.focusEditor();
  }

  insertText = (text, editorState) => {
    const currentContent = editorState.getCurrentContent(),
          currentSelection = editorState.getSelection();

    const newContent = Modifier.replaceText(
      currentContent,
      currentSelection,
      text
    );

    const newEditorState = EditorState.push(editorState, newContent, 'insert-characters');
    return  EditorState.forceSelection(newEditorState, newContent.getSelectionAfter());
  }

  render() {
    const { editorState } = this.state;
    return (
      <>
        <EditorStyled>
          <Editor
            ref={this.setEditor}
            editorState={editorState}
            wrapperClassName="demo-wrapper"
            editorClassName="demo-editor"
            onEditorStateChange={this.onEditorStateChange}
          />
        </EditorStyled>
        <button type="button" onClick={this.sendTextToEditor.bind(this, 'Sample text to put in editor')}>Copy sample text to editor</button>
      </>
    );
  }
}

export default EditorConvertToHTML;

const EditorStyled = styled.div`
  width: ${() => "calc(100% - 40px)"};
  min-height: 400px;
  margin: 20px;
  border: 1px solid black;
`;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Full access at Subfolder level I am trying to restrict few users to view only one folder in the library and those users should have access to add documents in that folder. Below is the approach I used:

*

*Provide Design, Contribute, Read access at the first level of the folder

*Click Manage Permissions for the specific folder for which I need to apply the access for users. Choose Stop Inheriting the permissions from Parent folder. Now, the user who was added in step 1 has got all access to this folder and any further changes applied at Parent level will not impact this folder is my understanding.

*Click Library Permissions at Parent folder level and removed the access.
Now, The user is able to view the specific folder and all other folders are invisible.. Good for me. But, He is unable to add documents in that specific folder.
can someone suggest the correct way of getting this done?

A: Try below steps

*

*Create new library

*Now the library will provide the same permission set in the site

*Create a folder

*Break Permission Inheritance - Then remove all users/groups

*Now add the user and provide contribute permission


text:
Q: constraining variables on scipy fsolve non linear simultaneous eq I'm trying to solve 4 simultaneous non linear equations with 4 unknowns iL,isat,Rshunt,Rseries the function first passes variables that are known iSC,vOC,imax,vmax,Nseries and then I define my set of functions using def func1(vars): my guesses are 9,1e-12,300,0.5 based on physical properties
def get_pvparms(iSC,vOC,imax,vmax,Nseries):
    import math as m
    from scipy.optimize import fsolve
    from numpy import sqrt

    n = 1
    boltzmann = 1.3806e-23
    q = 1.60218e-19
    refTemp = 25 + 273.15
    pmax = vmax/imax
    a = n * boltzmann * refTemp * Nseries / q

    def func1(vars):
        iL,isat,Rshunt,Rseries = vars

        iL = iL**2
        isat = isat**2
        Rshunt = Rshunt**2
        Rseries = Rseries**2

        return isat * (m.exp(vOC / a) - 1) + vOC / Rshunt - iL + 0*Rseries,\
               iSC + iSC*Rseries/Rshunt + isat * m.exp(iSC*Rseries/a - 1) - iL,\
               iL - isat*(m.exp((vmax + imax*Rseries)/a)-1) - (vmax + imax*Rseries)/Rshunt - imax,\
               (isat*m.exp((vmax+imax*Rseries)/a)/a + 1/Rshunt)/(1+(isat*Rseries*m.exp((vmax+imax*Rseries)/a)/a)+Rseries/Rshunt) - pmax + 0*iL

    guess = sqrt((iSC,5e-8,300,0.5))

    print fsolve(func1,guess)

I get this result
 File "C:\Users\Davis_2\Documents\RCL\MAPVsim\pvcalc.py", line 50, in get_pvparms
    print fsolve(func1,guess)
  File "C:\Anaconda2\lib\site-packages\scipy\optimize\minpack.py", line 146, in fsolve
    res = _root_hybr(func, x0, args, jac=fprime, **options)
  File "C:\Anaconda2\lib\site-packages\scipy\optimize\minpack.py", line 224, in _root_hybr
    ml, mu, epsfcn, factor, diag)
  File "C:\Users\Davis_2\Documents\RCL\MAPVsim\pvcalc.py", line 44, in func1
    iSC + iSC*Rseries/Rshunt + isat * m.exp(iSC*Rseries/a - 1) - iL,\
OverflowError: math range error

How can I pass constrains to my guesses? such as values cannot be negative?
I attempted to use the squaring method on the variables but i get overflow. Probably implementing it wrong. Any help would be much appreciated
Note: If you take out this piece of code:
    iL = iL**2
    isat = isat**2
    Rshunt = Rshunt**2
    Rseries = Rseries**2

and take out the sqrt here guess = sqrt((iSC,5e-8,300,0.5)) it converges to an an answer.


text:
Q: Ruby: would using Fibers increase my DB insert throughput? Currently I am using Ruby 1.9.1 and the 'ruby-mysql' gem, which unlike the 'mysql' gem is written in ruby only. This is pretty slow actually, as it seems to insert at a rate of almost 1 per second (SLOOOOOWWWWWW). And I have a lot of inserts to make too, its pretty much what this script does ultamitely. I am using just 1 connection (since I am using just one thread). I am hoping to speed things up by creating a fiber that will

*

*create a new DB connection

*insert 1-3 records

*close the DB connection

I would imagine launching 20-50 of these would greatly increase DB throughput. Am I correct to go along this route? I feel that this is the best option, as opposed to refactoring all of my DB code since the syntax is a quite a bit different for the default mysql driver :(

A: Why are you closing a connection after a few inserts? Your script should be:

*

*Open a connection

*Write however many records you need

*Close connection

Transactions can complicate this.
If you are doing non-transactional inserts, absolutely use one connection and write each record one at a time.
If you are using transactions and writing a truly huge data set (ie millions of rows) then your database may need to be tuned so it has sufficient temporary storage to deal with that.
Basically if a single insert is taking a second it suggests to me one or more of:

*

*You foreign keys aren't indexed so the referential integrity checks on the insert are woefully inefficient; or

*Excessive connection opening and closing.

Now all that being said, having multiple "workers" doing inserts can lead to useful increases in overall throughput but at 1 second per insert, that isn't your problem. You need to find what your problem is.
With truly huge batch inserts it may also be worth disabling check constraints, foreign keys and indices, doing all the inserts and then re-enabling them.

A: Since you are using ruby1.9.1, just use Threads. They are no longer green. Fibers are not going to help as they are too light weight for multiple, concurrent DB connections.


text:
Q: Passing data between Wordpress 'pages' I have a menu, when the user clicks on any menu item, I want to take them to the same page, but I want to style the page differently depending on the menu item...for ex: change the background color to be different.
What's the best way to do this?  I was thinking that when they click on a menu item, a variable can be set or a session variable can be set.
Is there an easier way to do this?  Does Wordpress have anything built into the architecture to make this easy?

A: Don't use the session for this. Since HTTP is a stateless protocol, you should avoid using session to the greatest lengths possible. Since the user is clicking on a link, it only makes sense making that link convey the information you're after. Just pass any data you want in the URL, e.g. as a a query string parameter:

*

*http://example.com/page_x?bgcolor=1

*http://example.com/page_x?bgcolor=2

*http://example.com/page_x?bgcolor=3
Then you can just query for this in the page template like so:
<?php
  /*
  Template Name: Varying Background Color Template
  */

  $bgcolor = $_GET['bgcolor'];

  switch ($bgcolor) {
    case 1:
      // Change the background to color 1
      break;

    case 2:
      // Change the background to color 2
      break;

    case 3:
      // Change the background to color 3
      break;
  }
?>

If you think query string parameters are ugly, you can use path info instead, but this requires you to create a special case rewrite rule that makes the path info "invisible" to WordPress so it doesn't think it's the slug of a page. Whether you want or need this depends on how your permalink configuration in WordPress is.

A: *

*you have to create your page as a wp template ( if you did not created already ) ( see this )

*you are right with the session variable. pass the variable to that page and process it there. there is a bit of programming involved...

I do not know of another way for doing what you ask.


text:
Q: Dapper always returning false in case of fetching bit datatype from SQL SERVER 2014 database I am using Dapper version="2.0.78" for .NETFramework = 4.7.2 based asp.net web api2 application.
Here goes my POCO class :
public class TestGroupResult : APIResult
{
    public TestGroupVM TestGroup
    {
        get;
        set;
    }
}

public class TestGroupVM
{
    public int TestGroupId
    {
        get;
        set;
    }

    public string GroupName
    {
        get;
        set;
    }

    public bool IsTestPublishedAndOnboarded
    {
        get;
        set;
    }

    public bool IsPublished
    {
        get;
        set;
    }

    public CountryVM Country
    {
        get;
        set;
    }
}

public async Task<TestGroupResult> GetDataAsync(RequestDTO value, string locale)
{
    var localeLangId = _commonService.GetLanguageFromLocale(locale).LanguageId;
    var result = new TestGroupVM();
    var cgresult = new TestGroupResult();
    using (var conn = await _dapperService.CreateConnection())
    {
        var data = await conn.QueryAsync<TestGroupVM, CountryVM, TestGroupVM>("stp_FetchData", (cg, c) =>
        {
            cg.Country = c;
            return cg;
        }, splitOn: "Uuid", param: new
        {
        @pI_NCOUNTRYCODE = value.Code, @pI_ILOCALELANGID = localeLangId
        }

        , commandType: CommandType.StoredProcedure);
        result = data.FirstOrDefault();
        var countryVM = new CountryVM{Uuid = Convert.ToString(result.Country.Uuid), DisplayName = result.Country.DisplayName, DisplayNameShort = result.Country.DisplayNameShort, Name = Helper.ReplaceChars(result.Country.DisplayName)};
        result.Country = countryVM;
        cgresult.CountryGroup = result;
    }

    return cgresult;
}

stp_FetchData:
SELECT CGC.TestGroupId, CGC.GroupName, C.CountryId AS Uuid, CC.DisplayName,CC.DisplayNameShort,case when C.IsPublished = 1 then 1 else 0 end AS IsTestPublishedAndOnboarded, C.IsPublished As IsPublished
       FROM [Countries] C join [CountryContents] CC ON CC.CountryId = C.CountryId
       join [CountryGroupAssociatedCountries] CGAC on C.CountryId = CGAC.CountryId
       join [CountryGroupContents] CGC on CGC.CountryGroupId = CGAC.CountryGroupId where C.CountryCode=@pI_NCOUNTRYCODE AND CC.LanguageId IN (@pI_ILOCALELANGID)

On testing the above stored procedure I see the below result :
TestGroupId : 5
GroupName: ABC
Uuid : 12
DisplayName : Test
DisplayNameShort = Testing
IsTestPublishedAndOnboarded : 1
IsPublished : 1

But the method : GetDataAsync always returns
TestGroupId : 5
GroupName: ABC
Uuid : 12
DisplayName : Test
DisplayNameShort = Testing
IsTestPublishedAndOnboarded : false
IsPublished : false

I am not sure why column type: Bit in SQL Server are not getting mapped to bool datatype in C# in this case.
Can anyone help me here by providing their guidance to fix this issue?

A: The problem here is in the column ordering, the components are the type structure here:
conn.QueryAsync<TestGroupVM, CountryVM, TestGroupVM>(...)

And note the splitOn: "Uuid".
The dapper args are: <Type1, Type2, ReturnType>. In the query your columns are, in order:

*

*CGC.TestGroupId (Type1: TestGroupVM)

*CGC.GroupName (Type1: TestGroupVM)

*C.CountryId AS Uuid (Type2: CountryVM - note: at this point, we switch to populating the CountryVM object, because that's what splitOn said to do)

*CC.DisplayName (Type2: CountryVM)

*CC.DisplayNameShort (Type2: CountryVM)

*case when C.IsPublished = 1 then 1 else 0 end AS IsTestPublishedAndOnboarded (Type2: CountryVM - not a property!)

*C.IsPublished As IsPublished (Type2: CountryVM - not a property!)

So overall, we're trying to populate properties on CountryVM after we've moved on to the second object...and it doesn't have those properties.
To resolve this, what you want to do is to move those 2 columns before the Uuid switch, so that it's mapping to the right place, for example:
SELECT CGC.TestGroupId, CGC.GroupName, case when C.IsPublished = 1 then 1 else 0 end AS IsTestPublishedAndOnboarded, C.IsPublished As IsPublished, C.CountryId AS Uuid, CC.DisplayName,CC.DisplayNameShort

...or, move those properties to country if that's where they belong (I'm noting a mismatch vs. your database model here - so consider that option!)


text:
Q: Create an annotation that has a specific @ConditionalOnProperty? My plan is to create an annotation that if I put that on a class, the class will be a bean only if the @ConditionalOnProperty is true.
I have this:
@ConditionalOnProperty(prefix = "backend-auth", value = "enabled", havingValue = "true", matchIfMissing = false)
I want to create some beans (controllers / services) only if the backend-auth.enabled=true exists in the application.properties file. Now at the moment I have this:
@RestController
@ConditionalOnProperty(prefix = "backend-auth", value = "enabled", havingValue = "true", matchIfMissing = false)
public class FirstController {}

@RestController
@ConditionalOnProperty(prefix = "backend-auth", value = "enabled", havingValue = "true", matchIfMissing = false)
public class SecondController{}

@Service
@ConditionalOnProperty(prefix = "backend-auth", value = "enabled", havingValue = "true", matchIfMissing = false)
public class FirstService {}

@Service
@ConditionalOnProperty(prefix = "backend-auth", value = "enabled", havingValue = "true", matchIfMissing = false)
public class SecondService{}

As you can see I am reusing the @ConditionalOnProperty part and in case I want to change the prefix, value or havingValue values, then I have to change it at 4 places and it can be missed if not paying attention...
I am thinking about creating an annotation that contains the @ConditionalOnProperty and use this custom annotation on my FirstController, SecondController, FirstService, SecondService.
I want to end up with something like this:
@RestController
@BackendAuthEnabled
public class FirstController {}

@RestController
@BackendAuthEnabled
public class SecondController{}

@Service
@BackendAuthEnabled
public class FirstService {}

@Service
@BackendAuthEnabled
public class SecondService{}

A: There you go:
@ConditionalOnProperty(prefix = "backend-auth", value = "enabled", havingValue = "true", matchIfMissing = false)
@Retention(RetentionPolicy.RUNTIME)
public @interface BackendAuthEnabled {
}

(Thanks Wim for the link)


text:
Q: Ponteiro Inválido Tenho um projeto em Asp.Net MVC com Entity Framework 4.5, que criei limpo, mas ao tentar criar uma View recebo o seguinte mensagem:
Erro :

There was an error running the selected code generator : 'Ponteiro
  inválido (Exception from HRESULT: 0x80004003 (E_POINTER))'

Você também pode visualizar o erro clicando aqui.
Procurei algo com o código apresentado, mas não encontrei nada.
Versão utilizada :
Community 2015 v 14.0.24720.00 Update 1.

A: Para a correção do problema citado apenas foi necessária a reinicialização do Windows! Tentei reiniciar o Projeto, o Visual Studio 2015 e não adiantou. Só ai que percebi que existia uma atualização do windows 10, pois, já aconteceram outras vezes da atualização do windows bugar o Visual Studio.
Minha sugestão seria:

*

*Verifique se existe atualização do windows.

*Atualiza e reinicie o windows.

A: O problema estava sendo causado por alguma extensão, fiz a remoção e reinstalação de algumas delas, além da reinstalação do Visual Studio, e tudo passou a funcionar normalmente.

A: Com o Visual Studio fechado, delete todos os arquivos que estão dentro do seguinte diretório: %LocalAppData%\Microsoft\VisualStudio\14.0\ComponentModelCache.
Provavelmente irá funcionar novamente.


text:
Q: IIS 7.x client certificate mapping to ApplicationPoolIdentity In IIS 6 I was able to use the following technique:

*

*Turn on requirement for client certificates

*Using adsutil.vbs figure out what IUSR_Server user password is

*Create a one-to-one mapping of the certificate to the IUSR_Server account (that's why I need to know IUSR's password)

*Disable anonymous access to the site

Taking into account all the breaking changes in IIS 7.x, I assume that client certificate mapping now has to be created to the ApplicationPoolIdentity? In any case: to create a mapping, I need to specify userName and password, however for both IUSR and ApplicationPoolIdentity passwords don't seem to exist?
My goal is to prevent access to the site without a particular client certificate. At the same time I do not want to create a separate Windows user, configure the AppPool to use it for identity, and then set up one-to-one certificate mapping to this user. Instead, I want to rely on the existing identities offered by IIS. Any ideas?

A: The ApplicationPoolIdentity is seen as COMPUTERNAME$ across the network, and it's a virtual account so it doesn't have a password.  I don't believe this will work for your mappings.

At the same time I do not want to
  create a separate Windows user,
  configure the AppPool to use it for
  identity, and then set up one-to-one
  certificate mapping to this user.

Why don't you want to use this method?  That's probably your best bet.  In IIS7 you don't need to add the user to the IIS_WPG group.  Just create a user+password that you manage and add to the app pool.
Also, for your authentication/anonymous setting, set it to use the app pool identity.  Then you don't need to worry about the IUSR anymore.  As long as you give each site its own app pool, or sites trust each other, then you can use this method and have one less user to manage.


text:
Q: Acumatica and N-Central API integration We're looking at integrating N-Central (an IT management app) with Acumatica, but N-Central doesn't support oAuth connections so I don't think we can use Connected Applications to do this.  N-Central only supports basic authentication, but their configuration for connecting to an API only offers a single URL path. Since Acumatica's basic API authentication has a different top level login URL than its actual web service endpoints, we have been unable to determine a way for it to connect to Acumatica's API.  Has anyone else done this successfully, or do you have any suggestions on getting this to work?  Is there any way to connect to the Acumatica API via basic authentication that wouldn't require sending requests to two different top level URLs, but instead the same top level path?

A: You might be able to relay your calls through an Acumatica WebHook. You would need to write the plumbing needed to reach your final destination. With WebHook you can roll your own basic authentication.


text:
Q: Windows cmd.exe - How to keep folder name intact in command? As per this answer, I'm trying to run an ffmpeg script through a folder recursively.
I run:
for /r "W:\Exports\1 - Dailies\" %f in (*.mov) do ffmpeg -i %f -vf fps=6/60 still%05d.jpg

But cmd.exe is only seeing the name of the folder as 1 instead of 1 - Dailies:
W:\Exports\1: No such file or directory

How can I modify this command to execute the ffmpeg command for the contents of the 1 - Dailies folder?


text:
Q: UHF RFID Microstrip antenna I want to design microstrip antenna for UHF RFID. The chip I'm using is SL3S1013FTB0. I found some demo kits and found some antenna examples. One of them has small antenna that I'm especially interested in and it looks like this:

But there is no information about this design and to be honest I'm having a hard time understaing how it works. What is more, when I checked the gerbers it seems to be shorted to ground!

Can anyone explain how it works or recommend any book/article that explains it?


text:
Q: generate an xml file from multiple nodes on content server, I'm running this content script (groovy):
List<CSNode> var1 = docman.getFolder(129335).getChildren()
log.error("start")
for(CSNode x : var1){
sendFile(admin.exportXml(x).content)
}

I would like it to create as many xml as there are folders in the folder with id = 129335, but it creates only one xml.
I would like to modify it to create a unique xml file, with inside the xml corresponding to the
various folders. I suspect that the sendFile statement executed on the server could only be one.


text:
Q: How do I get my build to generate multi-line problem messages in VSCode? The compiler I'm currently using (GHC) to build my project generates multi-line messages for each error. I currently have a tasks.json file that specifies how to parse the output from GHC and present it to the VS Code problem panel. However, it only captures the first line of each message, as until now the VS Code problem panel only permits one line of text for each problem messgae.
The latest update to VS Code, 1.31, promises multi-line messages in the problem panel. However, Microsoft does not explain how to get third-party build tools to generate multi-line messages. The regular expressions that match messages apparently cannot be made multi-line, and there does not seem to be any change to the tasks.json format.
How do I get multi-line messages from GHC and other tools to show up in the VS Code problem panel?


text:
Q: calculating sum with PHPExcel I am new with PHPExcel and I need your help-
I have problem with setCellValue in PHPExcel when calculating the sum. It gives me always 0.
Here is my code:
$objPHPExcel = PHPExcel_IOFactory::load("test.xls");

$row = 5;
$S = $objPHPExcel->getActiveSheet();
while($row_data = mysql_fetch_array($result)){

$S->setCellValueExplicit('B'.$row, $row_data['cn']);
$S->setCellValueExplicit('C'.$row, $row_data['ld']);
$S->setCellValueExplicit('D'.$row, $row_data['cust_notify']);
$S->setCellValueExplicit('E'.$row, $row_data['code']);
$S->setCellValueExplicit('F'.$row, $row_data['company_name']);
$S->setCellValueExplicit('G'.$row, $row_data['rs']);
$S->setCellValueExplicit('H'.$row, $row_data['status']);
$S->setCellValueExplicit('I'.$row, $row_data['sueend']);
$S->setCellValueExplicit('J'.$row, $row_data['vclaimed']);
$S->setCellValueExplicit('K'.$row, $row_data['ref']);
$S->setCellValueExplicit('M'.$row, $row_data['out']);

$row++;

$S->setCellValue("I$row", "Total");
$S->setCellValue("J$row", "=SUM(J5:J".($row-1).")");

}

The result I get is always "0". Bellow the print screen

I would really appreciate if someone can help me with this issue.
Thanks in advance

A: Oups I think I have  found my mistake in the code. I have changed the
    $S->setCellValueExplicit('J'.$row, $row_data['vclaimed']);
to  $S->setCellValue('J'.$row, $row_data['vclaimed']);
and now it works.

A: try this
$writer = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
$writer->setPreCalculateFormulas(true);


text:
Q: How to integrate samsung pay in ionic 6 app I am developing an app in ionic 6 framework and i want to integrate Samsung Pay payment gateway in it. I want to get a token from Samsung Pay and will then create a charge in stripe.
So guys, if anyone of you integrated it earlier in Ionic apps, or have knowledge of any available plugin. Please let me know.
Thanks in advance.

A: First of all you need you get the credentials, after that, you need to wait until samsung aproves your request. Then download and use the SDK.
Here's a GUIDE about how to use it.
The best practices are process, create, and manage payments in Backend


text:
Q: checking desktop power supply voltage range. I have a few computers. I know some of the power supply is 110-220 and some are only 220. I need to figure out which ones are which. How do I do that? I can't seem to find it in the control panel. Is it anywhere in the BIOS?

A: Can you open the tower case and check if there is a sticker on the side of the power supply? Not very technical, but might get the job done.


text:
Q: Using Fetch API with Rails application? I am trying to use the Fetch API with my Rails application. I can pass parameters to the controller as part of a query string, but still can't figure out how to pass JSON data or where to find it in the controller. A sample call looks like the below. Where can I access my test data on in the controller? Happy Sunday :)
    export const fetchControllerData = () => {
      return fetch('api/users',), {
        body: { "test": "test" }
      })
      .then(res => res.json());
    };

A: I'm in the process of working out my own issues with fetch and Rails. But I'll take a stab at this.
I expect that fetch is using GET as the default method - which won't use the body at all. You will likely need to set the method to be POST to get the body through. Further to that you might need to set the Content-Type header (to application/json) in order to send the data through as JSON.

A: May be u need to send params in this way for get request and use this link for https://github.com/axios/axios
 export const fetchControllerData = () => {
   params = { body: { "test": "test" } }
   return HTTP.get('api/users', params)
              .then((response) => {
                 if (response.success) {
                   // do something here
                 } else {
                    // handle error condtion here
                 }
              });
 }


text:
Q: Processing huge files in java I have a huge file of around 10 GB. I have to do operations such as sort, filter, etc on the files in Java. Each operation can be done in parallel.
Is it good to start 10 threads and read the file in parallel ? Each thread reads 1 GB of the file.
Is there any other option to solve the issue with extra large files and processing them as fast as possible? Is NIO good for such scenarios?
Currently, I am performing operations in serial and it takes around 20 mins to process such files.
Thanks,

A:
Is it good to start 10 threads and read the file in parallel ?

Almost certainly not - although it depends. If it's from an SSD (where there's effectively no seek time) then maybe. If it's a traditional disk, definitely not.
That doesn't mean you can't use multiple threads though - you could potentially create one thread to read the file, performing only the most rudimentary tasks to get the data into processable chunks. Then use a producer/consumer queue to let multiple threads process the data.
Without knowing more than "sort, filter, etc" (which is pretty vague) we can't really tell how parallelizable the process is in the first place - but trying to perform the IO in parallel on a single file will probably not help.

A: Try profiling the code to see where the bottlenecks are. Have you tried having one thread read the whole file (or as much as possible), and give that off to 10 threads for processing? If File I/O is your bottleneck (which seems plausible), this should improve your overall run time.


text:
Q: Youtube custom progressbar using YouTube iframe api and jquery not working I want to create a custom youtube progressbar. I made something but it's not working as it should. I want it to run smooth like YouTube's progressbar, to update more frequently not every second like mine and to go from 0 to 100%, now mine stops at 98%. Also I want the preogressbar to stop when the video is paused and to work again when video is playing again.
Progressbar
function progress(percent, $element) {
var progressBarWidth = percent * $element.width() / 100;

// $element.find('div').animate({ width: progressBarWidth }, 500).html(percent + "% ");

$element.find('div').animate({ width: progressBarWidth });
}

Progressbar css
#progressBar {
width: 960px;
height: 6px;
background-color: #444444;
display: none;
margin-top: 1px;
}

#progressBar div {
height: 100%;
width: 0;
background-color: #ffffff;
}

YouTube iframe api
// Load the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// Replace the 'ytplayer' element with an <iframe> and
// YouTube player after the API code downloads.
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('ytplayer', {
height: '540',
width: '960',
videoId: 'UDxzMcCrOyI',
playerVars: { 'showinfo': 0, 'modestbranding': 1, 'rel': 0, 'iv_load_policy': 3 }
});
}

When I press a button, the video is shown and also the progressbar. Video is playing automatically.
$('#ytplayer').show(0, function() {
player.playVideo();

$('#progressBar').show();

var playerTotalTime = player.getDuration();

mytimer = setInterval(function() {
var playerCurrentTime = Math.round(player.getCurrentTime());

var playerTimeDifference = (playerCurrentTime / playerTotalTime) * 100;
var playerTimePercent = Math.round(playerTimeDifference);

console.log(playerTimePercent);

progress(playerTimePercent, $('#progressBar'));
}, 1000);

});

A: Try this solution :
demo + code
And the full JS code :
function progress(percent, $element) {
  var progressBarWidth = percent * $element.width() / 100;

// $element.find('div').animate({ width: progressBarWidth }, 500).html(percent + "% ");

  $element.find('div').animate({ width: progressBarWidth });
}

var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// 3. This function creates an <iframe> (and YouTube player)
//    after the API code downloads.
var player;

function onYouTubeIframeAPIReady() {
    player = new YT.Player('ytplayer', {
      height: '540',
      width: '960',
      videoId: 'UDxzMcCrOyI',
        playerVars: {
        'controls' : 0,
        'modestbranding' : 1,
        'rel' : 0,
        'showinfo' : 0
      },
        events: {
            'onReady': onPlayerReady,
             'onStateChange': onPlayerStateChange
        }
    });
}

// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
    event.target.playVideo();
}

// 5. The API calls this function when the player's state changes.
//    The function indicates that when playing a video (state=1),
//    the player should play for six seconds and then stop.

function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING) {

      $('#progressBar').show();
      var playerTotalTime = player.getDuration();

      mytimer = setInterval(function() {
        var playerCurrentTime = player.getCurrentTime();

        var playerTimeDifference = (playerCurrentTime / playerTotalTime) * 100;

        progress(playerTimeDifference, $('#progressBar'));
      }, 1000);
    } else {

      clearTimeout(mytimer);
      $('#progressBar').hide();
    }
}

function stopVideo() {
    player.stopVideo();
}


text:
Q: How can I increase by one each value contained in the values list in Python values = [16, 1, 7, 2, 19, 12, 5, 20, 2, 10, 10, 14, 17, 14, 1, 16, 19, 7, 9, 19]

If I want to increase by one each value contained in the values list, why can't I do like this:
this is my answer, but it's wrong
for i in values:
    i += 1
print(values)

why do I only have to do in this way
for i in range(len(values)):
    values[i] += 1
print(values)


text:
Q: Optimización de Columna Tipo String Les platico, tengo la siguiente columna llamada "ASSET" es de tipo string y tiene 10 o 11 caracteres:

Y con esta columna genero otra llamada "CLASE" con el siguiente código:
join["CLASE"] = ""
for row in join["ASSET"]:
    join["CLASE"] = [row[0:3] if len(row)==11 else row[0:4] for row in join["ASSET"]]

En esencia el código funciona y hace lo que tiene que hacer, lo cual es lo siguiente: si el registro tiene 11 caracteres, me trae los primeros 3 caracteres, y en caso de que tenga 12 caracteres, me trae los primeros 4 caracteres.
Sin embargo demora muchísimo en hacerlo, no se si la comprensión de listas para el tamaño de datos que estoy manejando (aprox. 156,000 registros) es demasiado o que pasa. Por eso buscaba su ayuda para saber si se les ocurre alguna manera que pueda hacer lo mismo que hace este fragmento de código, pero mas eficiente. Actualmente demora aproximadamente una hora en correr solo esa celda.

A: Buen día,
El problema es que tienes un ciclo for, luego una comprensión de listas y además un if
Puedes hacerlo directamente del valor de tu columna con el método pandas.Series.str
Ya que no pusiste tus datos como texto cree un ejemplo genérico y tendrás que adaptar los nombres de las columnas.
Los datos que estoy utilizando en el archivo "sample2.csv" son estos:
asset
10012345678
20012345678
30012345678
40012345678
50012345678
60012345678
70012345678
80012345678
90012345678
1012345678
2012345678
3012345678
4012345678
5012345678
6012345678
7012345678
8012345678
9012345678
0112345678
0212345678
0312345678
0412345678
0512345678
0612345678
0712345678
0812345678
0912345678
1112345678
12123456789

En tu ejemplo mencionas que si el string es de 10 dígitos deseas obtener los primeros 3 y si es de 11, obtener los primeros 4 y por eso utilizas el if, pero en otras palabras, lo que deseas es tomar los caracteres del inicio del string hasta el caracter "-7"
Todo lo que tienes se puede reducir a una línea:
import pandas as pd

df = pd.read_csv('sample2.csv', dtype=str)

df['clase'] = df['asset'].str[:-7]

Esto devuelve:
    asset       clase
0   10012345678 1001
1   20012345678 2001
2   30012345678 3001
3   40012345678 4001
4   50012345678 5001
5   60012345678 6001
6   70012345678 7001
7   80012345678 8001
8   90012345678 9001
9   1012345678  101
10  2012345678  201
11  3012345678  301
12  4012345678  401
13  5012345678  501
14  6012345678  601
15  7012345678  701
16  8012345678  801
17  9012345678  901
18  0112345678  011
19  0212345678  021
20  0312345678  031
21  0412345678  041
22  0512345678  051
23  0612345678  061
24  0712345678  071
25  0812345678  081
26  0912345678  091
27  1112345678  111
28  12123456789 1212


text:
Q: UIView textFieldShouldReturn not working I am having some problems with function textFieldShouldReturn as far at i understand it should be called when enter are pressed on the keyboard but it does not. I have tried to search for solution on google and here but have not found a answer that solved the problem because most of the answers here on the webpage i have fund are a 3 years or older and the solutions from those did not help much.
I am using it in a UIView where the delegates for the textField is set in the function awakeFromNib() and i have tried some other delegate function textViewDidChangeSelection that does work so i am at a lost why it is not working.
Here is how the xib file looks

Here is the code that i am using as a popup:
import UIKit

class CuePointPopup: UIView,UITextFieldDelegate,UITextViewDelegate
{
    @IBOutlet var labelCueNumberInImage: UILabel!
    @IBOutlet var labelCueNumber: UILabel!
    @IBOutlet var labelLayerName: UILabel!
    @IBOutlet var labelPageNumber: UILabel!
    @IBOutlet weak var view: UIImageView!

    @IBOutlet var textFieldWhoText: UITextField!
    @IBOutlet var textViewWhatText: UITextView!
    @IBOutlet var textFieldWhereText: UITextField!
    @IBOutlet var textFieldPageNumber: UITextField!
    @IBOutlet var textFieldCueText: UITextField!

    @IBOutlet var boxArrowLeft: UIImageView!
    @IBOutlet var boxArrowRight: UIImageView!

    @IBOutlet var boxArrowLeftTopConstraint: NSLayoutConstraint!

    @IBOutlet var boxArrowRightTopConstraint: NSLayoutConstraint!
    var cuePointObj:CuePoint!

    var blockBtnClickedSave:((CuePoint) -> ())!
    var blockBtnClickedCancel:((CuePoint) -> ())!
    var blockBtnClickedDelete:((CuePoint) -> ())!
    var blockTextChangedForPageNumber:((String, CuePoint) -> ())!

    @IBOutlet var btnOutletVisibleOnPage: UIButton!
    var isVisible = false

    class func loadNib() -> CuePointPopup
    {
        return Bundle.main.loadNibNamed("CuePointPopup", owner: self,options: nil)!.last as! CuePointPopup
    }

    override func awakeFromNib() {

        self.textFieldWhoText.delegate = self
        self.textViewWhatText.delegate = self
        self.textFieldWhereText.delegate = self
        self.textFieldCueText.delegate = self
        textViewWhatText.text = "Hello"
    }

    func setViewData(cueModel:CuePoint) {
        self.cuePointObj = cueModel

        labelCueNumberInImage.text = cueModel.cueNumber
        labelCueNumber.text = "Cue #:" + cueModel.cueNumber
        labelLayerName.text = "Layer #:" + cueModel.layerName
        labelPageNumber.text = "Page #:" + cueModel.pageNumber
        textFieldPageNumber.text = cueModel.pageNumber

        textFieldWhoText.text = cueModel.whoString
        textViewWhatText.text = cueModel.whatString
        textFieldWhereText.text = cueModel.whereString
        textFieldCueText.text = cueModel.cueTextString

        if cueModel.isVisibleOnPage == true {
            btnOutletVisibleOnPage.setImage(UIImage(named: "SelectedBox"), for: [])
            btnOutletVisibleOnPage.tag = 1
        }else{
            btnOutletVisibleOnPage.setImage(UIImage(named: "UnselectedBox"), for: [])
            btnOutletVisibleOnPage.tag = 0
        }

    }

    func textFieldDidEndEditing(_ textField: UITextField) {

        if textField.text != "" {
            if blockTextChangedForPageNumber != nil {
                self.blockTextChangedForPageNumber(textField.text!, self.cuePointObj)
            }
        }
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        //self.view.endEditing(true)
        if self.textFieldWhoText.isEditing {
            self.textFieldWhoText.endEditing(true)
        } else if self.textFieldCueText.isEditing{
            self.textFieldCueText.endEditing(true)
        } else if self.textFieldWhereText.isEditing {
            self.textFieldWhereText.endEditing(true)
        } else {
            self.textViewWhatText.endEditing(true)
        }
        //self.view.endEditing(true)
        return false
    }
}

Here is how i load the XIB
@IBOutlet weak var bookView: UIView!
var objCuePopup:CuePointPopup!

if objCuePopup != nil {
    objCuePopup.removeFromSuperview()
}

objCuePopup = CuePointPopup.loadNib()
objCuePopup = CuePointPopup.loadNib()
objCuePopup.frame = CGRect(x:cuePointModal.cueX, y:0, width:465, height:410)
objCuePopup.center = CGPoint(x:objCuePopup.center.x, y:cuePointModal.cueY + 5)

//Set Y value for Popup View
if objCuePopup.frame.origin.y < bookView.frame.origin.y {
    objCuePopup.frame.origin.y = bookView.frame.origin.y
}

let popupMaxY = objCuePopup.frame.maxY
let bookViewMaxY = bookView.frame.maxY

if popupMaxY > bookViewMaxY {
    objCuePopup.frame.origin.y = bookViewMaxY - objCuePopup.frame.size.height
}

//Set X value for Popup View

if cuePointModal.cueX > 455 {
    objCuePopup.frame.origin.x =  cuePointModal.cueX - 455
    objCuePopup.boxArrowLeft.isHidden = true
    objCuePopup.boxArrowRight.isHidden = false

    let rightY = cuePointModal.cueY - objCuePopup.frame.origin.y
    objCuePopup.boxArrowRightTopConstraint.constant = rightY + 3

}else{

    objCuePopup.frame.origin.x = cuePointModal.cueX + 40
    objCuePopup.boxArrowLeft.isHidden = false
    objCuePopup.boxArrowRight.isHidden = true

    let leftY = cuePointModal.cueY - objCuePopup.frame.origin.y
    objCuePopup.boxArrowLeftTopConstraint.constant = leftY + 3
}

objCuePopup.setViewData(cueModel: cuePointModal)
objCuePopup.textFieldWhoText.delegate = self
objCuePopup.textFieldWhereText.delegate = self
objCuePopup.textViewWhatText.delegate = self
objCuePopup.textFieldCueText.delegate = self

bookView.addSubview(objCuePopup)

I hope that someone here can help me with this problem.


text:
Q: My PC wifi can't detect a particular hotspot device Just few days ago, I was able to use the wireless hotspot network ICTD5 in my work place. But now, my computer is not able to detect it. It can detect other networks including my phone's hotspot but not ICTD5. I've been able to use the internet on ICTD5 using my phone and my tablet, but my PC just can't see ICTD5. Other people's PCs can.
I've installed the latest driver for my wifi adapter as well as tried different things I saw online like uninstalling and reintsalling the adapter, disabling and reenabling it, restarting my PC etc, but none have worked.
I'd appreciate any help in finding what is going wrong. I use a HP G60 G3 with Ralink RT3290 wifi adapter.


text:
Q: React + MUI + Tabs + Style I have some issue to change the way tabs are rendered with MUI and React.
Despite the numerous solutions found in the internet, none of them succeeded.
I am currently using the latest version of MUI
"@emotion/react": "^11.9.3",
"@emotion/styled": "^11.9.3",
"@mui/icons-material": "^5.8.4",
"@mui/material": "^5.9.0"

Here is the code snipplet, the source of my problem:
<Tabs value={value} onChange={handleChange} aria-label='deals tabs'
      TabIndicatorProps={{ style: { backgroundColor: 'white' } }}
      centered>
</Tabs>

I have tried a dozen of solutions to change the default color of the selected tab and I just kept failing.
Did someone had the same issue ?
Best regards.

A: Instead of TabIndicatorProps, Try selecting the selected tab css class using sx prop:
<Tabs value={value} onChange={handleChange} aria-label='deals tabs'
  sx={{ "& .Mui-selected": { backgroundColor: "white" } }}
  centered>
</Tabs>

A: The problem came from the white space in the stylesheet, between the & and .Mui-selected:
<Tabs value={value} onChange={handleChange} aria-label='deals tabs'
  sx={{ "&.Mui-selected": { color: "white" } }}
  centered>
</Tabs>

Regards.

A: In my case i wanted to customise the Tabs for the default, selected, hover and solved it using the code below. As you can see I am using the sx on the parent <Tabs>
export const tabSx = {
  '& .MuiTabs-indicator': {
    backgroundColor: 'red',
  },
  '& .MuiButtonBase-root.MuiTab-root': {
    color: 'black',
    transition: 'color 0.2s ease-in-out',
    '&:hover': {
      color: 'green)',
    },
    '&.Mui-selected': {
      color: 'red',
    },
  },
};

            <Tabs
              value={value}
              onChange={handleChange}
              sx={tabSx}
              aria-label="test tabs"
            >
              <Tab label="Tab 1" {...a11yProps(0)} />
              <Tab label="Tab 2" {...a11yProps(1)} />
              <Tab label="Tab 3" {...a11yProps(2)} />
            </Tabs>


text: Q: Automatically switch to the strongest wifi known signal I have 2 known networks that I have signed into at my house. One is stronger at one side of the house and one is stronger at the other. Is there any way that they automatically switch to the strongest wifi signal instead of staying on one?


text:
Q: Web scrapping using Golang Colly, How to handle XML path not found? I am using Colly for scrapping an ecommerce website. I will loop over many products.
Here is a snippet of my code getting a sub-title
    c.OnXML("/html/body/div[4]/div/div[3]/div[2]/div/div[1]/div[3]/div/div/h1/1234", func(e *colly.XMLElement) {
        fmt.Println(e.Text)
})

However, not all products have a sub-title so the above XML path does not work for all cases.
When I reach a product which does not have a sub-title my code got crashed and return an error of
panic: expression must evaluate to a node-set
Here is my so far code:
    c := colly.NewCollector()
c.OnError(func(_ *colly.Response, err error) {
    log.Println("Something went wrong:", err)
})

//Sub Title
c.OnXML("/html/body/div[4]/div/div[3]/div[2]/div/div[1]/div[3]/div/div/h1/1234", func(e *colly.XMLElement) {
    fmt.Println(e.Text)
})

c.OnRequest(func(r *colly.Request) {
    fmt.Println("Visiting", r.URL)
})

c.Visit("https://www.lazada.vn/-i1701980654-s7563711492.html")

Here is what I want
c.OnXML("/html/b.....v/h1/1234", func(e *colly.XMLElement) {
    if no error {

        fmt.Println("NO ERROR)

    } else {

        fmt.Println("GOT ERROR")

    }

})

A: Maybe I figured out what went wrong in your code. Let me start with the final. As you can see, the error is originated from the panic statement at line 473 of the parse.go file. The package xpath has a method called parseNodeTest that does the following check:
func (p *parser) parseNodeTest(n node, axeTyp string) (opnd node) {
    switch p.r.typ {
    case itemName:
        if p.r.canBeFunc && isNodeType(p.r) {
            var prop string
            switch p.r.name {
            case "comment", "text", "processing-instruction", "node":
                prop = p.r.name
            }
            var name string
            p.next()
            p.skipItem(itemLParens)
            if prop == "processing-instruction" && p.r.typ != itemRParens {
                checkItem(p.r, itemString)
                name = p.r.strval
                p.next()
            }
            p.skipItem(itemRParens)
            opnd = newAxisNode(axeTyp, name, "", prop, n)
        } else {
            prefix := p.r.prefix
            name := p.r.name
            p.next()
            if p.r.name == "*" {
                name = ""
            }
            opnd = newAxisNode(axeTyp, name, prefix, "", n)
        }
    case itemStar:
        opnd = newAxisNode(axeTyp, "", "", "", n)
        p.next()
    default:
        panic("expression must evaluate to a node-set")
    }
    return opnd
}

The value of p.r.typ is itemNumber (28). This leads the switch to enter into the default branch and gives the error. The methods invoked before the above-mentioned one (you can see them in the call stack of your IDE) set the typ for the literal 1234 to this value and this caused an invalid XPath query. To make it works, you've to get rid of the 1234 and put some valid value.
Let me know if this solves your issue, thanks!


text:
Q: IE Run As... from C# Code I am calling the following piece of code in my C# winforms app to open specific IE windows:
var IE = new SHDocVw.InternetExplorer();
        object URL = "http://google.com";

        IE.ToolBar = 0;
        IE.StatusBar = false;
        IE.MenuBar = true;
        IE.AddressBar = true;
        IE.Top = 0;
        IE.Left = 0;
        IE.Width = 2590;
        IE.Height = 2160;
        IE.Visible = true;
        IE.Navigate2(ref URL);

I do that for several IE windows and that works just fine but for one in particular I need to be able to specify it to Run As Different User (Shift + Right Click) and pass on those credentials.
Is that possible to be done with SHDocVw.InternetExplorer?


text:
Q: Security features of WebBrowser Control Does the WebBrowser control have any securtiy features included in it? I mean, if i use the WebBrowser control in an application then would using this browser be any more vulnerable than any normal browser, say IE, to securtiy attacks.
Does the WebBrowser control share or use security features of IE?

A: From the official documentation:
"The WebBrowser control is designed to work in full trust only. The HTML content displayed in the control can come from external Web servers and may contain unmanaged code in the form of scripts or Web controls. If you use the WebBrowser control in this situation, the control is no less secure than Internet Explorer would be, but the managed WebBrowser control does not prevent such unmanaged code from running."

A: The WebBrowser control basically is IE. Looking at it from the other direction, IE is basically just a container for a WebBrowser control -- but most settings apply to the underlying WebBrowser control, not to the wrapper. As such, if you instantiate a WebBrowser control, it'll (mostly) act however the user has configured IE.
If you want, you can search for "MFCIE" on the MS web site -- this is a C++ using MFC that also wraps the WebBrowser control, and although it's rather dated, it still gives a pretty fair idea of how little is in the wrapper, and how much of IE is in the WebBrowser control.


text:
Q: Access violation reading location using Botan I have integrated botan library for TLS security.
I get below error:
First-chance exception at 0x6DBFD1CE (vcruntime140.dll) in jsonrpctest.exe: 0xC0000005: Access violation reading location 0x00962000.
If there is a handler for this exception, the program may be safely continued
Below is the code I am calling
int main(int argc, char *argv[])
{
// prepare all the parameters
Callbacks callbacks;
Botan::AutoSeeded_RNG rng;
Botan::TLS::Session_Manager_In_Memory session_mgr(rng);
Client_Credentials creds;
Botan::TLS::Strict_Policy policy;

// open the tls connection : Error comes here
Botan::TLS::Client client(callbacks,
    session_mgr,
    creds,
    policy,
    rng,
    Botan::TLS::Server_Information("10.193.252.14", 43733),
    Botan::TLS::Protocol_Version::TLS_V12);

while (!client.is_closed())
{
    //cout << client.is_active;
    // read data received from the tls server, e.g., using BSD sockets or
 boost asio
    // ...

    // send data to the tls server using client.send_data()
} }

A: The exact reason of this error is unknown. I think it's some build flag is visual studio maybe. I was getting similar error in the release build i made but it works fine in the debug build. Then i built it as a library (DLL) instead of an application (.exe) and i didn't see any issues. I think the best way to use Botan is to make an amalgamation build (i.e. not use the Botan DLL library but import Botan code into your application and then use it). Here is the build command that worked for me (run it from the Botan source folder):
configure.py --cpu=i386 --amalgamation --single-amalgamation-file --minimized-build --enable-modules=tls,x509,seed,rdseed,rdrand,rdrand_rng,auto_rng --disable-shared

You need to have Python installed and in path before running the above command.
The above command will generate the following files in the Botan source code directory (i.e. same path where you run the above command):
botan_all.h, botan_all_internal.h and botan_all.cpp
You need to include these files as part of your application code, use it and build it.
More info on Botan amalgamation build: https://botan.randombit.net/manual/building.html#amalgamation


text:
Q: XSLT 2.0: Creating child elements from an element's text value via known semantic hierarchy A bit stuck on this one.  Data is provided in the following format (non-important content snipped):
<?xml version="1.0" encoding="UTF-8"?>
<Content Type="Statutes">
  <Indexes>

    <Index Level="3" HasChildren="0">

      <Content><p> (1)(a)The statutes ... </p><p> (b)To ensure public ..: </p><p>
            (I)Shall authorize ...; </p><p> (II)May authorize and ...: </p><p> (A)Compact disks;
            </p><p> (B)On-line public ...; </p><p> (C)Electronic applications for ..;
            </p><p> (D)Electronic books or ... </p><p> (E)Other electronic products or formats;
            </p><p> (III)May, pursuant ... </p><p> (IV)Recognizes that ... </p><p>
            (2)(a)Any person, ...: </p><p> (I)A statement specifying ...; </p><p> (II)A statement
            specifying ...; </p><p> (3)A statement
            specifying ...; </p><p> (4)A statement
            specifying ...; </p></Content>
    </Index>

  </Indexes>
</Content>

Need to take the text value of element Content which contains a semantic hierarchy:
(1)
 +-(a)
    +-(I)
       +-(A)

...and place via XSLT 2.0 transformation as a parent-child element relationship as the final output:
    <?xml version="1.0" encoding="UTF-8"?>
    <law>

       <content>

The statutes ...

To ensure public ..:

Shall authorize ...;

May authorize and ...:

Compact disks;

On-line public ...;

Electronic applications for ..;

Electronic books or ...

Other electronic products or formats;

May, pursuant ...

Recognizes that ...

Any person, ...:

A statement specifying ...;

A statement specifying ...;

Level 1 node with no children

       </content>
    </law>

I was able to tokenize the ending html-encoded P tags from Content's text value, but no clue how to get dynamically created elements to create child elements on conditionals.
My XSLT 2.0 stylesheet:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output method="xml" encoding="UTF-8" indent="yes"/>

    <xsl:template match="/Content">

        <xsl:apply-templates select=".//Index[@HasChildren=0]"/>
    </xsl:template>

    <xsl:template match="Index[@HasChildren=0]">
        <law>
            <structure>
                <xsl:apply-templates select="Content"/>
            </structure>
        </law>
    </xsl:template>

    <xsl:template match="Content">
        <content>

            <xsl:for-each select="tokenize(.,'</p>')">

                <xsl:variable name="sectionText">
                    <xsl:value-of select="normalize-space(replace(current(),'<p>',''))"/>
                </xsl:variable>

                <xsl:if test="string-length($sectionText)!=0">

                        <xsl:analyze-string select="$sectionText" regex="^(\(([\w]+)\)){{1,3}}">
                            <xsl:matching-substring >
                                <xsl:attribute name="prefix" select="." />
                            </xsl:matching-substring>
                        </xsl:analyze-string>

                        <xsl:value-of select="$sectionText"/>

                </xsl:if>

            </xsl:for-each>
        </content>
    </xsl:template>
</xsl:stylesheet>

...which gets me out this far - doesn't have the semantic hierarchy within the section elements:
<?xml version="1.0" encoding="UTF-8"?>
<law>
   <structure>
      <content>

(1)(a)The statutes ...

(b)To ensure public ..:

(I)Shall authorize ...;

(II)May authorize and ...:

(A)Compact disks;

(B)On-line public ...;

(C)Electronic applications for ..;

(D)Electronic books or ...

(E)Other electronic products or formats;

(III)May, pursuant ...

(IV)Recognizes that ...

(2)(a)Any person, ...:

(I)A statement specifying ...;

(II)A statement specifying ...;

(3)Level 1 section with no children ...;

      </content>
   </structure>
</law>

Since the Section elements are being created dynamically by the XSLT 2.0 stylesheet via tokenizing the end P tags, how do you build the parent-child relationship dynamically with the known semantic hierarchy via the prefix attribute?
Other programming language experiences point me in the direction of recursion based on the tokenization and logic on the prefix to its previous prefix for nesting - struggling to find any information on how to do this with my limited XSLT knowledge with v2.0 (used v1.0 almost 10+ years ago).  I know I could just parse with an external Python script and be done, but trying to stick to a XSLT 2.0 stylesheet solution for maintainability.
Any help is appreciated to get me on the right track and/or solution.

A: You've tackled one tricky phase of the problem to create an intermediate output with elements like this:

text

My next step would be to compute a level number, so it looks like this:

text

Computing the level number is simply a question of seeing which of several regular expressions the prefix matches: (1) gives you level 1, (b) gives you level 2, etc.
Once you've got level numbers you can use recursive positional grouping as described in this paper: http://www.saxonica.com/papers/ideadb-1.1/mhk-paper.xml

A: I played with this a bit and came up with the following stylesheet:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"
 xmlns:xs="http://www.w3.org/2001/XMLSchema"
 xmlns:mf="http://example.com/mf"
 xmlns:d="data:,dpc"
 exclude-result-prefixes="xs d mf">

    <xsl:include href="htmlparse.xml"/>

    <xsl:param name="patterns" as="element(pattern)*" xmlns="">
      <pattern value="^\s*(\([0-9]+\))" group="1" next="1"/>
      <pattern value="^\s*(\([0-9]+\))?\s*(\([a-z]\))" group="2" next="0"/>
      <pattern value="^\s*(\(*(I|II|III|IV|V|VI|VII|VIII|IX|X|XI|XII|XIII)\))" group="1" next="0"/>
      <pattern value="^\s*(\([A-Z]?\))" group="1" next="0"/>
    </xsl:param>

    <xsl:output method="xml" encoding="UTF-8" indent="yes"/>

    <xsl:function name="mf:group" as="element(section)*">
      <xsl:param name="paragraphs" as="element(p)*"/>
      <xsl:param name="patterns" as="element(pattern)*"/>
      <xsl:variable name="pattern1" as="element(pattern)?" select="$patterns[1]"/>
      <xsl:for-each-group select="$paragraphs" group-starting-with="p[matches(., $pattern1/@value)]">
        <xsl:variable name="prefix" as="xs:string?">
          <xsl:analyze-string select="." regex="{$pattern1/@value}">
            <xsl:matching-substring>
              <xsl:sequence select="string(regex-group(xs:integer($pattern1/@group)))"/>
            </xsl:matching-substring>
          </xsl:analyze-string>
        </xsl:variable>

          <xsl:choose>
            <xsl:when test="xs:boolean(xs:integer($pattern1/@next))">
              <xsl:sequence select="mf:group(current-group(), $patterns[position() gt 1])"/>
            </xsl:when>
            <xsl:otherwise>
              <xsl:apply-templates select="node()">
                <xsl:with-param name="pattern" as="element(pattern)" select="$pattern1" tunnel="yes"/>
              </xsl:apply-templates>
              <xsl:sequence select="mf:group(current-group() except ., $patterns[position() gt 1])"/>
            </xsl:otherwise>
          </xsl:choose>

      </xsl:for-each-group>
    </xsl:function>

    <xsl:template match="/Content">

        <xsl:apply-templates select=".//Index[@HasChildren=0]"/>
    </xsl:template>

    <xsl:template match="Index[@HasChildren=0]">
        <law>
            <structure>
                <xsl:apply-templates select="Content"/>
            </structure>
        </law>
    </xsl:template>

    <xsl:template match="Content">

        <content>
            <xsl:sequence select="mf:group(d:htmlparse(., '', true())/*, $patterns)"/>
        </content>
    </xsl:template>

    <xsl:template match="p/text()[1]">
      <xsl:param name="pattern" as="element(pattern)" tunnel="yes"/>
      <xsl:value-of select="replace(., $pattern/@value, '')"/>
    </xsl:template>
</xsl:stylesheet>

It makes use of http://web-xslt.googlecode.com/svn/trunk/htmlparse/htmlparse.xsl, an HTML tag soup parser written in XSLT 2.0, to parse the escaped HTML fragment markup into nodes which are then grouped using the function mf:group in the stylesheet. The grouping is driven by a sequence of regular expression patterns passed in as a parameter.
When applying the stylesheet with Saxon 9.5 to your input sample, I get the result
<law>
   <structure>
      <content>

The statutes ...

To ensure public ..:
Shall authorize ...;

May authorize and ...:
Compact disks;

On-line public ...;

Electronic applications for ..;

Electronic books or ...

Other electronic products or formats;

May, pursuant ...

Recognizes that ...

Any person, ...:
A statement specifying ...;

A statement
            specifying ...;

      </content>
   </structure>
</law>

You would need to edit the parameter with the regular expression pattern for roman numbers to list more numbers if there can be more than 13 (XIII) sections as I have currently only listed the numbers including XIII.
Based on the comment and the edited input sample I have adapted the stylesheet a bit:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"
 xmlns:xs="http://www.w3.org/2001/XMLSchema"
 xmlns:mf="http://example.com/mf"
 xmlns:d="data:,dpc"
 exclude-result-prefixes="xs d mf">

    <xsl:include href="htmlparse.xml"/>

    <xsl:param name="patterns" as="element(pattern)*" xmlns="">
      <pattern value="^\s*(\([0-9]+\))" group="1" next="1"/>
      <pattern value="^\s*(\([0-9]+\))?\s*(\([a-z]\))" group="2" next="0"/>
      <pattern value="^\s*(\(*(I|II|III|IV|V|VI|VII|VIII|IX|X|XI|XII|XIII)\))" group="1" next="0"/>
      <pattern value="^\s*(\([A-Z]?\))" group="1" next="0"/>
    </xsl:param>

    <xsl:output method="xml" encoding="UTF-8" indent="yes"/>

    <xsl:function name="mf:group" as="element(section)*">
      <xsl:param name="paragraphs" as="element(p)*"/>
      <xsl:param name="patterns" as="element(pattern)*"/>
      <xsl:variable name="pattern1" as="element(pattern)?" select="$patterns[1]"/>
      <xsl:for-each-group select="$paragraphs" group-starting-with="p[matches(., $pattern1/@value)]">
        <xsl:variable name="prefix" as="xs:string?">
          <xsl:analyze-string select="." regex="{$pattern1/@value}">
            <xsl:matching-substring>
              <xsl:sequence select="string(regex-group(xs:integer($pattern1/@group)))"/>
            </xsl:matching-substring>
          </xsl:analyze-string>
        </xsl:variable>

          <xsl:choose>
            <xsl:when test="xs:boolean(xs:integer($pattern1/@next)) and matches(., $patterns[2]/@value)">
              <xsl:sequence select="mf:group(current-group(), $patterns[position() gt 1])"/>
            </xsl:when>
            <xsl:otherwise>
              <xsl:apply-templates select="node()">
                <xsl:with-param name="pattern" as="element(pattern)" select="$pattern1" tunnel="yes"/>
              </xsl:apply-templates>
              <xsl:sequence select="mf:group(current-group() except ., $patterns[position() gt 1])"/>
            </xsl:otherwise>
          </xsl:choose>

      </xsl:for-each-group>
    </xsl:function>

    <xsl:template match="/Content">

        <xsl:apply-templates select=".//Index[@HasChildren=0]"/>
    </xsl:template>

    <xsl:template match="Index[@HasChildren=0]">
        <law>
            <structure>
                <xsl:apply-templates select="Content"/>
            </structure>
        </law>
    </xsl:template>

    <xsl:template match="Content">

        <content>
            <xsl:sequence select="mf:group(d:htmlparse(., '', true())/*, $patterns)"/>
        </content>
    </xsl:template>

    <xsl:template match="p/text()[1]">
      <xsl:param name="pattern" as="element(pattern)" tunnel="yes"/>
      <xsl:value-of select="replace(., $pattern/@value, '')"/>
    </xsl:template>
</xsl:stylesheet>

Now it transforms
<?xml version="1.0" encoding="UTF-8"?>
<Content Type="Statutes">
  <Indexes>

    <Index Level="3" HasChildren="0">

      <Content><p> (1)(a)The statutes ... </p><p> (b)To ensure public ..: </p><p>
            (I)Shall authorize ...; </p><p> (II)May authorize and ...: </p><p> (A)Compact disks;
            </p><p> (B)On-line public ...; </p><p> (C)Electronic applications for ..;
            </p><p> (D)Electronic books or ... </p><p> (E)Other electronic products or formats;
            </p><p> (III)May, pursuant ... </p><p> (IV)Recognizes that ... </p><p>
            (2)(a)Any person, ...: </p><p> (I)A statement specifying ...; </p><p> (II)A statement
            specifying ...; </p><p> (3)A statement
            specifying ...; </p><p> (4)A statement
            specifying ...; </p></Content>
    </Index>

  </Indexes>
</Content>

to
<law>
   <structure>
      <content>

The statutes ...

To ensure public ..:
Shall authorize ...;

May authorize and ...:
Compact disks;

On-line public ...;

Electronic applications for ..;

Electronic books or ...

Other electronic products or formats;

May, pursuant ...

Recognizes that ...

Any person, ...:
A statement specifying ...;

A statement
            specifying ...;

A statement
            specifying ...;

A statement
            specifying ...;

      </content>
   </structure>
</law>


text:
Q: Confused about Gauss's Law for parallel plates I am having trouble understanding Gauss's Law. Suppose we wish to find the electric field strength between two parallel plates with charge density $\sigma$. I know it should be $E=\sigma/(2\epsilon_0)$.
But if we place a cylinder between the plates with base parallel to the plates such that the cylinder does not intersect the plates, then the charge enclosed is $0$ and the flux is $2EA$ where $A$ is the area of the base of the cylinder. Thus by Gauss's Law, $2EA=0$, which gives $E=0$. What is the error in my understanding?

A: Your equation is wrong. The flux is not $2EA$. Rather, is $-EA + EA = 0$. The reason is because Gauss's law involves the dot product of $E$ and $dA$. The direction of $dA$ is the way out of the cylinder. When the electric field goes through the bottom of the cylinder, the electric field is in the opposite direction of the area vector, so the electric flux is $-EA$. When the electric field vector exits the cylinder, it is in the same direction as the area vector, so the electric flux is $EA$. Hence, the net electric flux is $-EA + EA = 0$, not $2EA$. Hence, $0 = 0$, not $2EA = 0$. To solve for the electric field, take a cylinder which goes through one plate. Then, the electric field goes outside the cylinder through the inner base, so the electric field is $EA$. The charge enclosed is $\sigma A$, so $EA = \sigma A/\epsilon_0 $, and thus $E = \sigma /\epsilon_0$.

A: For a Gaussian surface between the two plates, the total flux through the surface is zero.  For the particular surface you give, all of the electric field lines crossing one of the circular faces cross the other face but in an opposite sense.
This is because the outward normal vector for one face of the cylinder is opposite in direction to the outward normal for the other face.
In other words, there is a sign difference; there is $EA$ flux through one face and $-EA$ flux through the other so the total flux is zero.

As an aside, if the (infinite) parallel plates have the same charge density $\sigma$, the electric field between the plates is actually zero.
If one plate has charge density $\sigma$ and the other has charge density $-\sigma$, then the electric field between the plates is $E = \frac{\sigma}{\epsilon_0}$, not $\frac{\sigma}{2\epsilon_0}$


text:
Q: No print preview in Chrome Why can't I see the print preview/can't I print this page with Chrome:
http://www.tuxx.nl/bellen/buitenland/collect_call/print/
It's just HTML, why doesn't it work?

A: You need to enable Print Preview in about:flags:
http://maketecheasier.com/enable-disable-google-chrome-print-preview/2011/04/13


text:
Q: How to Extract JSON Response Values Coming From PHP Backend in Swift iOS I uploaded an image using almofire and it is being uploaded to the correct path I require.
However, I need to get some of the responses that are in my PHP backend code into my swift such as the filepath.
An image to make my question more clear and precise about what I want to get from the .responseJSON
In the image below is my response from the PHP code, I want to get the value of the filepath in swift. How can I achieve that?

Here is my code:
PHP:
<?php

if (empty($_FILES["image"])) {
    $response = array("error" => "nodata");
}

else {
    $response['error'] = "NULL";

    $filename = uniqid() . ".jpg";

    if (move_uploaded_file($_FILES['image']['tmp_name'], "../propertyImages/" . $filename)) {

        $response['status'] = "success";
        $response['filepath'] = "https://example.com/WebService/propertyImages/" . $filename;
        $response['filename'] = "".$_FILES["file"]["name"];

} else{

    $response['status'] = "Failure";
    $response['error']  = "".$_FILES["image"]["error"];
    $response['name']   = "".$_FILES["image"]["name"];
    $response['path']   = "".$_FILES["image"]["tmp_name"];
    $response['type']   = "".$_FILES["image"]["type"];
    $response['size']   = "".$_FILES["image"]["size"];
  }
}

echo json_encode($response);
?>

Swift Code:
 self.imageData = propImage.image!.jpegData(compressionQuality: 0.5)!

        let headers: HTTPHeaders = [
                    "Content-type": "multipart/form-data"
                ]

                    AF.upload(
                        multipartFormData: { multipartFormData in
                            multipartFormData.append(self.imageData!, withName: "image" , fileName: "file.jpg", mimeType: "image/jpeg")
                    },
                        to:"https://example.com/WebService/api/uploadPropImage.php", method: .post , headers: headers)
                        .responseJSON { resp in
                            //let responseString: String = String(data: self.imageData!, encoding: .utf8)!
                            print(resp) //this prints all the responses from the PHP code, my problem is how do i get a specific response, such as the filepath only and so on?
            }

EDIT:
I tried some of the solutions, this one seems to be the one that will work but still gives an error reading
"No exact matches in call to class method 'jsonObject'"

Updated code:
AF.upload(multipartFormData: { multipartFormData in                           multipartFormData.append(self.imageData!, withName: "image" , fileName: "file.jpg", mimeType: "image/jpeg")},                      to:"https://example.com/WebService/api/uploadPropImage.php", method: .post , headers: headers).responseJSON {
   result in

 do{
   if let jsonResults = try JSONSerialization.jsonObject(with: result, options: []) as? [String: Any] { //error in this line
 let filePath = jsonResults["filepath"] as? String
                            }
          }catch{
         print("ERROR")
     }

A: Then just decode your response:
if let jsonResults = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
    let filePath = jsonResults["filepath"] as? String // here is your value
}

A: The value of the responseJSON block, is a Result. It's a basic concept used frequently, so you need to learn how do handle it. Common practice is then to use a switch.
let headers: HTTPHeaders = ["Content-type": "multipart/form-data"]

AF.upload(multipartFormData: { multipartFormData in
    multipartFormData.append(self.imageData!, withName: "image" , fileName: "file.jpg", mimeType: "image/jpeg")
                             },
                              to:"https://example.com/WebService/api/uploadPropImage.php", method: .post , headers: headers)
   .responseJSON { result in
    switch result {
        case .success(let json):
            guard let dictionary = json as? [String: Any] else { print("Response JSON is not a dictionary"); return }
            guard let filePath = json["filePath"] as? String else { print("filePath key is not present in "\(json)" or is not a String");  return }
            print("Filepath: \(filePath)")
        case .failure(let error):
            print("Error: \(error)")
    }

}
Now, it might be better to use a Codable struct to parse your response and call responseDecodable() instead of using responseJSON() which will use JSONSerialization, method which is by the way deprecated and will be removed in next Alamofire major release.


text:
Q: Composite C1 - How to have multiple editable areas in a master layout I have a MasterLayout.cshtml (same as in example site).
As I understand it there can only be one area where page templates can insert content?
However - I would like the main content area to be editable - and a footer area, to be editable on every page - without having to duplicate the structure of the end of the main area and the start of the footer on every page template.
Is this somehow possible?

A: You can move repeating parts of the template to page template features, editable in the Layout perspective.
http://docs.composite.net/Layout/Page-Template-Features
The editable parts of the content on a page can be defined as content placeholders in a template.
http://docs.composite.net/Layout/Razor-Page-Templates/Adding-Placeholders


text:
Q: $x^{2n} + x^{2n-1} + x^ {2n-2} +\ldots+ x + 1$ is irreducible for any $n\in \mathbb N$ in $F_2[x]$. True or false? Will the  polynomials of the following set $A$  be irreducible in $F_2[x]$?
$A = [x^{2n} + x^{2n-1} + x^ {2n-2} + \ldots+ x + 1 : n\in \mathbb N]$
Can anyone please give me hints how to proceed?
Every term is there. I meant every polynomial of degree $2n$ has $2n+1$ terms.

A: It's false in general, for example for $n=4$ : $x^8+x^7+x^6+x^5+x^4+x^3+x^2+x+1 = (x^2+x+1)(x^6+x^3+1)$.
In general $\frac{x^n-1}{x-1}$ is irreducible iff n is prime(the cyclotomic poly) over $ \mathbb{Q}[X]$


text:
Q: How to convert pandas float64 type to NUMERIC Bigquery type? I have a panda dataframe df:
<bound method NDFrame.head of                  DAT_RUN          DAT_FORECAST LIB_SOURCE  MES_LONGITUDE  MES_LATITUDE  MES_TEMPERATURE  MES_HUMIDITE  MES_PLUIE  MES_VITESSE_VENT  MES_U_WIND  MES_V_WIND
0   2022-03-29T00:00:00Z  2022-03-29T01:00:00Z    gfs_025          43.50          3.75        11.994824          72.0        0.0          2.653137   -2.402910   -1.124792
1   2022-03-29T00:00:00Z  2022-03-29T01:00:00Z    gfs_025          43.50          4.00        13.094824          74.3        0.0          2.976434   -2.972910   -0.144792
2   2022-03-29T00:00:00Z  2022-03-29T01:00:00Z    gfs_025          43.50          4.25        12.594824          75.3        0.0          3.128418   -2.702910    1.575208
3   2022-03-29T00:00:00Z  2022-03-29T01:00:00Z    gfs_025          43.50          4.50        12.094824          75.5        0.0          3.183418   -2.342910    2.155208

I convert DAT_RUN and DAT_FORECAST columns to datetime format :
df["DAT_RUN"]           = pd.to_datetime(df['DAT_RUN'],      format="%Y-%m-%dT%H:%M:%SZ") # previously "%Y-%m-%d %H:%M:%S"
df["DAT_FORECAST"]      = pd.to_datetime(df['DAT_FORECAST'], format="%Y-%m-%dT%H:%M:%SZ")

df.dtypes:

DAT_RUN             datetime64[ns]
DAT_FORECAST        datetime64[ns]
LIB_SOURCE                  object
MES_LONGITUDE              float64
MES_LATITUDE               float64
MES_TEMPERATURE            float64
MES_HUMIDITE               float64
MES_PLUIE                  float64
MES_VITESSE_VENT           float64
MES_U_WIND                 float64
MES_V_WIND                 float64

I use bigquery.Client().load_table_from_dataframe() function to insert data into Bigquery table which numeric columns have NUMERIC bigquery table.
It returns this error :
pyarrow.lib.ArrowInvalid: Got bytestring of length 8 (expected 16)

I tried to fix it with :
df["MES_LONGITUDE"]     = df["MES_LONGITUDE"].astype(str).map(decimal.Decimal)

But no more.
Thanks.

A: I managed to work around this issue with a decimal.Context, hope it helps:
import decimal

import numpy as np
import pandas as pd
from google.cloud import bigquery

df = pd.DataFrame(
    data={
        "MES_HUMIDITE": np.array([2.653137, 2.976434, 3.128418, 3.183418]),
        "MES_PLUIE": np.array([-2.402910, -2.972910, -2.702910, -2.342910]),
    },
    dtype="float",
)

We check data type declaration:
df.dtypes
# MES_HUMIDITE    float64
# MES_PLUIE       float64
# dtype: object

Initialize Context to 7 digits, because it is the precision in those columns, you can create multiple Context if you need different precision values for each column:
context = decimal.Context(prec=7)
df["MES_HUMIDITE"] = df["MES_HUMIDITE"].apply(context.create_decimal_from_float)
df["MES_PLUIE"] = df["MES_PLUIE"].apply(context.create_decimal_from_float)

Now, each item is a Decimal object:
df["MES_HUMIDITE"][0]
# Decimal('2.653137')

Types have changed and Pandas stores Decimals as objects, as I guess is not a native data format:
df.dtypes
# MES_HUMIDITE    object
# MES_PLUIE       object
# dtype: object

table_id = "test_dataset.test"
job_config = bigquery.LoadJobConfig(
    schema=[
        bigquery.SchemaField("MES_HUMIDITE", "NUMERIC"),
        bigquery.SchemaField("MES_PLUIE", "NUMERIC"),
    ],
    write_disposition="WRITE_TRUNCATE",
)

client = bigquery.Client.from_service_account_json("/path_to_key.json")
job = client.load_table_from_dataframe(df, table_id, job_config=job_config)
job.result()

However, decimal types are generally recommended for financial calculations and, although I do not know your exact case and usage, you are probably safe using FLOAT64, at least for latitude and longitude.


text:
Q: Elastic Search synonyms - Delete Action Are synonyms in Elastic Search (version 6.2.3) stored in the items when these are created/updated or are synonyms applied in every search query to the index?
We need to remove the synonyms of an index with 6 million items and I cannot see in the documentation if removing these synonyms from the index will be enough
DELETE /api/as/v1/engines/{ENGINE_NAME}/synonyms/{SYNONYM_SET_ID}
Or it is needed to reindex all the items afterwards, in which case it might be better to delete the current index and create a new one.

A: *

*If synonyms are applied during inserting the document

*

*Deletion of current synonyms, won't change anything in the existing data of an index, existing data should be searchable by synonyms.

*If synonyms are applied during query time

*

*In this case, removing the synonyms will stop searching the document using synonym.

Now the question is whether you are using index-time-analysis or query-time-analysis. You can check in your mappings. E.g
"mappings": {
    "properties": {
      "text": {
        "type": "text",
        "analyzer": "autocomplete", // <======== For index time analysis
        "search_analyzer": "synonym_analyzer" //<====== For Query time analysis
      }
    }
  }
}


text:
Q: iPhone graph of - Average sleep per week or month I am trying to track my sleep, currently using Pillow.  But there is a lot of variation in my sleep per night. I'm looking for an app that displays a graph of the average hours of sleep per night for a week so I can more easily see how the average is changing over weeks and months.
Something like a weeklong rolling avg as a  smoothing function on top of what Pillow and the Apple Health apps give you out of the box.
Does anyone know of an app with a graph like this?

A: Autosleep works for me really well the last 6 months.

*

*AutoSleep Tracker for Watch by Tantsissa https://itunes.apple.com/us/app/autosleep-tracker-for-watch/id1164801111?mt=8
I'm much more inclined to get the best data wearing my watch at night, but it does work well if you use charging your phone as proxy for when you lie down and when you get up. Of course you can manually start and stop your rest periods, but for me that is the last hint I want to do before and after resting.


text:
Q: Converting java.util.function.Function to Kotlin's functional interface type I am working with two modules that are coded in Java and Kotlin respectively, hence require some bit of interoperability.
In one of the cases the java module returns functional interfaces with the type java.util.function.Function, which is to be consumed by the kotlin code.
I could use the java type as it is. However, I would like to be able to cast this to kotlin's native type, be it kotlin.Function or kotlin.reflect.KFunction. The reason behind doing so is to be able to support a similar kotlin module as that of the java one, which surfaces functions for the client.
Is there any way to do this?

A: You can't cast between them, they are just two different interfaces. But it's trivial to write conversion functions:
import java.util.function.Function

fun <A, B> Function<A, B>.toKotlin(): (A) -> B = { this.apply(it) }

fun <A, B> ((A) -> B).toJava(): Function<A, B> = Function { this(it) }

kotlin-stdlib-jdk8 could provide these, but doesn't seem to.
And of course, you can just use both Kotlin and Java lambdas/method references for both in most circumstances.


text:
Q: Ruby Compass error: `basename': no implicit conversion of Array into String) I'm getting this error, when compiling sass:
(.../ruby/gems/2.3.0/gems/compass-1.0.3/lib/compass/sass_extensions/sprites/image.rb:24:in `basename': no implicit conversion of Array into String)

My Config.rb is like this:
require 'bootstrap-sass'
require 'compass/import-once/activate'
# Require any additional compass plugins here.

# Set this to the root of your project when deployed:
http_path = "/"
css_dir = "stylesheets"
css_path = "C:/Development/Projects/SparNord.SparNordDotcom/SparNord.SparNordDotcom/css"
sass_dir = "sass"
images_dir = "images"
images_path = "C:/Development/Projects/SparNord.SparNordDotcom/SparNord.SparNordDotcom/images"
javascripts_dir = "javascripts"
javascripts_path = "C:/Development/Projects/SparNord.SparNordDotcom/SparNord.SparNordDotcom/scripts"
cache_path = "C:/temp/sass/"

generated_images_path = "C:/Development/Projects/SparNord.SparNordDotcom/SparNord.SparNordDotcom/images/"

# You can select your preferred output style here (can be overridden via the command line):
# output_style = :expanded or :nested or :compact or :compressed

# To enable relative paths to assets via compass helper functions. Uncomment:
# relative_assets = true

# To disable debugging comments that display the original location of your selectors. Uncomment:
line_comments = false

# If you prefer the indented syntax, you might want to regenerate this
# project again passing --syntax sass, or you can uncomment this:
# preferred_syntax = :sass
# and then run:
# sass-convert -R --from scss --to sass sass scss && rm -rf sass && mv scss sass

I've tried to uncomment relative_assets without any luck.
Any help is more than welcome :)


text:
Q: Audio plays from both speakers and headphones My motherboard is a Gigabyte GA-H170-D3HP, which uses the Realtek HD Audio Manager. I'm on Windows 10 Education x64. I have both speakers and headphones plugged into my computer, and I only use one device at a time. I use nircmd to change the default device between the two and it works very well. The problem, however, is that the audio always plays out of the headphones regardless of which device is the default. If the headphones are the default then sound comes out only the headphones, but if speakers are the default then sound comes out both the speakers and the headphones.
How can I fix this so the audio comes out only the device I have set as the default? I would be fine with outright disabling the non-default device, but I can't find a way to do that via command line. The speakers are plugged into the motherboard, and the headphones are plugged into the front panel.
These are the two config screens in the Realtek utility. I can provide any additional information as needed.

A: Try disabling option 2 ("Make internal and external output devices playback two different audio streams").
Also post a screenshot of your Windows sound configuration.

A: If Windows sees two different drivers for the audio devices, you should be able to get away with disabling the simultaneous playback you have enabled while enabling the conditional mute of the internal device. Your hardware most likely sees the speaker input as any realtek input whereas you have a seperate headphone driver for specifically headphones. Try going into your main speakers menu and muting output on the front port. (I would provide screenshots, but I'm not at my desktop right now.)

A: I had to reinstall Windows for an unrelated reason, and the problem was resolved after that.


text:
Q: generating a random value with a while loop: random value repeating itself I am making a program that semi-randomly generates a string in a part of it I randomly generate a length for the string then I use a mix of generating random characters and random words until the length is reached: the problem is when running it whenever it generates a random word or a random string it does not regenerate it again but uses the same one it previously generated.
I've tried rewriting the code in lots of different ways but I ended up with this problem each time. I could not find anything that helped me on the internet either.
    rand5 = random.randrange(1, 5)
    while run < rand5:

        if random.randrange(1, 3) == 1:
            search_item_part = generate_word() + " "

        else:
            print(2)
            rand7 = random.randrange(2, 9)
            while run1 <= rand7:
                search_item_part += random.choice(letters_characters)
                run1 += 1
                if run1 == rand7:
                    search_item_part += " "
        search_item += search_item_part
        run += 1
    return search_item

I expect the outputs to be different words and strings but they end up being things like:
"cysticercosis cysticercosis CaE6k   cysticercosis CaE6k "
"nY3J KnY3J KnY3J Kpriming "
'F  jQel iF  jQel iF  jQel i'

A: If you want different words and strings each time, then I suggest saving the randomly generated word to a list. Then, add a check to make sure the newly generated word is not in that list. This way you will get a new word each time.


text:
Q: Do ORM frameworks like hibernate implement any kind of rowmapper while iterating over a result set? Do ORM frameworks like hibernate implement any kind of rowmapper while iterating over a result set? If not implementing a row mapper, do they at least iterate the resultset while creating  a list of entities or they directly get list of entities as resultset? i.e., internal working of the createQuery("from Employee").getResultlist();
And if we use a native query does it directly return the result set or iterate over the result set and return a list of object arrays i.e., List<Object[]>?

A: If you're asking if Hibernate is using some kind of object oriented extension when querying: Hibernate works with a lot of databases, it can't use OO vendor extensions because those won't be standardized.
If you look at annotations or mappings for an entity, those tell what column each property is mapped to. So yes, it does have row-mapping functionality where it generates a query, maps the columns to properties, and populates entities from it.
You can see the SQL Hibernate generates by setting the log level for the logger org.hibernate.sql to DEBUG.


text:
Q: How to mix f-string and LaTeX symbols in a print(...) statement? I am calculating pi with the Monte Carlo "quarter circle" method, using the following program:
from random import random as rd

def estimPi(n_points):
    counter = 0
    for i in range(n_points):
        x,y = rd(),rd()
        if x**2 + y**2 < 1:
            counter = counter + 1
    estimPi = 4*(counter/n_points)

    print(f'with {n_points} draws, the estimated value of pi is {estimPi}')

So that:
estimPi(10000)

gives me (as an example, of course):
with 10000 draws, the estimated value of pi is 3.1304

I would like to modify the print(...) line in order to have the pi symbol in the text printed, instead of having the string "pi".
I tried:
print(f'with {n_points} draws, the estimated value of ' + r'$ \pi $' + f' is {estimPi}')

but it doesn't give me what I expect:
with 10000 draws, the estimated value of $ \pi $ is 3.1276

Is there a way to mix f-strings and LaTeX symbols in a print(...)?

A: Why not use the unicode symbol for that?
    print(f'with {n_points} draws, the estimated value of \u03C0 is {estimPi}')

output:
with 10000 draws, the estimated value of π is 3.1164


text:
Q: PDE Laplace equation Calculate $u(x,0)$. Let $u(x,y)$ be a harmonic function in the domain $0\le x^2 +y^2\le 1$
that satisfy the following terms at the rim of the circle:
$$\begin{cases}
u(x,y)=3y & \text{if y>0} \\
u(x,y)=0 &\text{if y<0}
\end{cases}$$
Calculate $u(x,0)$.
My idea is:
we know that the solution to the equation is in the form of
$$u(r,\theta)=\frac{a_0}{2}+\sum_{n=1}^\infty {r^n(a_ncos{(n\theta)}+b_nsin{(}n\theta))}$$
we need to find $u(x,0)$ it's enough to calculate only the series $a_n$
but I Don't sure how we suppuse to do it :(
thanks !

A: You are on the right track. Let $f : [0,2 \pi] \to \mathbb{R}$, $f(\theta) = 3\sin(\theta)$ if $\theta \in [0,\pi]$, $f(\theta) = 0$ otherwise. Note that $u(x,y) = f(\theta)$ when $x^2 + y^2 = 1$. Substitute $r = 1$ in the solution, and impose
$$
\frac{a_0}{2} + \sum_{n = 1}^\infty [a_n \cos(n\theta) + b_n \sin(n\theta)] = f(\theta).
$$
Then expand $f(\theta)$ in Fourier series and impose the equality between coefficients.

A: For your problem, you only have half of a disk because $y >0$ and it is $0$ below there.
When you solve the eigenvalue problem it is a dirichlet problem
$$ \frac{d^{2}\phi}{d\theta^{2}} = -\lambda \theta \tag{1}$$
$$ \theta(0) = \theta(\pi) \tag{2} $$
$$ u(r,\theta) = \sum_{n=1}^{\infty} r^{n} B_{n} \sin(n \theta) \tag{3}$$
$$ f(\theta) = 3\sin(\theta) =\sum_{n=1}^{\infty} B_{n} \sin(n\theta) \tag{4} $$
what are the coefficients that make that true? In other words, what is $B_{n}$
$$ B_{n}a^{n} = \frac{2}{\pi} \int_{0}^{\pi} 3 \sin(\theta) \sin(n\theta) d\theta \tag{5}$$
$$ B_{n} = \frac{2}{\pi} \int_{0}^{\pi} 3 \sin(\theta) \sin(n\theta) d\theta \tag{6}$$


text:
Q: javascript chart library for every minutes data i'm looking for an open source java script library to accomplish a line chart of time-value one series,
that updating every 1min, and showing the last 24h,
eg: 24*60 = 1440 points that will create a line chart,
i want the x-index to be 1h units, e.g if now is 16:04, will be 16:04(yesterday) - 16:04 today.
data set is:
16:04 - [value]
16:05 - [value]
...
00:02 - [value]
...
15:27 - [value]
...
16:04 - [value]
x 1440 lines records
but the index must be in full hour 16:00, 17:00.. 16:00,
with 60 points resolution..
and i need the chart to update every minute with ajax that
every minute old record (eg: 16:04 yesterday) will be deleted and new record will be updated (16:05). (so the chart will  appear moving (possibly with effect))
i couldn't find any library that can do that kind of chart,
please help, did anyone implemented this kind of chart before?
can it be done with chart.js? it's need to be open-source library.
thanks allot! really appreciate it!
EDIT:
this is what i got so far:
http://jsfiddle.net/wbvwadkb/1
BUT i have a major problem with the line labels- it's overlapping and messed up... can anyone help me edit this jsfiddle and fix the lables?
i need the mouse hover label- but to show up only one point...
thanks.

A: To fix label add:
pointHitDetectionRadius : 0,

see last line of http://jsfiddle.net/hntsz4q8/

A: You can use chart Js with AngularJS. Do an interval call to your api to update your data.
Probably good to show some code to begin with.