text:
Q: Setting html using jQuery on li element results in error Here is jsfiddle link - http://jsfiddle.net/howg59sg/5/

test 1

test 2

function myclick() {
    alert("clicked");
    var elemId = "#li1";
    var elemCollection = jQuery(elemId);
    alert("len = " + elemCollection.length);
    if (elemCollection.length) {
        var selectedElem = elemCollection[0];
        alert("id of the element to work on " + selectedElem.attributes["id"].value);
        var stringToReplaceWith = "testing";
        alert("friendname = " + selectedElem.attributes["friendname"].value);
        //alert("html value of selected elem = " + selectedElem.html());

        selectedElem.html(stringToReplaceWith);
    } else {
        alert("none");
    }

}

As you can see, I am trying to update the html content of a li element using jQuery. This results in following error:
Uncaught TypeError: undefined is not a function
I am able to get attributes on this li element but html() setter fails. Even getter fails as well which i have commented out in the code for now...
Does anyone know, What might be wrong here?
Thanks for the help.

A: You get the error because selectedElem is not a jQuery object.
var selectedElem = elemCollection[0];  <-- gets the DOM node
selectedElem.html(stringToReplaceWith);  <-- you treat it as a jQuery object

either use .eq(0) to get the element as jQuery instead of bracket notation and use .attr() to read the attributes Or wrap it with jQuery() or use innerHTML

A: Your issue is likely with this line:
var selectedElem = elemCollection[0];

That will give you a regular DOM element object instead of a jQuery object. DOM elements don't have the html() function like jQuery objects do. You can replace the whole function with just these lines of code:
function myclick(){
  jQuery('#li1').html('testing');
}

A: The following line returns a native DOM Html element:
elemCollection[0];

If you want the first item in a collection as a jQuery element use first():
elemCollection.first();


text:
Q: How to call getItem() & getOptionList()in an Observer.php I have an observer and would like to get the selected custom options array.
I have found the two elements I require in: app/design/frontend/MY-THEME/default/template/checkout/cart/item/default.phtml
Which are:
$_item = $this->getItem();
$_options = $this->getOptionList();

I just don't know how to get them in an observer i.e. what else I have to call.

A: I assume your observer method looks something like this:
public function doSomething($observer)
{
    ...
}

If so, you can get the item like this:
$_item = $observer->getQuoteItem();

and you can get the options like this:
$options = Mage::helper('catalog/product_configuration')->getCustomOptions($_item); //where $_item is the result of the previous line.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Riemann-integration problem Here is the exercise

Let $f:[a,b]\rightarrow \mathbb{R}$ be Riemann-integrable. Prove that $f^+$, $f^-$ and $|f|$ are also Riemann-integrable, when
$$f^+=\begin{cases}
      f(x) & f(x)\geq 0 \\
      0 & otherwise
   \end{cases}$$
$$f^-=\begin{cases}
      -f(x) & f(x)\leq 0 \\
      0 & otherwise
   \end{cases}$$

This problem seems so obvious. Why wouldn't $f^+$ be integrable? Anyway, I need to prove this using this hint:
"$f$ is Riemann-integrable if with every $\epsilon>0$ there exists step functions $h\leq f\leq g $ such that $\int h -\int g <\epsilon$."
I have no idea where to start...

A: We prove the Riemann integrability of $f^+$. A similar proof can be done for $f^-$.
As $f$ is Riemann-integrable, for all $\epsilon>0$ there exists step functions $h \leq f\leq g $ such that $\int h -\int g <\epsilon$.
Now define $h^+ = \max(h,0)$ and $g^+ = \max(g,0)$. You can verify that:

*

*$h^+, g^+$ are step functions.

*You have $h^+ \le f^+ \le g^+$ for all $x \in [a,b]$.

*And also $g^+ - h^+ \le g-h$ for all $x \in [a,b]$. This implies $0 \le \int (g^+-h^+) \le \int (g-h) \le \epsilon$
And concludes the proof.


text:
Q: Mocking functions called from within another in golang I am trying to stub os.Stat and ioutil.ReadFile(path) as used the code below or if you like here on go playground [1]
package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "strings"
)

func AssignFileValueFrom(path string, val *string) {
    var (
        tempValue []byte
        err       error
    )

    if _, err = os.Stat(path); err == nil {
        if err != nil {
            fmt.Println("There was a os stat error:", err)
        }

        tempValue, err = ioutil.ReadFile(path)
        if err != nil {
            fmt.Println("There was an io read error:", err)
        }
        *val = strings.TrimSpace(string(tempValue))
    }
}

I have used testify and tried following the example here [2]
package main

import (
    "testing"

    "github.com/stretchr/testify/mock"
)

type osMock struct {
    mock.Mock
}

func (o osMock) Stat(path string) (interface{}, error) {
    return nil, nil
}

func TestAssignFileValueFrom(t *testing.T) {
    var test string
    osm := new(osMock)
    osm.On(`Stat`, `./.test`).Return([]byte(`1`), nil)

    AssignFileValueFrom(`./.test`, &test)
    // assert.Equal(t, `1`, test)
    osm.AssertExpectations(t)
}

What am I not doing correctly??
[1] https://play.golang.org/p/xcbdMkMwoBN
[2] https://github.com/stretchr/testify#mock-package

A: Your code with osMock doesn't any how influence execution of AssignFileValueFrom function. There is a direct call of os.Stat and it won't be substituted just because you have declared osMock somewhere.
To do actual testing you should use interfaces and dependency injection to be able to test your code.
First of all os.Stat call must be substituted with call to your struct that implements an interface with same method defined. And you need to create at least 2 implementations of this interface: 1 - is actual working code to use, 2 - mock as your osMock struct to use in test. And you need to inject it or pass it to AssignFileValueFrom and then use to call Stat method on it.

A: Thanks, guys for your inputs I have rewritten my tests as follows..
package main

import (
    "io/ioutil"
    "os"
    "testing"

    "github.com/stretchr/testify/assert"
)

var (
    err      error
    testFile *os.File
    test string
)

const (
    TestPrefix  = `test_file_prefix`
    FileContent = `1234`
)

func init() {
    testFile, err = ioutil.TempFile(os.TempDir(), TestPrefix)
    if err != nil {
        panic(err)
    }

    err = ioutil.WriteFile(testFile.Name(), []byte(FileContent), 0644)
    if err != nil {
        panic(err)
    }
}

func TestAssignFileValueFrom(t *testing.T) {
    AssignFileValueFrom(testFile.Name(), &test)

    assert.Equal(t, test, FileContent)
}


text:
Q: Trouble in handling item click of listview m getting exception while taping on listView item..
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listview);
    adapter = new MyAdapter(this,R.layout.list_item);
    listView = (ListView)findViewById(R.id.listView);
    listView.setAdapter(adapter);
    listView.setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> adaptr, View arg1, int position, long arg3) {

    Times times = (Times)adaptr.getItemAtPosition(position);
    //Times times = (Times)MyXMLHandler.array.get(position);
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(times.getDescription());
    builder.setTitle("Description");
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {

            finish();
        }
    });
}

Error.......
06-20 14:55:13.137: ERROR/AndroidRuntime(848): FATAL EXCEPTION: main
06-20 14:55:13.137: ERROR/AndroidRuntime(848): java.lang.IndexOutOfBoundsException: Invalid index 4, size is 0
06-20 14:55:13.137: ERROR/AndroidRuntime(848):     at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
06-20 14:55:13.137: ERROR/AndroidRuntime(848):     at java.util.ArrayList.get(ArrayList.java:311)
06-20 14:55:13.137: ERROR/AndroidRuntime(848):     at android.widget.ArrayAdapter.getItem(ArrayAdapter.java:298)
06-20 14:55:13.137: ERROR/AndroidRuntime(848):     at android.widget.AdapterView.getItemAtPosition(AdapterView.java:740)

A: You forgot to fill data in your adapter, Your adapter is empty..
adapter = new MyAdapter(this,R.layout.list_item);

Fill with some data like String[] or ArrayList...
UPDATE:
@Override
public void onItemClick(AdapterView<?> adaptr, View arg1, int position, long arg3) {

    Times times = MyXMLHandler.array.get(position);
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(times.getDescription());
    builder.setTitle("Description");
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {

            finish();
        }
    });
   builder.show();
}

A: You have Error here
adapter = new MyAdapter(this,R.layout.list_item);

Your adapter is Empty.


text:
Q: Use Resource Files In ASP.NET for HTML controls is it possible to use resource files (.resx) in ASP.NET for a HTML controls ?

A: You neeed to add runat="server" to the control.
<input type="button" value="Press Me" runat="server"
   meta:resourcekey="PressMeButtonResources"/>

Alternatively, you could retrieve resource values programmatically. Here is a an MSDN Article on how to do that. Then you could generate content on the Server side and apply it to your page.


text:
Q: Powershell replace lines stating with given pattern Background:
I am trying to read a config file and place it in a string variable for further use. For now I've managed to remove the newlines, which was fairly simple. However, I'm having a bit of trouble with removing comments (lines starting with a #).
What I have so far
$var = (Get-Content $HOME/path/to/config.txt -Raw).Replace("`r`n","")

What I've tried
A lot of it is something along the lines of
$var = (Get-Content $HOME/path/to/config.txt -Raw).Replace("#.*?`r`n","").Replace("`r`n","")

( .Replace("(?<=#).*?(?=`r`n)","") , .Replace('^[^#].*?`r`n','') etc)

A lot of the resources I've found have treated how to iteratively read from a file and write back to it or a new one, but what I need is for the result to stay in a variable and for the original file not to be altered in any way (also I'd rather avoid using temp files or even variables if possible). I think there is something fundamental I'm missing about the input to Replace. (Also found this semi-relevant piece when you're using the ConvertFrom-Csv Using Import-CSV in Powershell, ignoring commented lines .)
Sample input:
text;
weird text;
other-sort-of-text;
#commented out possibility;
more-input/with-comment;#comment

