text:
Q: Zeep python SOAP client sending empty value in the argument There is an external SOAP server that I'm trying to connect and make requests using the python-django framework with the zeep library.
The WSDL dump is as follows:
Prefixes:
 xsd: http://www.w3.org/2001/XMLSchema
 ns0: http://tempuri.org/

Global elements:
 ns0:GetJobCards(key: xsd:string, technicianID: xsd:string, jobCardNumber: xsd:string, jobcards: ns0:ArrayOfJobCardsEnt, message: xsd:string)
 ns0:GetJobCardsResponse(GetJobCardsResult: xsd:boolean, jobcards:ns0:ArrayOfJobCardsEnt, message: xsd:string)

Global types:
  xsd:anyType
  ns0:ArrayOfJobCardsEnt(JobCardsEnt: {schema: , _value_1: ANY}[])
  xsd:ID
  xsd:IDREF
  xsd:IDREFS
  xsd:NCName
  xsd:NMTOKEN
  xsd:NMTOKENS
  xsd:NOTATION
  xsd:Name
  xsd:QName
  xsd:anySimpleType
  xsd:anyURI
  xsd:base64Binary
  xsd:boolean
  xsd:byte
  xsd:date
  xsd:dateTime
  xsd:decimal
  xsd:double
  xsd:duration
  xsd:float
  xsd:gDay
  xsd:gMonth
  xsd:gMonthDay
  xsd:gYear
  xsd:gYearMonth
  xsd:hexBinary
  xsd:int
  xsd:integer
  xsd:language
  ....

  Bindings:
   Soap11Binding: {http://tempuri.org/}CallSoap
   Soap12Binding: {http://tempuri.org/}CallSoap12

  Service: Call
   Port: CallSoap (Soap11Binding: {http://tempuri.org/}CallSoap)
   Operations:
      GetJobCards(key: xsd:string, technicianID: xsd:string,
      jobCardNumber: xsd:string, jobcards: ns0:ArrayOfJobCardsEnt,
      message: xsd:string) -> GetJobCardsResult: xsd:boolean,
      jobcards: ns0:ArrayOfJobCardsEnt, message: xsd:string

  ....(some other operations)

One of the calls is to get a list of jobCards with the following schema
<s:element name="GetJobCards">
 <s:complexType>
  <s:sequence>
   <s:element minOccurs="0" maxOccurs="1" name="key" type="s:string"/>
   <s:element minOccurs="0" maxOccurs="1" name="technicianID" type="s:string"/>
   <s:element minOccurs="0" maxOccurs="1" name="jobCardNumber" type="s:string"/>
   <s:element minOccurs="0" maxOccurs="1" name="jobcards" type="tns:ArrayOfJobCardsEnt"/>
   <s:element minOccurs="0" maxOccurs="1" name="message" type="s:string"/>
  </s:sequence>
 </s:complexType>
</s:element>

<s:complexType name="ArrayOfJobCardsEnt">
 <s:sequence>
  <s:element minOccurs="0" maxOccurs="unbounded" name="JobCardsEnt" nillable="true">
   <s:complexType>
    <s:sequence>
     <s:element ref="s:schema"/>
     <s:any/>
    </s:sequence>
   </s:complexType>
  </s:element>
 </s:sequence>
</s:complexType>

When I make the call using Postman I send the following request and it works:
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
     <GetJobCards xmlns="http://tempuri.org/">
        <key>some_valid_key</key>
        <technicianID>some_technician_id</technicianID>
        <jobCardNumber></jobCardNumber>
        <jobcards></jobcards>
        <message>""</message>
    </GetJobCards>
</soap:Body>

Please note that the values for "jobCardNumber" and "jobcards" need to be empty to get all the jobCards. But I cannot seem to replicate this same call using the zeep library.
Here is what I have tried.
1 - tried adding xsd.SkipValue for the empty values
request_data = {
  'key': some_valid_key,
  'technicianID': some_technician_ID,
  'jobCardNumber': xsd.SkipValue,
  'jobcards': xsd.SkipValue,
  'message': ''
}
response_body = client.service.GetJobCards(**request_data)

2 - setting the values to Nil
from zeep.xsd import Nil

jobCardEnt = client.get_type('ns0:ArrayOfJobCardsEnt')
jobCardEnt = jobCardEnt()
request_data = {
  'key': some_valid_key,
  'technicianID': some_technician_ID,
  'jobCardNumber': Nil,
  'jobcards': Nil,
  'message': ''
}
response_body = client.service.GetJobCards(**request_data)

None of these seems to works and I'm not sure how to get it to work.
Can someone please guide me on this?
Thanks in advance!

A: Here is how I got it working
with self.client.settings(strict=False):
        response_body = self.client.service.GetJobCards(
            key=some_valid_key,
            technicianID=some_technician_id,
            message=''
        )

And omitted the values for 'jobCardNumber' and 'jobcards'


text:
Q: Socket size not exceeding 1 MB in ios I'm trying to increase the socket buffer size in iOS but I've only been able to get 1 MB size maximum so far.
I've heard that it can be extended till 4 MB, Can anyone help?
uint8_t buffer[1024*4];
int len;

NSMutableString *output = [[NSMutableString alloc] init];

while ([inputStream hasBytesAvailable])
{
    len = (int)[inputStream read:buffer maxLength:sizeof(buffer)];

    if (len > 0)
    {
        [output appendString: [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding]];
    }
}
if (output.length > 0)
{
    [self messageReceived:output];
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Special zeta value and zeroes Are there known relationships linking special values of the Riemann zeta function or MZV (multiple zeta values, i.e. $\zeta(n_1, \cdots n_k)$ with $n_i \in \mathbb Z^+$) to the nontrivial zeroes of the Riemann zeta function?
I became curious of this because MZVs appear in Feynman amplitude calculations. For example, we find a $\zeta(3,5)$ in the $\phi^4$ theory of page 7 of Francis Brown's paper. Also, $\zeta(3), \zeta(5)$ are seen from a quantum electrodynamics calculation for the magnetic dipole moment of a muon, as seen on page 164 of this collaborative effort.
Mysticism should be avoided, but if the zeroes of the Riemann zeta say something about MZVs or just $\zeta(2n+1)$'s, then maybe the distribution of prime numbers says something about Feynman amplitudes.


text:
Q: qwt plot curve axis not visible I am using qwt plot curve to draw curve.
the x axis and the y axis are not visible, only the curve is visible.
How to show the axis with showing some first, last and middle values in
the scale interval of the axis

A: I give you a small example:
   // xBottom - x-axis yBottom - y-axis

    plot->setAxisMaxMinor(QwtPlot::xBottom, 2);
    plot->setAxisScale(QwtPlot::xBottom, 0, MAX_X_VALUE, 2);
    plot->setAxisMaxMinor(QwtPlot::yLeft, 2);
    plot->setAxisScale(QwtPlot::yLeft, 0, 1, 1);
    plot->setAxisMaxMinor(QwtPlot::yLeft, 1);
    plot->setAxisScale(QwtPlot::yLeft, -1, 1, 1);

A: 1) You should have some QwtPlot object. I assume you want to draw xBottom and yLeft axes.
QwtPlot *plot=new QwtPlot(this);
//following 4 lines may not be required because
//QwtPlot defaults are to show xBottom and yLeft axes
//and you use autoscaling for these axes
plot->enableAxis(QwtPlot::xBottom);
plot->enableAxis(QwtPlot::yLeft);
plot->setAxisAutoScale(QwtPlot::xBottom,true);
plot->setAxisAutoScale(QwtPlot::yLeft,true);

You already have it if you were using QtDesigner and QwtPlot widget with it. You can access it with ui->plot
2) You should have
QwtPlotCurve * curve = new QwtPlotCurve();
//.... attach some data to curve
curve->attach(plot);

3) Probably you want to call replot
plot->replot();


text:
Q: Merge multiple GeoPackage raster tilesets I have multiple GeoPackage raster tilesets. They have the same tiling scheme created with GDAL using -co TILING_SCHEME=GoogleMapsCompatible option. They also have the same projection EPSG:3857
The GeoPackages only contain data in one zoom level.
Is it possible to merge these GeoPackages into one GeoPackage?

A: Yes, you can import datasets from other GeoPackages into the current one. The easiest way would be to use ArcGIS 10.5/Pro Add Raster To GeoPackage GP Tool. There is a raster2gpkg Python based GP Tool for ArcGIS 10.3+ versions as well.
arcpy.AddRasterToGeoPackage_conversion("c:/data/Maps.gpkg/main.SanDiego", "c:/data/san_diego.gpkg", "SanDiego", "TILED")

Maps is the GeoPackage name and main.SanDiego is the raster table name you need to import. You can explore the rasters inside a GeoPackage using the catalog window.
You could achieve this with gdal tools as well. ( Make sure the gdal is build with sqlite support )
Usage:
View all rasters inside GeoPackage name:
% gdalinfo sample.gpkg
Translation of a GeoPackage raster into a separate GeoPackage with new raster name
% gdal_translate -of GPKG GPKG:sample.gpkg:Test existing.gpkg -co APPEND_SUBDATASET=YES -co RASTER_TABLE=new_table


text:
Q: to use a library dll with LoadLibrary() method on C++ Can I use LoadLibrary method for to import a data of type struct??
excuse me for my English.
thanks.

A: Let me assume some things that are left out in the question:

*

*You have a dynamic library called flubber.dll

*The library exports the function bool GetFlubber(Flubber* flubber).

*The function and the type Flubber (which just happens to be a struct!) are declared in a header file called flubber.h.

If those 3 conditions are met, then you can use LoadLibrary on flubber.dll, followed by GetProcAddress with GetFlubber as proc name, and finally you can declare a Flubber instance locally and pass it to GetFlubber via the retrieved proc address.

A: Do you mean to put data in a dll, and use LoadLibrary and Getprocaddres to get a pointer to the data? That is possible, although it is more common to put functions in a dll, and let them return a pointer to the data.

A: Hm ... That question was a bit hard to understand, I'm afraid.
In C++, a struct declaration is just that, a declaration. It does not generate something you can load at run-time, it's a pure compile-time construction that just tells the compiler how something is laid out in memory, the fields involved, their types and order, and so on.

A: I assume that you are using VC++ 2005.
MS now providing you Delay Loading Dll's.
The Visual C++ linker now supports the delayed loading of DLLs. This relieves you of the need to use the Windows SDK functions LoadLibrary and GetProcAddress to implement DLL delayed loading.
Steps to follow in order to setup the Delay Load.
Goto to Project->Properties->Linker->Input and then specify your Dll in 'Delay Loaded DLLs'

A: As other responses have suggested it's hard to tell what's being asked here, but I'll throw in a response for another interpretation of the question.  I'm not sure if it's "officially supported", but you can have a DLL export a global variable and then dynamically access it via GetProcAddress.
For instance, if a library called foo.dll contains a global of type FOO named g_MyGlobal, then it can export the variable in foo.def.  Client code can then call:
MyPointer = GetProcAddress(..., "g_MyGlobal");

and get a "FOO *" pointer to the global.
...but with that said, if you find yourself needing to do this for something other than private testing purposes, you might want to re-think your design.  It would probably be much safer and cleaner to hide this global behind an exported function in the DLL.


text:
Q: name of rule that says: x(x+1) is even number What is the name of the rule that states that $x(x+1)$ is always even number?
Mathworld says: "The product of an even number and an odd number is always even"
But it does not state any name: http://mathworld.wolfram.com/OddNumber.html

A: If you want to say this on an olympiad, I'd say it'd be pretty safe to just say "by parity", since this is a pretty trivial result. Others might also state it as follows:

Since $x$ and $x+1$ have opposing parity, the product $x(x+1)$ must be even.

or

Either $x$ or $x+1$ must be even, since they have opposing parity. Thus, their product is even.

I wouldn't really assert a name to it.

A: $0(0+1) = 0$, given that $0\cdot2=0$ then $0$ is an even number.
Let's assume $n(n+1)$ is even as hypothesis of induction.  Then there is $k\in\Bbb N$ such as
\begin{align}
n(n+1)&=2k &&\text{Let's add $2(n+1)$ at both sides:}\\
n(n+1)+2(n+1)&=2k+2(n+1) &&\text{Let's apply distributive rule:} \\
(n+2)(n+1)&=2(k+n+1) &&\text{and conmutiative rule in products:} \\
(n+1)((n+1)+1)&=2(k+n+1)
\end{align}
Where $k+n+1\in\Bbb N$, therefor $(n+1)((n+1)+1)$ is even, and the result has been proved by mathematica induction.
But if you want a name for a rule that even times odd is even, it is just definition of even and transitivity of the relationship "divides".  If $n$ is even, then $2$ divides $n$.  Now, if $nm$ is the product of $n$ and $m$ (even or odd) it means $n$ divides $nm$, as divides is transitive, then $2$ divides $nm$.
For the specific part of $x$ and $x+1$ (with $x\in\Bbb N$) then we need a theorem of one of them being even.  That can be granted by modularity and can be extended that for every $n\in\Bbb N$, the set $\{x,x+1,\ldots,x+(n-1)\}$ will include a multiple of $n$.  Modularity for $n=2$ has a special name: parity.
So parity grants that either $x$ or $x+1$ is even, and transitivity of the divides relationship grants that the product of an even number with any other natural number is even.

A: Or you could just prove it (if you are afraid of using it because it doesn't have a name):

*

*if $x=2k$ then

$x(x+1)=(2k)(2k+1)=2*[k(k+1)]=2m$, where $m=k(k+1)$

*

*if $x=2k+1$ then

$x(x+1)=(2k+1)(2k+2)=(2k+1)*[2(k+1)]=2(2k+1)(k+1)=2m$, where $m=(2k+1)(k+1)$

A: You can think of this as follows.
The product $x(x+1) $ is basically the addition of $x$ with itself $(x+1)$ times.This is same as the addition of $(x+1)$ with itself $x$ times.[that is how we define the MULTIPLICATION of two natural numbers]
If $x$ is odd add $x$ to itself $(x+1)$ times.
Now $x$ being even it can be written in the form of $2j$ where $j$ is any natural number.
Thus $(x+x+x+....+x)$ [$(x+1)$ times]= $(2j+2j+2j+...+2j)$ [$(x+1)$ times]=$2(j+j+j+...+j)$[$(x+1)$times] which is obviously even.
you can then extend the proof when $x$ is odd that is $(x+1)$ is even.
Having proved these two you can then easily extend the proof for negative integers.


text:
Q: Error with add user in a group using Add-MsolGroupMember I am trying to add user in a group but I am getting error:
Add-MsolGroupMember -GroupObjectId $group1.ObjectId -GroupMemberType "User" -GroupMemberObjectId 077cf65b-4b9f-44e4-9f34-6c96a063a0df

A: As bunzab said, we should use Add-DistributionGroupMember to add member.
First, we should connect to exchange online powershell:
$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session

After that, we can use this powershell to add member, like this:

More information about connect to exchange online powershell, please refer to this link.


text:
Q: Boot on USB disk, downgrading Ubuntu I would like to downgrade from Ubuntu 16.04 to Ubuntu 14.04 since my MacBook is very slow. I have made a bootable USB disk with startup disk creator but when I reboot my computer, it starts 16.04.
How can I boot on this USB disk and downgrade my Ubuntu ?
Thanks


text:
Q: how to delete index with deleteRequest API in elasticsearch(6.4.3) I'd like to delete index in elasticsearch 6.4.3 by using DeleteRequest API
But elastic.co guide 3 arguments(index,document,id)
(https://www.elastic.co/guide/en/elasticsearch/client/java-rest/6.4/java-rest-high-document-delete.html)
I want use 2 arguments for deleting index (index,document)
So, Anybody help me about this?
DeleteRequest deleteRequest = new DeleteRequest(index);
DeleteResponse response = mClient.delete(deleteRequest, RequestOptions.DEFAULT);

Exception in thread "main"
  org.elasticsearch.action.ActionRequestValidationException: Validation
  Failed: 1: type is missing;2: id is missing;  at
  org.elasticsearch.action.ValidateActions.addValidationError(ValidateActions.java:26)
    at
  org.elasticsearch.action.delete.DeleteRequest.validate(DeleteRequest.java:87)
    at
  org.elasticsearch.client.RestHighLevelClient.performRequest(RestHighLevelClient.java:1248)
    at
  org.elasticsearch.client.RestHighLevelClient.performRequestAndParseEntity(RestHighLevelClient.java:1231)
    at
  org.elasticsearch.client.RestHighLevelClient.delete(RestHighLevelClient.java:681)
    at
  com.sds.imp.gm.comm.es.RestHighLevelClientAPI.deleteIndex(RestHighLevelClientAPI.java:52)
    at
  com.sds.imp.gm.comm.es.RestHighLevelClientAPI.main(RestHighLevelClientAPI.java:220)

A: If you want to delete an index in Elastic Search, you need to use the Delete Index API
https://www.elastic.co/guide/en/elasticsearch/client/java-rest/6.4/java-rest-high-delete-index.html
This is the basic example, using the synchronous execution:
DeleteIndexRequest request = new DeleteIndexRequest(*IndexName*);
DeleteIndexResponse deleteIndexResponse = client.indices().delete(request, RequestOptions.DEFAULT);

The API you are using is meant to delete documents, that is why it requires 3 arguments: the name of the index, the type, and the id of the document you want to delete.

A: DeleteRequest request = new DeleteRequest(
    "index",
    "doc",
    "id");
DeleteResponse deleteResponse = client.delete(request,RequestOptions.DEFAULT);
        return deleteResponse.getResult().name();

where "index" is the index name and id is the document id.
As per https://www.elastic.co/guide/en/elasticsearch/client/java-rest/6.4/java-rest-high-document-delete.html documentation, you need to pass 3 arguments. 2 argument should be "doc".


text:
Q: Simple local html webpage to host multiple html images Disclaimer: I program predominately in C/C++/Python/matlab so html is brand new to me.
I have a Matlab program that generates plots, and saves the plots into a image1.html file. I have many image$$$.html files all saved locally to my computer. For example:

*

*/home/username/image1.html

*/home/username/image2.html

*etc.

What I would like to do is :

*

*Create a top level html page: my_awesome_page.html (this I can do with a simple hello world example)

*I open my_awesome_page.html and it has links Image1, Image2, etc, that links to /home/username/image1.html and opens the content in /home/username/image1.html when I click on the link

*If possible, show the contents of /home/username/image1.html on the side when I click on Image1, not in a new page. So I can easily navigate between image$$.html pages

These images are scientific plots and I am just trying to create a single source of all the data to make my life easier. I am not looking for anything pretty, fancy, just something simple+functional.
The more simple it is, the easier it is for me to write a program that generates the my_awesome_page.html and the links for each image.
My general question is: where to start and what to look for? After a quick google search I realized why I stick to C/C++; react js, node js, CSS, etc. So many things I do not know about.
Edit: This is all going to run locally on my laptop, and be opened in chrome. No intention to send this into the wild, or be able to access the webpage from outside my device.

A: Here's a minimalistic crude example that should give you a pattern you can follow (you can probably write it all using printf in a C/C++ program):

            <button id="button-1">Image 1</button>

            <button id="button-2">Image 2</button>


text:
Q: Sending data into a nested Controller/View in EmberJS I'm messing around with JSON structures in EmberJS starting from the top level Application level and trying to pass data to a general MenuController/MenuView child so I can reuse it.
The JSON I've come up with to play around with how data gets passed through nested ember structures is this:
JSON
{
appName: "CheesyPuffs"
menuItems: [
    {name:"Gouda"}
    {name:"Crackers", menuItems: [
                              {name: "Cheezeits"}
                            ]
    }
]

}

Handlebars

JS
App.MenuController = Ember.ArrayController.extend({
    actions: {
        click: function(){
           // Signal Event to App
        }
    }
});
App.MenuView = Ember.View.extend({

   click: function(){
        console.log("I clicked a menu");
   }

});

All the examples I've seen concerning nested stuff involves routes with the classic _id subroute. I'm not sure how I would go about telling the App Router that it needs to pass the menuItems data to a child controller that's embedded in the same view. I have a feeling you can do this both via the template and programmically? If so, how would you do it both ways?

A: using the template you should use render.  And that's the way you should do it, programmatically doesn't make sense.


text:
Q: Do there exist conditions to guarantee that $\int_{-\infty}^{+\infty} \left( \frac{p(x)}{q(x)}-1 \right) q'(x)^2 \, dx < 0$? Let $p(x)$ and $q(x)$ be two smooth probability density functions defined on the whole real line s.t. $p(x),q(x) > 0 \ \forall x \in R$.
Do there exist conditions that one can impose on $p(x)$ and $q(x)$ and the relation between them so that
$$\int_{-\infty}^{+\infty} \left( \frac{p(x)}{q(x)}-1 \right) q'(x)^2 \, dx < 0$$ ?
Is there a way to approach this problem maybe through the calculus of variations minimizing a functional?

A: Too long for a comment.  The idea is that you can construct classes of $p,q$ so that your inequality is true.
If you let $p(x)=q(x)(1+r(x))$, where $|r(x)|<1$; then you need two conditions to be satisfied: normalization of $p$:
$$
\int_{-\infty}^\infty q(x)r(x)dx=0,
$$
and your inequality,
$$
\int_{-\infty}^\infty r(x)q'(x)^2dx<0.
$$
Let us suppose for simplicity that $r$ and $q$ are even functions, so that it suffices to show
$$
\int_0^\infty q(x)r(x)dx=0,\\
\int_0^\infty r(x)q'(x)^2dx<0.
$$
Let us also suppose that $q=Q$ (constant) on $I=[0,1]$, and decreases to $0$ on $[1,2]$, with $q=0$ on $[2,\infty)$.  Then we need
$$
Q\int_0^1r(x)dx+\int_1^2q(x)r(x)dx=0,\\
\int_1^2r(x)q'(x)^2dx<0.
$$
You can then choose $r<0$ on $[1,2]$ and $r>0$ on $[0,1]$ appropriately to get a class of solutions.


text:
Q: How to use ruled/horizontal lines to align text in EditText in Android? Basically I want to do something like this in Android:

I am trying to draw horizontal lines in a custom EditText, and then typing on these lines.
I am using the text size for the distance between two horizontal lines. However, the size of cursor and that of text is not same. Hence, I am not able to maintain placing text "on" these lines.
The alignment of the text base to these horizontal lines are not coming as proper.
Here is the code used for drawing the lines:-
float textSize = getTextSize());
Paint paint = new Paint();
for (int i = 0; i < 50; i++) {
    canvas.drawLine(0, textSize * i, getWidth(), textSize * i, paint);
}

EditText doesn't privides has any method for getting the cursor size.
Kindly suggest if  there is any workaround for this, or any other better way of doing this.

A: A custom EditText that draws lines between each line of text that is displayed:
public class LinedEditText extends EditText {
    private Rect mRect;
    private Paint mPaint;

    // we need this constructor for LayoutInflater
    public LinedEditText(Context context, AttributeSet attrs) {
        super(context, attrs);

        mRect = new Rect();
        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(0x800000FF);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int count = getLineCount();
        Rect r = mRect;
        Paint paint = mPaint;

        for (int i = 0; i < count; i++) {
            int baseline = getLineBounds(i, r);

            canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint);
        }

        super.onDraw(canvas);
    }
}

Now use object of LinedEditText class where you need.
An Example:
public class HorizontalLine extends Activity{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("Android: Ruled/horizonal lines in Textview");

        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        LayoutParams textViewLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

        LinedEditText et = new LinedEditText(this, null);
        et.setText("The name of our country is Bangladesh. I am proud of my country :)");
        et.setLayoutParams(textViewLayoutParams);

        ll.addView(et);
        this.setContentView(ll);

    }

}

The Output:


text:
Q: Spring MVC - Autowired Repository NullPointerException in static context In my model I have a repository called UserRepository. Additionally I have a UserFacade that basically adds the user to the repository and is accessed by the Controller. The repo is @Autowired in the Facade. When I want to add a new user I get a nullPointerException for the repository.
My spring-servlet.xml contains the required
<jpa:repositories base-package="project.user.repositories" />
while repositories is the folder containing the UserRepository.java. It extends the CrudRepository:
@Repository
public interface UserRepository extends CrudRepository<User, Long> {
    User findByUsername(String username);
}

Facade.java is the object containing repository:
public class UserFacade {
    @Autowired
    private static UserRepository userRepo;

    private static Logger logger = LoggerFactory.getLogger(UserFacade.class);

    public UserFacade(){} //Thought it might work if I add a constructor and call it?

    public static User findByUsername(String username) {
        logger.debug(username+userRepo);  // prints SomeStringnull
        return userRepo.findByUsername(username); //NullPointerException
    }
}

And from my controller I have a method like:
@RequestMapping(value = CONTEXT)
public String test(){
    User user = UserFacade.findByUsername("get");
    //obviously user will be null if there is no such user
    return "success";
}

Imports will should not be a problem as I am using Android Studio. What did I miss?
Note: There are many great answers to related questions (like this one), but each has it's own, different context and didn't help me.

A: Spring doesn't autowire static fields. That is why userRepo field is null. One way is to make the UserFacade a bean itself, and then you can make userRepo a non-static field. I would prefer this way. UserFacade shouldn't really be a utility class, since it is interacting with the repository bean. It would make much more sense to make it a bean.
Another option is to provide a setter, and use @Autowired on that:
@Autowired
public void setUserRepo(UserRepository userRepo) {
    UserFacade.userRepo = userRepo;
}

Or using it even on a parameterized constructor would work.


text:
Q: CDATA element in WSDL client I'm doing a WSDL client and want to know how I can set an XML element to be CDATA.
I'm using the wsimport to generate the source code, and the CDATA element is part of the request XML.
This is the XML class of the request:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "dataRequest" })
@XmlRootElement(name = "ProcessTransaction")
public class ProcessTransaction {

    protected String dataRequest;

    public String getDataRequest() {
        return dataRequest;
    }

    public void setDataRequest(String value) {
        this.dataRequest = value;
    }
}

I've already tried the @XmlAdapter, but it changes nothing on the output...
import javax.xml.bind.annotation.adapters.XmlAdapter;

public class AdaptorCDATA extends XmlAdapter<String, String> {

    @Override
    public String marshal(String arg0) throws Exception {
        return "<![CDATA[" + arg0 + "]]>";
    }

    @Override
    public String unmarshal(String arg0) throws Exception {
        return arg0;
    }
}

In the XML class:
@XmlJavaTypeAdapter(value=AdaptorCDATA.class)
protected String dataRequest;

I tried to debug, but it never steps on the AdaptorCDATA function.
The wsimport version is 2.2.9 and the jaxb-api version is 2.1.

A: So, as @user1516873 suggested, i moved the code to cxf, and with this, is working well. Now i'm using the "wsdl2java" to generate the code, and the jars from cxf on my project.
What is different in the code:
CdataInterceptor
import javax.xml.stream.XMLStreamWriter;

import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;

public class CdataInterceptor extends AbstractPhaseInterceptor<Message> {

    public CdataInterceptor() {
        super(Phase.MARSHAL);
    }

    public void handleMessage(Message message) {
        message.put("disable.outputstream.optimization", Boolean.TRUE);
        XMLStreamWriter writer = (XMLStreamWriter) message.getContent(XMLStreamWriter.class);
        if (writer != null && !(writer instanceof CDataContentWriter)) {
            message.setContent(XMLStreamWriter.class, new CDataContentWriter(writer));
        }
    }

    public void handleFault(Message messageParam) {
        System.out.println(messageParam);
    }
}

CDataContentWriter
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

import org.apache.cxf.staxutils.DelegatingXMLStreamWriter;

public class CDataContentWriter extends DelegatingXMLStreamWriter {

    public CDataContentWriter(XMLStreamWriter writer) {
        super(writer);
    }

    public void writeCharacters(String text) throws XMLStreamException {
        boolean useCData = text.contains("RequestGeneric");
        if (useCData) {
            super.writeCData(text);
        } else {
            super.writeCharacters(text);
        }
    }

    // optional
    public void writeStartElement(String prefix, String local, String uri) throws XMLStreamException {
        super.writeStartElement(prefix, local, uri);
    }
}

Using the Writer and the Interceptor:
MyService wcf = new MyService(url, qName);
IMyService a = wcf.getBasicHttpBinding();

Client cxfClient = ClientProxy.getClient(a);
CdataInterceptor myInterceptor = new CdataInterceptor();
cxfClient.getInInterceptors().add(myInterceptor);
cxfClient.getOutInterceptors().add(myInterceptor);

And it works perfect!


text: Q: flash upload button not wroking for more than one field on a page i have taken a code from http://webdeveloperplus.com/jquery/multiple-file-upload-with-progress-bar-using-jquery/ where multiple file upload is possible, i have integrated the code in my project, but here my issue is my form is created dynamically by the user, so field name is dynamic, in such case  my js function having an id as #swfupload-control and button_placeholder : $('#button)[0], only works for a single input type button, and other buttons are blank as they are getting the id but not working


text:
Q: showDirectoryPicker() to display directory path I am using window.showDirectoryPicker() to retrieve and save directory handle to IndexedDB.
My question - is there a way to display the whole path of the selected directory? (not just the directory name)
Thanks!
Reference: https://web.dev/file-system-access/

A: No you can't. That's a frequently asked feature but the privacy risks are too high for the specs authors to allow this.
Maybe the feature proposed in #156 could help for your use case, as it aims at exposing a web-API able to open the folder where your handle lives using the OS file manager. However even this is not going to be ready soon...


text:
Q: how to Change Codeigniter pagination query string I want to change CodeIgniter pagination query string. When I use query string it will run & the url is good but data remaining same, without query string it will run properly.
My URL look like
example.com/1

But I want it to be like
example.com?page=1

Here is my controller code..
$this->load->library('pagination');

$config['base_url'] = base_url().'/purchase/index';
$config['total_rows'] = $this->db->count_all('purchase');
$config['per_page'] = 10;
$config['page_query_string'] = TRUE;
$config['query_string_segment'] = 'page';

$this->pagination->initialize($config);

$page =($this->uri->segment(3)) ? $this->uri->segment(3) : 0;

$data['pur_list'] = $this->purchase_model->purchase_list($config['per_page'],$page);

A: this will give you output like
example.com?page=1&q=banana

$config = $this->config->item('pagination_config');
$config["base_url"] = base_url("search");
$config["total_rows"] = $this->SearchModel->getResultCount($query);
$config["per_page"] = 6;
$config['enable_query_strings'] = TRUE;
$config['page_query_string'] = TRUE;
$config['use_page_numbers'] = TRUE;
$config['reuse_query_string'] = TRUE;
$config['query_string_segment'] = 'page';
$this->pagination->initialize($config);
$current_page = $this->input->get('page',0);
$this->data["links"] = $this->pagination->create_links();
$this->data['results'] = $this->SearchModel->getResults($query, $config["per_page"], $current_page);

A: public function index()
  {
    $config = [];
    $config["base_url"] = base_url() . "admin/subscribers";
    $config["total_rows"] = $this->subscriber_model->count();
    $config["per_page"] = 10;
    $config['num_links'] = 9;
    $config['enable_query_strings'] = TRUE;
    $config['page_query_string'] = TRUE;
    $config['use_page_numbers'] = TRUE;
    $config['query_string_segment'] = 'page';
    $this->pagination->initialize( $config );
    $offset = ($this->input->get('page')) ? ( ( $this->input->get('page') - 1 ) * $config["per_page"] ) : 0;
    $data["results"] = $this->subscriber_model->get($config["per_page"], $offset );
    $data["links"] = explode(' ', $this->pagination->create_links() );
    $this->load->view("index", $data);
  }


text:
Q: Sharepoint script webpart in Gantt not working i couldn't understand  why, but i built gantt chart from ms project on sharepoint, with many subtask, and I would like to hide subtasks by default.
Unfortunately, any script that i put above my gantt chart doesn't work and produce anything...
i tried every type of link , nothing work... i couldn't understand the problem..
i tried what is explained here, with that code : Why is this jQuery not working on my Sharepoint page?
but nothing work enter image description here

<script
      src="https://code.jquery.com/jquery-3.2.1.min.js"
      integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
      crossorigin="anonymous"></script>

<script>
jQuery(document).ready(function(){
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', run);
});

function run(){
    jQuery('div[class="ms-vb  itx"]').find('span[style]').each(function(){
        if(jQuery(this).css('margin-left')!="0px"){
            jQuery(this).parent().parent().parent().hide();
        }
    });
}
</script>

thanks

A: I reinstalled everything on a new site and it works now...
very strange issue.
I would like to know if its also possible to change formating in Task listing view :

{
  "$schema": "http://columnformatting.sharepointpnp.com/columnFormattingSchema.json",
  "elmType": "div",
  "attributes": {
    "class": {
      "operator": "?",
      "operands": [
        {
          "operator": "==",
          "operands": [
            "@currentField",
            "No Issues"
          ]
        },
        "sp-field-severity--good",
        {
          "operator": "?",
          "operands": [
            {
              "operator": "==",
              "operands": [
                "@currentField",
                "Inactive"
              ]
            },
            "sp-field-severity--low",
            {
              "operator": "?",
              "operands": [
                {
                  "operator": "==",
                  "operands": [
                    "@currentField",
                    "Warning"
                  ]
                },
                "sp-field-severity--warning",
                {
                  "operator": "?",
                  "operands": [
                    {
                      "operator": "==",
                      "operands": [
                        "@currentField",
                        "In Review"
                      ]
                    },
                    "sp-field-severity--severeWarning",
                    "sp-field-severity--blocked"
                  ]
                }
              ]
            }
          ]
        }
      ]
    }
  },
  "children": [
    {
      "elmType": "span",
      "style": {
        "display": "inline-block",
        "padding-left": "4px"
      },
      "attributes": {
        "iconName": {
          "operator": "?",
          "operands": [
            {
              "operator": "==",
              "operands": [
                "@currentField",
                "No Issues"
              ]
            },
            "CheckMark",
            {
              "operator": "?",
              "operands": [
                {
                  "operator": "==",
                  "operands": [
                    "@currentField",
                    "Inactive"
                  ]
                },
                "Forward",
                {
                  "operator": "?",
                  "operands": [
                    {
                      "operator": "==",
                      "operands": [
                        "@currentField",
                        "In Review"
                      ]
                    },
                    "Error",
                    {
                      "operator": "?",
                      "operands": [
                        {
                          "operator": "==",
                          "operands": [
                            "@currentField",
                            "Warning"
                          ]
                        },
                        "Warning",
                        "ErrorBadge"
                      ]
                    }
                  ]
                }
              ]
            }
          ]
        }
      }
    },
    {
      "elmType": "span",
      "txtContent": "@currentField",
      "style": {
        "padding-left": "10px",
        "font-weight": "bold"
      }
    }
  ]
}

with something like that (this code is working with list but not tasks listing app, cant see why)

A: The JSON formatting below for your reference, it also works in modern task list.
{
    "$schema": "https://developer.microsoft.com/json-schemas/sp/v2/column-formatting.schema.json",
    "elmType": "div",
    "style": {
        "display": "table",
        "width": "100%"
    },
    "attributes": {
        "class": "=if(@currentField == 'No Issues', 'sp-field-severity--good', if(@currentField == 'Inactive', 'sp-field-severity--low', if(@currentField == 'Warning', 'sp-field-severity--warning', if(@currentField == 'In Review', 'sp-field-severity--severeWarning', 'sp-field-severity--blocked')))) + ' ms-fontColor-neutralSecondary'"
    },
    "children": [
        {
            "elmType": "span",
            "style": {
                "padding": "0 4px",
                "display": "table-cell",
                "vertical-align": "middle",
                "width":"16px"
            },
            "attributes": {
                "iconName": "=if(@currentField == 'No Issues', 'CheckMark', if(@currentField == 'Inactive', 'Forward', if(@currentField == 'In Review', 'Error', if(@currentField == 'Warning', 'Warning', 'ErrorBadge'))))"
            }
        },
        {
            "elmType": "span",
            "txtContent": "@currentField",
            "style": {
                "display": "table-cell",
                "font-weight": "bold",
                "padding-left": "10px",
                "vertical-align": "middle"
            }
        }
    ]
}


text:
Q: Conversão de virgula para ponto java Estou com dificuldades de conseguir fazer o meu getPreco() ficar formatado. A entrada do dado é por meio de um textField.
if (radioGuitar.isSelected()) {
  Guitarra guitarra = new Guitarra();
  guitarra.setMarca(txtMarca.getText());
  guitarra.setModelo(txtModelo.getText());

  if (btnRevisado.isSelected()) {
    guitarra.setPreco(150 + Double.parseDouble(txtPreco.getText()));
  }

  else {
    guitarra.setPreco(Double.parseDouble(txtPreco.getText()));
  }

  guitarra.getPreco().toString().replaceAll(",", ".");

  System.out.println(guitarra.toString());

  bw.write(guitarra.getMarca());
  bw.write(separador);
  bw.write(guitarra.getModelo());
  bw.write(separador);
  bw.write(Double.toString(guitarra.getPreco()));
  bw.write(separador);
  bw.newLine();
  bw.close();
  fw.close();
}

A: Para formatar valores monetários, uma boa alternativa é usar NumberFormat. Ex:
NumberFormat formatter = NumberFormat.getCurrencyInstance(new Locale("pt", "BR"));
System.out.println(formatter.format(123456.78)); // R$ 123.456,78

Eu uso um Locale (no exemplo acima usei pt_BR, que equivale ao português do Brasil), pois ele controla alguns aspectos da formatação, como os caracteres usados para separar os milhares e as casas decimais, além do prefixo "R$". Se você usar por exemplo Locale.US - inglês americano, o resultado será $123,456.78 (e se chamar getCurrencyInstance() sem parâmetros, é usado o locale default que estiver configurado na JVM, por isso recomendo usar um locale específico para não depender dessas configurações, que inclusive podem mudar em runtime sem você perceber).

Com NumberFormat você pode controlar outros aspectos, como a opção de não incluir o ponto para separar os milhares, mudar a quantidade de casas decimais e até mesmo o modo de arredondamento. Alguns exemplos:
double valor = 123456.78987;
NumberFormat formatter = NumberFormat.getCurrencyInstance(new Locale("pt", "BR"));

System.out.println(formatter.format(valor)); // R$ 123.456,79

formatter.setGroupingUsed(false); // não separar os milhares
System.out.println(formatter.format(valor)); // R$ 123456,79

formatter.setRoundingMode(RoundingMode.DOWN); // arredondar sempre para baixo
System.out.println(formatter.format(valor)); // R$ 123456,78

// mudar a quantidade de casas decimais
formatter.setMaximumFractionDigits(3);
System.out.println(formatter.format(valor)); // R$ 123456,789

Consulte a documentação para mais detalhes.

Se não quiser imprimir o símbolo da moeda e quiser somente formatar o número, aí bastaria usar DecimalFormat, como já sugeriu a outra resposta. Ela também possui os mesmos métodos para controlar a quantidade de casas decimais, etc, mas por padrão não imprime o código da moeda (R$) - embora também seja possível:
// \u00A4 corresponde ao código da moeda
DecimalFormat df = new DecimalFormat("\u00A4 #,##0.00");
df.setCurrency(Currency.getInstance("BRL")); // BRL = código do Real
System.out.println(df.format(valor)); // R$ 123.456,79

O código da moeda passado para Currency.getInstance é baseado na ISO 4217. No caso, usei BRL, que equivale ao Real.
Outro detalhe é que, se for trabalhar com valores monetários, talvez double não seja a melhor opção. Saiba mais lendo aqui e aqui

A: Boa noite, eu utilizo os seguintes métodos, o primeiro você define o número de casas decimais após a virgula, já o segundo é padrão:
public static String DoubleToString(double valor, int casasDecimais) throws ParseException{
    String retorno;
    String mascara = "#,##0.";
    if(casasDecimais < 0)
    {
        casasDecimais = 0;
    }
    for(int i = 0; i < casasDecimais; i++)
    {
        mascara += "0";
    }
    java.text.DecimalFormat df = new java.text.DecimalFormat(mascara);
    return df.format(valor);
}

public static String DoubleToString(double valor) throws ParseException{
    String retorno;
    java.text.DecimalFormat df = new java.text.DecimalFormat("#,##0.00");
    return df.format(valor);
}


text:
Q: Is there a better way to share variables between modules? I'm making a package now and I want people can direct call this package so I'm using the entry point in setup.py.
Right now I have application.py which contains main() as the entry point.
And the variable inside this main() function are sent to tex.py which helps me generate the latex report. (The way to generate latex file comes from this: Generating pdf-latex with python script)
# application.py
def main():
    a = 123
    b = 456
    from tex import generate
    generate()

#tex.py
content = f'{a} is not equal to {b}'
def generate():
    with open('report.tex','w') as f:
        f.write(content)

but this would lead to alb not defined.
I found one solution is to use global and add from application import *
But since I have tens of variables, it'll be too long.
I wonder if there is a way to share the variables to my latex generator and keep this entry point feature.
Thanks in advance.

A: Like @juanpa.arrivilaga and @rv.kvetch suggested why not passing the arguments directly?
# application.py
def main():
  a = 123
  b = 456
  from tex import generate
  generate(a, b)

#tex.py
def generate(a, b):
  content = f'{a} is not equal to {b}'
  with open('report.tex','w') as f:
    f.write(content)

Or if you have a lot of variables create a model and pass it
class Model:
  __init__(a,b,c,d):
     self.a = a
     ....

    # application.py
def main():
  a = 123
  b = 456
  from tex import generate
  generate(Model(a,b))

#tex.py
def generate(model):
  content = f'{model.a} is not equal to {model.b}'
  with open('report.tex','w') as f:
    f.write(content)

Even better you can add the print logic into the model itself (using some associated methods), there so many solutions!
class Model:
   ...init
    def __str__(self):
      return '{} is not equal to {}'.format(self.a, self.b)

    def __repr__(self):
      return '{} is not equal to {}'.format(self.a, self.b)


text:
Q: Updating Tables MySql/PHP - inserting variable name instead of values i've searched too much about it, but, i'm not even rookie in PHP scripting... so I need     help.
i'm developing a homemade system to home automation, based on PHP/MySql, and, i need a backend to update the database tables and make things really happen in live.
so, i found the code i need, and, after some adaptation, here it is.
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$database = "domonet";
$tabela = "AtuadorAnalogico";
$valor1 = "AA_id";
$valor2 = "AA_nome";
$valor3 = "AA_valor";

//connection to the database

$dbhandle = mysql_connect($hostname, $username, $password)
  or die("Unable to connect to MySQL");
echo "Connected to MySQL
";

//select a database to work with

$selected = mysql_select_db($database,$dbhandle)
  or die("Could not select examples");
  echo "Connected ao banco
";

//get data from db

$sql = mysql_query("SELECT * FROM $tabela");
$count=mysql_num_rows($sql);

//start a table

echo '<form name="form1" method="post" action="">

';

//start header of table

echo '

Name
Email

';

//loop through all results

while($r=mysql_fetch_object($sql)){

//print out table contents and add id into an array and email into an array

echo '

<input type="hidden" name="id[]" value='.$r->$valor1.' readonly>
'.$r->$valor2.'
<input name="email[]" type="text" id="price" value="'.$r->$valor3.'">

';
}

//submit button

echo'

<input type="submit" name="Submit" value="Submit">

</form>';

// if form has been submitted, process it

if(isset($_POST["Submit"]))
{
   // get data from form

 $name = $_POST['name'];

   // loop through all array items

   foreach($_POST['id'] as $value)
   {

   // minus value by 1 since arrays start at 0

           $item = $value-1;

                //update table

    //appending suggested changes
    //place of var_dumps
   //$sql1 = mysql_query("UPDATE $tabela SET $valor3='$valor3[$item]' WHERE     $valor1='$value'") or die(mysql_error());
   $sql1 = mysql_query("UPDATE $tabela SET $valor3='$email[$item]' WHERE $valor1='$value'") or die(mysql_error());

   }

// redirect user

$_SESSION['success'] = 'Updated';
header("location:index.php");
}

The problem is, after clicking at the 'submit' button, the database table just get weird.
From This:
mysql> select * from AtuadorAnalogico;
+-------+---------+----------+
| AA_id | AA_nome | AA_valor |
+-------+---------+----------+
|     0 | nome1   | d        |
|     1 | nome2   | Agfd     |
|     2 | nome3   | Aasd     |
|     3 | nome4   | _asda    |
|     5 | teste5  | a        |
|     6 | teste6  | asda     |
|     7 | testte1 | o        |
|     8 | testte2 | rwqdq    |
|     9 | asdadsd | gwrg     |
|    10 | asdadsd | qdw      |
|    11 | adasd   | 234      |
|    12 | adasd   | g42      |
+-------+---------+----------+
12 rows in set (0.00 sec)

and
To This:
mysql> select * from AtuadorAnalogico
+-------+---------+----------+
| AA_id | AA_nome | AA_valor |
+-------+---------+----------+
|     0 | nome1   |          |
|     1 | nome2   |          |
|     2 | nome3   |          |
|     3 | nome4   |          |
|     5 | teste5  |          |
|     6 | teste6  |          |
|     7 | testte1 |          |
|     8 | testte2 |          |
|     9 | asdadsd |          |
|    10 | asdadsd |          |
|    11 | adasd   |          |
|    12 | adasd   |          |
+-------+---------+----------+
12 rows in set (0.00 sec)

Please, I really can't see my mistake.
Thanks a lot for the code revision.
PS.: just to remember. When i run the php in browser, it DOES show the contents of the database table just as it is. after clicking the submit, the thing goes crazy.
EDIT1
after renaming 'valor3' to 'email', it is not writing the string to the table anymore.
but, leaving the whole column blank (writing blank in all column cells as shown above) .
EDIT2
in comments, we just figured that is a logical problem with the code.
just can't figure out what to do.
Update
the output from just before the sql1 query:
var_dump($email);
var_dump($tabela);
var_dump($item);
var_dump($valor3);
var_dump($valor1);
var_dump($value);

vardump $email: NULL
vardump $tabela: string(16) "AtuadorAnalogico"
vardump $item: int(-1)
vardump $valor3: string(8) "AA_valor"
vardump $valor1: string(5) "AA_id"
vardump $value: string(1) "0"

vardump $email: NULL
vardump $tabela: string(16) "AtuadorAnalogico"
vardump $item: int(0)
vardump $valor3: string(8) "AA_valor"
vardump $valor1: string(5) "AA_id"
vardump $value: string(1) "1"
vardump $email: NULL

vardump $tabela: string(16) "AtuadorAnalogico"
vardump $item: int(1)
vardump $valor3: string(8) "AA_valor"
vardump $valor1: string(5) "AA_id"
vardump $value: string(1) "2"

ps.: i reduced the number of rows, so makes easyer to see and think.
I FOUND IT!
stack didn't allowed me to answer my own question, so, i'm editing as they wish.
renaming this line fields 'name' and 'id' to ""anything"":
<input name="valores[]" type="text" id="valores" value="'.$r->$valor3.'">

renaming this to the same as before:
     $valores = $_POST['valores'];

changing this to EQUAL (as stated by @JA):
  $item = $value;

and adapting the query like this:
    $sql1 = mysql_query("UPDATE $tabela SET $valor3='$valores[$item]' WHERE $valor1='$value'") or die(mysql_error());

and IT's DONE!
Thanks so much for your brainstorming.
and special thanks for @arielnmz who gave me the idea of dumping the vars so i can find the logic error.
by the way, the code finished.
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$database = "domonet";
$tabela = "AtuadorAnalogico";
$valor1 = "AA_id";
$valor2 = "AA_nome";
$valor3 = "AA_valor";

//connection to the database

$dbhandle = mysql_connect($hostname, $username, $password)
  or die("Unable to connect to MySQL");
echo "Connected to MySQL
";

//select a database to work with

$selected = mysql_select_db($database,$dbhandle)
  or die("Could not select examples");
  echo "Connected ao banco
";

//get data from db

$sql = mysql_query("SELECT * FROM $tabela");
$count=mysql_num_rows($sql);

//start a table

echo '<form name="form1" method="post" action="">

';

//start header of table

echo '

Name
Email

';

//loop through all results

while($r=mysql_fetch_object($sql)){

//print out table contents and add id into an array and email into an array

echo '

<input type="hidden" name="id[]" value='.$r->$valor1.' readonly>
'.$r->$valor2.'
<input name="valores[]" type="text" id="valores" value="'.$r->$valor3.'">

';
}

//submit button

echo'

<input type="submit" name="Submit" value="Submit">

</form>';

// if form has been submitted, process it

if(isset($_POST["Submit"]))
{
       // get data from form

     $valores = $_POST['valores'];

       // loop through all array items

   foreach($_POST['id'] as $value)
       {
       // minus value by 1 since arrays start at 0 (not anymore)

               $item = $value;
                //update table

       $sql1 = mysql_query("UPDATE $tabela SET $valor3='$valores[$item]' WHERE     $valor1='$value'") or die(mysql_error());

   }

// redirect user

$_SESSION['success'] = 'Updated';
header("location:index.php");
};

Everybody have a great night!

A: Change your form element for email as following..
<input name="email['.$r->$valor1.']" type="text" id="price" value="'.$r->$valor3.'">

You can get rid of "id[]" element
Then the loop,
foreach($_POST['email'] as $id=>$value)

$sql1 = mysql_query('UPDATE '.$tabela.' SET '.$valor3.'="'.$value.'" WHERE '.$valor1.'="'.$id.'" LIMIT 1') or die(mysql_error());

Make sure you enter something in email field before hitting submit.


text:
Q: Like and comment a Post on a Page with Open Graph API to evaluate the title of the question, I have created a page. And also app for getting a appID.
i have posted a like(action) on a techcrunch article(Object) on my timeline with the mention of my FB app name. But, is it possible to let users of my website  like & comment a particular post , which the admin posted to public on my Page using graph api.
how can we get access tokens for users to do so ?
would we still need app ID. even if it is about the facebook page. ?

A: Yes you can create Like and Comment over a particular Post. And to do so you would be required to have a Facebook app and get User's authorization for publish_stream permission. After that you can create Like for a particular Post by making a HTTP POST request to
POST_ID/comments

with message field and would return comment_id as success. And like by making HTTP POST to
POST_ID/likes

which would return true as success on creation of like.

A: If you are using Rails, you can use gems like 'Koala' to easily use Open Graph API.
After you initialize open graph object and have object ID of the post, you can use gem methods to comment or like:
token = user.access_token
@graph = Koala::Facebook::API.new(token)
post_id = @graph.put_wall_post("hey, i'm testing!")
@graph.put_comment(post_id, "Comment")
@graph.put_like(post_id)


text:
Q: system.file not exported error I get the error when I try to use devtools:system.file()
Error : object 'system.file' is not exported by 'namespace:devtools' while buiding my package.
In my roxygen2 I have added the following line
 #' @importFrom devtools system.file

but I get this error. Where I should I do this export?
I had to try this because the 'Build check' of  examples section of my roxygen2 lines fail
  pathToFile <- system.file("data",package = "yorkr")
  getBatsmanDetails(team="India",name="Kohli",dir=pathToFile)

with this  error
  Warning in readChar(con, 5L, useBytes = TRUE) :cannot open compressed file
:/Users/Ganesh/AppData/Local/Temp/RtmpCQxCAB/RLIBS_2c8411c225be/yorkr/data/Ind ia-BattingDetails.RData', probable reason 'No such file or directory'
   Error in readChar(con, 5L, useBytes = TRUE) : cannot open the connection

The system.file() seems to call the base version instead of devtools version
Please let me know what has to be done


text:
Q: Custom Post Type active link - Wordpress I have a custom post type named 'schools' on my wordpress site. When you hover over the schools tab a list of schools are shown in the submenu. These are pages I created with different school names. Now when you click on one of the school pages I have a sidebar with all the schools so they can naviate through the different schools from the sidebar rather than using the menu.
I have the sidebar being populated using the following snippet.
while( $shools_loop->have_posts() ) : $schools_loop->the_post();

  $content .= '
';
  $content .= ''.get_the_title().'';
  $content .= '
';

endwhile;

This works perfectly and I can navigate through all the schools without a problem from my sidebar. I'm trying to find a way to when I view a school via the sidebar or nav that when I'm on the active page I create some css styling to the li of the ACTIVE page. I've already figured out how to do this with the nav menu. But need help on the sidebar menu. Since the sidebar list menu is being populated I'm unsure how to check if the custom post type link is active and corresponds to the /schools/get-title page.
I found something like this online and I've tried editing it, but I'm not sure if this only works for nav menu
add_action( 'init', 'create_post_type' );
function create_post_type() {
  register_post_type( 'services',
    array(
      'labels' => array(
        'name' => __( 'Services' ),
        'singular_name' => __( 'Services' )
      ),
    'public' => true,
    'has_archive' => true,
    'rewrite' => array('slug' => 'services'),
    )
  );
}

// highlight active custom post page in nav
add_filter( 'nav_menu_css_class', 'namespace_menu_classes', 10, 2 );
function namespace_menu_classes( $classes , $item ){
  if ( get_post_type() == 'services' ) {
    // remove unwanted classes if found
    $classes = str_replace( 'current_page_parent', '', $classes );
    // find the url you want and add the class you want
    if ( $item->url == 'services/physical-therapy-services/' ) {
      $classes = str_replace( 'menu-item', 'menu-item current_page_parent', $classes );
    }
  }
  return $classes;
  }

Basically need to find a way to check whether the custom post type is active or not.

A: You can set a global variable in the main template page with the ID of the current post and then in your sidebar loop, you can retrieve that global variable and compare it with current post's ID by using get_the_ID() function and then perform the necessary actions.
Example:
single-cpt.php
// Inside the loop
global $post_id = get_the_ID();

sidebar-cpt.php
$post_id = isset($_GLOBALS['post_id']) ? $_GLOBALS['post_id'] : 0;
while( $shools_loop->have_posts() ) : $schools_loop->the_post();
  if($post_id == get_the_ID()){
      // This is the active link
      $content .= '
';

  } else {
      $content .= '
';

  }

  $content .= ''.get_the_title().'';
  $content .= '
';

endwhile;


text:
Q: Does TFS 2010 Team Build suppress checkins during the build, even if part of the build? I have created some custom CodeActivity-derived clases which:

*

*successfully check an assembly info file, GlobalAssemblyInfo.cs,

*changes the value of AssemblyFileVersion,

*and then checks it back in, returning the change set value.
I based some of this work on Ewald Hofman's wonderful blog Customize Team Build 2010 – Part 5: Increase AssemblyVersion

The Problem:
Later in the build, one of my projects in this solution uses the version number to create a subdirectory by getting the version number from the newly built assembly. The problem is the subdirectory always lags behind in the version number. I've noticed that when I test the build definition based on the BuildProcessTemplate, that my included change sets never include the GlobalAssemblyInfo from that build.
The build log tells me that steps 1, 2, and 3 all work. It also tells me that Associated Change Sets in the summary don't include the change set number in step 3. Does anyone know how I can work around this problem?

A: I found the answer to this question experimentally. As soon as a build is started, that point in the version tree is used for the associated change sets. Since I am checking out and checking in a file after that point, it is not part of the build. I got around this problem by calling my GetLatest activity after the Get All (specific), as seen in the DefaultTemplate. It's accomplishes the goal of getting my changed version number used in the assemblies.


text:
Q: Uncaught Reference Error when trying to pass a function through a button in JavaScript? I'm trying to write a navigation bar at the top of my web app to change a parameter in backend, but when I call the function it always return an unexpected end of input or an uncaught reference error that says my function was not defined on click. Can someone please help me figure out what I'm doing wrong?
JS File:
let typearray=["supermarkets_and_groceries", "churches", "cafes"];
let type = "supermarkets_and_groceries";
function changeType(randomstring){
    console.log('ok');
    type = randomstring;
    console.log(type);
}

let str = '
';
for(let count = 0; count < typearray.length; count++){
    str = str +
    '<button onclick ="changeType("'+typearray[count]+'")" title = " '+ typearray[count] + '">' +typearray[count] +'</button>';
}
str = str + '
' +
'
';
console.log(str);

document.getElementById('navbar').innerHTML = str;

HTML File(includes the rest of the program)

    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1">
    <meta charset="utf-8">

A: Looks like you just had some errors when building str. Try this
let typearray = ["supermarkets_and_groceries", "churches", "cafes"];

let str = '
';

for (let count = 0; count < typearray.length; count++) {
    str += `<button onclick="changeType('${typearray[count]}')" title ="${typearray[count]}"> ${typearray[count]} </button>`;
}
str += "
";
console.log(str);

A: use properly Template literals (Template strings)
str += `<button onclick="changeType('${typearray[count]}')" title ="${typearray[count]}"> ${typearray[count]} </button>`;

let typearray=["supermarkets_and_groceries", "churches", "cafes"];
let type = "supermarkets_and_groceries";
function changeType(randomstring){
    console.log('ok');
    type = randomstring;
    console.log(randomstring);
}

let str = '
';
for(let count = 0; count < typearray.length; count++){
    str += `<button onclick="changeType('${typearray[count]}')" title ="${typearray[count]}"> ${typearray[count]} </button>`;
}
str = str + '
' +
'
';
console.log(str);

document.getElementById('navbar').innerHTML = str;

    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1">
    <meta charset="utf-8">

use properly Template literals (Template strings)
str += `<button onclick="changeType('${typearray[count]}')" title ="${typearray[count]}"> ${typearray[count]} </button>`;

A: Just for understanding purpose:
The problem here is that a html attribute value has to be wrapped around single or double quotes. With your code, the quotes that wrap around the value of the button's onlick attribute end not there where you want because you start with double quotes but wrap the function with double quotes as well so the element at the end looks like this:
<button onclick="changeType(" supermarkets_and_groceries")"="" title=" supermarkets_and_groceries">supermarkets_and_groceries</button>
to fix this either use double and single quotes:
str = str +
"<button onclick='changeType(" + '"' + typearray[count] + '"' + ")' title = ' " + typearray[count] + "'>" + typearray[count] + "</button>";

or use template literals (already mentioned by the other answers):
str = str + `<button onclick="changeType('${typearray[count]}')" title ="${typearray[count]}"> ${typearray[count]} </button>`;

template literals explanation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

A: Modified Code Snippet
let typearray = ["supermarkets_and_groceries", "churches", "cafes"];
  let type = "supermarkets_and_groceries";
  function changeType(event) {
    type = event.target.getAttribute("type");
    console.log(type);
  }

  let navHtml = document.createElement("div");

  for (let count = 0; count < typearray.length; count++) {
    let btn = document.createElement("button");
    btn.setAttribute("type", typearray[count]);
    btn.setAttribute("title", typearray[count]);
    btn.innerText = typearray[count];
    btn.addEventListener("click", changeType);
    navHtml.appendChild(btn);
  }
  document.getElementById("navbar").appendChild(navHtml);


text:
Q: Why the extraneous padding-bottom and/or margin-bottom? This jsFiddle illustrates what this question refers to (full code below).  Note that, even though #outer-div should have 0 padding, and #inner-div should have 0 margin-bottom, it appears as though the there's some padding and/or margin between the bottom edges of #outer-div and #inner-div.
Where does this come from, and, more importantly, how can I suppress it?
css
html,body,div{margin:0;padding:0;border:0;outline:0}
body{background:white;}
#outer-div{
  background:lightgray;
  margin-top:20px;
  text-align:center;
}
#inner-div{
  background:black;
  display:inline-block;
}

