text:
Q: child_of not working in wp_dropdown_categories I have wp_dropdown_categories working without setting child_of. Once I set child_of, all categories disappear. Here's my code, what should I do to enable child_of?
function dropdown(){
    $book_term=term_exists('book','category');
    $book_term_id = $book_term['term_id'];
    $dropdown = array(
    'child_of'   => $book_term_id,
    'hide_empty' => 0
    )
?>
    wp_dropdown_categories( $dropdown );
<?php
}

A: The variable $book_term_id has not been set. You either need to pass it to your function or set it in your function.
Pass it to your function:
<?php dropdown($book_term_id); ?>

Set it in your function:
function dropdown(){
  $book_term_id = 5; // if a global variable, you can just use:  global $book_term_id;
  $dropdown = array(
    'child_of'   => $book_term_id,
    'hide_empty' => 0
  )
  wp_dropdown_categories( $dropdown );
}

A: not sure if this is THE problem, but there are problems. your PHP (WP) function is outside of PHP:
?>
    wp_dropdown_categories( $dropdown );
<?php

so it'll print as text, not execute.
also, when you put it w/in PHP, make sure to add a semi-colon after the array's closing parenthesis:
  $dropdown = array(
    'child_of'   => $book_term_id,
    'hide_empty' => 0
  );
  wp_dropdown_categories( $dropdown );
}


text:
Q: Responsive email table keeps breaking - what is causing this? I'm working on an HTML Email which is working perfectly in the multiple email client/browser combinations I need to support save for this one problem which I just cannot figure out. I have a table that is 600px (which is the width of the email) wide and within this there is another table which is comprised of a top and bottom 'curve' image which has some text in the middle. As this email is responsive, when the browser window is made smaller the inner grey table just 'breaks'. I know this because I am using Litmus to test across a multitude of browser/email clients combinations.
Note: this ONLY happens when email is "resized" i.e. only on mobile email clients. If you look at the below fiddle, the portion I am talking about is the inner grey box that begins The Victims of Fraud.... This box (when resized) just will not play nice. I have tried everything I can think of, using padding, removing padding, nested tables and everything inbetween. It's driving me crazy.
In order to see what I mean open the fiddle then make the HTML window smaller.
Here is a fiddle to try and illustrate what I mean: http://jsfiddle.net/39gzj/2/
UPDATE: If you look using Firebug / Chrome Developer Settings, you will see that for some reason the table has this magic 2px added to the inner grey table. This is what I need to eradicate!
UPDATE 2: Tried again with what was posted in the comments but again this does not work.
http://jsfiddle.net/39gzj/2/
UPDATE 3 - I've even tried using a media query to explicitly resize this middle box but it still doesn't work. Here is the updated fiddle; http://jsfiddle.net/39gzj/5/

A: Try setting up your table like this instead:

text here. Put this inside a container with any media queries, should always stretch to full width.

A: If you pull your static-width columns out that you're using for spacing and apply margin to the sub-tables to accomplish your spacing everything should line up properly.  I'd imagine the spacing columns are the source of your angst.

A: Have you tried using min-width. To limit the size that it will shrink to. I would assume that if it shrinks it should only shrink to the point before it breaks. Am I right?

A: Right, so I finally managed to fix this but needed to use the media queries to fix the "breaking" of that middle row. Here's what I did;
Use a media query to explicitly size EVERY SINGLE ROW! So now, the image resizes properly, but once it gets to mobile viewport size it just snaps down to the correct size (max 300px) which you can see in the CSS. Here is the updated fiddle
Here is the media query that worked:
@media only screen and (min-width:300px) and (max-width: 500px) { /* MOBILE CODE */
    *[id=mobile] {
        width:300px!important;
    }
}

This I know isn't really the correct way to answer this as I still haven't fixed the initial problem (why the table is breaking) so no sure what the mods wish to do with this bounty I put out there.
EDIT: As pointed out helpfully in the comments, if the screen size is BELOW 300pxthe email will automatically become normal size again, this can again be fixed by changing the media query but as noted, this answer currently solves issues specifically for the email clients/browser combinations I need to support.

redpajama_set_name: RedPajamaStackExchange


text:
Q: TransferFunctionModel produces large coefficients First, I define the following transfer functions using TransferFunctionModel:
tfmGc[s_, a_, t_] := TransferFunctionModel[(1 + a*t*s)/(1 + t*s), s];
tfmGp[s_, k_] := TransferFunctionModel[k/(s*(s + 5)), s];

Next, the two transfer functions above are connected in series using SystemsModelSeriesConnect, and a unity feedback connection is established using SystemsModelFeedbackConnect to produce the open loop and closed loop transfer functions respectively:
tfmOLTF[s_, a_, t_, k_] := SystemsModelSeriesConnect[tfmGc[s, a, t], tfmGp[s, k]];
tfmCLTF[s_, a_, t_, k_] := SystemsModelFeedbackConnect[tfmOLTF[s, a, t, k]];

Finally, I evaluate tfmCLTF with the following parameters:
a1 = 0.166521;
t1 = 12.010533;
k1 = 9;

tfmCLTF[s, a1, t1, k1] // TransferFunctionExpand

Mathematica produces the following result:

My question is: Is there a way to change this so that the coefficients are not too large?
Thanks in advance!

A: You can get rid of those large coefficients by using TransferFunctionCancel.
tfmCLTF[s, a1, t1, k1] // TransferFunctionCancel // TransferFunctionExpand // Chop

I'm not quite sure why it produces them in the first place.
(You may also consider using TransferFunctionFactor instead of TransferFunctionCancel, because the latter will also cancel common pole-zero pairs. This does not happen in this case.)


text:
Q: Open in new tab (not new window) using any method possible I know that there are lots of duplicate questions like mine but I couldn't find any solution. I'm having trouble with opening a new tab in my code. I want to open a new tab - not a window - without any click on any button, and I need it to run automatically.
This is my code but it open's a new window instead of a new tap.
code:
if (isset($_POST['check'])){
  ?><?php
}

meta refresh version:
(it redirects to the target page in the same page, and I wonder is there any way to redirect to a new tab?)
if (isset($_POST['check'])){
  echo "<meta http-equiv=\"refresh\" content=\"0; URL=javascript:window.open('reports/relation_with_health.php\','_new');\">";
}