Sample output:
text;weird text;other-sort-of-text;more-input/with-comment;

Additional info:
Am going to run this on current builds of Windows 10, locally now I seem to have pwershell version 5.1.14393.693

A: Split the string at semicolons, remove element starting with a #, then join the result back to a string.
((Get-Content $HOME/path/to/config.txt -Raw).Replace("`r`n","") -split ';' |
    Where-Object { $_.Trim() -notlike '#*' }) -join ';'

A: This might be identical to some of the other responses, but here is how I would do it:
$Data = Get-Content $HOME/path/to/config.txt -Raw
(($Data -split(';')).replace("`r`n",'') | Where-Object { $_ -notlike '^#*' }) -join(';')

Anyway you do it, remember that rn needs to be expanded, so it has to be encased in double quotes, unlike the rest of your characters.

A: #############solution 1 with convertfrom-string####################

#short version
(gc "$HOME/path/to/config.txt" | ? {$_ -notlike "#*"} |  cfs -D ";").P1 -join ";"

#verbose version
(Get-Content "$HOME/path/to/config.txt"  | where {$_ -notlike "#*"} |  ConvertFrom-String -Delimiter ";").P1 -join ";"

#############Solution 2 with convertfrom-csv#######################

(Get-Content "C:\temp\test\config.txt"  | where {$_ -notlike "#*"} |  ConvertFrom-csv -Delimiter ";" -Header "P1").P1 -join ";"

#############Solution 3 with split #######################

(Get-Content "C:\temp\test\config.txt"  | where {$_ -notlike "#*"} |  %{$_.Split(';')[0]}) -join ";"


text:
Q: How to speed up per column iteration I would like to loop through a data.table and apply a function that requires info from another column in the data.table, sometimes even multiple...
Let's take the mtcars as an example
I have the feeling that you can stick to the .SD way but provide extra arguments and make this much more efficient...
require(data.table)
dt = data.table(mtcars)

#looping through columns of mtcars...
cols = c('mpg', 'hp', 'disp')
dt[,lapply(.SD, function(x) x/mean(x)), .SDcols=cols]

# But actually I want to devide x by the mean of x where am==1

# Now I am doing this...

specificMean= function(DT) {
  x = DT$feature
  xAM = DT[AM==1]$feature
  MEAN = mean(xAM, na.rm=TRUE)
  x = x/MEAN
  return(x)
}

dt[,(cols):=lapply(cols, function(x) specificMean(data.table(feature=get(x), AM=am))), .SDcols=cols]
print(dt)

I have the feeling this is much slower because it performs the data.table() function in each iteration...
A vectorized solution would be nice..

A: A possible approach:
dt[, (cols) := mapply(`/`, .SD[,-"am"], lapply(.SD[am==1, -"am"], mean), SIMPLIFY=FALSE),
    .SDcols=c("am", cols)]

A: Edit: This seems to produce the same result as yours.
library(data.table)

dt = data.table(mtcars)
cols = c('mpg', 'hp', 'disp')

dt[, (cols) := .SD / lapply(.SD[am == 1], mean, na.rm = TRUE), .SDcols = cols]

A: system.time(dt[,lapply(cols, function(x) specificMean(data.table(feature=get(x), AM=am))), .SDcols=cols])
user  system elapsed
0.010   0.000   0.005
efficient way using two loop thanks to @chinsoon12
system.time(dt[,mapply(`/`, .SD[,-"am"], lapply(.SD[am==1, -"am"], mean), SIMPLIFY=FALSE), .SDcols=c("am", cols)])
user  system elapsed
0.001   0.000   0.001
The winning efficient way using one loop thanks to @Cole
system.time(dt[,.SD / lapply(.SD[am == 1], mean, na.rm = TRUE), .SDcols = cols])
user  system elapsed
0.001   0.000   0.001


text:
Q: Почему первое число не добавляется в массив? при выполнении приведенного ниже кода в массив не добавляется самое первое значение i. Я не понимаю почему? Объясните кто может пожалуйста.введите сюда код
i = int(input())
lst = []
while i !=0:
        i = int(input())
        lst.append(i)
print((lst))

A: у вас первая строка кода, создает переменную (i) и не куда ее не записывает, уберите первую строку измените условия выхода из цикла и код будет валиден, как вы хотите
lst = []
while True:
        i = int(input())
        lst.append(i)
        if i == 0:
            break
print((lst))


text:
Q: Show that $f_n\to f$ uniformly

Let $(f_n)$ be a sequence of continuous functions on a compact set $K$ with pointwise and continuous limit $f$. Show that $(f_n)$ converges uniformly to $f$.

My professor gave me a proof, but to be honest, I cannot understand this proof! I cite it therefore:
Quote:
Because of continuity on $K$  it follows that $s_n:=\sup\lvert f_n(x)-f(x)\rvert$ is taken at a $x=x_N$ in $K$ and because of the compactness of $K$ there is a convergent subsequence $y_k=x_{n_k}\to y_*$.
It is true that
$$
f_n(y_n)\to f(y_*)
$$
because of the continuity of $f_n$ and $f$.
So
$$
s_n\to\sup\lvert f(y_*)-f(y_*)\rvert =0.
$$
because of the choice of $s_n$ this shows the uniformly convergence.
Do you understand this? I do not.

A: As others have commented, the statement is false.  A very simple counter-example is
$$f_n(x) = \begin{cases}
 n x & 0\leq x<\frac{1}{n} \\
 2-n x & \frac{1}{n}\leq x<\frac{2}{n} \\
 0 & \frac{2}{n} \leq x \leq 1
\end{cases}.$$
I personally visualize the picture first.

A: This is false! The mistake in the proof is the claim that $f_n(y_n)\to f(y^*)$. That is true only if you know uniform convergence.
You should have among your bag of examples functions $f_n$ on $[0,1]$ converging non-uniformly to $f=0$.

A: The proof is wrong as is the statement. You can let $K = [0,1]$ and then let $f_n(x)$ be zero except on $(1/n, 2/n)$ such that $f_n(x)$ has a "hump" of height $1$ between $1/n$ and $2/n$. The pointwise limit is zero but the convergence is not uniform.
The problem with the proof is the statement $f_n(y_n)\to f(y_*)$, which isn't true here. You can see in this example that $f_n(y_n) = 1$ but $f(y_*) = 0$.


text:
Q: Dart: SecurityError when getting ImageData from Context I'm not sure why, but I get this error:

Breaking on exception: SecurityError: Internal Dartium Exception

When I try to get a ImageData from a context of a Canvas I have filled with an external Url.
I suppose the problem is that the image on the canvas does not come from the same url as my code. Is it the case?
ImageData id = mainContext.getImageData(0, 0, mainCanvas.width, mainCanvas.height);

The rest of the code works and it's just the creation of the canvas and its context. I draw an image on the canvas
ImageElement image = new ImageElement(src: fileNameElement.value);
image.onLoad.listen((e) {
  mainCanvas.width= image.width;
  mainCanvas.height = image.height;
  mainContext.drawImage(image,0,0);
});


text:
Q: amazon turk, submit is not working I've created an amazon Turk HIT.
after submitting the HIT. we are always getting emails from people telling us the submit is not working...
honestly, I don't know what I'm doing wrong.
form inside my HTML:
<form name='mturk_form' method='post' id='mturk_form' action='https://www.mturk.com/mturk/externalSubmit'>

        <input name="EXISTS" type="radio" value="YES" id="ckeck-yes">YES
          <input name="EXISTS" type="radio" value="NO"  id="ckeck-no">NO

    <input type="hidden" name="IMG_ID" value="${Img_ind}">
    <input type="hidden" id="assignment_id" name="assignmentId" value=""/>

<input type="submit" id="submitButton" class="btn btn-primary" value="Submit">

</form>

Javascript:

What I'm missing?

A: the problem was amazon turk replace my http:// WITH http%3A%2F%2F
so i created a new hit, inspect the new HIT javascript and copied 2 javascript function from amazon example.
function decode(strToDecode) {
  var encoded = strToDecode;
  return unescape(encoded.replace(/\+/g,  " "));
};

function turkGetSubmitToHost() {
      return decode(turkGetParam("turkSubmitTo", "https://www.mturk.com"));
};

  var form = document.getElementById("mturk_form");
  if (form) {
     form.action = turkGetSubmitToHost() + "/mturk/externalSubmit";
  }

thank you


text:
Q: ArgumentNullException on dynamic binding I am trying to fetch last 100 rows from database and show it in datatable.But Im getting Argument.NullException while doing so.How can I resolve this?
ViewModel
public class WalkInnVM
{
    ...
    ...
    public class WalkInnDataTable
    {
        public string SlNo { get; set; }
        public string Name { get; set; }
        public string Center { get; set; }
        public string Mobile { get; set; }
        public string CareGiverMobileNo { get; set; }
        public string Qualification { get; set; }
        public string CourseRecommended { get; set; }
        public int Id { get; set; }
    }
}