html
<!doctype html>

A: Inline elements are sensitive to white space and that gap is reserved for descender elements. Adding vertical-align:top to #inner-div is one way to fix this:
#inner-div {
    background:black;
    display:inline-block;
    vertical-align:top;
}

jsFiddle example
A second way is to set font-size:0 on the parent element in this jsFiddle example.


text:
Q: The Requested Service cannot be activated WCF I have a wcf service(REST) with webHttpBinding,I first configured it for HTTP and hosted in local IIS it was working great there, Now i moved it to my testing server with Https ,Changed the security mode to transport but now i am getting an exception which says service cannot be activated.IIS didnt log anything
Server stack trace:
   at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory`1 factory, WebException responseException, ChannelBinding channelBinding)
   at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
   at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
   at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Configuration is like this
 <webHttpBinding>
    <binding name="WebHttpBinding_StatusReportService"
      closeTimeout="10:10:00" openTimeout="10:10:00" sendTimeout="10:10:00"
      maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
      <security mode="Transport">
        <transport clientCredentialType="None" />
      </security>
    </binding>
  </webHttpBinding>

  <endpoint address="https://...../Services/StatusReportingService.svc"
   behaviorConfiguration="webEndpoint" binding="webHttpBinding"
   bindingConfiguration="WebHttpBinding_StatusReportService"
   contract="ServiceReference1.StatusReportService"
   name="WebHttpBinding_StatusReportService" />

   <behavior name="webEndpoint">
              <webHttp />
            </behavior>

What might be the reason for this

A: Please try with adding a certificate and also change the SSL settings in IIS.
The link http://msdn.microsoft.com/en-us/library/hh556232(v=vs.110).aspx captures all the steps.


text:
Q: Knockout textInput and maskedinput plugin Is there an easy way to use data-bind="textInput: aProperty" and add an input mask or some automatic formatting as the user types?
Using the masked input plugin kind of works, but I lose the "as-you-type" updates that Knockout's "textInput:" provides, so other parts of the script only see the change after the field loses focus (effectively behaving as a plain old "value:" binding in Knockout).
A naïve solution with a computed observable that does the formatting doesn't work because each keystroke to a field that updates itself changes the input focus to somewhere else in the page, so the user can't keep typing.
Can I make these two libraries play nice with each other or should I make my custom solution? They do a lot of things in their event handlers to be compatible with all browsers, so it's not a surprise that it's hard to make them work together, but that is also exactly why I don't want to fiddle with all those keyup, input, change, events by myself.
All previous answers on StackOverflow don't mind propagating the changes only after the field loses focus. Maybe those answers were posted before textInput was added to Knockout, so there wasn't anything better at the time. That's why I'm asking a new question.

A: I've written a fiddle that uses just a computed observable, and I don't have a focus problem with it. Does this work as you expect?
var displayString = ko.observable('');
var formattedString = ko.computed({
    read: function () {
        return displayString();
    },
    write: function (newValue) {
        var f = format(newValue);
        console.debug("Format", newValue, "=", f);
        displayString(f);
    }
});

http://jsfiddle.net/csmmnq25/


text:
Q: How can I use jQuery with Puppeteer? So, I am using Puppeteer (a headless browser) to scrape through a website, and when I access that url, how can I load jQuery to use it inside my page.evaluate() function.
All I have now is a .js file and I'm running the code below. It goes to my URL as intended until I get an error on page.evaluate() since it seems like it's not loading the jQuery as I thought it would from the code on line 7: await page.addScriptTag({url: 'https://code.jquery.com/jquery-3.2.1.min.js'})
Any ideas how I can load jQuery correctly here, so that I can use jQuery inside my page.evaluate() function?
(async() => {
  let url = "[website url I'm scraping]"
  let browser = await puppeteer.launch({headless:false});
  let page = await browser.newPage();
  await page.goto(url, {waitUntil: 'networkidle2'});
  // code below doesn't seem to load jQuery, since I get an error in page.evaluate()
  await page.addScriptTag({url: 'https://code.jquery.com/jquery-3.2.1.min.js'})
  await page.evaluate( () => {
      // want to use jQuery here to do access DOM
      var classes = $( "td:contains('Lec')")
      classes = classes.not('.Comments')
      classes = classes.not('.Pct100')
      classes = Array.from(classes)
  });
})();

A: You are on the right path.
Also I don't see any jQuery code being used in your evaluate function.
There is no document.getElement function.
The best way would to be to add a local copy of jQuery to avoid any cross origin errors.
More details can be found in the already answered question here.
UPDATE: I tried a small snippet to test jquery. The puppeteer version is 10.4.0.

(async () => {
    const browser = await puppeteer.launch({headless:false});
    const page = await browser.newPage();
    await page.goto('https://google.com',{waitUntil: 'networkidle2'});
    await page.addScriptTag({path: "jquery.js"})
    await page.evaluate( () => {
        let wrapper = $(".L3eUgb");
        wrapper.css("background-color","red");
    })
    await page.screenshot({path:"hello.png"});
    await browser.close();
})();

The screenshot is

So the jquery code is definitely working.
Also check if the host website doesn't have a jQuery instance already. In that case you would need to use jquery noConflict
$.noConflict();

A: Fixed it!
I realized I forgot to include the code where I did some extra navigation clicks after going to my initial URL, so the problem was from adding the script tag to my initial URL instead of after navigating to my final destination URL.
I also needed to use
await page.waitForNavigation({waitUntil: 'networkidle2'})

before adding the script tag so that the page was fully loaded before adding the script.


text:
Q: Creating an empty object with nested attributes in Python I'm trying to create an empty object which contains nested attributes like this:
form = type('', (), {})()
form.foo.data = ''

But I get following attribute error:
>>> form = type('', (), {})()
>>> form.foo.data = ''
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'data'

How should I construct the object to accomplish that?

A: As per the type function , the third argument should be in the form of dictionary. So, for nested attributes, you can create the object before itself and then use it in the dictionary.
Something like this might work -
da = type('',(),{'data':1})
a = type('',(),{'foo':da})

A: I dont get your point but you may use namedtuple :
>>>from collections import namedtuple

>>>foo = namedtuple('foo', "data tuple dict")
>>>foo.data = ""
''
>>> foo.tuple = ()
>>> foo.tuple
()


text:
Q: Why callback function still delay even after the setting timeout to 0

console.log(10);
setTimeout(()=>{console.log(20),0});
console.log(30);

Why the callback timeout function still delays in output?

A: setTimeout() is asynchronous and that means that even if you set timer to zero, it will still be done after all of your code. Search asynchronous function to learn more.


text:
Q: How to fix reversed winding on simple model? I develop a little addon for the Minecraft game, and it includes quite a few models that I import from blender-created .obj (wavefront) model files. One of the features I add is a set of "transmitters" that can transport items and fluids throughout the world. Well anyway, a new version of the game came out and it really screwed up the way my models render. The link below is an album of the before and after shots of these "transmitters":
http://imgur.com/DtmUYFU,Y2PxNYh#1
I'm not the smartest when it comes to this kind of rendering (I depend upon quite a few high level libraries that help me out), but I was curious if someone could explain what happened/what is going on render-wise in the second picture. If you can't tell, the textures are basically "inside-out" - the front texture is rendering on the back of the model, and as you walk around the object this remains consistent. I'm hoping there's a single fix that could completely fix this - I don't expect anyone to actually learn the libraries and give me the fix in code, but just a detailed explanation of what is going wrong would really help me fix it myself!
Here are the wavefront model resources (transmitter_small is pictured).
Let me know if anything else is necessary, and thanks a bunch for helping!


text:
Q: Could not getting correct text in output after refresh of search results This is a site related to find shoe costs. Initially I have entered the text and performed the search and output the number of results obtained.
After selecting a criteria, the search result refresh according to new criteria.
but the output still shows the previous result. I tried with implicit wait but it still shows old result.
This is the code:
public void openBrowser()
{
    StaticData.driver.get("http://laceup.io/phase2");
}

public void homeSearchAndClick()
{
    System.out.println("In home search");
    StaticData.driver.findElement(By.xpath(".//*[@id='search_field']")).sendKeys("Nike");
    StaticData.driver.findElement(By.xpath("html/body/div[1]/div/div[1]/div[1]/div[1]/div/button")).click();
}

// Function to search by FEMALE gender

public void searchForFemale()
{
    System.out.println("Gender: Female clicked");
    StaticData.driver.findElement(By.xpath("html/body/div[1]/div/section/div[1]/div[1]/div/div[1]/div/div[2]/label/span")).click();
}

public void filterSearchCount()
{
    StaticData.driver.manage().timeouts().implicitlyWait(500, TimeUnit.SECONDS);
    String searchCount = StaticData.driver.findElement(By.xpath(".//*[@id='show_query']/h2")).getText();
    System.out.println("Filter search count: " + searchCount);
}

A: I discovered that a     driver.navigate().refresh(); used in the method filterSearchCount() do the trick. Even so, I've noticed that the Nike checkbox for filter isn't checked. In this way, the program will display Filter search count: 1919 RESULTS (1918 from Nike + 1 from Warrior)
If you want the exact result for Nike- woman you should check also Nike in the filer area, as I've told you before that the site doesn't check it automatically even if you have been written Nike in the Search Textbox.

A: If your objective is to fetch the number of results for "Nike" for Women gender there is another way to do it. You can toggle the Ladies beforehand on the homepage itself.

FYI, I'm using PageObjectFactory to simplify your code
Phase2Page.java - Page Object Factory for your Home Page
public class Phase2Page {
    WebDriver driver;

    public Phase2Page(WebDriver driver){
        this.driver = driver;
        PageFactory.initElements(driver, this);
    }

    @FindBy(xpath = "//*[@id='search_field']")
    WebElement searchField;

    @FindBy (xpath = "html/body/div[1]/div/div[1]/div[1]/div[1]/div/button")
    WebElement searchBtn;

    @FindBy(xpath = ".//*[@id='filter_gender_ul']/li[2]")
    WebElement LadiesToggle;

    public void homeSearchAndClick() {
        System.out.println("In home search");
        LadiesToggle.click();
        searchField.sendKeys("Nike");
        searchBtn.click();
    }
}

SearchPage.java - Page Object Factory for Search Page
public class SearchPage {
    WebDriver driver;

    @FindBy(xpath = ".//*[@id='show_query']/h2")
    WebElement searchCount;

    public SearchPage(WebDriver driver){
        this.driver = driver;
        PageFactory.initElements(new AjaxElementLocatorFactory(driver, 50),this);
    }

    @FindBy(xpath = "html/body/div[1]/div/section/div[1]/div[1]/div/div[1]/div/div[2]/label/span")
    WebElement femaleCheckbox;

    // Function to search by FEMALE gender
    public void searchForFemale() {
        System.out.println("Gender: Female clicked");
        femaleCheckbox.click();
    }

    public void filterSearchCount() {
        String count = searchCount.getText();
        System.out.println("Filter search count: " + count);
    }
}

Test1.java - Your Actual Test for execution
public class Test1 {
    WebDriver driver;

    public void openBrowser() {
        driver.get("http://laceup.io/phase2");
    }

    @Test
    public void testSearch(){
        System.setProperty("webdriver.chrome.driver", "D:\\Selenium Webdriver/chromedriver.exe");
        driver = new ChromeDriver();
        openBrowser();
        Phase2Page objHome = new Phase2Page(driver);
        SearchPage objSearch = new SearchPage(driver);
        objHome.homeSearchAndClick();
        objSearch.filterSearchCount();
        driver.quit();

    }
}

A: My code worked when i used thread.sleep in filterSearchCount().


text:
Q: Как запустить не-Main.java файл на Repl.it? Уважаемые, подскажите, пожалуйста, как можно выйти из ситуации? Постигаю азы ООП, и пишу код на работе на сайте repl.it. Создаю новый Repl, удаляю базовый файл Main.java, создаю простецкий класс с объектом в файле Cat.java:
public class Cat {
  String name;
  int age;
  public static void main(String[] args) {
    Cat Mars = new Cat();
    Cat.name = "Mars";
    Cat.age = 1;
    System.out.println(Cat.name + " & " + Cat.age);
  }
}

Жму на Run, и выдаёт ошибку: "unable to run, main file "Main.java" not found". Т. е. Repl'у важно, чтобы в обязательном порядке в проекте присутствовал файл Main.java, а уже потом всё остальное. Как выкрутится? Мне не нужен этот Main.java. Я пока хочу создавать/прописывать котов с хорьками, и только.
Можно типа некий трюк провернуть, но я не понял как. :( Там в ответах одна строчка кода, вырванная из контекста.
В общем, на конкретном примере моего небольшого кода как быть, что бы я мог создавать классы, объекты, называя их так, как мне хочется, и чтобы меня не волновало существование файла Main.java в проекте. Ну пусть он практически или вовсе пустой висит и всё, если уж без него совсем никак. Но только как в моём коде этот трюк провернуть?

A: Можно добавить вложенный класс с котиком:
class Main {
  private static class Cat {
    private String name;

    public Cat(String name) {
      this.name = name;
    }

    public void meow() {
      System.out.println("Cat " + this.name + " says \"MEOW!!1\"");
    }
  }

  public static void main(String[] args) {
    Cat cat = new Cat("Yasa");
    cat.meow();
  }
}

Либо создать отдельный класс Cat.java
public class Cat {
  private String name;

  public Cat(String name) {
    this.name = name;
  }

  public void meow() {
    System.out.println("Cat " + this.name + " says \"MEOW!!1\"");
  }
}

и вызвать его в Main.java
class Main {
  public static void main(String[] args) {
    Cat cat = new Cat("Yasa");
    cat.meow();
  }
}


text:
Q: how to make style sheet for tablet and iphone I was thinking the link target on the stylesheet would make my css file only load when it loads on a tablet or iphone. But the elements I'm trying to hide are still there. Im currently using (media="handheld")
  <link rel="stylesheet" type="text/css" hrf="css/media.css" media="handheld" />

A: There are too many mobile device models out there to write stylesheets for; you'd be better off adjusting your CSS based on Screen Size.
This is especially helpful for targeting Android Tablets which comes in different sizes.
See this useful tutorial for further explanation:
http://css-tricks.com/resolution-specific-stylesheets/
So, instead of targeting a specific screen dimensions (which would keep changing as more devices are released), you'd want stylesheets that change according to the screen size.
Then you'll add several stylesheets:
<link rel="stylesheet" media="screen and (min-width: 480px) and (max-width: 700px)"     href="css/small.css" />
<link rel='stylesheet' media='screen and (min-width: 701px) and (max-width: 900px)'     href='css/medium.css' />

etc.
So iPhones would use the small.css, and tablets larger than 700px will use medium.css.

A: Handheld is more for devices like PDAs or feature phones than iOS or Android devices. You're much better off using media queries to detect device capabilities and then adjust accordingly. Here's an example article: http://mobile.smashingmagazine.com/2010/07/19/how-to-use-css3-media-queries-to-create-a-mobile-version-of-your-website/


text:
Q: Increasing Alphanumeric value in user defined function I'm trying to code a user defined function  under SQL Server 2005 that will increase integer part of alphanumeric value by one. For example,  uf_AlphanumericIncrease ('A000299')  should return 'A000300'. Here's what I've done so far;
ALTER FUNCTION uf_AlphaNumericIncrement
(
@ID varchar(10)
)
RETURNS VARCHAR(10) AS
BEGIN
    DECLARE @RES varchar(10);
    IF SUBSTRING(@ID,LEN(@ID),1)='9'
        SET @RES=SUBSTRING(@ID,1,LEN(@ID)-2)+CAST (CAST(SUBSTRING(@ID,LEN(@ID)-1,1) AS smallint)+1 AS VARCHAR(10))+'0';
    ELSE
        SET @RES=SUBSTRING(@ID,1,LEN(@ID)-1)+CAST (CAST(SUBSTRING(@ID,LEN(@ID),1) AS smallint)+1 AS VARCHAR(10));
    RETURN @RES;
END

But as you can see it only works for last digit. I need to get it under loop so it can work for A002999 and so on.  Any ideas?
Edit: Given value might have alpha prefix longer than one character, or none at all.

A: Now works with any length of prefix and number part (well upto 20 each)
DECLARE @prefix varchar(20), @numberstr varchar(20), @number int, @Val varchar(40)

SELECT @Val = 'ABCD000006'
--SELECT @Val = 'A03'

SELECT @prefix = LEFT(@Val, PATINDEX ('%[0-9]%', @Val) -1)
SELECT @numberstr = SUBSTRING(@Val, PATINDEX ('%[0-9]%', @Val), 8000)
SELECT @number = CAST(@numberstr AS int) + 1
SELECT @prefix + RIGHT(REPLACE(SPACE(LEN(@numberstr)), ' ', '0') + CAST(@number AS varchar(20)), LEN(@numberstr))

A: Assuming that the alpha part of your alphanumeric is always only the first character, this should work.
EDIT: OK, if the alpha part varies in length this gets ugly pretty quickly for a UDF.  This is just a quick-and-dirty solution, so it can probably be optimized a bit, but the logic should be sound.
EDIT AGAIN: patindex() ftw - I learned something new today  ;-)
ALTER FUNCTION uf_AlphaNumericIncrement
(
@ID varchar(10)
)
RETURNS VARCHAR(10) AS
BEGIN
    DECLARE @RES varchar(10);
    DECLARE @num int;
    DECLARE @prefix varchar(10);
    set @prefix = left(@id, patindex('%[0-9]%', @id) -1)
    set @num = cast(right(@id, len(@id) - len(@prefix)) as int) + 1
    set @res = @prefix + replicate('0', len(@id) - len(@prefix) - len(@num)) + cast(@num as varchar(10))

    RETURN @RES;
END

A: CREATE FUNCTION dbo.uf_ANinc
(
  @in varchar(10)
)
RETURNS varchar(10) AS
BEGIN
    DECLARE @prefix varchar(10);
    DECLARE @res varchar(10);
    DECLARE @pad varchar(10);
    DECLARE @num int;
    DECLARE @start int;

    SET @start = PATINDEX('%[0-9]%',@in);
    SET @prefix = LEFT(@in, @start - 1 );
    SET @num = CAST(  RIGHT( @in, LEN(@in) - @start ) AS int  ) + 1
    SET @pad = REPLICATE( '0', 10 - LEN(@prefix) - CEILING(LOG(@num)/LOG(10)) );
    SET @res = @prefix + @pad + CAST( @num AS varchar);

    RETURN @res
END
GO

SELECT dbo.uf_ANinc('ABC000123');


text:
Q: Chatter feed tracking for new record creation I want to notify users  through chatter Stream  when a new record is created on an object
So when a new account record is created , a post at chatter will be notified to all or select users.
User should be notified of a new record creation only, without following objects and records hence being inundated with chatter noise. I am aware of chatter feed, however clearly this isn't sufficient.
Is this possible, or would an apex trigger be required.
Much thanks to all, would be grateful for anyone to elaborate if this is possible with workarounds.

A: Here's a link to the Help page for Customizing Chatter Feed Tracking:
http://help.salesforce.com/apex/HTViewHelpDoc?id=collab_feed_tracking.htm
Like you said, the out-of-the-box Chatter might not have sufficient capabilities to do what you're asking, and their are more complex alternatives.  First, I believe you can create a Trigger on the appropriate Chatter Objects.  That would give you the greatest control over Chatter Feed records generation.  In the Trigger, you could evaluate who the User is and do different actions based on the User and the record itself (like create new appropiate Chatter Feed Records).
However, if that doesn't work, there is another alternative of using Streaming API.  It's kind of nifty: first you set up Queries (PushTopic).  The code then performs the PushTopic query at regular intervals (near-continuous or in a trigger-fashion) and it detects when a new record is created (or edited depending on your settings).  The Streaming API then sends a message to the client when it detects a change.  The client can then do whatever they want with it (like create a Chatter Feed Record).
I believe Streaming API is more for the use-case of a 3rd-party application or like you would use Salesforce SOAP API with Javascript on a page.
Streaming API docs:  http://www.salesforce.com/us/developer/docs/api_streaming/

A: A potential workaround:

*

*Create a field, perhaps called this record and give it two picklist values: not created and created

*Write a workflow rule to run on creation and modify this_record__c, setting it equal to created (make sure the default is set to not created)

*Turn on Chatter Feed Tracking for this_record__c
The resulting chatter post would read something to the effect of:

user2878773 changed this record from not created to created

A: I think you'll need  trigger for that. Maybe you could create a group called New Records and users who want to see that a new record has been created could be a member of that group. You could then have a trigger on the objects you want to track make a post into the New Records group so everyone is notified.


text:
Q: How to get access to this special character? I just bought the font Uberschrift which brings tons of ligatures with it, but u nfortunately I'm not able to get access to them.

I tried to find out wich is the symbol's name and this is what fontmatrix tells me:

I found it not in the standard latin1 alphabet but in "un-mapped glyphs".
It is symbol I+191.
How do I get access to this ligature with xelatex or luatex with fontspec?
\documentclass[11pt]{standalone}
\usepackage{fontspec}
\usepackage{xltxtra}
\usepackage{polyglossia}% babel for Xelatex
\setdefaultlanguage{german}
\defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase}
\setmainfont{Uberschrift}

\pagestyle{empty}
\begin{document}

Überschrift

\end{document}

A: Apparently, the program you used tells you the glyph index as a decimal number; with XeTeX you can access a glyph by index using \XeTeXglyph.
I suggest a macro, instead of the raw primitive:
\newcommand{\glyph}[1]{\XeTeXglyph#1\relax}

so, after this, you can type
Übers\glyph{191}rift

Why a macro? Because there could be a similar trick with LuaLaTeX (that I don't know at the moment), and the macro can be adapted to both engines without requiring changing the input.
See https://tex.stackexchange.com/a/120762/4427 for a LuaTeX function that should do the job.


text:
Q: Solving configuration mismatch between Google Analytics and Google Optimize? So I'm using Google Analytics, Google Optimize, and Google Tag Manager. I also  feel that I may be losing my mind.
For performance reasons, we don't want to add the google optimize script through GTM. We want to hard-code it. But every time I try that, the installation doesn't work. Specifically, when I click "Run Diagnostics" on the google optimize setup page, I get an error that says

All Analytics tracking code on the page must have the same tracker configuration settings. [...] The following tracker configuration properties do not have the same configurations: alwaysSendReferrer.

So I go into my handy Analytics debugger, find the alwaysSendReferrer property, and note that it's set to true. Great. I edit the config object that i'm passing to the google optimize init script, and I add alwaysSendReferrer: true. So far so good. Except... I get the same error.
I thought maybe something was wrong with our analytics setup, so I got rid of the hardcoded google optimize script and instead included it via the Google Optimize GTM tag -- which, unexpectedly, worked perfectly. I thought "Okay i'll just find the script that GTM is adding and copy/paste it into the codebase" but of course it's minified within an inch of its life, and untangling that javascript from the rest of the tags would be a whole other endeavor.
I have access to a {{Default UA Settings}} variable in GTM, and google's documentation would really like me to just pass that object to the official "Google Optimize" tag in GTM. That works (I've tested it), but as mentioned, we don't want to do that.
If anyone knows what the Google Optimize config object should look like, that would help me massively.
Right now mine looks like this (with identifying details removed)
dataLayer.push(['config', 'UA-12345', {
    'optimize_id': 'GTM-55555',
    'linker': { 'domains': ['mywebsite.com <http://mywebsite.com>'] },
    'alwaysSendReferrer': true
});

I've tried false, "true", 1, and basically everything else I can think of (I'm quite confident that Google Analytics has this property set to true on our site) -- my only guess is that maybe I'm setting the value in the wrong place and google optimize isn't seeing it. Help?

A: I know the feeling of losing your mind trying to read through Google documentation!
This is the code I use on pages I wish to run Optimize experiments on:
<head>
...
  <!-- Google Tag Manager --> <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-PRMQXXX');</script> <!-- End Google Tag Manager -->

  <!-- Page-hiding snippet (recommended)  -->
  <style>.async-hide { opacity: 0 !important} </style>
  <script>(function(a,s,y,n,c,h,i,d,e){s.className+=' '+y;h.start=1*new Date;
  h.end=i=function(){s.className=s.className.replace(RegExp(' ?'+y),'')};
  (a[n]=a[n]||[]).hide=h;setTimeout(function(){i();h.end=null},c);h.timeout=c;
  })(window,document.documentElement,'async-hide','dataLayer',4000,
  {'GTM-KL7XXXX':true});</script>

  <!-- Modified Analytics tracking code with Optimize plugin -->
  <script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-99999999-1', 'auto');
  ga('require', 'GTM-KL7XXXX');
  ga('send', 'pageview');
  </script>
...
</head>

Where:

*

*GTM-PRMQXXX is the Google Tag Manager container id

*GTM-KL7XXXX is the Google Optimize container id, and

*UA-99999999-1 is my Google Analytics id

Note that you need to remove your usual GA script once you add the scripts above.
I hope this helps you!


text:
Q: an option already selected on page load in drop down list and also changeble
Possible Duplicate:
PHP - PRE-select drop down option

I have a situation in my php  project where a user can edit his account.
In editing, there is a city field  which is a drop down list of cities.
I want to already select one city which is in profile before editing(the one which user enter at the time of registration).
Also he is able to change his city by choosing fron drop down list.
Html code:

State:

<select class="styled" name="state_trainer">
 <option>-select-</option>
 <option>washington</option>
 <option>perth</option>
 <option>delhi</option>
 <option>london</option>
 </select>

on editing I am using this code to fetch current data(city) of user:
<?php
if(isset($_GET['userid']))
{
$sql = "select city from `wp_pelleresuser` where userId =".$_GET['userid'];
$result = mysql_query($sql);
$value = mysql_fetch_assoc($result);
}?>

please tell me how can I get already selected one option which is fetch from database.
And also it is changeable.

A:
State:

  <select class="styled" name="state_trainer">
   <option <?if($value['city']=='-select-') echo "selected";?>>-select-</option>
   <option <?if($value['city']=='washington') echo "selected";?>>washington</option>
   <option <?if($value['city']=='perth') echo "selected";?>>perth</option>
   <option <?if($value['city']=='delhi') echo "selected";?>>delhi</option>
   <option <?if($value['city']=='london') echo "selected";?>>london</option>
  </select>

A: I'm not sure if it is clear way but you can put code inside every option cell like this:
<option <?php if($value['city'] == "washington") echo "selected=selected"; ?> >washington</option>

A: You can do it in a number of ways, the simplest (and probably least elegant) is to do something like this:
<select class="styled" name="state_trainer">
<?php
$myCity='london'; // assumed to be data from database...
echo '<option'.($myCity=='-select-') ? ' selected ' : ' ' .'-select-</option>';
echo '<option'.($myCity=='washington') ? ' selected ' : ' ' .'washington</option>';
?>

This is of course horrid.
I would rather suggest that you check the data as you are pulling your information out of the database and putting your initial dropdown list together.
If you are making an array of data to create the drop down list (for example) check it right there and then. If the city matches what you want, do it inside your loop right off the bat.
$usersCity="london";
$myCityList=array();

while( ... ) // Database loop that is pulling the data from the database.
{
    $selected='';
    if($userCity==$row['city'])
    {
        $selected=' selected ';
    }
    $myCityList[]='<option'.$selected.'>'.$row['city'].'</option>';
}

Then to display the drop down list, you can simply do this:
$cityCount=count($myCityList);
for($i=0;$i<$cityCount;$i++)
{
    echo $myCityList[$i].'\n';
}

The users city will already be selected.

A: This way you can get what u want.
And better use mysqli function for database interactions.
<option
<?php if ($value['city'] == delhi)
          {
                                echo "selected = true";

          }  ?>
 >delhi
</option>

A: Just het the selected value form db like
$choosen = $some value form db

then
    $options = array(1 => 'data1', 2 => 'data2', 3 => 'data3');
                    foreach ($options as $key => $value)
                    {
                        echo '' . $value . '';
                    }
to get your selection box in php.I thnk you understand,it works for me


text:
Q: What if i define a character array of X elements and add Y (>X) elements to it? There is the NUL character that is added after every string.
So if I define a character array of 10 elements and put 6 elements, the 7th element is automatically the null character. (If I'm wrong somewhere please
correct me.)
So if I make a character array of 3 elements and put 4 letters into it like
char array[3]={'h','i','y','a'};

and I do not put the NUL character, what happens?
Is the null character added in the last position?
Do I get an error?
I'm so sorry, normally I would simply try running the code but my virtual machine keeps crashing for some reason.

A: According to the C Standard (C11 6.7.9. Initialization) it's a constraint violation that must be diagnosed:

Constraints
2 No initializer shall attempt to provide a value for an object not contained within the entity being initialized.

For example, gcc and clang will report
x.c: In function 'main':
x.c:4:30: warning: excess elements in array initializer
   char array[3]={'h','i','y','a'};
                              ^
x.c:4:30: note: (near initialization for 'array')

So what happens, i.e. what code does the compiler generate? In C lingo, violating a constraint is undefined behavior, so the answer is: we can't tell. Some compiler might ignore the extra character, some might extend the array dimension. Some might refuse to compile it. Some might create a corrupt program. This is the reason why good programmers steer clear of undefined behavior.

A: You initialize a 3 byte long buffer with a 4 byte long string literal, w/o terminating zero. GCC does it for you for the 1st 3 bytes, ignores the 4th byte and gives you a warning:
warning: initializer-string for array of chars is too long

When you printf it, you just pass a pointer, in our case the array symbol means the start address of the array. printf has no idea about its length, it will just happily iterate over bytes in memory until it finds a terminating zero.
So printf will print the memory area following your array, which is undefined behaviour, as only the compiler knows what it has placed after your array. If you're lucky, there will be a zero byte pretty soon, and printf stops before reaching a page of virtual memory it can't read. You end up with hiy and some garbage.
If you're not so lucky, printf reaches an unreadable page of memory and you die a painful death of segmentation fault.
Just trying to explain what the lawyers mean with undefined behaviour... :)