A: try this:
window.open('reports/relation_with_health.php\','_blank')

A: With the bel open a new tap and stay in current tap (crtl+click) function like.
java code :

html code :
education efficacy


text:
Q: VB and XML Encoding (UTF-8)? Guys...I really need your help..
I have this vb code where i will send a value typed in a textbox to MSMQ...
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim mq As MessageQueue
    'Dim format As XmlMessageFormatter
    Dim msg As Message
    'Dim dec As XmlDeclaration

    Try
        msg = New Message
        msg.Priority = MessagePriority.Normal

        If Not (MessageQueue.Exists(".\Private$\toNavision")) Then
            mq = MessageQueue.Create(".\Private$\toNavision")

        Else
            mq = New MessageQueue(".\Private$\toNavision")

        End If
        msg.Label = "Navision MSMQ-BA"
        msg.Body = TextBox1.Text

        mq.Send(msg)
        Label1.Text = "Message sent."

    Catch ex As MessageQueueException
        Label1.Text = ("MSMQ Error: " + ex.ToString())

    Catch ex As Exception
        Label2.Text = ("Error: " + ex.ToString())

    Finally
        mq.Close()

    End Try

End Sub

And the result is successful...where by I can see the message in the queue...but i'm not sure of the XML encoding...and i need to send the message in UTF-8, furthermore i can't figure out how to send those message to be UTF-8 into the Queue...
Please help..

A: The Encoding can be altered with the use of the encoding-class.
Dim value As Encoding

value = Encoding.UTF8

More about using that with UFT8 can be read here in the MSDN.


text:
Q: how can i set the alias of column`s sum value based on another column in same table in sql? I have a table of Accounts, having columns:
Acc_Id, Transaction_TypeId, Amount
I want to get result as When Transaction_TypeId = 1 then Sum of Amount as 'Total Advance Payments'.
Else when Transaction_typeId = 2 then Sum of Amount as 'Total Reciepts'
Here is my SQL query:
SELECT SUM(Amount) AS 'Sum' , Transaction_TypeId INTO #temp1  FROM AccountDetailTable WHERE  Account_MasterId = 1 GROUP BY Transaction_TypeId

SELECT Sum as 'Total Advance' from #temp1  WHERE #temp1.Transaction_TypeId = 1;
SELECT Sum as 'Total Cash Receipts' FROM #temp1  WHERE #temp1.Transaction_TypeId = 2;

DROP TABLE #temp1;

but this query returns me two different result sets. How can i get the values in same result sets?

A: Use a CASE expression:
SELECT  SUM(CASE WHEN Transaction_TypeId = 1 THEN somecolumn END) as [Total Advance],
        SUM(CASE WHEN Transaction_TypeId = 2 THEN somecolumn END) as [Total Cash Receipts]
FROM #temp1;

A: You should use CASE EXPRESSION like this:
SELECT
       sum(case when #temp1.Transaction_TypeId = 1 then amount else 0 end) as 'Total Advance',
       sum(case when #temp1.Transaction_TypeId = 2 then amount else 0 end) as 'Total Cash Receipts'
FROM #temp1


text:
Q: RESTful Authentication via Spring Problem:
We have a Spring MVC-based RESTful API which contains sensitive information. The API should be secured, however sending the user's credentials (user/pass combo) with each request is not desirable. Per REST guidelines (and internal business requirements), the server must remain stateless. The API will be consumed by another server in a mashup-style approach.
Requirements:

*

*Client makes a request to .../authenticate (unprotected URL) with credentials; server returns a secure token which contains enough information for the server to validate future requests and remain stateless. This would likely consist of the same information as Spring Security's Remember-Me Token.

*Client makes subsequent requests to various (protected) URLs, appending the previously obtained token as a query parameter (or, less desirably, an HTTP request header).

*Client cannot be expected to store cookies.

*Since we use Spring already, the solution should make use of Spring Security.
We've been banging our heads against the wall trying to make this work, so hopefully someone out there has already solved this problem.
Given the above scenario, how might you solve this particular need?

A: Regarding tokens carrying information, JSON Web Tokens (http://jwt.io) is a brilliant technology. The main concept is to embed information elements (claims) into the token, and then signing the whole token so that the validating end can verify that the claims are indeed trustworthy.
I use this Java implementation: https://bitbucket.org/b_c/jose4j/wiki/Home
There is also a Spring module (spring-security-jwt), but I haven't looked into what it supports.

A: Why don't you start using OAuth with JSON WebTokens
http://projects.spring.io/spring-security-oauth/
OAuth2 is an standardized authorization protocol/framework. As per Official OAuth2 Specification:
You can  find more info here

A: You might consider Digest Access Authentication.  Essentially the protocol is as follows:

*

*Request is made from client

*Server responds with a unique nonce string

*Client supplies a username and password (and some other values) md5 hashed with the nonce; this hash is known as HA1

*Server is then able to verify client's identity and serve up the requested materials

*Communication with the nonce can continue until the server supplies a new nonce (a counter is used to eliminate replay attacks)

All of this communication is made through headers, which, as jmort253 points out, is generally more secure than communicating sensitive material in the url parameters.
Digest Access Authentication is supported by Spring Security.  Notice that, although the docs say that you must have access to your client's plain-text password, you can successfully authenticate if you have the HA1 hash for your client.

A: We managed to get this working exactly as described in the OP, and hopefully someone else can make use of the solution. Here's what we did:
Set up the security context like so:
<security:http realm="Protected API" use-expressions="true" auto-config="false" create-session="stateless" entry-point-ref="CustomAuthenticationEntryPoint">
    <security:custom-filter ref="authenticationTokenProcessingFilter" position="FORM_LOGIN_FILTER" />
    <security:intercept-url pattern="/authenticate" access="permitAll"/>
    <security:intercept-url pattern="/**" access="isAuthenticated()" />
</security:http>

<bean id="CustomAuthenticationEntryPoint"
    class="com.demo.api.support.spring.CustomAuthenticationEntryPoint" />

<bean id="authenticationTokenProcessingFilter"
    class="com.demo.api.support.spring.AuthenticationTokenProcessingFilter" >
    <constructor-arg ref="authenticationManager" />
</bean>

As you can see, we've created a custom AuthenticationEntryPoint, which basically just returns a 401 Unauthorized if the request wasn't authenticated in the filter chain by our AuthenticationTokenProcessingFilter.
CustomAuthenticationEntryPoint:
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException authException) throws IOException, ServletException {
        response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized: Authentication token was either missing or invalid." );
    }
}

AuthenticationTokenProcessingFilter:
public class AuthenticationTokenProcessingFilter extends GenericFilterBean {

    @Autowired UserService userService;
    @Autowired TokenUtils tokenUtils;
    AuthenticationManager authManager;

    public AuthenticationTokenProcessingFilter(AuthenticationManager authManager) {
        this.authManager = authManager;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        @SuppressWarnings("unchecked")
        Map<String, String[]> parms = request.getParameterMap();

        if(parms.containsKey("token")) {
            String token = parms.get("token")[0]; // grab the first "token" parameter

            // validate the token
            if (tokenUtils.validate(token)) {
                // determine the user based on the (already validated) token
                UserDetails userDetails = tokenUtils.getUserFromToken(token);
                // build an Authentication object with the user's info
                UsernamePasswordAuthenticationToken authentication =
                        new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails((HttpServletRequest) request));
                // set the authentication into the SecurityContext
                SecurityContextHolder.getContext().setAuthentication(authManager.authenticate(authentication));
            }
        }
        // continue thru the filter chain
        chain.doFilter(request, response);
    }
}

Obviously, TokenUtils contains some privy (and very case-specific) code and can't be readily shared. Here's its interface:
public interface TokenUtils {
    String getToken(UserDetails userDetails);
    String getToken(UserDetails userDetails, Long expiration);
    boolean validate(String token);
    UserDetails getUserFromToken(String token);
}

That ought to get you off to a good start.


text:
Q: XAdES validation fails with Reference URI="" for document with stylesheet processing instruction The document I am signing looks like this.
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="CDA_PL_IG_1.3.1.xsl" type="text/xsl"?>
<ClinicalDocument></ClinicalDocument>

I am using xadesjs to sign this XML with the following code:
const crypto = new Crypto();
xadesjs.Application.setEngine('NodeJS', crypto);

export async function sign(xml: string, { publicKey, privateKey }: any) {
    const hash = 'SHA-1';
    const alg = {
        name: 'RSASSA-PKCS1-v1_5',
        hash
    };
    const keyDer = pem2der(privateKey.toString());
    const key = await crypto.subtle.importKey('pkcs8', keyDer, alg, true, [ 'sign' ]);
    const parsed = xadesjs.Parse(xml.trim());
    const xadesXml = new xadesjs.SignedXml();
    const signature = await xadesXml.Sign(alg, key, parsed, {
        signingCertificate: preparePem(publicKey.toString()),
        references: [ { uri: '', hash, transforms: [ 'enveloped' ] } ],
        x509: [ preparePem(publicKey.toString()) ]
    });

    parsed.documentElement.appendChild(signature.GetXml()!);
    return parsed.toString();
}

function preparePem(pem: string) {
    return pem.replace(/-----(BEGIN|END)[\w\d\s]+-----/g, '').replace(/[\r\n]/g, '');
}

function pem2der(pem: string) {
    pem = preparePem(pem);
    return new Uint8Array(Buffer.from(pem, 'base64')).buffer;
}

The generated signature is valid only if I remove the xml declaration and stylesheet instruction. So only signing this returns a correctly signed document:
<ClinicalDocument></ClinicalDocument>

Signing this
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="CDA_PL_IG_1.3.1.xsl" type="text/xsl"?>
<ClinicalDocument></ClinicalDocument>

errors with message saying that not the entire document is signed.
I assume the problem is with the URI="" reference. It signs only the <ClinicalDocument> and leaves the <?xml version> and <?xml-stylesheet> with no signature.
How do I sign everything?

A: You need to canonicalize (C14N) the document before you sign it. I cannot comment on using xadesjs but here is some general advice.
For a Xades signature you need to compute a message digest over three parts, all of them C14N-ed.
(1) the full document excluding the ds:Signature element - this gives you the digest value for the URI="" reference.
(2) The subset of the xades:SignedProperties element, which needs to inherit any namespaces from the full document. This gives the digest value for the SignedProperties reference.
(3) The final subset of the ds:SignedInfo element, which again needs to include inherited namespaces - this value is used indirectly to compute the signature value.
The <?xml version> is always excluded. The <?xml-stylesheet> is included when computing the digest value for the enveloped-signature (with reference URI="") but is excluded when C14N-ing over the two subsets.
Computing the C14n transformation is not trivial. I will plug my own canonicalization utility here, SC14N https://www.cryptosys.net/sc14n/.
You can generate the digest values directly as follows:
sc14n -d -x ds:Signature clindoc.xml
sc14n -d -s xades:SignedProperties clindoc.xml
sc14n -d -s ds:SignedInfo clindoc.xml

To see the C14N-ed output, omit the -d option
sc14n  -x ds:Signature clindoc.xml
<?xml-stylesheet href="CDA_PL_IG_1.3.1.xsl" type="text/xsl"?>
<ClinicalDocument ...>

Note that the <xml-stylesheet line is included on a line of its own.


text:
Q: VMWare can't find linux headers path I'm using ubuntu 12.10 with the kernel 3.7.0-7 from xorg-edgers fresh X crack. Now when I try to launch wmware workstation it asks for linux header path like shown here. I tried all the solutions on that page but nothing works...
It was working before I switched to the 3.7 kernel.
Any idea what I can do to get it work?

A: To make the original answer a little clearer for other folks:
In Ubuntu 13.04 (should work in 12.10 as well), with just the kernel headers installed, you can do this:
sudo ln -s /usr/src/linux-headers-$(uname -r)/include/generated/uapi/linux/version.h /usr/src/linux-headers-$(uname -r)/include/linux/version.h

I have to do that every time I update the kernel right now.

A: First thing to check is for the availability of a newer version of VMplayer or workstation to download.
If the latest version does not work, then start looking at the error messages and try to add a link to fix the problem.
Looks like the version.h file got moved again, so adding a symlink is needed:
ln -s /usr/src/linux-3.7-rc6/include/generated/uapi/linux/version.h /usr/src/linux-3.7-rc6/include/linux/version.h

See the link http://rglinuxtech.com/2012/11/18/vmware-9-0-1-not-so-clever-after-all/
The headers have been a moving target since 3.2, and vmware does not keep up.

A: After making sure the proper Linux header files were installed for my kernel, manually creating symbolic links, installing build-essential, and basically following all advice that you linked to here, I still was receiving an error saying the path to the linux headers were invalid.
After doing a sudo apt-get update, it turns out there was a newer version of the Linux headers available than was previously reported. Upgrading the currently installed headers package to the latest version fixed the problem, and the VMWare Config Tool was able to find the headers. In my case, the packages which needed to be upgraded were linux-headers-generic-pae and linux-generic-pae.

A: If following the instruction that VMware gives you in the error messages doesn't work, you might have to re-install VMware.
I have the same problem with VirtualBox PUEL every time the kernel is updated because I installed it manually from the .deb files.  Fortunately the VBox error message includes instruction for re-running the installation script to install the right code into the kernel.
I surmise that if you use a PPA it might get around this problem by including it in the kernel each time it is updated, but I haven't tried it yet.

A: In my case, the symlink to version.h didn't work. I found that this helped on a 64-bit 13.04 system:
http://linuxg.net/how-to-install-vmware-player-5-0-2-on-ubuntu-13-04-12-10-12-04-linux-mint-15-14-13-debian-sid-wheezy-and-squeeze/
The headers package was already installed, but what seemed to make the difference was installing 'build-essential'. I then uninstalled vmplayer (running the installer with -u vmware-player does this) and reinstalled, and everything was copacetic after that.

A: I have found that with Ubuntu 14.04 the solution is very simple:
In the terminal:
sudo apt-get install build-essential linux-headers-$(uname -r)

Now run VmWare again and it will ask to rebuild and run perfectly. I do not think Smeghead needed to reinstall.


text:
Q: Hide tooltip when value is zero on amcharts5 Trying to hide all the tooltips of an XY area chart when the value is 0.
Have found a solution for amcharts4, but this is not possible for amcharts5.
The labelText key of the tooltip is a string and no function.
Solution for amcharts4: https://www.amcharts.com/docs/v4/tutorials/do-not-show-tooltip-for-zero-value-columns/
function createSeries(field: string) {
 const series = chart.series.push(
        LineSeries.new(root, {
          name,
          xAxis,
          yAxis,
          valueXField: 'timestamp',
          valueYField: field,
          categoryXField: 'timestamp',
          legendValueText: '{valueY}',
          tooltip: Tooltip.new(root, {
            pointerOrientation: 'horizontal',
            labelText: // --> this needs to be a string
              '[bold]{name}[/]\n{timestamp.formatDate()}: {field} {valueY}',
          }),
        })
      );
}

for (const key of data.keys) {
  createSeries(key);
}

DEMO
CodeSandBox

A: You can also do this with amCharts 5 using an adapter.
The following code should be inside your createSeries() function, right after the series constant declaration and initialization:
series.get("tooltip").adapters.add("visible", (visible, target) => {
  return target.dataItem?.dataContext[field] > 0;
});

Adapters are custom functions that can be used to dynamically alter value of an element's setting.

Adapters – amCharts 5 Documentation
So here we put an adapter on the series tooltip to alter its visibility. If target.dataItem exists, then we can test the value stored in dataContext for the given key. If this value is strictly positive, the Boolean expression is evaluated as true, which means that the tooltip will be visible. Otherwise, the Boolean expression is evaluated as false and the tooltip will be hidden.


text:
Q: Pivot table with count if I want to count if the number is higher than 0.1 and then group them by month-year to see which month-year has the most days with more than 0.1 variations.
I have a df like these with daily data but only showing month-year index.

table = df.pivot_table(df, columns=['btc','bnb','eth','xmr','xrp'], aggfunc=df[df > 0.1].count())

print(table)

Why not working?
The result needs to be something like this

A: You can stack the dataframe then compare the stacked frame with 0.1 to create a booolean mask then take sum on level=0 to count the values which are greater than 0.1 per month-year:
df.stack().gt(0.1).sum(level=0)

Alternate approach:
df[df > 0.1].stack().count(level=0)

EDIT: If you want to count the values which are greater than 0.1 in each of the column per month-year:
df.gt(0.1).sum(level=0)


text:
Q: local d drive run CNN to error Input 0 of layer "sequential" is incompatible with the layer I try to run it by training a simple Convolutional Neural Network (CNN) to captcha images.
training model tells me the captcha number.
but run model.fit tell me error message
ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 38, 321, 3), found shape=(None, 321, 38, 3)
python.py
IMAGEPATH = 'captcha'
dirs = os.listdir(IMAGEPATH)

images=[]
test_images=[]
train_labels=[]
train_images, train_labels = [],[]
test_labels=[]

X=[]
Y=[]

w=38
h=321
i=0

for name in dirs:
    file_paths = glob.glob(path.join(IMAGEPATH+"/"+name, '*.*'))
    for path3 in file_paths:
        try:
            img = cv2.imread(path3)
            img = cv2.resize(img, (w, h))
            im_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
            ret, im_res = cv2.threshold(im_rgb,180,255,cv2.THRESH_BINARY)
            if img is not None:
                images.append(im_res)
                test_images.append(im_res)
                name=path3.split(os.path.sep)[-1]
                getdata=(name.split('.')[-2])
                labels=getdata.split('-')[-1]
                train_labels.append(labels)
                #train_labels.append(i)
            i=i+1
        except:
            print(os.path.join(file_paths,name),"error!")
            pass

print(len(images),len(train_labels))

images=np.array(images)
train_labels==np.array(train_labels)

(X_train, X_test, Y_train, Y_test) = train_test_split(images, train_labels, test_size=0.2, random_state=0)

X_train_normalize=X_train.reshape(X_train.shape).astype("float")/255.0
X_test_normalize=X_test.reshape(X_test.shape).astype("float")/255.0

lb = LabelBinarizer().fit(Y_train)
Y_train_OneHot = lb.transform(Y_train)
Y_test_OneHot = lb.transform(Y_test)

model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(w,h,3)))
model.add(tf.keras.layers.MaxPooling2D((2, 2)))
model.add(tf.keras.layers.Conv2D(64, (3, 3), activation='relu'))
model.add(tf.keras.layers.MaxPooling2D((2, 2)))
model.add(tf.keras.layers.Conv2D(64, (3, 3), activation='relu'))

model.summary()

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

history = model.fit(X_train_normalize,
                              epochs=10
                              )

My local d drive in save twenty-four captcha images.
Path
captcha\0A3F0A\teacher-26.jpg
captcha\1673A2\teacher-24.jpg
captcha\1E82F1\teacher-25.jpg
captcha\33C958\teacher-20.jpg
captcha\33DC34\teacher-17.jpg
captcha\3AF35E\teacher-14.jpg
captcha\3B1C9E\teacher-12.jpg
captcha\4207C9\teacher-9.jpg
captcha\4B5AC4\teacher-21.jpg
captcha\4DD685\teacher-3.jpg
captcha\4E44F0\teacher-16.jpg
captcha\6BEBFE\teacher-11.jpg
captcha\6DCE49\teacher-15.jpg
captcha\6E16E9\teacher-4.jpg
captcha\c8BA540\teacher-8.jpg
captcha\949BA9\teacher-23.jpg
captcha\99F671\teacher-7.jpg
captcha\A1564D\teacher-10.jpg
captcha\A4B883\teacher-13.jpg
captcha\D27153\teacher-6.jpg
captcha\D36E65\teacher-19.jpg
captcha\DC602A\teacher-22.jpg
captcha\DDE328\teacher-18.jpg
captcha\DED2FB\teacher-2.jpg

error message.
Showing Error
d:\OpecvImage\lookthree.py:83: UserWarning: `Model.fit_generator` is deprecated and will be removed in a future version. Please use `Model.fit`, which supports generators.
  history = model.fit_generator(X_train_normalize,
Traceback (most recent call last):
  File "d:\OpecvImage\lookthree.py", line 83, in <module>
    history = model.fit_generator(X_train_normalize,
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\engine\training.py", line 2209, in fit_generator
    return self.fit(
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\tensorflow\python\framework\func_graph.py", line 1147, in autograph_handler
    raise e.ag_error_metadata.to_exception(e)
ValueError: in user code:

    File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\engine\training.py", line 1021, in train_function  *
        return step_function(self, iterator)
    File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\engine\training.py", line 1010, in step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\engine\training.py", line 1000, in run_step  **
        outputs = model.train_step(data)
    File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\engine\training.py", line 859, in train_step
        y_pred = self(x, training=True)
    File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
        raise e.with_traceback(filtered_tb) from None
    File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\engine\input_spec.py", line 264, in assert_input_compatibility
        raise ValueError(f'Input {input_index} of layer "{layer_name}" is '

    ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 38, 321, 3), found shape=(None, 321, 38, 3)

A: i modified cv2.resize(img, (w, h)) to cv2.resize(img, (h, w))
Add Dense layers on top

model.add(tf.keras.layers.Flatten())

model.add(tf.keras.layers.Dense(512, activation='relu'))

model.add(tf.keras.layers.Dense(27))
modified Compile and train the model

model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])
history = model.fit(X_train, Y_train_OneHot, epochs=10, validation_data=(X_test, Y_test_OneHot))
Simple Code
import tensorflow as tf
from sklearn.model_selection import train_test_split
import glob
import numpy as np
import os.path as path
import os
import cv2
from sklearn.preprocessing import LabelBinarizer

IMAGEPATH = 'captcha'
dirs = os.listdir(IMAGEPATH)

images=[]
test_images=[]
train_labels=[]

w=38
h=321

for name in dirs:
    file_paths = glob.glob(path.join(IMAGEPATH+"/"+name, '*.*'))
    for path3 in file_paths:
        try:
            img = cv2.imread(path3)
            img = cv2.resize(img, (h, w))
            im_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
            ret, im_res = cv2.threshold(im_rgb,180,255,cv2.THRESH_BINARY)
            if img is not None:
                images.append(im_res)
                test_images.append(im_res)
                name=path3.split(os.path.sep)[-1]
                getdata=(name.split('.')[-2])
                labels=getdata.split('-')[-1]
                getint=int(labels)
                train_labels.append(getint)
        except:
            print(os.path.join(file_paths,name),"error!")
            pass

print(len(images),len(train_labels))

images=np.array(images)
train_labels==np.array(train_labels)

(X_train, X_test, Y_train, Y_test) = train_test_split(images, train_labels, test_size=0.2, random_state=0)

X_train_normalize=X_train.reshape(X_train.shape).astype("float")/255.0
X_test_normalize=X_test.reshape(X_test.shape).astype("float")/255.0

lb = LabelBinarizer().fit(Y_train)
Y_train_OneHot = lb.transform(Y_train)
Y_test_OneHot = lb.transform(Y_test)

model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(w,h,3)))
model.add(tf.keras.layers.MaxPooling2D((2, 2)))
model.add(tf.keras.layers.Conv2D(64, (3, 3), activation='relu'))
model.add(tf.keras.layers.MaxPooling2D((2, 2)))
model.add(tf.keras.layers.Conv2D(64, (3, 3), activation='relu'))

model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(512, activation='relu'))
model.add(tf.keras.layers.Dense(27))

model.summary()

model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])

history = model.fit(X_train, Y_train_OneHot, epochs=10, validation_data=(X_test, Y_test_OneHot))


text:
Q: What is the advantage of Dual-Band Wireless? I've been looking around for a good wireless router, and I've been seeing a lot of dual-band routers, but everyone I've asked at the stores seems to give me a different answer as to what it actually does. So I'd like to ask the wireless gurus over here at SU, what are the advantages and disadvantages to using the cliche dual-band wireless routers?

A: 802.11b and 802.11g both use the same frequency band, 2.4Ghz. 802.11n can also use the 5Ghz frequency band. By using this area as well as 2.4 you get more available channels, so potential for less interference. Also in the 5Ghz band 802.11n uses channels which are twice as large, which increases the speed.
Therefore a dual-band wireless router, which is 802.11n enabled, will give you faster bandwidth, less interference, and better reliability.


text:
Q: how can i strip http https and www. from url in mysql database I want to strip http https and www. and trailing / from a url held in a mysql database, but am having trouble formulating my query
Here's what I have so far but its not working.  The query doesnt seem to be structured properly:
$checkUrl = mysql_query("SELECT DISTINCT SUBSTRING_INDEX(REPLACE(REPLACE(REPLACE(url, "http://", ""), "www.", ""), "https://","") '/', 1) FROM directory_listings WHERE url = '$url'");

if (mysql_num_rows($checkUrl) > 0) {
            //match directory.';
            }

A: $url = "http://www.yourwebsite.com";
$find = array("http://", "https://", "ftp://", "www.");
$replace = array("", "", "");

$finalUrl = str_replace($find, $replace, $url);
    echo $finalUrl;
//yourwebsite.com


text:
Q: How to abend job intentionally Is it possible to abend your job intentionally through COBOL program.
suppose I have an Input file having Header,Detail and Trailer records. I will write a COBOL pgm which reads this file.If no Detail records are found in this file then I want to abend my job by giving some Abend Message and some Abend Code.Is it Possible?

A: Do you want to ABEND your program or just set a RETURN-CODE?
I suspect setting a RETURN-CODE, writing a message
and then terminating the program via a STOP RUN or GOBACK is all that
you really want to do. Causing an actual ABEND may not be necessary.
In an IBM batch environment, the RETURN-CODE set by your program becomes the
RC for the JCL job step the program was run under. This is typically what you
want to set and test for.
The RETURN-CODE is set by MOVEing a numeric value to it. For example:
         DISPLAY 'No Detail Records found in file.'
         MOVE 16 TO RETURN-CODE
         GOBACK.

You may also issue a program dump from a program run under Language Environment (IBM
Mainframe option) using
the CEE3DMP--Generate dump
utility.
In older IBM Mainframe COBOL programs, you might see calls to the ILBOABN0 routine. This call
abended your program and issued a dump. This routine is now depreciated in favour of the
technique outlined above.
Finally, really old programs might have code in them to generate abends. This can be done in any number of ways, but division by zero was
often a favourite:
        DIVIDE SOME-NUMBER BY ZERO GIVING SOME-NUMBER.

Works every time!
Personally, I recommend setting the RETURN-CODE over calling ILBOABN0 or data-exception tehcniques.
Note: The RETURN-CODE special-register is not part of the COBOL-85 standard. It is available as an IBM extention to the language. You may need to resort to a different mechanism if you are working in a non-IBM compatible environment.

A: see the following link on how to set the return code passed back to a JCL job step as well as force an Abened code.
http://www.tek-tips.com/viewthread.cfm?qid=1058302&page=22

A: First, you should check what is accepted by your own shop's/site's working standards. Most teams will already have an accepted way to deliberately abend a program for a 'logic' reason. One company I worked at has a very simple program called SYSABND2, which I believe is written in assembler, which is called just to abend the program.
That said, to ABEND (not just set return code), you should call module CEE3ABD (or previous version ILBOABN0, which is now deprecated).
For details, see:

*

*https://www.ibm.com/support/knowledgecenter/SSLTBW_2.4.0/com.ibm.zos.v2r4.ceea300/clcdump.htm

*http://publib.boulder.ibm.com/infocenter/zvm/v5r4/index.jsp?topic=/com.ibm.zos.r9.ceea400/ceea4150320.htm

A: One method for doing an abnormal end of run is to output a message to the user terminal or to the operator at a mainframe computer centre and possibly to a printer if necessary, all depending on the type of computer the program is to be run on. In cobol it is possible to use DISPLAY UPON .. and use an identifier for the terminal, operator console, or printer as defined in an entry in the SPECIAL-NAMES section of the ENVIRONMENT DIVISION. An example may be similar to this using the correct device names for your case
OPERATOR-CONSOLE IS OUT-OP2 in special-names with DISPLAY "RUN ERROR - NO DETAIL RECORDS, ABORTING" UPON OUT-OP2 and
DISPLAY "REPORT TO OPERATIONS MANAGER" UPON OUT-OP2 and STOP RUN. in procedure division.
A reference to the circumstance would need to be included in any job or macro and operating instructions.

A: Yes, it is possible to abend your job intentionally through COBOL program by simply calling one module which doesn't exist. It will give S806 abend code.


text:
Q: Convert System.Linq.IOrderedEnumerable to List .NET compiler will not implicitly convert System.Linq.IOrderedEnumerable<T> to System.Collections.Generic.List<T>
An explicit cast:
using System.Collections.Generic;

var items = new List<MyType>;

var selectedItems =
  from item in items
  where item.Active
  select item;

return (List<MyType>)selectedItems;

gives this warning:

Suspicious cast: there is no type in the solution which inherits from
both System.Linq.IOrderedEnumerable and
System.Collections.Generic.List

What is best practice here?

A: Use the System.Linq.Enumerable.ToList<T>() extension:
selectedItems.ToList();

A: Simply use the ToList extension:
return selectedItems.ToList();

You should be aware though: best practice (since you asked) would actually want you to return an IEnumerable<MyType> in most cases. Therefore, you may want to change your signature in this way:
public IEnumerable<MyType> MyFunction()
{
    // your code here
}

And THEN, if you need to, have the function's result in a list:
var myList = MyFunction().ToList();

Unless you have a very precise reason of returning a List<> type, I strongly suggest that you don't.
Hope that helps.


text:
Q: Melt multiple columns into only two columns I have a dataframe that looks like this :

id
date1
date2
cond1
cond2

1
a
1
One
Two

2
b
2
One
Two

2
c
3
One
Two

4
d
4
One
Two

5
e
5
One
Two

But i want to melt date1 and date2 values into one column and con1 and cond2 into one column as well ! I tried using melt but i couldn't apply it to generate multiple columns at once ! is there a way to do that?


text:
Q: HTML agility pack is adding unnecessary string to the outer html I am trying to remove class, style and such attributes from given tagged string
for example string is
<math>K_B \cap\left \{ |k| < \beta\right \} </math>

Once i load it to the HtmlDocument it becomes as below
<math>K_B \cap\left \{ |k| < \beta\right="" \}=""></math>

How can I prevent this behavior from happening? Because this behavior is breaking my code
My aim is for example if string is like below
<math style="gg" class="cg" >K_B \cap\left \{ |k| < \beta\right \} </math>

Turning it like below
<math>K_B \cap\left \{ |k| < \beta\right \} </math>


text:
Q: Async Await deadlock I'm working with the Accelerometer sensor on Windows Phone 8.1. I must access the UI from the ReadingChanged callback of the sensor. I also have a DispatcherTimer that, every two seconds, updates the ReportInterval of the sensor. The program blocks when the timer fires and try to set the ReportInterval of the Accelerometer. The example here below is a minimum executable example that reproduces the error.
namespace TryAccelerometer
{
    public sealed partial class MainPage : Page
    {
        private Accelerometer acc;
        private DispatcherTimer timer;
        private int numberAcc = 0;
        private int numberTimer = 0;

        public MainPage()
        {
            this.InitializeComponent();
            this.NavigationCacheMode = NavigationCacheMode.Required;

            acc = Accelerometer.GetDefault();
            acc.ReadingChanged += acc_ReadingChanged;

            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(2);
            timer.Tick += timer_Tick;
            timer.Start();
        }

        async void acc_ReadingChanged(Accelerometer sender, AccelerometerReadingChangedEventArgs args)
        {
            await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                //HERE I WILL HAVE TO ACCESS THE UI, BUT FOR SAKE OF SIMPLICITY I WROTE AN INCREMENT
                numberAcc++;
            });
        }

        void timer_Tick(object sender, object e)
        {
            numberTimer++;
            //PUT A BREAKPOINT HERE BELOW AND SEE THAT THE PROGRAM BLOCKS
            acc.ReportInterval = acc.ReportInterval++;
        }
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.
        /// This parameter is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // TODO: Prepare page for display here.

            // TODO: If your application contains multiple pages, ensure that you are
            // handling the hardware Back button by registering for the
            // Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
            // If you are using the NavigationHelper provided by some templates,
            // this event is handled for you.
        }
    }
}

I don't understand why the deadlock happens. Thank you in advance.

A: Well I'm stumped.
Dispatcher.RunAsync shouldn't possibly cause a deadlock. Therefore, to find out where exactly the issue is, I rewrote your code on multiple lines:
async void acc_ReadingChanged(Accelerometer sender, AccelerometerReadingChangedEventArgs args)
{
    var view = Windows.ApplicationModel.Core.CoreApplication.MainView;

    var window = view.CoreWindow;

    var dispatcher = window.Dispatcher;

    await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { numberAcc++; });
}

The real culprit is var window = view.CoreWindow;. It's hard to explain why without seeing the WinRT source code, I guess there is some weird interaction between WinRT needing to switch to the UI thread to retrieve the reference to the window, and the ReportInterval property of the Accelerometer executing synchronously the ReadingChanged event.
From there, I can think of a few solutions:

*

*Retrieve the dispatcher another way:
async void acc_ReadingChanged(Accelerometer sender, AccelerometerReadingChangedEventArgs args)
{
    await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { numberAcc++; });
}

Of course, whether it's possible or not depends on your actual code.

*Rewrite your code to use a Timer instead of a DispatcherTimer. I understand that you need to use the UI thread to retrieve the value of a textbox (or something like that), but if you use databinding (with or without the MVVM pattern), then you should be able to access the read the value of the bound property from any thread

*Change the ReportInterval in another thread. Feels really hackish though.
void timer_Tick(object sender, object e)
{
    numberTimer++;
    Task.Run(() => { acc.ReportInterval = acc.ReportInterval++; });
}

A: According to the @KooKiz explanation and the @StephenCleary comment I found another possible solution. Since we have understood that the problem is here:
var window = view.CoreWindow;

we can cache the dispatcher saving it as an instance variable. Doing so, we avoid to access it at the same time of the timer:
namespace TryAccelerometer
{
    public sealed partial class MainPage : Page
    {
        private Accelerometer acc;
        private DispatcherTimer timer;
        private int numberAcc = 0;
        private int numberTimer = 0;
        private CoreDispatcher dispatcher;

        public MainPage()
        {
            this.InitializeComponent();
            this.NavigationCacheMode = NavigationCacheMode.Required;

            dispatcher = Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher;

            acc = Accelerometer.GetDefault();
            acc.ReadingChanged += acc_ReadingChanged;

            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(2);
            timer.Tick += timer_Tick;
            timer.Start();
        }

        async void acc_ReadingChanged(Accelerometer sender, AccelerometerReadingChangedEventArgs args)
        {
            await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                numberAcc++;
            });
        }

        void timer_Tick(object sender, object e)
        {
            numberTimer++;
            acc.ReportInterval = acc.ReportInterval++;
            //acc.ReadingChanged -= acc_ReadingChanged;
        }
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.
        /// This parameter is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // TODO: Prepare page for display here.

            // TODO: If your application contains multiple pages, ensure that you are
            // handling the hardware Back button by registering for the
            // Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
            // If you are using the NavigationHelper provided by some templates,
            // this event is handled for you.
        }
    }
}

This way the deadlock doesn't happen.

A: I created this extension after having deadlock issues on WinRT, and it solved my problems (so far):
using global::Windows.ApplicationModel.Core;
using global::Windows.UI.Core;

public static class UIThread
{
    private static readonly CoreDispatcher Dispatcher;

    static DispatcherExt()
    {
        Dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher;
    }

    public static async Task Run(DispatchedHandler handler)
    {
        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, handler);
    }
}

Usage
public async Task Foo()
{
    await UIThread.Run(() => { var test = 0; });
}


text:
Q: How do I solve a for-each not applicable to expression type? The removePanel () is used to get the components in the mainPanel using getComponent () and an enhanced loop. Then check which components are visible & call the removeLayoutComponent () on that component.
THIS IS THE REMOVEJPANEL METHOD
public void removeJPanel () {
 for (Component comp : mainPanel.getComponent (number)) {
    if (comp.isVisible () == true) {
        card.removeLayoutComponent (comp);
        number++;
    } else {
      System.out.print("It didn't work!");
    }
 }
}

mainPanel uses a card layout, JPanels from the panel array are then added onto mainPanel.
THIS IS THE CODE WHERE I CREATE THE MAINPANEL & ADD JPANELS ONTO IT
public TicTacToeFrame () {
 if (badge.num == 0) {
   playerX = JOptionPane.showInputDialog ("Enter Player X name: ");
   playerO = JOptionPane.showInputDialog ("Enter Player O name: ");
   badge.setLabel (playerX);
 }
   mainPanel = new JPanel ();//THIS IS WHERE I CREATE MAINPANEL
   mainPanel.setLayout (card);//THIS IS WHERE CARDLAYOUT IS SET AS LAYOUT MANAGER
   panels [0] = new JPanel (new GridLayout (3, 3, 0, 0));
   panels [1] = new JPanel (new GridLayout (3, 3, 0, 0));
   panels [2] = new JPanel (new GridLayout (3, 3, 0, 0));
   JPanelArray ();

   panels [0].setBorder (new LineBorder (Color.red, 1));
   panels [1].setBorder (new LineBorder (Color.red, 1));
   panels [2].setBorder (new LineBorder (Color.red, 1));

   mainPanel.add (panels [0], "one");//JPANELS FROM THE PANEL ARRAY ARE ADDED TO THE MAINPANEL
   mainPanel.add (panels [1], "two");
   mainPanel.add (panels [2], "three");

   badge.jlblStatus.setBorder (new LineBorder (Color.yellow, 1));

   add (mainPanel, BorderLayout.CENTER);
   add (badge.jlblStatus, BorderLayout.SOUTH);
}

The expected result was for the player to click a JDialog button and for the removePanel () to be executed. Instead what happened was the current panel did not get removed & a for-each not applicable to expression type compilation error occurred.
THIS IS WHERE REMOVEJPANEL () IS CALLED
public void replayDialog () {
   int response = JOptionPane.showConfirmDialog (this, "Do you want to play again ?", "TicTacToe", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
   if (response == JOptionPane.YES_OPTION) {
       frame.removeJPanel ();
       frame.newCells = null;
       label.num++;
       frame.JPanelArray ();
   } else if (response == JOptionPane.NO_OPTION) {
        frame.gameOver = true;
   }
}

COMPILATION ERROR
.\TicTacToeFrame.java:139: error: for-each not applicable to expression type
     for (Component comp : mainPanel.getComponent (number)) {
                                              ^
 required: array or java.lang.Iterable
 found:    Component
1 error

I found this foreach not applicable to expression type on this site, but this doesn't meet my needs as I struggled to understand what was on the page since I am still a beginner in java.

A: The JPanel.getComponent(int) just returns one component, the one at the location for the index you pass in.  If you want to iterate over all the components in the JPanel you can use JPanel.getComponents, like this:
public void removeJPanel () {
 Component[] components : mainPanel.getComponents();
 for (int i = 0; i < components.length; i++) {
    Component comp = components[i];
    if (comp.isVisible () == true) {
        card.removeLayoutComponent (comp);
        number++;
    } else {
      System.out.print("It didn't work!");
    }
 }
}


text:
Q: nextpage break redesign for wordpress How do I change the next page tab in wordpress so instead of it showing Next, Previous ect that it shows simply one bar that says Continue, this then goes to the next page.
I cant find this information anywhere


text:
Q: What does the symbol :=: mean (colon equals colon) I've found the symbol :=: in some Clarion code and I can't seem to figure out exactly what it does.  The code was written by a previous developer many years ago, so I can't ask him.  I also have not been able to find any results for "colon equals colon" in Google.
Here is an example of the code, where bufSlcdpaDtl is a file object:
lCCRecord Like(bufSlcdpaDtl),Pre(lCCRecord)

! ...other stuff...

lCCRecord :=: bufSlcdpaDtl

I'm wondering if it's something similar to ::= in Python or possibly the assignment operator :=.

A: In the language reference manual on page 561 This is called the Deep assignment operator. The syntax is destination :=: source. Destination can be a label of a GROUP, RECORD, QUEUE ds or an array. The source can be the same plus a numeric, string const, variable, procedure, or expression. It will perform multiple individual component variable assignments from one ds to another. More information can be found in that document as well as the apparent home of clarion: http://www.softvelocity.com/
A great example of what the Deep Assignment operator does:
Group1 GROUP
    S    SHORT
    L    LONG
END

Group2 GROUP
    L    SHORT
    S    REAL
    T    LONG
END

ArrayField SHORT,DIM(1000)

CODE

Group2 :=: Group1   ! Is equivalent to:
                    !     Group2.S = Group1.S
                    !     Group2.L = Group1.L
                    ! and performs all necessary data conversion

ArrayField :=: 7    ! Is equivalent to:
                    !     LOOP I# = 1 to 1000
                    !         ArrayField[I#] = 7
                    !     END


text:
Q: PHP new page redirect What I am trying to do is
On "Page 1", user fills a form, and when he clicks on "Submit",
a new page, say "Page 2" should get automatically created (in the same folder as index.php) in such a way that name of the page is say first_name.php (what the user filled on page 1) and it should display the contents of what he filled in on the first page.
Something like showed in the figure.

A: showName.php:
<?php

   echo "    Your name is {$_REQUEST['name']}";

?>

This is under the assumption that your form contains an input with  name=name
So a form like this:
<form action="showName.php">
   Enter your name: <input name="name" />
</form>

Eventually you might want some validation on the submit, but for now this should suit for what you want to do.

Update:
I read your question more carefully --
You should NEVER do what you proposed it could lead all kinds of attacks and hacks on your site.
You could use a mod-rewrite to seem as if the page went to john.php but really it is showing showName.php?name=john

A: No, you should never do this. Say if this were off your main site, and I were to do something like "../../../etc/passwd%00" as my name, I could rewrite your etc/passwd file, or any other system file. Also, this would make you vulnerable to something called cross site scripting, also known as XSS.

A: Heheh, OP, I am reiterating the advices of the above 2 posters. Never do this. He could even post a CGI exploit. Use mod_rewrite.


text:
Q: How to set time zone for calendar event programmatically? In android app, while inserting calendar event, how to set time zone for that inserting calendar event. Any help is really appreciated and thanks in advance...

A: you can create a Calender instance.
 public static Date getDate(Date date,TimeZone zone){

   Calendar cal= Calendar.getInstance(zone);
    cal.setTimeInMillis(date.getTime());

    Calendar output = Calendar.getInstance();

    output.set(Calendar.DAY_OF_MONTH, first.get(Calendar.DAY_OF_MONTH));
    output.set(Calendar.MONTH, first.get(Calendar.MONTH));
    output.set(Calendar.YEAR, first.get(Calendar.YEAR));
    output.set(Calendar.HOUR_OF_DAY, first.get(Calendar.HOUR_OF_DAY));
    output.set(Calendar.MINUTE, first.get(Calendar.MINUTE));
    output.set(Calendar.SECOND, first.get(Calendar.SECOND));
    output.set(Calendar.MILLISECOND, first.get(Calendar.MILLISECOND));

    return output.getTime();

}


text:
Q: How to print stacktrace for an exception Android I want to print the stack trace because at the moment I have this running.
} catch (IOException e) {
    throw new Error("Copying Failed");
}

And I have been told to print e.stacktrace();
How do I do this?

A: } catch (IOException e) {
    Log.e("YOUR_APP_LOG_TAG", "I got an error", e);
}

And check the LogCat for the output.

A: An other method, very useful :
try
{
...
}
catch (Exception e)
{
    Log.e(APP_TAG, "STACKTRACE");
    Log.e(APP_TAG, Log.getStackTraceString(e));
}

A: In Android you should use the log methods that work nicely with the Logcat log viewer used by Android.
} catch (IOException e) {
   Log.e("YOUR ERROR TAG HERE", "Copying failed", e);
}

Using the Log.e method that takes a throwable as an argument you make sure that the log class will take the stacktrace and log it correctly to Logcat. If you use e.printStackTrace this will use the general Java logging methods and it will not appear correctly in Logcat and in some cases it will not be possible to double click on a class name in logcat to jump into the  class and method mentioned in the stacktrace.
Print Stacktrace for a divide by zero will look like this:
11-21 20:55:47.360: W/System.err(989): java.lang.ArithmeticException: divide by zero
11-21 20:55:47.379: W/System.err(989):  at test.tabs.TabChooser.onCreate(TabChooser.java:15)
11-21 20:55:47.390: W/System.err(989):  at android.app.Activity.performCreate(Activity.java:4465)
11-21 20:55:47.410: W/System.err(989):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
11-21 20:55:47.410: W/System.err(989):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
11-21 20:55:47.420: W/System.err(989):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
11-21 20:55:47.420: W/System.err(989):  at android.app.ActivityThread.access$600(ActivityThread.java:122)
11-21 20:55:47.420: W/System.err(989):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
11-21 20:55:47.420: W/System.err(989):  at android.os.Handler.dispatchMessage(Handler.java:99)
11-21 20:55:47.420: W/System.err(989):  at android.os.Looper.loop(Looper.java:137)
11-21 20:55:47.420: W/System.err(989):  at android.app.ActivityThread.main(ActivityThread.java:4340)
11-21 20:55:47.430: W/System.err(989):  at java.lang.reflect.Method.invokeNative(Native Method)
11-21 20:55:47.430: W/System.err(989):  at java.lang.reflect.Method.invoke(Method.java:511)
11-21 20:55:47.430: W/System.err(989):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
11-21 20:55:47.430: W/System.err(989):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
11-21 20:55:47.430: W/System.err(989):  at dalvik.system.NativeStart.main(Native Method)

The exception is logged as a warning and the log tag is not very helpful.
Correct logging of a divide by zero will look like this:
11-21 21:03:32.480: E/YOUR ERROR TAG HERE(1356): Copying failed
11-21 21:03:32.480: E/YOUR ERROR TAG HERE(1356): java.lang.ArithmeticException: divide by zero
11-21 21:03:32.480: E/YOUR ERROR TAG HERE(1356):    at test.tabs.TabChooser.onCreate(TabChooser.java:16)
11-21 21:03:32.480: E/YOUR ERROR TAG HERE(1356):    at android.app.Activity.performCreate(Activity.java:4465)
11-21 21:03:32.480: E/YOUR ERROR TAG HERE(1356):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
11-21 21:03:32.480: E/YOUR ERROR TAG HERE(1356):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
11-21 21:03:32.480: E/YOUR ERROR TAG HERE(1356):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
11-21 21:03:32.480: E/YOUR ERROR TAG HERE(1356):    at android.app.ActivityThread.access$600(ActivityThread.java:122)
11-21 21:03:32.480: E/YOUR ERROR TAG HERE(1356):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
11-21 21:03:32.480: E/YOUR ERROR TAG HERE(1356):    at android.os.Handler.dispatchMessage(Handler.java:99)
11-21 21:03:32.480: E/YOUR ERROR TAG HERE(1356):    at android.os.Looper.loop(Looper.java:137)
11-21 21:03:32.480: E/YOUR ERROR TAG HERE(1356):    at android.app.ActivityThread.main(ActivityThread.java:4340)
11-21 21:03:32.480: E/YOUR ERROR TAG HERE(1356):    at java.lang.reflect.Method.invokeNative(Native Method)
11-21 21:03:32.480: E/YOUR ERROR TAG HERE(1356):    at java.lang.reflect.Method.invoke(Method.java:511)
11-21 21:03:32.480: E/YOUR ERROR TAG HERE(1356):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
11-21 21:03:32.480: E/YOUR ERROR TAG HERE(1356):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
11-21 21:03:32.480: E/YOUR ERROR TAG HERE(1356):    at dalvik.system.NativeStart.main(Native Method)

The exception is correctly logged as an error with your log tag and log message.

A: } catch (IOException e) {
    e.printStackTrace();
}

A: It is most likely you were requested to print the stack trace via e.printStackTrace();...
} catch (IOException e) {
    e.printStackTrace();
    throw new Error("Copying Failed");
}


text:
Q: using recursion error. Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 The Program I am trying to write will count the amount of "A"'s within a given string using recursion. What it should do is count how many times the program recurses itself. The Program compiles correctly but when run I am given this error
class hw10

{
public static void main(String[] args)
{
    System.out.println(f(""))
    System.out.println(f("A"));
    System.out.println(f("B"));
    System.out.println(f("BCA"));
    System.out.println(f("ABC"));
    System.out.println(f("ABACAD"));

}

public static int f(String s)
{

    if(s.length() <= 0)
    {
        if(s.charAt(0) == 'A')
        {
            return 1;
        }
        else
        {
            return 0;
        }

    }
    else
    {
        if(s.charAt(0) == 'A')
        {
            return 1 + f(s.substring(1));
        }
        else
        {
            return f(s.substring(1));
        }
    }

}

}
This is the full message
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
        at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:47)
        at java.base/java.lang.String.charAt(String.java:702)
        at hw10.f(hw10.java:20)
        at hw10.f(hw10.java:35)
        at hw10.main(hw10.java:7)

A: recursivity lead to short code
try this :
        public static int f(String s) {
          if(s.length() == 0) return 0;
          if(s.charAt(0) == 'A') return (1 + f(s.substring(1)));
          return f(s.substring(1));
    }


text:
Q: JQuery: Click on div text to set input field value I am trying to use jquery to set the input field value to the text inside the option field when the user clicks on it. This will require keeping record of the last input field that was focused on, so I can later set its value when the user click on an 'option'.
Markup

apples

oranges

pears

<input type="text" value="default" class="fruit-name"/>
<input type="text" value="default" class="fruit-name"/>
<input type="text" value="default" class="fruit-name"/>

JQuery (With pseudo code)
$(document).ready(function(){
   $('.fruit-name').click(function(){
      $('.option').click(function(){
           $((this)(fruit-name)).val($((this)(option)).text());

      });

});

A: $(document).ready(function() {
    var $option = $('.option'),
        $fruit = $('.fruit-name'),
        $last;

    $fruit.focus(function() {
        $last = $(this);
    })

    $option.click(function() {
        $last.val(this.innerHTML)
    })
});

http://jsfiddle.net/jgBxs/


text:
Q: nopcommerce pulling images from news page Hi I'm new to NopCommerce, but I need some help, I'm currently doing some work on the news list page and I'm wondering is there any code that will need to be added to pull any images that are on the actual news page. So the list page will display some of the content and a image.

A: Just to clarify, you want to display images on http://yoursitename.com/news. These images are currently available if you go to the actual news article.
I don't think there's an out of the box solution for what you want. On Views/News/List.cshtml, you'll have to retrieve the news' full description and parse the html for images.
Alternately, you can reference the image in the Short Description. Unfortunately, you'll have to write the HTML yourself instead of getting an editor the way the full description provides. But, its not too difficult. So, in the short description, put something like the following into the short description field.
<img src="https://www.google.co.uk/images/srpr/logo11w.png" /> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Of course, style accordingly using CSS.


text:
Q: Javascript URL redirect not working I have a search function here:
<form class="form-wrapper cf">
    <input type="text" placeholder="Enter keywords..">
    <button onclick="search_click();">Search</button>
</form>

search_click() is defined as follows:
function search_click(){
    window.location.replace("http://stackoverflow.com");
}

However, every time I click the button, it just reloads the current page and appends a '?' to the end of the URL if it wasn't already there.  I've tried doing window.location.href also, but that doesn't work either.  If I just replace that line with alert('test');, it does show a popup, so I know it's executing.  What's wrong with my code?  Or is this a problem with Django?

A: The form is actually submitting causing your Javascript to be ignored.  Prevent the default event using the following script:
function search_click(event){
    event.preventDefault();
    window.location.replace("http://stackoverflow.com");
}

HTML
<form class="form-wrapper cf">
    <input type="text" placeholder="Enter keywords..">
    <button onclick="search_click(event);">Search</button>
</form>


text:
Q: Invalid date en safari e IOS (ionic framework) Tengo el siguiente Json con fechas:
nuevo=[
    { "rr":"4-1-2016" }, { "rr":"4-2-2016" }, { "rr":"4-3-2016" },
    { "rr":"4-4-2016" }, { "rr":"4-5-2016" }, { "rr":"4-6-2016" },
    { "rr":"4-7-2016" }, { "rr":"4-8-2016" }, { "rr":"4-9-2016" },
    { "rr":"4-10-2016" }, { "rr":"4-11-2016" }, { "rr":"4-12-2016" },
    { "rr":"4-13-2016" }, { "rr":"4-14-2016" }, { "rr":"4-15-2016" },
    { "rr":"4-16-2016" }, { "rr":"4-17-2016" }, { "rr":"4-18-2016" },
    { "rr":"4-19-2016" }, { "rr":"4-20-2016" }, { "rr":"4-21-2016" },
    { "rr":"4-22-2016" }, { "rr":"4-23-2016" }, { "rr":"4-24-2016" },
    { "rr":"4-25-2016" }, { "rr":"4-26-2016" }, { "rr":"4-27-2016" },
    { "rr":"4-28-2016" }, { "rr":"4-29-2016" }, {"rr":"4-30-2016" },
    { "rr":"5-1-2016" },{ "rr":"5-2-2016" },{ "rr":"5-3-2016" },
    { "rr":"5-4-2016" },{ "rr":"5-5-2016"} ,{ "rr":"5-6-2016" },
    { "rr":"5-7-2016" },{ "rr":"5-8-2016" },{ "rr":"5-9-2016" },
    { "rr":"5-10-2016" },{ "rr":"5-11-2016" },{ "rr":"5-12-2016" },
    { "rr":"5-13-2016" },{ "rr":"5-14-2016" },{ "rr":"5-15-2016" },
    { "rr":"5-16-2016" },{ "rr":"5-17-2016" },{ "rr":"5-18-2016" },
    { "rr":"5-19-2016" },{ "rr":"5-20-2016" },{ "rr":"5-21-2016" },
    { "rr":"5-22-2016" },{ "rr":"5-23-2016" },{ "rr":"5-...16" },
    { "rr":"6-14-2016" },{ "rr":"6-15-2016" },{ "rr":"6-16-2016" },
    { "rr":"6-17-2016" },{ "rr":"6-18-2016" },{ "rr":"6-19-2016" },
    { "rr":"6-20-2016" },{ "rr":"6-21-2016" },{ "rr":"6-22-2016" },
    { "rr":"6-23-2016" },{ "rr":"6-24-2016" },{ "rr":"6-25-2016" },
    { "rr":"6-26-2016" },{ "rr":"6-27-2016" },{ "rr":"6-28-2016" },
    { "rr":"6-29-2016" },{ "rr":"6-30-2016" },{ "rr":"7-1-2016" },
    { "rr":"7-2-2016" },{ "rr":"7-3-2016" },{ "rr":"7-4-2016" },
    { "rr":"7-5-2016" },{ "rr":"7-6-2016" },{ "rr":"7-7-2016" },
    { "rr":"7-8-2016" },{ "rr":"7-9-2016" },{ "rr":"7-10-2016" },
    { "rr":"7-11-2016" },{ "rr":"7-12-2016" },{ "rr":"7-13-2016" },
    { "rr":"7-14-2016" },{ "rr":"7-15-2016" },{ "rr":"7-16-2016" },
    { "rr":"7-17-2016" },{ "rr":"7-18-2016" },{ "rr":"7-19-2016" },
    { "rr":"7-20-2016" },{ "rr":"7-21-2016" },{ "rr":"7-22-2016" },
    { "rr":"7-23-2016" },{ "rr":"7-24-2016" },{ "rr":"7-25-2016" },
    { "rr":"7-26-2016" },{ "rr":"7-27-2016" },{ "rr":"7-28-2016" },
    { "rr":"7-29-2016" },{ "rr":"7-30-2016" },{ "rr":"7-31-2016" },
    { "rr":"8-1-2016" },{ "rr":"8-2-2016" },{ "rr":"8-3-2016" },
    { "rr":"8-4-2016" },{ "rr":"8-5-2016" }
];

El cual convierto con moment js cada item; el resultado debe ser asi: abril-viernes-2016, abril-sabado-2016, abril-domingo-2016, etc ..... En navegadores como Chrome y en Android OS el resultado es correcto pero al mostrar el resultado en un alert en safari o IOS me da como resultado invalid date
for(var p = 0; p < nuevo.length; p++){
    alert(moment(nuevo[p].rr).format('MMMM-dddd-YYYY'));
}

Por que se da este error, que deberia hacer?
También tengo el siguiente error en consola:

Deprecation warning: moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.
  Arguments: [object Object]

A: Lo que está ocurriendo aquí es que tus fechas no están en el formato de fechas estandard ISO 8601. Moment.js usa internamente new Date() para crear las fechas y cuando le pasas un formato no estandar depende principalmente del navegador interpretar la fecha y por lo tanto en unos te funciona y en otros no.
La solución para esto es darle como formato de entradas a tus fechas el estandar aceptado que es algo como
 YYYY-MM-DDTHH:mm:ss.sssZ

Tu estas usando
M-D-YYYY

Almacena tus fechas en el formato estándard o transformalas manualmente antes de parsearlas. Te recomiendo siempre la primer variante.
Puedes leer un poco mas acerca del standard en el spec de javascript y en los siguientes links
https://stackoverflow.com/questions/4310953/invalid-date-in-safari
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse


text:
Q: GridView_RowUpdating not firing I have Gridview with ItemTemplate and EditItemTemplate:
But when i click "Ok" button, nothing happens. I tried to put trace point on RowUpdating event and click "Ok" button, but its not even triggered. I assume, that problem could be in the same "Id" of ItemTemplate and EditItemTemplate lbl_first_fl. But earlier this worked fine, the only thing was changed - i updated Visual studio to 2015 and changed Windows to 8. So i installed VS 2013, but problem still occures. Any suggestions? Or maybe how can i deal with it using different id's?
aspx page:

   <asp:GridView ID="GridView5" runat="server" AutoGenerateColumns="false" CellPadding="4" ForeColor="#333333" Height="430px" OnRowCancelingEdit="GridView5_RowCancelingEdit" OnRowDataBound="GridView5_RowDataBound" OnRowEditing="GridView5_RowEditing" OnRowUpdating="GridView5_RowUpdating" Width="100%" CssClass="gridview" GridLines="none">
                                <AlternatingRowStyle BackColor="White" ForeColor="#284775" />

                                <Columns>

  <asp:TemplateField ItemStyle-Width="100">
<EditItemTemplate>
                  <asp:Button ID="btn_Update_fl" runat="server" CommandName="Update" Text="Ок" />
<asp:Button ID="btn_Cancel_fl" runat="server" CommandName="Cancel" Text="Отмена" />
</EditItemTemplate>
<ItemTemplate>
 <asp:Button ID="btn_Edit_fl" runat="server" CommandName="Edit" Text="✎" Enabled='<%# Flag %>' />
</ItemTemplate>

</asp:TemplateField>

 <asp:TemplateField HeaderText="08:00 - 17:00" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
 <asp:Label ID="lbl_first_fl" runat="server" Text='<%# Eval("First") %>' Visible="true"></asp:Label>
 </ItemTemplate>

 <EditItemTemplate>
 <asp:Label ID="lbl_first_fl" runat="server" Text='<%# Eval("First") %>' Visible="false"></asp:Label>
 <asp:DropDownList ID="ddl_first_fl" runat="server">
</asp:DropDownList>

</EditItemTemplate>

</asp:TemplateField>

    <asp:CommandField/>

</Columns>
</asp:GridView>

OnRowUpdating event:
 protected void GridView5_RowUpdating(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
    {

        DropDownList First_fl = GridView5.Rows[e.RowIndex].FindControl("ddl_first_fl") as DropDownList;

        con = new SqlConnection(cs);
        con.Open();
        //updating the record
        SqlCommand cmd_fl = new SqlCommand("Update [Duty].[dbo].[Schedule_FirstLine] set First='" + First_fl.Text + "', con);
        cmd_fl.ExecuteNonQuery();

        con.Close();

        GridView5.EditIndex = -1;

        ShowDataFirstLine();

    }

Binding Gridview:
 protected void ShowDataFirstLine()
    {
        DateTime date = Convert.ToDateTime(Calendar1.VisibleDate.Date.ToString());

        var firstDayOfMonth = new DateTime(date.Year, date.Month, 1);
        var lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1);

        string GridDS_FirstLine = "set dateformat dmy  Select DutyDate,WeekDay,First, Second from [Duty].[dbo].[Schedule_FirstLine] WHERE DutyDate >= '" + firstDayOfMonth + "' AND DutyDate <= '" + lastDayOfMonth + "'";

        dt_FirstLine = new DataTable();
        con_FirstLine = new SqlConnection(cs);
        con_FirstLine.Open();
        adapt_FirstLine = new SqlDataAdapter(GridDS_FirstLine, con_FirstLine);
        adapt_FirstLine.Fill(dt_FirstLine);
        if (dt_FirstLine.Rows.Count > 0)
        {
            GridView5.DataSource = dt_FirstLine;
            GridView5.DataBind();
        }

        GridView5.Columns[0].Visible = true;
    }

A: You name the event on the grid like this?
<asp:GridView ID="TaskGridView" runat="server"
        AutoGenerateEditButton="True"
        AllowPaging="true"
        OnRowEditing="TaskGridView_RowEditing"
        OnRowCancelingEdit="TaskGridView_RowCancelingEdit"
        OnRowUpdating="TaskGridView_RowUpdating"
        OnPageIndexChanging="TaskGridView_PageIndexChanging">
      </asp:GridView>


text:
Q: DUDA VUE, error para escuchar evento desde un componente a la instancia principal(single file components) El problema es cuando desde un componente listaClientes uso un emit para que lo escuche la instancia principal al agregar un cliente, no logro ver el error. solo uso un this.$emit en el componente y un this.$on en la app.
asi esta listaClientes.vue

<template>

lista de clientes

        <input type="text" v-model="cliente_agregar">
        <input type="button" value="Agregar cliente" @click="agregarCliente">

          {{ cliente.nombre  }} -
          <button @click="eliminarcliente(cliente.nombre)">Eliminar</button>
          <button @click="seleccionar(cliente.nombre)">Mostrar Receta</button>

     No hay clientes agregados

</template>

y este es App.vue

<template>

    <listaClientes :listaclientes="clientes">
    </listaClientes>

       <farmacos :nombre="farmaco.nombre" :precio="farmaco.precio" v-for="(farmaco,key,value) in farmacos" ></farmacos>

    No hay farmacos agregados

</template>


text:
Q: Drupal 7 hook_menu() throws a 404 I have tried to acces it through an ajax call and by simply going to it by url,
It always give me a 404
i have flushed my caches multiple times and even tried to remove and re-add the module (as i have had the problem with other modules and read on other responses on the problem)
i also have looked it up on internet, but i can't seem to find any solution
(module name : TTK_rest)
.module:
function TTK_rest_menu() {
    $items = array();
    $items['TTK_rest_api/TTK_task_progression'] = array(
        'page callback' => 'TTK_task_progression_view',
        'access arguments' => array('access content'),
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
    );

    return $items;
}

function TTK_task_progression_view(){

    return '{"pom":"pom"}';
}

and the ajax call to it:
$.ajax({
                url:'/TTK_rest_api/TTK_task_progression',
                data: {"getProgress": "true"},//, "event_id":settings['TTK_task_progression']['jsEvent_id']
                type: "POST",
                contentType: "JSON",
                success: function(data){
                    var $data = $(data);
                    console.log(data);

                },
                error: function(err){
                    console.log("neupe, try again");
                }
            });

A: finally found the solution (posted the question after multiple hours of searching, if i've known i would have find an answer this quick i wouldn't have asked it.. still going to leave it up with a response in case there is someone with the same problem
solution to the problem was that i had to have my function name had to have the module name prefix
note: i have an other module called 'TTK_task_progression', might be the origin of the problem i had
solution:
function TTK_rest_menu() {
    $items = array();
    $items['TTK_rest_api/TTK_task_progression'] = array(
        'page callback' => 'TTK_rest_progression', // <- changed
        'access arguments' => array('access content'),
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
    );

    return $items;
}

function TTK_rest_progression(){ // <- changed

    return '{"pom":"pom"}';
}


text:
Q: Multiple 'In' operator in python arr = [1, True, 'a', 2]
print('a' in arr in arr) # False

Can you explain me why this code will output 'False'?
The question is closed.
Answer from @KlausD.: Actually it is a comparison operator chaining and will be interpreted as ('a' in arr) and (arr in arr).

A: It is False because 'a' is in 'arr' but 'arr' is not in 'arr'.
Meaning 'arr' can't be in itself.

A: I believe this is what you are trying to do:
arr = [1, True, 'a', 2]
print( 'a' in arr)

Output:
True

Or this:
arr = [1, True, 'a', 2]
print(bool(['a' in arr]) in arr)

Output:
True

A: *

*print('a' in arr in arr) // False is interpeted as print('a' in arr in arr) // 0 which throws ZeroDivisionError: integer division or modulo by zero error. If you meant to comment out the False, do it using "#", not "//" (e.g. print('a' in arr in arr) # False)

*'a' in arr in arr is read from right to left[1]: check if arr in arr (False), and then check if 'a' in False (False)

*Using @Klaus D's helpful comment - print('a' in arr in arr) is evaluated as print(('a' in arr) and (arr in arr)) due to operator chaining. This, in turn is processed into print(True and False) -> print(False)
To check if 'a' is in arr, just check print('a' in arr) # prints True
[1]  Well, not exactly. As can seen from [ In which order is an if statement evaluated in Python ], the evaluation is right to left ,so this is what actually happens: (1) check if 'a' is in "something". (2) evaluate this "something" by checking if arr in arr. (3) use the reault of said something (which is False as sadly, arr isn't a member of itslef) and check if 'a' is inside that (meaning, check if 'a' in True, which again, is False[1]


text:
Q: Convert expression to disjunctive normal form (DNF)  Problem
Convert following to DNF
$$ p \rightarrow (q \wedge \neg p) $$
 Attempt to convert
$$ p \rightarrow (q \wedge \neg p) $$
$$ \iff \neg p \vee (q \wedge \neg p) $$
$$ \iff q \vee (\neg p \wedge \neg p) $$
$$ \iff q \vee \neg p $$
is this correct?


text:
Q: Selenium Webdriver (Java) - exclude a particular tag from the css selector How can I exclude a tag from the css selector. I have a html code below:

Test 1

    John Smith

I need to getText() only for John Smith not for
.
The statement below is return full text Test 1 John Smith:
String txtFix = new WebDriverWait(Login.driver, 100).until(ExpectedConditions.visibilityOfElementLocated
                (By.cssSelector(".info"))).getText();

Is it possible to get somehow only John Smith using css selector?

A: This is a "classic" problem with selenium since a CSS selector or xpath expression has to always refer to an actual element - you cannot directly get the text node.
What you can do here is to:

*

*get the div element's text

*get the h3 element's text

*remove the h3 element's text from the div element's text

Implementation:
String div = new WebDriverWait(Login.driver, 100).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".info"))).getText();
String h3 = div.findElement(By.tagName('h3')).getText();
String txtFix = div.replace(h3, '');

A: If you get text using following:
driver.findElement(By.cssSelector(".info")).getText();

it returns following:
Test 1
John Smith

If you see properly, after Test 1, char \n is introduced hence John Smith is on another line.
Hence, if you want to retrieve only John Smith, it can be achieved using split like following:
String text = driver.findElement(By.cssSelector(".info")).getText().split("\n")[1];

A: JavascriptExecutor jse = (JavascriptExecutor) driver;
       if (jse instanceof WebDriver) {
           String text = jse.executeScript("document.getElementByClassName("info").nextSibling";");
           System.out.println(text);
       }


text:
Q: Does mass just cause a volume of spacetime to curve or is it -its gravitational field- also a local extension of spacetime itself? As seen from outside the gravitational field of an object (a black hole, say) in (where the field is very weak) clocks inside the field are observed to run at a slower pace, the length of measuring rods to look shorter nearer to its source as the field is stronger compared to the field at the observer. Does this mean that the rest energy of the object just warps an already existing spacetime (which exists even in the absence of the object) or is the field itself to some extent a local extension of spacetime -in which case the creation of energy would be the creation of spacetime?

A: The Einstein equations answer your question, the curvature of the space time is related to the mass, which is related to the energy. The concept of gravitational field is one from Newtonian mechanics, and is replaced by curvature of spacetime in General Relativity.


text:
Q: WP7 XNA without DX10 XNA game fails to deploy on the WP7 emulator, I suppose, it's because I have Intel GMA950 video adapter without DX10 support (it says that I have incompatible monitor adapter). Is it possible to use emulator & xna without changing PC configuration?

A: Check your Project properties and see if you have the Reach profile selected or HiDef.  If you have HiDef, change it to Reach.  I have a laptop with an Intel G945 video adapter and HiDef doesnt work, but Reach does.
EDIT
I have just seen your edit and unfortunately you won't be able to do anything unless you change the the graphics device.


text:
Q: Recursivity acces? Alright then implement the objContains function: must search inside a nested object for a pair {key: value} specific. Both the object and the property name and its value will be received by parameter.
In the event that it finds the indicated value at any level of the object, it must return true, otherwise return false.
Ex:
const user = {
    id: 6,
    email: 'homero@maxpower.com',
    Personal info: {
        name: 'Homer Simpson',
        address: {
            street: 'Avenue AlwaysLive',
            number: 742,
            neighborhood: 'Springfield',
            state: 'Massachusetts'
        }
    }
}

Case that returns true -> objContains (user, "neighborhood", "Springfield");
Case that returns false -> objContains (user, "employment", "Employee in nuclear plant");
Hint: use typeof to determine if the value of a property is an object to apply
there the recursion
this is what i've try
var objContains = function (obj, prop, value) {
   object var = prop.value
  if (typeof prop.value === obj) {
    var current = this.value;
    objContains (object, prop, current)
  } else if (this.prop === prop && prop.value === value) {
      return true;
  } else {
    return false;
  }
}

AssertionError: expected false to equal true

      32 | }
      33 | it ('It should return true if it finds the property and its correct value', fun
ction () {
    > 34 | expect (objContains (user, "neighborhood", "Springfield")). to.equal (true);
      35 | });
      36 | it ('Should return false if the property is NOT found', function () {
      37 | expect (objContains (user, "employment", "Employee at nuclear power plant")). to.equal (
false);

A: There are a couple of problems:

*

*typeof prop.value checks the type of the property with the literal name value on whatever prop is. You've described prop as the name of an object property, so it doesn't make sense to try to look for value on it. You want to look on obj, not prop, using the syntax described in this question's answers. I don't think it's writing it for you to say that that looks like this: if (obj[prop] === value)

*If you don't find the property with that value on obj, you should be looking through the other properties on obj and, if any of them refer to objects, calling your function with the object they refer to (and prop and value) and, if the function returns true, return true. Looping through the properties on the object is covered by this question's answers.
So the general form of a solution would be:

*

*See if obj has a property whose name is the value of prop that matches the value of value. If so, return true.

*If not, loop through obj's other properties and check the type of their values; for each one that's an object (typeof is "object" and the value isn't null), call your function again with that property value, prop, and value. If it returns true, return true. If not, keep looping.

I'm purposefully just giving an indication of where to go, rather than writing the code, because this seems like an assignment we should help you with rather than doing for you.

A: I loop through each key in object...  if the the key refers to an object itself then recursively call... else check to see if that's the key we're looking for and if so check its value...   using the |= operator makes it easy to not worry about results of individual calls...  we just care if the conditions are true ANYWHERE in the tree..

const user = {
  id: 6,
  email: 'homero@maxpower.com',
  "Personal info": {
    name: 'Homer Simpson',
    address: {
      street: 'Avenue AlwaysLive',
      number: 742,
      neighborhood: 'Springfield',
      state: 'Massachusetts'
    }
  }
}

var objContains = function(obj, prop, value) {
  var returnValue = false;
  var keyArray = Object.keys(obj);
  keyArray.forEach(property => {
    if (typeof(obj[property]) == 'object') {
      returnValue |= objContains(obj[property], prop, value);
    } else if (property == prop) {
      returnValue |= obj[property] == value;
    }
  });

  return !!returnValue;
}

console.log(objContains(user, 'neighborhood', 'Springfield'));


text:
Q: How to create a new separate buffer list in vim? There are some occasions that I wanted to open several files to be references and didn't want them to mess up my current buffer list. I have tried :new, sp, vs, and :tabnew, however, the new opened files are always kept in my current buffer list. Are there a way to create a brand new buffer list in order to keep these opened files separately? So, I could close these files entirely, whenever I didn't need to see them anymore, by using 1,100bd. I have been googling it but still no luck.

A: You can try this plugin: vim-ctrlspace.
From  README.md of mentioned plugin:

The answer are tabs – a secret weapon of Vim-CtrlSpace. Each tab holds
  a separate list of buffers. And this is something very different when
  compared to plain Vim. Tabs powered by the plugin can be seen as piles
  of documents on the desk.
With tabs you can, for example:

*

*group related buffers

*extract to other tabs

*name them accordingly

*move or copy them

  Tabs usage in Vim-CtrlSpace is quite more extensive than in Vim. This
  is because they serve mainly as independent buffer lists, so you are
  likely to have plenty of them. Tabs can be accessed and managed within
  Tab List.
All your buffers, tabs, and tab layouts can be persisted as a
  workspace. It's like taking a picture of your desk with an instant
  camera. You can save multiple workspaces per project with Workspace
  List.

A: Try using the argument list. See :help :args and surrounding sections. If all your reference files (and only those) are in your arg list, you could :argdo bd to get rid of them all. There are local arg lists too, if you are already using the global list.

A: Disclaimer: Using the plugin is almost certainly a more robust solution as I made this myself and I'm relatively new to vim. But this is at least a good exercise in the uses of quickfix lists.
My Answer:
You could use quickfix error lists as file lists. see :help quickfix for full documentation. Here is my work flow for when I want to go through all the files that differ from master (using git).

*

*vim to open vim in the directory you are working on.

*new to open a new buffer

*read ! git diff --name-only master to paste the output of my bash command into the new buffer. You can run any command or manually enter a file list here. You may want to clean it a little by removing any blank lines.

*w! /tmp/quickfix.txt to create a file name we can use later.

*set errorformat+=%f to change the errorformat to accept vanilla lists of file paths. see :help errorformat for more details on that.

*cfile /tmp/quickfix.txt to read the list of files and create a quickfix "error" list using the new errorformat.

*set errorformat-="%f" (optional) this removes the added errorformat to make sure you're not messing with any other use of errorformat, like for a vimgrep.

Now you can use quickfix options to move between files. :copen to open an interactive list and :cnext/:cprevious to cycle them. You can also have multiple lists at once. I use :colder to go back to previous lists. You should be familiar with this if you use any grep commands in vim.
These are just the manual steps. You can make a function that does all this in one go or any part that you need. Here's what I'm using.
function! LoadQuickfixFileList(filename)
    set errorformat+=%f
    execute "cfile ".a:filename
    set errorformat-=%f
endfunction

function! WriteBufferToQuickFixFileList(filename)
    call writefile(getbufline(bufnr(bufname("%")), 0, "$"), a:filename)
endfunction

function! GitDiffNameOnlyMaster()
    execute "new"
    execute "read ! git diff --name-only master"
    execute "normal! ggdd"
    call WriteBufferToQuickFixFileList("/tmp/quickfix.txt")
    call LoadQuickfixFileList("/tmp/quickfix.txt")
endfunction

nnoremap <silent> <leader>cgd :call GitDiffNameOnlyMaster()<CR>
nnoremap <silent> <leader>cw :call WriteBufferToQuickFixFileList("/tmp/quickfix.txt")<CR>
nnoremap <silent> <leader>cf :call LoadQuickfixFileList("/tmp/quickfix.txt")<CR>

<leader>cgd does the whole thing for git diff --name-only master. If I make a list of files in a new buffer myself, I can use <leader>cw to write it to /tmp/quickfix.txt. Once I've done that or if I create a /tmp/quickfix.txt file myself in another way I use <leader>cf to load that file.


text:
Q: Union two query result column-wise Say if I have two queries returning two tables with the same number of rows.
For example, if query 1 returns
| a | b | c |
| 1 | 2 | 3 |
| 4 | 5 | 6 |

and query 2 returns
| d  | e  | f  |
| 7  | 8  | 9  |
| 10 | 11 | 12 |

How to obtain the following, assuming both queries are opaque
| a | b | c | d  | e  | f  |
| 1 | 2 | 3 | 7  | 8  | 9  |
| 4 | 5 | 6 | 10 | 11 | 12 |

My current solution is to add to each query a row number column and inner join them
on this column.
SELECT
    q1_with_rownum.*,
    q2_with_rownum.*
FROM (
    SELECT ROW_NUMBER() OVER () AS q1_rownum, q1.*
    FROM (.......) q1
) q1_with_rownum
INNER JOIN (
    SELECT ROW_NUMBER() OVER () AS q2_rownum, q2.*
    FROM (.......) q2
) q2_with_rownum
ON q1_rownum = q2_rownum

However, if there is a column named q1_rownum in either of the query,
the above will break. It is not possible for me to look into q1 or q2;
the only information available is that they are both valid SQL queries
and do not contain columns with same names. Are there any SQL construct
similar to UNION but for columns instead of rows?

A: There is no such function.  A row in a table is an entity.
If you are constructing generic code to run on any tables, you can try using less common values, such as "an unusual query rownum" -- or something more esoteric than that.  I would suggest using the same name in both tables and then using using clause for the join.

A: Not sure if I understood your exact problem, but I think you mean both q1 and q2 are joined on a column with the same name?
You should add each table name before the column to distinguish which column is referenced:
"table1"."similarColumnName" = "table2"."similarColumnName"
EDIT:
So, problem is that if there is already a column with the same alias as your ROW_NUMBER(), the JOIN cannot be made because you have an ambiguous column name.
The easier solution if you cannot know your incoming table's columns is to make a solid alias, for example _query_join_row_number
EDIT2:
You could look into prefixing all columns with their original table's name, thus removing any conflict (you get q1_with_rows.rows and conflict column is q1_with_rows.q1.rows)
an example stack on this: In a join, how to prefix all column names with the table it came from


text:
Q: Formula compile error with lots of dates I am receiving this error:
Error: Invalid Data.
Review all error messages below to correct your data.
Formula(s) that reference this field are no longer valid: Compiled formula is too big to execute (5,573 characters). Maximum size is 5,000 characters (Related field: Formula)
I have a formula to calculate whether NZ day light savings is on for a date. This is the logic:
If the dateis after may and it's after the last sunday of septemeber.
Or
If the date is before may and before the 1st sunday in April
if(
Month( Attitude_presentation_date__c )>5
&&
Attitude_presentation_date__c>=
(DATE(YEAR( Attitude_presentation_date__c ),9+1,01) - 1
-
MOD( DATE(YEAR( Attitude_presentation_date__c ),9+1,01) - 1 - DATE(1900, 1, 7), 7))
,1,0)

+

if(
Month( Attitude_presentation_date__c )<5
&&
Attitude_presentation_date__c<=
(DATE(YEAR(Attitude_presentation_date__c ),4,01)
+
CASE( MOD( DATE(YEAR(Attitude_presentation_date__c ),4,01) - DATE(1900, 1, 7), 7), 0, 0, 1, 6, 2, 5, 3,
4, 4, 3, 5, 2, 6, 1,0))

,1,0)

I Then have a second formula that uses it to create calendar entries:
DATETIMEVALUE(
TEXT(YEAR(Attitude_presentation_date__c))+"-" +
TEXT(MONTH(Attitude_presentation_date__c))+"-" +
TEXT(DAY(Attitude_presentation_date__c))+" "+

Start_time__c
+":00")

-
if( Date_NZ_Daylight_savings_on__c >0, 1/24*13,1/24*12)

How can I modify this to get it under the 5000 compile limit?

A: Assuming that it's the second formula that's throwing the compile size error, try moving the first formula into a workflow field update or process instead of a formula field. The steps for a workflow field update are:

*

*Create a custom field of the type your field update formula will return (I don't think you can create a WF field update for checkbox, so you might need to make it numeric -- e.g. 1 if true and 0 if false).

*Create a workflow rule on the object. Set it to execute whenever a record is created or updated.

*Create a Field Update workflow action. Choose the custom field you created in Step 1 as the target, and use your first formula as the content.

*In your formula field, replace the part of the formula you copied to the field update action with a reference to your custom field.

When you reference another formula field, it pulls the compile size of that formula into the new formula. When you use a workflow field update, the size of the field is much smaller because it's just a regular field (not compiled at the time it's referenced).
See the Tips for Reducing Formula Size tip sheet in the Salesforce Help (the last section, "If all else fails use a workflow field update").


text:
Q: Pycharm warning that variable is unused I am not very familiar with Python, especially with the scope of variables. I am trying to access a sqlite database. However, Pycharm's code inspection is warning me that the variable data is not being used.
def getIndexFromDB(self, user, username, domID):
    data = None #warning that this variable is unused
    with lite.connect(self.DBName) as con:
        cur = con.cursor()
        cur.execute('PRAGMA foreign_keys = ON')
        cur.execute('select idx from Upass where username = ? and uname = ? and dom = ?', (user, username, domID))
        data = cur.fetchone()
    return data

Is this a pycharm problem?

A: The warning is correct.
Assigning data = None is a useless line and may as well be deleted.
def getIndexFromDB(self, user, username, domID):
    with lite.connect(self.DBName) as con:
        cur = con.cursor()
        cur.execute('PRAGMA foreign_keys = ON')
        cur.execute('select idx from Upass where username = ? and uname = ? and dom = ?', (user, username, domID))
        return cur.fetchone()

The code above is equivalent, because the function getIndexFromDB can only exit in one of three possible ways:

*

*An unhandled exception is raised (no return value)

*An exception is raised inside the indented block, but marked as handled by the __exit__ method of the context manager (None is returned). That can not happen in this particular code because this db context manager, presumably from sqlite, is not swallowing exceptions. But it's worth to keep in mind in other cases.

*No errors. The result of cur.fetchone() is returned, which itself might be None in case of no data.

A: How about use the below code instead of assigning data at the very top? Thats safe and cures the warning as well...
def getIndexFromDB(self, user, username, domID):
    with lite.connect(self.DBName) as con:
        cur = con.cursor()
        cur.execute('PRAGMA foreign_keys = ON')
        cur.execute('select idx from Upass where username = ? and uname = ? and dom = ?', (user, username, domID))
        data = cur.fetchone()
    data = data or None
    return data