Controller Class
  WalkInnVM.WalkInnDataTable _dTableWalkInn = new WalkInnVM.WalkInnDataTable();
   if (_currentRole == (int)EnumClass.Role.SALESINDIVIDUAL)
            {
                _dTableWalkInn = _db.StudentWalkInns
                                 .AsEnumerable()
                                 .Where(x => x.ProspectHandledEmpID == Int32.Parse(Session["LoggedUserId"].ToString()))
                                 .OrderByDescending(x => x.Id)
                                 .Select(x => new WalkInnVM.WalkInnDataTable
                                 {
                                     SlNo = "",
                                     Name = x.CandidateName,
                                     Center = x.CenterCode.CentreCode,
                                     Mobile = x.MobileNo,
                                     CareGiverMobileNo = x.GuardianType == (int)EnumClass.CareGiver.Father ? "FATHER :" + x.GuardianContactNo :
                                                       x.GuardianType == (int)EnumClass.CareGiver.Guardian ? "GUARDIAN :" + x.GuardianContactNo :
                                                       x.GuardianType == (int)EnumClass.CareGiver.Mother ? "MOTHER :" + x.GuardianContactNo :
                                                                       "SPOUSE :" + x.GuardianContactNo,
                                     Qualification = x.QlfnMain.Name + "," + x.QlfnSub.Name,
                                     CourseRecommended = x.StudentWalkInnCourses
                                                      .Select(c => c.Course.Name)
                                                      .Aggregate((m, n) => m + "," + n),
                                     Id = x.Id
                                 })
                                 .Take(100);
            }

Here Take(100) is showing ArgumentNullException and the problem is solved when using var variable instead of typos.


text:
Q: How can I get a URL to the recipient view of an existing envelope using the DocuSign API? I've looked through the documentation but haven't been able to find a way to do this. What I'm currently doing is storing envelope IDs along with their expiration date in a database, so I want to be able to show the user the same envelope if they have one already open. However I don't know how to retrieve this URL after the creation of the envelope.

A: I have found it, you will need to POST by using the createRecipient method. More information can be found here.
https://developers.docusign.com/esign-rest-api/reference/Envelopes/EnvelopeViews/createRecipient


text:
Q: python scrapy yield request typerror on url paramter with f string Trying to get data from excel column then start scraping by concatenating the value taken from excel to url. Script gives a TypeError raise TypeError(f"Request url must be str, got {type(url).__name__}")
Below is my script.
import scrapy
from scrapy.crawler import CrawlerProcess
import pandas as pd

plate_num_xlsx = 'LA55ERR'
base_url=[f"https://dvlaregistrations.dvla.gov.uk/search/results.html?search={plate_num_xlsx}&action=index&pricefrom=0&priceto=&prefixmatches=&currentmatches=&limitprefix=&limitcurrent=&limitauction=&searched=true&openoption=&language=en&prefix2=Search&super=&super_pricefrom=&super_priceto="]

class plateScraper(scrapy.Spider):
    name = 'scrapePlate'
    allowed_domains = ['dvlaregistrations.direct.gov.uk']
    start_urls = [f"https://dvlaregistrations.dvla.gov.uk/search/results.html?search={plate_num_xlsx}&action=index&pricefrom=0&priceto=&prefixmatches=&currentmatches=&limitprefix=&limitcurrent=&limitauction=&searched=true&openoption=&language=en&prefix2=Search&super=&super_pricefrom=&super_priceto="]

    def start_requests(self):
        df=pd.read_excel('data.xlsx')
        columnA_values=df['PLATE']
        for row in columnA_values:
            print(row)
            plate_num_xlsx=row
            print(plate_num_xlsx)
            url=base_url
            yield scrapy.Request(url)

    def parse(self, response):
        for row in response.css('div.resultsstrip'):
            plate = row.css('a::text').get()
            price = row.css('p::text').get()
            if plate_num_xlsx==plate.replace(" ","").strip():
                print(plate.replace(" ", ""))
                yield {"plate": plate.strip(), "price": price.strip()}

process = CrawlerProcess()
process.crawl(plateScraper)
process.start()


text:
Q: trying to use pynput's globalhotkeys and pynput's keyboard controller in same script - is this possible? I cannot get pynput's keyboard.GlobablHotKeys() and keyboard.Controller() to work in the same script. In this example script, CTRL+c isn't being sent (or received by system, as selected text doesn't get copied into clipboard). I'm using pygetwindow just to confirm that the correct window has focus prior to sending CTRL+c.
from pynput import keyboard
import clipboard
import pygetwindow as gw

keybrd = keyboard.Controller()

def copy_clipboard():
    print(gw.getActiveWindowTitle())
    with keybrd.pressed(keyboard.Key.ctrl.value):
        keybrd.press('c')
        keybrd.release('c')
    return clipboard.paste()

def function_1():
    print('Function 1 activated')
    clipboardContents = copy_clipboard()
    print(clipboardContents)

def function_2():
    print('Function 2 activated')
    clipboardContents = copy_clipboard()
    print(clipboardContents)

with keyboard.GlobalHotKeys({
        '<alt>+<shift>+u': function_1,
        '<ctrl>+<alt>+b': function_2}
        ) as h:
    h.join()


text:
Q: Why would running 32 bit executeable on 64 bit FreeBSD v8.1 give ELF error? I have a 32 bit build on FreeBSD v8.1 and attempt to run it on a 64 bit FreeBSD v8.1 and it fails:
[si-fbsd8x64b ~] flume --version
ELF interpreter /libexec/ld-elf.so.1 not found
Abort trap: 6

Can this work, if so, what change do I need to make to enable it?

A: Install lib32 part of distribution.
ftp://ftp.freebsd.org/pub/FreeBSD/releases/amd64/8.1-RELEASE/lib32/


text:
Q: How to parse xml with PL/SQL correctly I got an xml response, and I have to parseit using PL/SQL.
This is my XML:
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
  <GetFacturasClienteResponse xmlns="http://tempuri.org/">
     <GetFacturasClienteResult>
        <xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
           <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:MainDataTable="table" msdata:UseCurrentLocale="true">
              <xs:complexType>
                 <xs:choice minOccurs="0" maxOccurs="unbounded">
                    <xs:element name="table">
                       <xs:complexType>
                          <xs:sequence>
                             <xs:element name="NUM_FACTURA" minOccurs="0">
                                <xs:simpleType>
                                   <xs:restriction base="xs:string">
                                      <xs:maxLength value="30"/>
                                   </xs:restriction>
                                </xs:simpleType>
                             </xs:element>
                             <xs:element name="NPE" minOccurs="0">
                                <xs:simpleType>
                                   <xs:restriction base="xs:string">
                                      <xs:maxLength value="26"/>
                                   </xs:restriction>
                                </xs:simpleType>
                             </xs:element>
                             <xs:element name="TIPO_DOC" minOccurs="0">
                                <xs:simpleType>
                                   <xs:restriction base="xs:string">
                                      <xs:maxLength value="3"/>
                                   </xs:restriction>
                                </xs:simpleType>
                             </xs:element>
                             <xs:element name="FECHA_VENCIMIENTO" minOccurs="0">
                                <xs:simpleType>
                                   <xs:restriction base="xs:string">
                                      <xs:maxLength value="10"/>
                                   </xs:restriction>
                                </xs:simpleType>
                             </xs:element>
                             <xs:element name="SALDO_ACTUAL" type="xs:decimal" minOccurs="0"/>
                             <xs:element name="SALDO_ACTUAL_SC" type="xs:decimal" minOccurs="0"/>
                             <xs:element name="TIPO_FACTURA" minOccurs="0">
                                <xs:simpleType>
                                   <xs:restriction base="xs:string">
                                      <xs:maxLength value="2"/>
                                   </xs:restriction>
                                </xs:simpleType>
                             </xs:element>
                             <xs:element name="DIAS_DIF" type="xs:decimal" minOccurs="0"/>
                             <xs:element name="TOTAL_CANCELADO" type="xs:decimal" minOccurs="0"/>
                             <xs:element name="LINEA_PREPAGO" minOccurs="0">
                                <xs:simpleType>
                                   <xs:restriction base="xs:string">
                                      <xs:maxLength value="2"/>
                                   </xs:restriction>
                                </xs:simpleType>
                             </xs:element>
                             <xs:element name="CICLO" minOccurs="0">
                                <xs:simpleType>
                                   <xs:restriction base="xs:string">
                                      <xs:maxLength value="2"/>
                                   </xs:restriction>
                                </xs:simpleType>
                             </xs:element>
                             <xs:element name="NOMBRE_CLIENTE" minOccurs="0">
                                <xs:simpleType>
                                   <xs:restriction base="xs:string">
                                      <xs:maxLength value="40"/>
                                   </xs:restriction>
                                </xs:simpleType>
                             </xs:element>
                          </xs:sequence>
                       </xs:complexType>
                    </xs:element>
                 </xs:choice>
              </xs:complexType>
           </xs:element>
        </xs:schema>
        <diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
           <DocumentElement xmlns="">
              <table diffgr:id="table1" msdata:rowOrder="0">
                 <NUM_FACTURA>047-001-01-10640742</NUM_FACTURA>
                 <NPE>001-01-10640742</NPE>
                 <TIPO_DOC>047</TIPO_DOC>
                 <FECHA_VENCIMIENTO>08/05/2017</FECHA_VENCIMIENTO>
                 <SALDO_ACTUAL>271.54</SALDO_ACTUAL>
                 <SALDO_ACTUAL_SC>271.54</SALDO_ACTUAL_SC>
                 <DIAS_DIF>11</DIAS_DIF>
                 <TOTAL_CANCELADO>0</TOTAL_CANCELADO>
                 <CICLO>48</CICLO>
                 <NOMBRE_CLIENTE>RED TECNOLOGICA ARPU</NOMBRE_CLIENTE>
              </table>
              <table diffgr:id="table2" msdata:rowOrder="1">
                 <NUM_FACTURA>047-001-01-10793193</NUM_FACTURA>
                 <NPE>001-01-10793193</NPE>
                 <TIPO_DOC>047</TIPO_DOC>
                 <FECHA_VENCIMIENTO>06/06/2017</FECHA_VENCIMIENTO>
                 <SALDO_ACTUAL>271.72</SALDO_ACTUAL>
                 <SALDO_ACTUAL_SC>271.72</SALDO_ACTUAL_SC>
                 <DIAS_DIF>-18</DIAS_DIF>
                 <TOTAL_CANCELADO>0</TOTAL_CANCELADO>
                 <CICLO>48</CICLO>
                 <NOMBRE_CLIENTE>RED TECNOLOGICA ARPU</NOMBRE_CLIENTE>
              </table>
           </DocumentElement>
        </diffgr:diffgram>
     </GetFacturasClienteResult>
  </GetFacturasClienteResponse>

This is my PL/SQL code:
create or replace PROCEDURE          "GETFACTURASCLIENTEPOSPAGO"
(origenpago in varchar2,
telefono in varchar2,
corrbanco in varchar2,
p_recordset     out sys_refcursor) as
soap_request VARCHAR2(30000);
soap_respond CLOB; --VARCHAR2(32000);
--soap_respond varchar2(30000);

http_req utl_http.req;
http_resp utl_http.resp;
resp XMLType;
resp1 CLOB;
--resp1        varchar2(30000);
resp2      VARCHAR2(30000);
soap_err   EXCEPTION;
v_code     VARCHAR2(200);
v_msg      VARCHAR2(1800);
v_len      NUMBER;
v_txt      VARCHAR2(32767);
i          INTEGER;
tablaTemp  VARCHAR2(2000);
tablaTemp2 VARCHAR2(2000);
tablaTemp3 VARCHAR2(2000);
tablaTemp4 VARCHAR2(2000);
tablaTemp5 VARCHAR2(2000);
tablaTemp6 VARCHAR2(2000);
--p_recordset sys_refcursor;
vCampo CLOB;
buffer    VARCHAR2(32767);
tramaenee VARCHAR2(384);
BEGIN
soap_request := '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05
/soap-envelope" xmlns:tem="http://tempuri.org/">
<soap:Header/>
<soap:Body>
  <tem:GetFacturasCliente>
     <tem:cod_pais>504</tem:cod_pais>
     <tem:cod_banco>11</tem:cod_banco>
     <tem:origen_pago>'||origenpago||'</tem:origen_pago>
     <tem:tipo_producto>02</tem:tipo_producto>
     <tem:num_browse></tem:num_browse>
     <tem:telefono>'||telefono||'</tem:telefono>
     <tem:corr_banco>'||corrbanco||'</tem:corr_banco>
  </tem:GetFacturasCliente>
</soap:Body>
</soap:Envelope>';
-- dbms_output.put_line('Paso 1' || soap_request);
http_req := utl_http.begin_request('http://172.28.2.72:4909
/ExternListenerWs.asmx', 'POST', 'HTTP/1.1');
--utl_http.set_header(http_req, 'Content-Type',
'application/soap+xml;charset=UTF-8');
 utl_http.set_header(http_req, 'Content-Type', 'text/xml');
--UTL_HTTP.SET_HEADER(http_req, 'User-Agent', 'Mozilla/4.0');
--utl_http.set_header(http_req, 'Content-Type',
'application/soap+xml;charset=UTF-8');
utl_http.set_header(http_req, 'Content-Length', LENGTH(soap_request));
utl_http.set_header(http_req, 'SOAPAction', 'http://tempuri.org
/GetFacturasCliente');
dbms_output.put_line('Request : '||soap_request);
utl_http.write_text(http_req, soap_request);
http_resp := utl_http.get_response(http_req);
/*
SELECT EXTRACTVALUE(http_resp
              , 'ns2:strPasthrResponse'
              , 'xmlns:ns2="http://dom.jet.com/"')
 INTO l_response_result
 FROM dual;
 DBMS_OUTPUT.put_line ( 'Result> NonExistingWaybills=' ||
 l_response_result);

*/

DBMS_LOB.CREATETEMPORARY(vCampo, true);
LOOP
 BEGIN
  utl_http.read_text(http_resp, buffer, 32767);
  IF buffer IS NOT NULL AND LENGTH(buffer) > 0 THEN
    dbms_lob.writeappend(vCampo, LENGTH(buffer), buffer);
  END IF;
EXCEPTION
WHEN OTHERS THEN
  EXIT;
END;
END LOOP;
dbms_output.put_line('Respuesta : ' || vCampo);
--utl_http.read_text(http_resp, soap_respond);
utl_http.end_response(http_resp);
OPEN p_recordset FOR
WITH XML AS
(SELECT XMLTYPE(vCampo) AS OBJECT_VALUE FROM dual
)
select x.*
from XML,
XMLTABLE
( XMLNAMESPACES('http://www.w3.org/2003/05/soap-envelope' as "soap",
'http://www.w3.org/2001/XMLSchema' as "xs",
'urn:schemas-microsoft-com:xml-diffgram-v1' as "diffgr",
default 'http://tempuri.org/'),
 '*:Envelope/*:Body/GetFacturasClienteResponse'
 --'*:Envelope/*:Body/GetFacturasClienteResponse/GetFacturasClienteResult'
passing OBJECT_VALUE
columns
GetFacturasClienteResult varchar2(1000) path './GetFacturasClienteResult',
GetFacturasClienteResult1 varchar2(100) path './xs:schema/diffgr:diffgram
/DocumentElement/table/NUM_FACTURA'
 )  x;

END GETFACTURASCLIENTEPOSPAGO;

I'm getting this result:
GetFacturasClienteResult.
047-001-01-10640742001-01-1064074204708/05/2017271.54271.5411048RED TECNOLOGICA ARPU047-001-01-10793193001-01-1079319304706/06/2017271.72271.72-18048RED TECNOLOGICA ARPU

but what I need is this values :
    NUM_FACTURA        NPE      FECHA_VENCIMIENTO     NOMBRE_CLIENTE
047-001-01-10640742   001-01-10640742     08/05/2017       RED TECNOLOGICA ARPU
047-001-01-10793193   001-01-10793193      06/06/2017        RED TECNOLOGICA ARPU

Can anybody help me. Thank you in advance.

A: It's possible to do this in SQL:
WITH sd AS (SELECT XMLTYPE('<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetFacturasClienteResponse xmlns="http://tempuri.org/">
<GetFacturasClienteResult>
<xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:MainDataTable="table" msdata:UseCurrentLocale="true">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="table">
<xs:complexType>
<xs:sequence>
<xs:element name="NUM_FACTURA" minOccurs="0">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:maxLength value="30"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="NPE" minOccurs="0">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:maxLength value="26"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="TIPO_DOC" minOccurs="0">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:maxLength value="3"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="FECHA_VENCIMIENTO" minOccurs="0">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:maxLength value="10"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="SALDO_ACTUAL" type="xs:decimal" minOccurs="0"/>
<xs:element name="SALDO_ACTUAL_SC" type="xs:decimal" minOccurs="0"/>
<xs:element name="TIPO_FACTURA" minOccurs="0">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:maxLength value="2"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="DIAS_DIF" type="xs:decimal" minOccurs="0"/>
<xs:element name="TOTAL_CANCELADO" type="xs:decimal" minOccurs="0"/>
<xs:element name="LINEA_PREPAGO" minOccurs="0">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:maxLength value="2"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="CICLO" minOccurs="0">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:maxLength value="2"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="NOMBRE_CLIENTE" minOccurs="0">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:maxLength value="40"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
           <DocumentElement xmlns="">
              <table diffgr:id="table1" msdata:rowOrder="0">
                 <NUM_FACTURA>047-001-01-10640742</NUM_FACTURA>
                 <NPE>001-01-10640742</NPE>
                 <TIPO_DOC>047</TIPO_DOC>
                 <FECHA_VENCIMIENTO>08/05/2017</FECHA_VENCIMIENTO>
                 <SALDO_ACTUAL>271.54</SALDO_ACTUAL>
                 <SALDO_ACTUAL_SC>271.54</SALDO_ACTUAL_SC>
                 <DIAS_DIF>11</DIAS_DIF>
                 <TOTAL_CANCELADO>0</TOTAL_CANCELADO>
                 <CICLO>48</CICLO>
                 <NOMBRE_CLIENTE>RED TECNOLOGICA ARPU</NOMBRE_CLIENTE>
              </table>
              <table diffgr:id="table2" msdata:rowOrder="1">
                 <NUM_FACTURA>047-001-01-10793193</NUM_FACTURA>
                 <NPE>001-01-10793193</NPE>
                 <TIPO_DOC>047</TIPO_DOC>
                 <FECHA_VENCIMIENTO>06/06/2017</FECHA_VENCIMIENTO>
                 <SALDO_ACTUAL>271.72</SALDO_ACTUAL>
                 <SALDO_ACTUAL_SC>271.72</SALDO_ACTUAL_SC>
                 <DIAS_DIF>-18</DIAS_DIF>
                 <TOTAL_CANCELADO>0</TOTAL_CANCELADO>
                 <CICLO>48</CICLO>
                 <NOMBRE_CLIENTE>RED TECNOLOGICA ARPU</NOMBRE_CLIENTE>
              </table>
           </DocumentElement>
        </diffgr:diffgram>
     </GetFacturasClienteResult>
  </GetFacturasClienteResponse>
</soap:Body>
</soap:Envelope>') x FROM dual)
SELECT xmldata.*
FROM sd
     CROSS JOIN XMLTABLE('//DocumentElement/table' PASSING sd.x
                         COLUMNS num_factura VARCHAR2(30) PATH 'NUM_FACTURA',
                                 npe VARCHAR2(26) PATH 'NPE',
                                 fecha_vencimiento VARCHAR2(10) PATH 'FECHA_VENCIMIENTO',
                                 nombr_cliente VARCHAR2(40) PATH 'NOMBRE_CLIENTE') xmldata;

NUM_FACTURA                    NPE                        FECHA_VENCIMIENTO NOMBR_CLIENTE
------------------------------ -------------------------- ----------------- ----------------------------------------
047-001-01-10640742            001-01-10640742            08/05/2017        RED TECNOLOGICA ARPU
047-001-01-10793193            001-01-10793193            06/06/2017        RED TECNOLOGICA ARPU

A: Your example XML is not valid, There are not 2 closing tag.
create test_clob (a clob) ;
-- src xml is inserted into test_clob  table
with xml_src as (
select diffgram, xsSchema inot
from test_clob,
XMLTABLE
( XMLNAMESPACES('http://www.w3.org/2003/05/soap-envelope' as "soap",
'http://www.w3.org/2001/XMLSchema' as "xs",
'urn:schemas-microsoft-com:xml-diffgram-v1' as "diffgr",
default 'http://tempuri.org/'),
 '/soap:Envelope/soap:Body/GetFacturasClienteResponse/GetFacturasClienteResult'
 --'*:Envelope/*:Body/GetFacturasClienteResponse/GetFacturasClienteResult'
passing xmltype(a)
columns
diffgram xmltype path './diffgr:diffgram',
xsSchema xmltype path './xs:schema') )
select s.* from xml_src,xmltable( XMLNAMESPACES('urn:schemas-microsoft-com:xml-diffgram-v1' as "diffgr"
, 'urn:schemas-microsoft-com:xml-msdata'  as "msdata"
    ),'/diffgr:diffgram/DocumentElement/table'
 passing diffgram
 columns

  NUM_FACTURA varchar2 (100) path 'NUM_FACTURA' ,
  NPE varchar2 (100) path 'NPE' ,
  TIPO_DOC varchar2 (100) path 'TIPO_DOC',
  diffgr_id varchar2 (100) path '@diffgr:id',
  -- ...more column
   rowOrder varchar2 (100) path '@msdata:rowOrder'
 ) s

The problem is your xml has more than one default namespace.
GetFacturasClienteResponse is in http://tempuri.org/
DocumentElement is in default standard namespace


text:
Q: For Loop in Worksheet change malfunction Please I have an issue, everytime a change occcurs on the sheet it affects all the rows instead of the row (i) concerned. Confused. Don't for-loops work for worksheet_change ? Pls help. Thanks.
Private Sub Worksheet_Change(ByVal Target As Range)

Dim LR As Long

'create a variable for last row of column C, LR
LR = Cells(Rows.Count, "C").End(xlUp).Row

For i = 2 To LR
      If Cells(i, 6) = "Yes" And Cells(i, 7).Value = "Full" Then
       Target.Value = Cells(i, 3).Value
       Cells(i, 9).ClearContents
       Cells(i, 10).Value = Cells(i, 8).Value + Cells(i, 9).Value
     End If

    If Not Intersect(Target, Range("G" & i & ":G" & LR)) Is Nothing And Range("F" & i) = "Yes"
    And Target.Value = "Full" Then
      Application.EnableEvents = False
      Cells(i, 8).Value = Cells(i, 3).Value
      Cells(i, 9).ClearContents
      Cells(i, 10).Value = Cells(i, 8).Value + Cells(i, 9).Value
      Application.EnableEvents = True
    End If

    If Not Intersect(Target, Range("G" & i & ":G" & LR)) Is Nothing And Range("F" & i) = "Yes" And
    Target.Value = "Portion" Then
      Application.EnableEvents = False
      Cells(i, 8).Value = Cells(i, 3).Value
      Cells(i, 10).Value = Cells(i, 8).Value + Cells(i, 9).Value
      Application.EnableEvents = True
    End If

Next i
End Sub

A: It seems you need to launch this event for the columns A-E. So, you can start your macro with:
IF Target.Column <= 5 THEN
...
END IF 'at the end of your macro

Like this, when you launch code like Cells(i, 8).Value = ..., Cells(i, 10).Value = ..., ... this macro will be called but it will be stopped immediately.
Apparently you are checking on column, maximum 10, which is in the range of the cells you are changing within your macro. Let's go for another approach:
At the very beginning of your macro, put this line:
Application.EnableEvents = False

At the very end of your macro, put this line:
Application.EnableEvents = True

(and remove the other occurences).
This will make sure you don't call your macro while running it.


text:
Q: Close the lid immediately After putting macbook to sleep manually by  → Sleep will cause the system awake, is this a bug? I have MacBook Pro (Retina, 13-inch, Mid 2014) and OS: 10.13.6.
My current pmset -g:
$ pmset -g
System-wide power settings:
Currently in use:
 standbydelay         10800
 standby              1
 womp                 1
 halfdim              1
 hibernatefile        /var/vm/sleepimage
 powernap             0
 gpuswitch            2
 networkoversleep     0
 disksleep            10
 sleep                1
 autopoweroffdelay    28800
 hibernatemode        3
 autopoweroff         1
 ttyskeepawake        1
 displaysleep         10
 acwake               0
 lidwake              0

I was testing what the best practice is to make sure my macbook is asleep before putting it to my backbag. So I wrote a simple script like this:
$ cat sleep-detector.sh
while true;
do
    echo `date` " -------- not sleep yet"
    tput bel
    sleep 1s
done

I ran this script for all my following tests from terminal.app.

*

*When I close the lid directly, the bell sound will be off immediately (even if the script will continue to run for about 20s). This is expected.

*I thought it was much safer to put the system to sleep manually by  → Sleep , but I was wrong.

*If I use  → Sleep, and wait for 20 seconds and then close the lid, everything is expected as before.

*But If I use  → Sleep and close the lid immediately, the weird thing happened. At the beginning, when I click  → Sleep, the bell is off immediately, but when I close the lid very quickly, the bell is on. And it's on for a long time. (I don't bother wait for a long time. my test is actually 3 minutes).
This surprises me a lot. How come closing a lid cause the system back online and awake?! Is this a bug?


text:
Q: How to open external links in a WebView Swift? I've a question about opening external links in my webView of SwiftUI. The web page loaded properly, but I can't open external links from this website (for example: Facebook, YouTube, Mail, Phone etc). Please, who can give me a help on this one?
I added the code below:
You can call an url, like ShowWebpage("https://www.wordpress.com"), in the ContentView.
  struct WebView: UIViewRepresentable {
    let request: URLRequest
    private var webView: WKWebView?

    init(request: URLRequest) {
            self.webView = WKWebView()
            self.request = request
            self.webView?.configuration.defaultWebpagePreferences.allowsContentJavaScript = true

        }

    func makeUIView(context: Context) -> WKWebView {
        return webView!
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {
        uiView.load(request)
    }
}

struct ShowWebpage : View {
    //get URL Page
    var urlpage: String

    var body: some View {
        let webview = WebView(request: URLRequest(url: URL(string: urlpage)!))

        VStack{
            //Load URL page
            webview
        }
    }
}


text:
Q: Returning object obtained from a WCF web service I have a function that returns an entity obtained from a WCF web service. How should I return this entity as? I don't think I can return the original object (from the web service), because that would mean that the function's caller (from other assembly) will be forced to have a service reference to this web service (because the class is defined in the service reference) and I think I want to avoid that. And I don't think I can use interface either, since I can't modify the WCF entity to implement my interface.
On the other hand, I need to return precisely all properties that the original entity has, eg. all properties needed to be there, and there is no conversion/adjustment needed to any value or any property name and type.
Is it better to create a new class that duplicate the same properties from the original WCF class? How should I implement it, is it better to create a new object that copies all values from the original object, e.g.
return new Foo() { Id = original.Id, Name = original.Name, ... etc. }?
or just wrap it with get set methods like :
public int Id
{
   get { return _original.Id; }
   set { _original.Id = value; }
}

And any idea how to name the new class to avoid ambiguity with the original class name from the WCF reference?

A: as you have figured out, it is not a good idea to force the client to use the same types as the server. This would unnecessarily expose server application architecture to the client. The best option is to use Data Transfer Objects (DTOs).
You may have DTO for each of the entity you wish to expose to the client and the DTO will have properties to expose all the required fields of the entity. There are libraries such as value injector (valueinjecter.codeplex.com) or auto mapper as suggested by @stephenl to help you in copying the values from one object to another.
Place the DTOs in a separate namespace and assembly for best physical decoupling. You can use YourCompany.YourProduct.Data.Entities as the namespace for entities and YourCompany.YourProduct.Data.DTO for the DTOs

A: Actually, it depends on whether you are the consumer. If you are the consumer, reusing the type assembly is ok. However if you are not in control of the consuming services, it is better to use DTO objects with [DataContract] attributes.


text:
Q: What's the best way to normalize "time" in PHP? I'm looking for a way to turn user input into normalized data fit for calculation. The input is some length of time, and is coming from Twitter, so it's string only. Ideally I'd love these results:
an hour and a half --> 01:30
27.52              --> 00:28
5:24               --> 05:24
Is this is a particularly difficult thing to do? I could focus on coaching the users on how to create good input, but also don't want to be too strict.
Any suggestions would be great,
Thanks!

A: Three things to make it work:

*

*regular expressions

*fuzzy logic (lots of if/else statements)

*strtotime to normalize to standard unix epoch time (which makes additions/subtractions very easy)

Since it's user input and non-deterministic that's the only way. Even then the results won't be 100% reliable and a small margin of error should be acceptable.

A: I think the best you'll get is the strtotime (http://us3.php.net/strtotime) function.


text:
Q: nested if statement vs && operator javascript jquery I've been converting some of my code from nested if statements by using the && operator, one of these nested statements works in it's old form, but once converted ceases to function.
Am I doing it wrong?
Consider:
;(function( $, window ){
    var jsonData = <venda_block></venda_block>,

    isActive = jsonData.isActive, // false = off, true = on
    spendThreshold = jsonData.spendThreshold,
    displayThreshold = jsonData.displayThreshold,
    orderTotal = <venda_total>,
    remainingSpend = spendThreshold - orderTotal;

    $('.deliveryType').text(jsonData.deliveryType);

    if (isActive) {
    if (orderTotal >= displayThreshold) {
    if (!(orderTotal >= spendThreshold)) {
        $('.freeDeliveryBlurb2').show();
        $('.remainingSpend').html(remainingSpend);
    }}}
    }( jQuery, window ));

&&
if (isActive) {
    if (orderTotal >= displayThreshold && !(orderTotal >= spendThreshold)) {
        $('.freeDeliveryBlurb2').show();
        $('.remainingSpend').html(remainingSpend);
    }}
    }( jQuery, window ));

A: If you want to convert the following if block with && :
if (isActive) {
if (orderTotal >= displayThreshold) {
if (!(orderTotal >= spendThreshold)) {
    $('.freeDeliveryBlurb2').show();
    $('.remainingSpend').html(remainingSpend);
}}}

The result could be like this :
if (isActive && orderTotal >= displayThreshold && !(orderTotal >= spendThreshold)) {
    $('.freeDeliveryBlurb2').show();
    $('.remainingSpend').html(remainingSpend);
}

Or, as !(orderTotal >= spendThreshold) is equivalent to (orderTotal < spendThreshold), be like this :
if (isActive && orderTotal >= displayThreshold && orderTotal < spendThreshold) {
    $('.freeDeliveryBlurb2').show();
    $('.remainingSpend').html(remainingSpend);
}

Be aware that there may be a bug in your original code as the below if statement is wrongly written :
if (orderTotal >= displayThreshold {

instead of
if (orderTotal >= displayThreshold) {


text:
Q: How to implement alternately waiting for two elements in Pytest? try except doesn't match After submitting the request, there are two possible options:

*

*The request cannot be executed and a notification about the rejection of the request will appear

*The request can be executed and a button will appear to confirm the request.
Now the implementation is as follows, try waits for a rejection notification, and if not executed by timeout, then except looks for a request confirmation button. The disadvantage of this approach is that it takes 10 minutes to process the request. And if the button for confirming the request appears at 5 seconds, then all the same there will be a 10 minute wait for the notification about the rejection of the request, we lose time. I saw on the Internet the approach of waiting for two elements through the lambda functions of Python, but I could not figure out what and how. Can someone help? or suggest alternative solutions to the problem
 def reject_request(self):
 id_pending = self._get_element_text(Main.pending_locates.pending_id)

 try:
     self._wait_for_visible(Main.pending_locates.reject_window)
     id_result = self._get_element_text(Main.results.result_id)

     assert id_pending == id_result, 'The ID of the request is not found in the result table'
     print('Your request automatically rejected')

 except TimeoutException:
     self._click(Main.pending_locates.button_reject)
     sleep(1)
     id_result = self._get_element_text(Main.results.result_id)

     assert id_pending == id_result, 'The ID of the request is not found in the result table'
     print('Your request manually Rejected')
 return self

I want to implement it in a way similar to this, but I have little experience. If anyone can help I will explain in more detail


text:
Q: How to get the return of a created object in Mongoose with express api In my express api, using mongoose, i create a new user on api using User.create. How i can get the return of the created object to include on the response?
My method to create a object is:
async store (req, res) {
const { name, lastName, email, password } = req.body

if (await User.findOne({ email })) {
  return res.status(400).json({ error: 'User already exists' })
}

try {
  await User.create({
    name,
    lastName,
    email,
    password,
    role: 'USER_ROLE'
  })

  res.status(201).json({
    ok: true,
    message: 'User created'
  })
} catch (e) {
  res.status(500).json({
    ok: false,
    message: 'Failed to create User'
  })
}

}
I want to return the user created on the res, like:
 res.status(201).json({
    ok: true,
    message: 'User created',
    user: user

  })

A: async store(req, res) {
  const { name, lastName, email, password } = req.body

  if (await User.findOne({ email })) {
    return res.status(400).json({ error: 'User already exists' })
  }

  try {
    let user = await User.create({
      name,
      lastName,
      email,
      password,
      role: 'USER_ROLE'
    })
    user = user.toJson();
    delete user.password;
    delete user.role;
    res.status(201).json({
      ok: true,
      user: user,
      message: 'User created'
    })
  } catch (e) {
    res.status(500).json({
      ok: false,
      message: 'Failed to create User'
    })
  }
}

You can covert mongoose object to JSON using
user.toJson()

Then you can delete the fields that you don't want to send into the response.
delete user.password;


text:
Q: How to join two tables using JPA Criteria Builder? I have an sql table called school, and another called student. Every school has an ID, and every student has a "school ID", which is the ID of the school they belong to.
Now I want to find all schools in which there is a student called "John".
The SQL syntax would be something like :
SELECT * FROM school
INNER JOIN student
   on student.school_id = school.id
where student.name = "John"

However, I have to use the Spring Boot Specification to make my Query (ie use it like) :
schoolDao.findAll(new mySpecification("John"));

I have to use that because there is already a Specification and I just want to add a new on top of it :
schoolDao.findAll(
    (Specification) Specifications.where(new oldSpecification(), new mySpecification("John"));

So how can I do that ?
I tried
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
    if (this.filterTag == "") {
        return null;
    }
    Class clazz = query.getResultType();
    if (clazz.equals(Long.class) || clazz.equals(long.class)) {
        return null;
    }
    Join<School,Student> tags = root.join("student", JoinType.LEFT);

    return cb.equal(tags.get("name"), "John");
}

but it doesn't work. Anyone can help ?
EDIT : The Student class
@Entity
@Table(name = "student")
public class Student implements Serializable {

    private static final long serialVersionUID = 1L;

    @ManyToOne
    private Long schoolId;

    private String name;

    public Long getSchoolId() {
        return schoolId;
    }

    public void setSchoolId(Long schoolId) {
        this.schoolId = schoolId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

and the School class :
@Entity
@Table(name = "school")
public class School implements Serializable {

    private static final long serialVersionUID = 1L;

    //other fields

    @OneToMany(targetEntity = Student.class, mappedBy = "schoolId")
    @Transient
    private List<Student> students = new ArrayList<Student>();

   //all getters and setters
}

EDIT 2 :
The error is
java.lang.IllegalArgumentException: Unable to locate Attribute  with the the given name [student] on this ManagedType [School]
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:384) ~[spring-orm-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:227) ~[spring-orm-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:417) ~[spring-orm-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59) ~[spring-tx-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213) ~[spring-tx-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147) ~[spring-tx-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:131) ~[spring-data-jpa-1.9.1.RELEASE.jar!/:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) ~[spring-aop-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208) ~[spring-aop-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at com.sun.proxy.$Proxy113.findAll(Unknown Source) ~[na:na]
    at com.visenze.evaluation.service.SearchExperimentService.getSearchExperiments(SearchExperimentService.java:132) ~[classes!/:na]
    at com.visenze.evaluation.service.SearchExperimentService$$FastClassBySpringCGLIB$$30203a2c.invoke(<generated>) ~[classes!/:na]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:650) ~[spring-aop-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at com.visenze.evaluation.service.SearchExperimentService$$EnhancerBySpringCGLIB$$2cf73334.getSearchExperiments(<generated>) ~[classes!/:na]
    at com.visenze.evaluation.controller.SearchExperimentController.getSearchExperiments(SearchExperimentController.java:126) ~[classes!/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_92]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_92]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_92]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_92]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222) ~[spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137) ~[spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) ~[spring-webmvc-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814) ~[spring-webmvc-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737) ~[spring-webmvc-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959) ~[spring-webmvc-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893) ~[spring-webmvc-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) [spring-webmvc-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) [spring-webmvc-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) [spring-webmvc-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat-embed-websocket-8.0.28.jar!/:8.0.28]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration$ApplicationContextHeaderFilter.doFilterInternal(EndpointWebMvcAutoConfiguration.java:242) [spring-boot-actuator-1.3.0.RELEASE.jar!/:1.3.0.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:111) [spring-boot-actuator-1.3.0.RELEASE.jar!/:1.3.0.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:316) [spring-security-web-4.0.3.RELEASE.jar!/:4.0.3.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126) [spring-security-web-4.0.3.RELEASE.jar!/:4.0.3.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90) [spring-security-web-4.0.3.RELEASE.jar!/:4.0.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.3.RELEASE.jar!/:4.0.3.RELEASE]
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114) [spring-security-web-4.0.3.RELEASE.jar!/:4.0.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.3.RELEASE.jar!/:4.0.3.RELEASE]
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:122) [spring-security-web-4.0.3.RELEASE.jar!/:4.0.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.3.RELEASE.jar!/:4.0.3.RELEASE]
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) [spring-security-web-4.0.3.RELEASE.jar!/:4.0.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.3.RELEASE.jar!/:4.0.3.RELEASE]
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:169) [spring-security-web-4.0.3.RELEASE.jar!/:4.0.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.3.RELEASE.jar!/:4.0.3.RELEASE]
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:48) [spring-security-web-4.0.3.RELEASE.jar!/:4.0.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.3.RELEASE.jar!/:4.0.3.RELEASE]
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:158) [spring-security-web-4.0.3.RELEASE.jar!/:4.0.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.3.RELEASE.jar!/:4.0.3.RELEASE]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:120) [spring-security-web-4.0.3.RELEASE.jar!/:4.0.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.3.RELEASE.jar!/:4.0.3.RELEASE]
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) [spring-security-web-4.0.3.RELEASE.jar!/:4.0.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.3.RELEASE.jar!/:4.0.3.RELEASE]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:91) [spring-security-web-4.0.3.RELEASE.jar!/:4.0.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.3.RELEASE.jar!/:4.0.3.RELEASE]
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:53) [spring-security-web-4.0.3.RELEASE.jar!/:4.0.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) [spring-security-web-4.0.3.RELEASE.jar!/:4.0.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213) [spring-security-web-4.0.3.RELEASE.jar!/:4.0.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176) [spring-security-web-4.0.3.RELEASE.jar!/:4.0.3.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) [spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262) [spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:87) [spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77) [spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121) [spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:103) [spring-boot-actuator-1.3.0.RELEASE.jar!/:1.3.0.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_92]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_92]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_92]
Caused by: java.lang.IllegalArgumentException: Unable to locate Attribute  with the the given name [ExperimentTag] on this ManagedType [com.visenze.evaluation.model.base.IdEntity]
    at org.hibernate.jpa.internal.metamodel.AbstractManagedType.checkNotNull(AbstractManagedType.java:144) ~[hibernate-entitymanager-4.3.11.Final.jar!/:4.3.11.Final]
    at org.hibernate.jpa.internal.metamodel.AbstractManagedType.getAttribute(AbstractManagedType.java:130) ~[hibernate-entitymanager-4.3.11.Final.jar!/:4.3.11.Final]
    at org.hibernate.jpa.internal.metamodel.AbstractManagedType.getAttribute(AbstractManagedType.java:128) ~[hibernate-entitymanager-4.3.11.Final.jar!/:4.3.11.Final]
    at org.hibernate.jpa.internal.metamodel.AbstractManagedType.getAttribute(AbstractManagedType.java:128) ~[hibernate-entitymanager-4.3.11.Final.jar!/:4.3.11.Final]
    at org.hibernate.jpa.criteria.path.AbstractFromImpl.locateAttributeInternal(AbstractFromImpl.java:133) ~[hibernate-entitymanager-4.3.11.Final.jar!/:4.3.11.Final]
    at org.hibernate.jpa.criteria.path.AbstractPathImpl.locateAttribute(AbstractPathImpl.java:221) ~[hibernate-entitymanager-4.3.11.Final.jar!/:4.3.11.Final]
    at org.hibernate.jpa.criteria.path.AbstractFromImpl.join(AbstractFromImpl.java:419) ~[hibernate-entitymanager-4.3.11.Final.jar!/:4.3.11.Final]
    at org.hibernate.jpa.criteria.path.AbstractFromImpl.join(AbstractFromImpl.java:405) ~[hibernate-entitymanager-4.3.11.Final.jar!/:4.3.11.Final]
    at com.visenze.evaluation.dao.jpa.TagFilterSpecification.toPredicate(TagFilterSpecification.java:39) ~[classes!/:na]
    at org.springframework.data.jpa.domain.Specifications$ComposedSpecification.toPredicate(Specifications.java:189) ~[spring-data-jpa-1.9.1.RELEASE.jar!/:na]
    at org.springframework.data.jpa.domain.Specifications.toPredicate(Specifications.java:99) ~[spring-data-jpa-1.9.1.RELEASE.jar!/:na]
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.applySpecificationToCriteria(SimpleJpaRepository.java:583) ~[spring-data-jpa-1.9.1.RELEASE.jar!/:na]
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.getQuery(SimpleJpaRepository.java:534) ~[spring-data-jpa-1.9.1.RELEASE.jar!/:na]
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.getQuery(SimpleJpaRepository.java:519) ~[spring-data-jpa-1.9.1.RELEASE.jar!/:na]
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:401) ~[spring-data-jpa-1.9.1.RELEASE.jar!/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_92]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_92]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_92]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_92]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:483) ~[spring-data-commons-1.11.1.RELEASE.jar!/:na]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:468) ~[spring-data-commons-1.11.1.RELEASE.jar!/:na]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:440) ~[spring-data-commons-1.11.1.RELEASE.jar!/:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61) ~[spring-data-commons-1.11.1.RELEASE.jar!/:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281) ~[spring-tx-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
    ... 111 common frames omitted

Thanks

A: This is how I do it
    EntityManager em = emf.createEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Object> cq = cb.createQuery();
    Root<Item> ri = cq.from(School.class);

    // joins
    Join<Object, Object> h = ri.join("Student");
    Query query = em.createQuery(cq);
    List<Object[]> result = query.getResultList();

But as you have your Entities setup, which not just use JPA?


text:
Q: Vue iterate over array of image paths and display them So I have an array of image paths that I retrieve from rest API and i'm trying to display them using a v-for loop
this is the code of the page that displays them
<template>
  <v-app>

    <app-navbar />

    <v-main>

test {{$route.params.name}}, {{$route.query.status}},{{$route.query.tag}}

{{imagesref}}

        {{item}}

    </v-main>
  </v-app>
</template>

the images are inside the assets folder like this
/assets
  /captures
     /test_..
        /@DHRD_..
           /testname
              /1.png

the path of the images are retrieved as an array with each element being a path to an image like this
projectname/assets/captures/test../@DHRD../testname/1.png

How can I display all the images


text:
Q: What builtin functions shouldn't be run by untrusted users? I'm creating a corewars type application that runs on django and allows a user to upload some python code that will control their character.  Now, I know the real answer to this is that as long as I'm taking code input from untrusted users I'll have security vulnerabilities.  I'm just trying to minimize the risk as much as possible.  Here are some that spring to mind:

*

*__import__ (I'll probably also do some ast scanning to make sure there aren't any import statements)

*open

*file

*input

*raw_input
Are there any others I'm missing?

A: There are lots of answers on what to do in general about restricting Python at http://wiki.python.org/moin/SandboxedPython. When I looked at it some time ago, the Zope RestrictedPython looked the best solution, working with a whitelist system. You'll still need to take care in your own code so that you don't expose any security vulnerabilities, but that seems to be the best system out there.

A: You will really need to avoid eval.
Imagine code such as:
eval("__impor" + "t__('whatever').destroy_your_server")

This is probably the most important one.

A: Since you sound determined to do this, I'll link you to the standard rexec module, not because I think you should use it (don't - it has known vulnerabilities), but because it might be a good starting point for getting your webserver compromised your own restricted-execution framework.
In particular, under the heading "Defining restricted environments" several modules and functions are listed that were considered reasonably safe by the rexec designer; these might be usable as an initial whitelist of sorts. I'd also suggest examining its code for other gotchas you might not have thought of.

A: Yeah, you have to whitelist.  There are so many ways to hide the bad commands.
This is NOT the worst case scenario:

the worst case scenario is that someone gets into the database

The worst case scenario is getting the entire machine rooted and you not noticing as it probes your other machines and keylogs your passwords.  Isolate this machine and consider it hostile (DMZ, block it from being able to launch attacks internally and externally, etc).  Run tripwire or AIDE on non-writeable media and log everything to a second host.
Finally, as plash shows, there are a lot of dangerous system calls that need to be protected against.

A: You should use a whitelist, rather than a blacklist.  If you use a blacklist, you will always miss something.  Even if you don't, Python will add a function to the standard library, and you won't update your blacklist in time.
Things you're currently allowing but probably should not include:

*

*compile

*eval

*reload (if they do access the filesystem somehow, this is basically import)

I agree that this would be very tricky to do correctly.  One complication (among many) could be a user accessing one of these functions through a field in another class.
I would consider using another isolation mechanism, such as a virtual machine, instead or in addition to this.  You might look at how codepad does it.

A: If you're not committed to using Python as the language inside the game, one possibility would be to embed Lua using LunaticPython (I suggest the bugfixes branch at https://code.launchpad.net/~dne/lunatic-python/bugfixes).
It's much easier to sandbox Lua than Python, and it's much easier to embed Lua than to create your own programming language.


text:
Q: PcapDotNet only runs on development machine I'm using the PcapDotNet Library (https://github.com/PcapDotNet/Pcap.Net/wiki) to build a protocol-specific remote sniffer for a private network.
I can include the DLLs in Visual Studio 2017 in a C# application, and it runs fine. There are 5 PCAP DLLs required for the application at runtime.
The problem is when I move the application and the DLLs to another host on the network; the application throws a 'file not found' exception even though the DLLs are in the same folder as the EXE.  I think this might be a catch-all error code and the real problem is with dependencies inside the PCAP library.
The only difference I can find between the development host and the deployment host is the Visual Studio environment.  I've tried several fixes on the development side, including trying to rebuild the PCAP library from source (still has file-not-found issues) and targeting different platforms (x86, x64, any) but always get the same result. Has anyone run into this problem?

A: A colleague at work found the solution for this: PcapNet.Core.DLL is built with C++, and has a dependency on the Visual C++ Redistributable library. So for PcapDotNet to work, you must install the redistributable on the target machine. The x86 version is the one to use:
vcredist_x86.exe
Once this was run, my PcapDotNet applications worked fine. Thanks BC for your efforts!


text:
Q: To show a new Form on click of a button in C# I am new to C# can anybody tell me on How to show a new Form on click of a button.

A: private void ButtonClick(object sender, System.EventArgs e)
{
    MyForm form = new MyForm();
    form.Show(); // or form.ShowDialog(this);
}

A: Double click the button in the form designer and write the code:
    var form2 = new Form2();
    form2.Show();

Search some samples on the Internet.

A: Try this:
private void Button1_Click(Object sender, EventArgs e )
{
   var myForm = new Form1();
   myForm.Show();
}

A: This is the code that I needed. A defined user control's .show() function doesn't actually show anything. It must first be wrapped into a form like so:
CustomControl customControl = new CustomControl();
Form newForm = new Form();
newForm.Controls.Add(customControl);
newForm.ShowDialog();

A: This worked for me using it in a toolstrip menu:
 private void calculatorToolStripMenuItem_Click(object sender, EventArgs e)
 {
     calculator form = new calculator();
     form.Show(); // or form.ShowDialog(this);
 }

A: Game_Menu Form1 = new Game_Menu();
Form1.ShowDialog();

Game_Menu is the form name
Form1 is the object name

A: 1.Click Add on your project file new item and add windows form, the default name will be Form2.
2.Create button in form1 (your original first form) and click it.
Under that button add the above code i.e:
var form2 = new Form2();
form2.Show();

3.It will work.


text:
Q: How do I replace a javascript object's value with a calculated value? I am setting up Google Analytics Ecommerce tracking for a client who hosts their shopping cart on Shopify. I have the integration working just fine, except that Shopify's total revenue per order needs to be divided by 100 for it to be accurate. For example, an order comes in with $8.72 in revenue, but the value passed to Google Analytics is 872.
Here is the entire code for bringing Shopify's data into Google Analytics. The field I need to divide by 100 is {{ total_price }}.
<!-- Begin Google Analytics Ecommerce Tracking -->
<script>
ga('require', 'ecommerce');

ga('ecommerce:addTransaction', {
  'id': '{{ id }}',                             // Transaction ID. Required.
  'affiliation': 'myClient',                    // Affiliation or store name.
  'revenue': '{{ total_price }}',               // Total revenue.
  'shipping': '{{ order.shipping_price }}',     // Shipping.
  'tax': '{{ order.tax_price }}'                // Tax.
  'currency': 'USD'                             // Local currency.
});

ga('ecommerce:send');

</script>

A: I was able to find a different solution. Shopify provides a filter called "money_without_currency" that somehow adds a decimal in the right place, effectively dividing the amount by 100. Silly. So, I never needed to use javascript for the solution. Thanks for the help anyways!

A: You can do the calculation right in there, as it's standard JS:
ga('ecommerce:addTransaction',{
   // some parameters
   'revenue': {{total_price}}/100,
   // some other parameters
});


text:
Q: Trying to rewrite a history (rebase -i) with merged branches I have a repository with a project in which I work alone, so I have no big issues forcing re-writing of history if really needed. Right now my history repo looks like:
(initial repo)
                                  P   (feature2)
                                 /
          A-B-...-C-D-E-J-K-M-N-O (develop)
                      |    \ \
                      F-G-H-I-L (feature1)

Where ... is a list of sequential commits I've omited in the graph, and K and M are merge commits from feature1 into develop. The issue is I've found a typo in my .gitignore and I can't really run the project if a clone the repo in another pc right now. The fix was introduced in two commits, N and O and I'd like to move N and O to their right places  in time to be able to clone the project in any commit and be workable something like:
(moving the commits)
                                  P   (feature2)
                                 /
          A-N-B-...-C-O-D-E-J-K-M (develop)
                      |      / /
                      F-G-H-I-L (feature1)

As you can see I would like to retain the merge structure from K, M, etc.
Ideally N should be a fixup of the initital commit A, and O a fixup of commit C:
(after squash/fixup)
                                P   (feature2)
                               /
          A*-B-...-C*-D-E-J-K-M (develop)
                        |    \ \
                        F-G-H-I-L (feature1)

I've tried both --preserve-merges or -i --rebase-merges as I read related questions on SO and the git docs but have to go end up undoing it because it messes up more.
How would you proceed to achieve this?


text:
Q: Cytoscape - graph entire screen i need to render graphs and i want to use cytoscape (plotly dash cytoscape).
Because with the plotly dash wrapper it is possible to write everything in python and i don't need to split my (small) application into a backend and a frontend part.
I want that the graph uses the entire screen and orders the nodes in a good and readable way.
Unfortunately i don't find a description of all possible parameters in the api documentation.
Instead of the rendering in  picture i would like to have it in way.
Do you have any idea how to solve this?
The graph has the entire space available, i can move it with my mouse everwhere i want.
These are my current properties:
cyto.Cytoscape(
id='knowledge-graph',
layout={
    'name': 'cose',
    'idealEdgeLength': 1000,
    'nodeOverlap': 500,
    'refresh': 20,
    'fit': True,
    'padding': 30,
    'randomize': False,
    'componentSpacing': 1000,
    'nodeRepulsion': 400000,
    'nestingFactor': 5,
    'gravity': 800,
    'numIter': 1000,
    'initialTemp': 200,
    'coolingFactor': 0.95,
    'minTemp': 1.0
},
style={
    "width": "100%",
    "height": "calc(100vh - 150px)",
},
stylesheet=[
    {'selector': 'edge', 'style': {'label': 'data(label)', 'curve-style': 'haystack',
                                   'haystack-radius': 0,
                                   'width': 5,
                                   'opacity': 0.5,
                                   'line-color': '#a8eae5'}, 'text-wrap': 'wrap'},
    {'selector': 'node', 'style': {'label': 'data(label)', 'background-color': '#30c9bc'}, 'text-wrap': 'wrap'},
]

)
Thank you!

A: You can try using cytoscape-spread layout which first applies a force-directed layout for initial positions and then uses voronoi-based method to spread the nodes in the remaining space. You can check its demos here and here.


text:
Q: Returning a variable from a class with python Hey I'm trying to get a variable from a class but for some reason its not coming through. its probably really simple but I really cant think of anything
Here is the code its not done yet I've only made a login screen:
from tkinter import *
import tkinter.messagebox as tm
correct = False
#-------------Functions-----------------------------------------------------

class LoginMenu(Frame):
    def __init__(self, master):
        super().__init__(master)

        self.label_2 = Label(self, text="Welcome to the rota system")
        self.label_3 = Label(self, text="Please enter the password to continue:")
        self.label_1 = Label(self, text="Password")

        self.entry_1 = Entry(self)

        self.label_1.grid(row=3, sticky=W)
        self.label_2.grid(row=1, sticky=W)
        self.label_3.grid(row=2, sticky=W)
        self.entry_1.grid(row=3, sticky=W)

        self.logbtn = Button(self, text="Login", command = self.login_btn_clicked)
        self.logbtn.grid(columnspan=2)

        self.pack()

    def login_btn_clicked(self):

        password = self.entry_1.get()

        if password == "1234":
            correct = True

        else:
            tm.showerror("Login error", "Incorrect password")
        return correct

#-----------------Main-Program----------------------------------------------

window = Tk()
LoginMenu(window)
if correct == True:
    print("Yay")
    LoginMenu.self.destroy()
window.mainloop()

A: Your variable within the class only has a local scope.
A good way would be to define the variable correct as a class member:
class LoginMenu(Frame):
    def __init__(self, master):
        super().__init__(master)
        self.correct = False

and then set it in your function:
def login_btn_clicked(self):

        password = self.entry_1.get()

        if password == "1234":
            self.correct = True

Your could access it from the global scope via (no need for == True, btw)
loginmenu = LoginMenu(window)
if loginmenu.correct:

The problem is though that this won't work in your case. You enter your main loop after your if construct. Please have a look at the Tkinter docs how to properly structure a Tkinter app.

A: To reference a global variable inside a local scope you have to define that variable inside the class like this:
global correct

(inside the function login_btn_clicked)


text:
Q: Heroku help: ActionView::Template::Error (Permission de nied I get this error on heroku:
2011-06-01T09:13:29+00:00 app[web.1]: Started GET "/" for MYIP at 2011
-06-01 11:13:29 +0200
2011-06-01T09:13:29+00:00 app[web.1]:
2011-06-01T09:13:29+00:00 app[web.1]: ActionView::Template::Error (Permission de
nied - /app/public/javascripts/.permissions_check.6011580.1.163351):
2011-06-01T09:13:29+00:00 app[web.1]:     19:                         <meta http
-equiv="Content-type" content="text/html; charset=utf-8" />
2011-06-01T09:13:29+00:00 heroku[router]: GET www.vinderhimlen.dk/ dyno=web.1 qu
eue=0 wait=0ms service=476ms bytes=934
2011-06-01T09:13:29+00:00 app[web.1]:     20:                 <% end %>
2011-06-01T09:13:29+00:00 app[web.1]:     21:                 <%= stylesheet_lin
k_tag "public", "rateit" %>
2011-06-01T09:13:29+00:00 app[web.1]:     22:                 <%= javascript_inc
lude_tag 'rails.js', 'jquery.js', 'vis.js', 'jquery.rateit.js', :cache => true %
>
2011-06-01T09:13:29+00:00 app[web.1]:     23:                              <scri
pt type="text/javascript">
2011-06-01T09:13:29+00:00 app[web.1]:     24: $(document).ready(function() {
2011-06-01T09:13:29+00:00 app[web.1]:     25:
2011-06-01T09:13:29+00:00 app[web.1]:   app/views/layouts/application.html.erb:2
2:in `_app_views_layouts_application_html_erb__1541079903689551625_21945980__132
3620808994783512'
2011-06-01T09:13:29+00:00 app[web.1]:
2011-06-01T09:13:29+00:00 app[web.1]:
2011-06-01T09:13:29+00:00 heroku[web.1]: Stopping process with SIGTERM
2011-06-01T09:13:29+00:00 app[web.1]: >> Stopping ...
2011-06-01T09:13:29+00:00 heroku[web.1]: Process exited

Iceberg@ICEBERG-PC /c/rails/konkurranceportalen (master)
$

A: Your application is attempting to compile your javascript files into one and then cache it on the disk, which Heroku won't allow as it does not allow write access to disk. Remove the :cache => true from your javascript_include_tag line and find an alternate method to doing this for Heroku.


text:
Q: jQuery allow only number or decimal point or percentage sign i just want to allow value like below to pass:
18
12.5%
13%
not allowing any other like:
12ad
aa21

if( /[0-9\.]+%?/.test( shop_price ) == true){
    $("#shop_price_label").html("Please enter number or number % only")
    event.preventDefault();

but its not working with the above code. can anyone help me with this?

A: You need to use the line start(^) and line end($) notations also
^\d+(\.\d+)?%?$

Debuggex Demo