text:
Q: show text above and below ion-input inside ion-item Objective:
Show text above and below ion-input inside ion-item like below

To add only the above label, add stacked to ion-label
To add only the below label, add style flex-direction: column-reverse to input-wrapper as stated in Ionic Stacked input - Show label below text field
Difficulties:
There's one input-wrapper => cannot alter it to handle both case
Or I haven't find the solution
Workaround:
open new ion-item to show text below ion-input
But then need special handle in css to ignore font, margin...
Playground:
stackblitz
Please concern only home page
"input prefix..." is intended to be under input as remark
Is there any way to add text above and below ion-input easily?
Thanks


text:
Q: Excel VBA to Internet Explorer - select all doesn't work on a pdf The code below is my problem. It is meant to copy fund information from a website into a spreadsheet. It worked fine when the funds were on a non-pdf website but it doesn't work for pdf websites. It's the Select-All (ie2.ExecWB 17, 0) that fails and I can't crack it. If I do keyboard ctrl-A on the pdf website it selects all and a sendkeys version kind of half works but what I need is a solution to getting this "ie2.ExecWB 17, 0" to do what it is supposed to do.
any help greatly appreciated.
cheers
Sub ListFunds()
Dim DataObj As New MSForms.DataObject
Dim S As String
Dim ie1, ie2
Set ie1 = CreateObject("internetexplorer.application")
Set ie2 = CreateObject("internetexplorer.application")
HWNDSrc = ie2.HWND
ie1.Visible = True
ie2.Visible = True
ie1.navigate "http://www.legalandgeneral.com/workplacebenefits/employees/help-support/fund-zone/fund-factsheets/wpp-tbop-pptip.html"
Do Until ie1.readystate = 4
    DoEvents
Loop
Dim LinkFound As Boolean
Dim linkCollection
Set linkCollection = ie1.document.all.tags("A")
For Each link In linkCollection
        If InStr(1, link.outerhtml, "fundslibrary") <> 0 Then
            ie2.navigate link
            Do Until ie2.readystate = 4
                DoEvents
            Loop
            ie2.ExecWB 17, 0 '// SelectAll
            ie2.ExecWB 12, 2 '// Copy selection
            DataObj.GetFromClipboard
            S = DataObj.GetText
            Selection.Value = S
            Selection.Offset(1, 0).Select
        End If
Next link
ie1.Quit
ie2.Quit

End Sub

A: Check this out, this might help you:
http://www.xtremevbtalk.com/showthread.php?t=299104
I'm not crazy about SendKeys at all, but I can't think of another way to capture the data from a PDF through a browser.

redpajama_set_name: RedPajamaStackExchange


text:
Q: phonegap and appcache not working I use phonegap 2.8.1. I load a page from a url which has appcahe enable for html5.
Page loads correctly.
If I turn the wifi off when accessing with
window.location.href = 'http://192.168.0.20/myapp';

it says that it cannot find the server rather then loading the cached version.
Any hints?
thanks

A: I think this is a limitation of iOS/smartphone and not your app. From experience when working on HTML5 apps turning off the device connectivity, e.g. going into aeroplane mode, the OS no longer tries to load your app.
If you are interested you can follow the changes to the application cache at the w3c http://www.w3.org/community/fixing-appcache/ I don't see any mention of this behaviour though


text:
Q: Retrieve failed entities from ExecuteMultipleResponse method I am using the Execute Multiple Response class to pass in an Entity Collection for Upsert into Dynamics CRM, I would like to know how to add the failed entity names to a collection and then use exception handling on each of these entities.

A: Assuming you create your ExecuteMultipleRequest something like this:
var entityCollection; // your EntityCollection
var requests = new ExecuteMultipleRequest();

foreach (var entity in entityCollection.Entities) {
    var upsertRequest = new UpsertRequest { Target = entity };
    requests.Requests.Add(upsertRequest);
}

You should be able to execute the request, iterate through the responses and for each determine whether a fault occurred:
var responses = service.Execute(requests);
var errors = new List<Entity>();

foreach (var response in responses.Responses) {
    if (response.Fault != null) {
        var entity = entityCollection[response.RequestIndex];
        errors.Add(entity);
    }
}

response.RequestIndex is used to access the response's corresponding request by matching their indexes.
responses.Responses contains a collection of ExecuteMultipleResponseItem. Documentation on their properties can be found here.


text:
Q: How can we read GPS in Silverlight 4 application? I need to read the GPS receiver attached to a COM port.
How can we read GPS in a Silverlight 4 application?

A: Couple of option I can think of.

*

*In OOB (out of browser) mode you can
access COM components to do pretty
much anything. That does mean you
will need a COM component to access
your GPS.

*You can create javascript apps that can send information to the
Silverlight component within the
browser. I have seen this used to
pass on card scanner information to a
Silverlight app.


text:
Q: How can I remove only density from antd design pro table toolbar?   <ProTable
  search={false}
  dateFormatter="string"
  cardBordered
  tooltip={false}

  {...props}

  size="large"
></ProTable>

I want to only remove density not refresh or settings. I even asked the question in ChatGPT but it had not answer :)


text:
Q: Returning String value of Ljava.lang.Object I have the following code
TreePath tp = jTree.getSelectionPath();
String path = tp.getPath().toString();

This will set path as Ljava.lang.Object;@33530691, I understand this is because

The toString method for class Object returns a string consisting of
the name of the class of which the object is an instance, the at-sign
character `@', and the unsigned hexadecimal representation of the hash
code of the object. In other words, this method returns a string equal
to the value of:
getClass().getName() + '@' +Integer.toHexString(hashCode())

But how do you actually get this value as a String?

A: getPath() returns an array of String values representing the components in the tree. If you need the String representation of the root, you will do getPath()[0];

A: String's toString() method is by defalut overloaded, so the problem is not here with the String path, but try to see the TreePath tp.
I think you need to take a look at tp.

A: I don't quite get your question. Isn't that already answered in the quote you posted?
getClass().getName() + '@' +Integer.toHexString(hashCode()) the default implementation of the toString() method, but you can override that, if you need a better representation (keep in mind that you need to extend TreePath in your case ).
Edit: I think, I now understand:
Since TreePath.getPath() returns an object array you get that java.lang.Object in the output.

A: The object that is the component of the tree needs to have its toString() method overridden. You can override it with whatever you what it to return. I presume you are adding a custom object to the tree so you are in control of that object and its toString() method

A: If you want to get a comma separated string of the values you can do
String path = new ArrayList(tp.getPath()).toString();

A: Try something like this:
Object[] treeNodes = tp.getPath();
StringBuilder sb = new StringBuilder();
for(Object tn : treeNodes) {
    sb.append(File.separatorChar).append(tn.toString());
}
String path = sb.toString();

A: You have an array of objects (which may all be Strings)
To toString these you need to use Arrays.toString()
String path = Arrays.toString(tp.getPath());

A: If it's for output/logging only, I guess Arrays.asList(tp.getPath()).toString() could suffice.

A: The TreePath object represent the whole path to go from the root-node to the actual node. If you call getPath on it, it returns you an array containing the root-node and the actual selected node, and all nodes in between.
How to get the "correct String" depends on what you actually want to achieve:

*

*If you want the string representation of the actual selected node, use the getLastPathComponent method
TreePath tp = jTree.getSelectionPath();
String path = tp.getLastPathComponent().toString();

*If you want to have the complete path, you will have to loop over the array
TreePath tp = jTree.getSelectionPath();
StringBuilder pathBuilder = new StringBuilder();
for( Object node : tp.getPath() ){
  pathBuilder.append( node.toString() );
  //possibly append a separator as well
}
String path = pathBuilder.toString();

or simply use the Arrays#toString method on tp.getPath() instead of the toString method


text:
Q: Finding the probability of a type II error for a poisson distribution A poisson distribution is being tested with the hypothesis
H0: λ = 1.7 and H1: λ ≠ 1.7
The true value of the mean is 2.3. For the significant level 10% calculate:
a )The critical region
b) The probability of a type II error
c) The power
just need help with part a, I used a poisson cumulative distribution, with a lower boundary of 4, an upper boundary of  100000000 and λ = 1.7 to receive the following values.
P(X ≥ 3) = 0.24277679
P(X ≥ 4) = 0.09318943
P(X ≥ 5) = 0.0296148
Therefore, I said that the critical region was X ≥ 4 because P(X ≥ 4) < 0.1, however, the textbook says the critical region was X ≥ 5. Am I correct, or have I missed something?


text:
Q: How to get Image src using Swift-Html-Parser I am a newbie on Swift and Swift-HTML-Parser. I am using Swift-HTML-Parser from : https://github.com/tid-kijyun/Swift-HTML-Parser
I need some help for below question.

    let myURLString = "http://MytestingWebsite.com/MyAds.html"
    let myURL = NSURL(string: myURLString)

    var error: NSError?

    let myHTMLString = NSString(contentsOfURL: myURL, encoding: NSUTF8StringEncoding, error: &error)

    if let error = error {

        //for below question 2
        println("Error : \(error)")

    } else {

        // code

    }

1) How to get the Src of the Image if there is a) only one image b) a collection of images?

      < image Src="....."/>

2) What to use to show message when there is an error?

Adding the the required files as per the above link for Swift-HTML-Parser :

1. Add a Bridging file. click Project and goto Building Setting
Use search: type in Bridging
Double click on the result : Objective-C Bridging Header
and Click (+) at the Top to add.

Error msg show: When adding file name with (-) Like Swift-HTML-Parser-Bridging-Header.h

So, I add SwiftHTMLParserBridgingHeader

2) Copy the File Swift-HTML-Parser-Bridging-Header.h and rename it as SwiftHTMLParserBridgingHeader.h in the project file.

3) Copy HTMLParser.Swift and HTMLNode.swift

4) Have added the reference Libxml2.dylib

When compile, (2) and (3) have red dot. Am I doing something wrong?

A: This have have a emum for each node that you can search in the HTML
public enum HTMLNodeType : String {
    case HTMLUnkownNode     = ""
    case HTMLHrefNode       = "href"
    case HTMLTextNode       = "text"
    case HTMLCodeNode       = "code"
    case HTMLSpanNode       = "span"
    case HTMLPNode          = "p"
    case HTMLLiNode         = "li"
    case HTMLUiNode         = "ui"
    case HTMLImageNode      = "image"
    case HTMLOlNode         = "ol"
    case HTMLStrongNode     = "strong"
    case HTMLPreNode        = "pre"
    case HTMLBlockQuoteNode = "blockquote"
}

From the example they have in the website:
var err : NSError?
//myHTMLString is the value you retrive from the website
var parser     = HTMLParser(html: myHTMLString, error: &err)
if err != nil {
    //This will log the error and exit the app
    //You probably should display an alert to the user
    println(err)
    exit(1)
}

var bodyNode   = parser.body

if let inputNodes = bodyNode?.findChildTags(HTMLNodeType.HTMLImageNode) {
    for node in inputNodes {
        println(node.contents)
        //this should display the address where the Image is
    }
}


text:
Q: Mouse in games - Alternative input methods My shoulder hurts if I use the mouse for more than 30 minutes at a time, that's why I currently only play games with an xbox 360 gamepad.
However, with Diablo 3 I will not be able to do that.
Does anyone know of an alternate input method that has similar precision to a mouse? I've been thinking about using a Wiimote, but I don't think its accurate enough. Maybe a PS Move?

A: You might still consider mice, as there are Trackball mice which are similar to normal mouse precision but operate in a different way:

This for example is the "Logitech M570 Trackball". Basically instead of moving the mouse on your table you move the Trackball with your thumb. Your shoulder does not move a bit.
There was once a top professional Counter Strike player that used a similar mouse, but I forgot his name, which proves that you can make it work even in precision games that require fast reflexes. Here is an old discussion about this topic: Gamespot Thread
This does not really concern your question, but I guess you are using your mouse in a wrong way. Day[9], a professional Starcraft veteran has a 1 hour show that explains how to correctly use your mouse and keyboard for Starcraft 2. You can easily adapt this to Diablo 3 or any computer game. Check it out: Day9 Daily 252.

A: There are a million options, but I consider most novelties. As others point out, ergonomics are probably the core of your issue. Since thumbs seem to work better for you then wrist movements, one option to consider is a trackball mouse like the Logitech 570 I've linked below. There is a definite learning curve for using them, and I think they'll never be "FPS" precision or speed, but I've played with folks that converted and used them effectively in games like Starcraft and Diablo.
http://www.officedepot.com/mb/skupage.do?skuid=989412


text:
Q: Selecting all Primefaces menuitems with JQuery I want to run some JQuery code when the user clicks on a menu item using Primefaces. I successfully run JQuery because I tested displaying an alert when the document is ready.
Next, I tried this:
$(".ui-menuitem").click(function() {
    alert("You pressed a menuitem");
});

because as seen in the inspector the menu item belongs to the class ui-menuitem.

The above code does not work and I do not understand why.
Please help, thanks in advance.


text:
Q: ReactClassInterface: You are attempting to define `constructor` on your component more than once. This conflict may be due to a mixin So, I'm having an issue when attempting to create an Apollo/GraphCool subscription, which is throwing up the following error message:

[React Transform HMR] There was an error updating C:/Users/d0475/Documents/Projects/learn-redux-graphql/client/components/Comments.js:
(anonymous) @ index.js:59
hotApply @ bootstrap ac9bfc0…:514
cb @ process-update.js:52
hotUpdateDownloaded @ bootstrap ac9bfc0…:311
hotAddUpdateChunk @ bootstrap ac9bfc0…:283
webpackHotUpdateCallback @ bootstrap ac9bfc0…:4
(anonymous) @ 0.92fd6f4….hot-update.js:1
index.js:60 Error: ReactClassInterface: You are attempting to define `constructor` on your component more than once. This conflict may be due to a mixin.
    at invariant (invariant.js:39)
    at validateMethodOverride (ReactClass.js:384)
    at mixSpecIntoComponent (ReactClass.js:420)
    at Object.createClass (ReactClass.js:726)
    at Object.<anonymous> (Comments.js?32c0:17)
    at Object.748 (0.92fd6f4….hot-update.js:207)
    at __webpack_require__ (bootstrap ac9bfc0…:555)
    at Object.hotApply [as apply] (bootstrap ac9bfc0…:510)
    at cb (process-update.js:52)
    at hotUpdateDownloaded (bootstrap ac9bfc0…:311)
    at hotAddUpdateChunk (bootstrap ac9bfc0…:283)
    at webpackHotUpdateCallback (bootstrap ac9bfc0…:4)
    at 0.92fd6f4….hot-update.js:1

My Comments.js reads as follows:

import { subscriptionObservable } from '../apolloClient';

const Comments = React.createClass({

  constructor() {
    this.subscription = this.subscribe();
    console.log(`Subscribed for new messages with ID: ${this.subscription._networkSubscriptionId}`);
  },
  subscribe() {
    return subscriptionObservable.subscribe({
      error: (error) => {
        console.log(`Subscription error: ${error}`);
      },
      next: (result) => {
        console.log(`Subscription result: ${result}`);
      }
    });
  },
  render() {
    const comments = this.props.post.comments || [];
    return (
      <div className="comments">

        {_.map(comments, this.renderComment)}

        <form onSubmit={this.handleSubmit} ref="commentForm" className="comment-form">
          <input type="text" ref="author" placeholder="author"/>
          <input type="text" ref="comment" placeholder="comment"/>
          <input type="submit" hidden/>
        </form>
      </div>
    );
  }
});

Comments.propTypes = {
  client: React.PropTypes.instanceOf(ApolloClient).isRequired,
}
const CommentsWithApollo = withApollo(Comments);

export default CommentsWithApollo;

And my apolloClient.js reads as follows:

import ApolloClient, {
  createNetworkInterface,
  addTypeName,
} from 'apollo-client';

import {
    SubscriptionClient,
    addGraphQLSubscriptions,
} from 'subscriptions-transport-ws';

import {
  Subscription_Add_Delete_Comment_Query,
} from './graphql/mutations-queries';

// Create WebSocket client
const wsClient = new SubscriptionClient('wss://subscriptions.graph.cool/v1/myID', {
  reconnect: true,
  connectionParams: {
    // Pass any arguments you want for initialization
  }
})
const networkInterface = createNetworkInterface({
  uri: 'https://api.graph.cool/simple/v1/myID',
  opts: {
    // Additional fetch options like `credentials` or `headers`
    credentials: 'same-origin',
  }
})

const networkInterfaceWithSubscriptions = addGraphQLSubscriptions(
  networkInterface,
  wsClient
)

const client = new ApolloClient({
  networkInterface: networkInterfaceWithSubscriptions,
  dataIdFromObject: (o) => o.id,
   addTypeName: true
})

let createDeleteSubscription = {
  query: Subscription_Add_Delete_Comment_Query,
  variables: {}
};

export let subscriptionObservable = client.subscribe(createDeleteSubscription);

export default client;

What am I overlooking here?

A: What you are overlooking here is the fact that you are mixing the es6 and es5 syntax of using react.
In the ES5 syntax this is how you create components -> const Comments = React.createClass
Here you do not need to define a constructor. createClass does that for you.
In the ES6 syntax, this is how you create components -> class Comments extends React.Component
And here you have to define your own constructor.
What you can do is either switch to the new syntax completely or do this.subscription = this.subscribe(); in a lifecycle method like componentWillMount or componentDidMount.


text:
Q: Copying iTunes playlists to external USB flash drive On my Macbook Pro running OSX 10.6.8, is there a way to have my playlists synchronize to a USB flash drive for my car stereo? The flash drive is formatted as FAT32, and I know you can do it in Windows Media Player; however, I have all my playlists set up in iTunes already.

A: Fixed. I don't know why it didn't work the first time, but I was able to (the second time) just drag the music from my playlist over to the flash drive, and it started copying. Thanks for all the views, sorry if I puzzled anyone


text:
Q: Proof that if $R$ is a commutative ring and $R^n \cong R^m$ then $n=m$. Problem: Let $R$ be a commutative ring, show that if $R^n \cong R^m$ then $n = m$.
I have an attempt which I think is alright, but I just want to double check that there are no issues in my attempt. It's a very basic from the definitions approach, and didn't see anything exactly like it on the site. I saw this but I haven't studied tensor products yet.

Attempt:We use exercise 10.2.12 from DF, if $R$ is a ring and $I$ is a left ideal of $R$, then $R^n/IR^n \cong \underbrace{R/IR \times \dots \times R/IR}_{n \text{ times}}$. Let $I$ be a maximal ideal of $R$, note that because $R$ is commutative, $I$ is a $2$-sided ideal. Because $R^n \cong R^m$ there is an $R$-module isomorphism $\varphi:R^n \rightarrow R^m$ which induces an isomorphism $\psi: R^n/IR^n \rightarrow R^m/IR^m$ defined by $r+IR^n \mapsto \varphi(r)+IR^m$. To see that this map is well-defined, let $r,r'$ be representatives of the same equivalence class, i.e $r+IR^n = r'+IR^n$. Then it follows that $r-r' \in IR^n$ so $r-r' = \sum_1^k a_im_i$ where $a_i \in I$ and $m_i \in R^n$. Then notice
\begin{align*}
  \psi(r)-\psi(r') &= \varphi(r)+IR^m - \varphi(r')+IR^m \\
  & = \varphi(r-r')+IR^m \\
  & = \varphi \left( \sum_1^k a_i m_i \right) + IR^m \\
  & = \sum_1^k a_i\varphi(m_i) + IR^m \\
  &= IR^m \tag{$\varphi(m_i) \in R^m$ and $a_i \in I$}
 \end{align*}
so $\psi(r)+IR^m = \psi(r')+IR^m$ and the map is well-defined. It follows from the fact that $\varphi$ is an isomorphism that $\psi$ is also an isomorphism. Therefore we can apply 10.2.12 from Dummit and Foote. We have that $R^n/IR^n \cong R^m/IR^m$ and so by 10.2.12 we have that
$$
\underbrace{R/IR \times \dots \times R/IR}_{n \text{ times }} \cong \underbrace{R/IR \times \dots \times R/IR}_{m \text{ times}}
$$
Since $R$ is commutative $I$ is two sided and it follows that $IR = I$; it's obvious that $I \subseteq IR$, if $\sum_1^ka_ir_i \in IR$ since $I$ is a two sided ideal $a_ir_i \in I$ for all $i$ so is an element of the ideal. Therefore This becomes
$$
\underbrace{R/I \times \dots \times R/I}_{n \text{ times }} \cong \underbrace{R/I \times \dots \times R/I}_{m \text{ times}}.
$$
Because $I$ was a maximal ideal we know that $R/I$ is a field and so this gives that $F^n \cong F^m$, but we know from vector space theory that these are isomorphic if and only if they have the same dimension, i.,e $n = m$.

Let me know if there are any missteps or places to trim the fat.


text:
Q: Error with GoogleSignIn with the error code extra argument I'm a newbie in development and I want to do an app for my classroom, with a Google Drive and Google calendar access, after reading on the Internet what I should do, I debuted to make the GoogleSignIn code, but I have a problem all things are ok in my AppDelegate except this line of code:
return GIDSignIn.sharedInstance()?
    .handle(url, sourceApplication: sourceApplication, annotation: annotation) ?? false

Xcode says to me that there an extra argument "sourceApplication" in call, but even when I delete what I think is problematic, the problem is not solved, can someone helps me because I relly don't know very much how to debug apps
return GIDSignIn.sharedInstance()?
    .handle(url, sourceApplication: sourceApplication, annotation: annotation) ?? false

A: If you control+command+click on the handle method call, it'll open GIDSignIn.h and you'll see the method only accepts a URL.
Change
return GIDSignIn.sharedInstance()?
.handle(url, sourceApplication: sourceApplication, annotation: annotation) ?? false

to
return GIDSignIn.sharedInstance().handle(url)

Also, I believe they recently updated their library, so any code examples you find may be out of date. It helps to check the source code.


text:
Q: WordPress weird Archive Year bug I have a custom page template for my archive template. However, when I go to
http://www.myurl.com/news-and-events/?year=2014
The posts are showing up properly. However when I try to go to 2013 (there is one post in that year), it shows my 404 page.
This is a custom developed theme.
What could be the issue?


text:
Q: Jackson JSON how to set http connection and read timeout (jersey-common=2.21.0, jackson-core=2.6.1)
How do I set http connection timeouts (connect, read) if createParser(URL url) was invoked? What is the default values used?
    JsonFactory jsonF = new JsonFactory();
    jsonF.enable(JsonParser.Feature.AUTO_CLOSE_SOURCE);
    JsonParser jsonP = jsonF.createParser(url); // URL instance
    try {
        JsonToken token;
        while ( (token=jsonP.nextToken()) != null) {
           if (token == JsonToken.START_OBJECT)
           ..rest "json sax" parser code...
        }
    } finally {
        jsonP.close();
    }

I have few times a week recurring problem when webapp stops reading json sources, task is autorun every 30 minutes. I suspect this http call stalls and starts piling up until JVM goes down.
Should I not use createParser(URL) function in production apps?

A: You could hack the values
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");

More on the settings can be found on
https://docs.oracle.com/javase/7/docs/technotes/guides/net/properties.html
Or you can instead do a proper call and then pass the result into the json parser. I would go with the latter.
So to put it simply while URL is great light weight alternative I suggest switching to apache http client or some high level solution.

A: That particular read method is for convenience, but not configurable and generally not that useful for most production usage.
Instead, you may want to obtain InputStream from URL endpoints using other means, then pass it to ObjectMapper / ObjectReader; this allows for full control over details of connection, timeouts and so forth. It allows lets you use other HTTP clients than the default one JDK comes equipped with.


text:
Q: android Position AlertDialog not working in 4.1 as on 2.3 I have an AlertDialog, whose Y is set and set to show on center. It shows perfectly on 2.3 emulator & device, but on 4.1 (emulator & 4.0 device) it shows on more top than expected.
Here's the code :
        AlertDialog adg = scrnDlg.create();
    WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
    lp.copyFrom(adg.getWindow().getAttributes());
    lp.width = WindowManager.LayoutParams.MATCH_PARENT;
    //lp.height = WindowManager.LayoutParams.MATCH_PARENT;
    lp.y = 05;
    lp.gravity = Gravity.TOP | Gravity.CENTER_HORIZONTAL;
    adg.getWindow().setAttributes(lp);
                adg.show();
    /*  working with 2.3 but nt proper position with 4.0
        WindowManager.LayoutParams lp = adg.getWindow().getAttributes();
        lp.y = 05;
        lp.gravity = Gravity.TOP | Gravity.CENTER_HORIZONTAL;
        adg.getWindow().setAttributes(lp);
        */

Screen shot of obth versions emulator :

Can any one help me wort out this problem ?
Also this height is perfect for Ld, Md. But for Hd & xD this height seems to be small & more space is left on bottom. How do I set the height based on screen height.
Any help ishighly appreciated.
Thanks

A: I finally got the above by setting the Gravity by testing the Android OS Version. This is how I did and get resutls as expected :
alertDlg.show();
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(alertDlg.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.y = 02;
if (MyActivity.Build_Version < Build.VERSION_CODES.ICE_CREAM_SANDWICH)
lp.gravity = Gravity.TOP | Gravity.CENTER_HORIZONTAL;
else if (MyActivity.Build_Version >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
lp.gravity = Gravity.CENTER_HORIZONTAL;

alertDlg.getWindow().setAttributes(lp);

Gravity of LayoutParams are treated differently by 4.1 and below 4.1 versions of the Android, thus the above is set and works perfectly.
Hope this sharing help someone.


text:
Q: SyntaxError: import declarations may only appear at top level of a module, how to fix? I'm importing import { io } from "./socket.io-client"; at the top of app.js, but I get this error SyntaxError: import declarations may only appear at top level of a module. I have a script tag under body like this:
<script src="app.js"></script>
What should I do to fix the error?

A:
<script type="module" src="app.js"></script>


text:
Q: Rijndael-256 encryption - Padding on end of decrypted string So, I'm trying to decrypt Rijndael-256 using mcrypt, that's all good.
However, there is padding on the very end of the string to make it exactly 32-bytes long.
Any idea why? Here's what it outputs.
array (size=9)
  'cryptedText' => string 'O¿{žû¦ê§Þøµ; *¬rÄÅϧ"•T' (length=32)
  'IV' => string 'ÄêKG£ED^°"F¨ŠêFx)\e_¶üŠèJÂ|' (length=32)
  'title' => string 'Untitled' (length=8)
  'deleteKey' => string 'ff349d33af4cff27143f66680586121e3c17d1f81aee42c7beb645684ca95558447f0eba757c7ecc785ea39633cfad5a6144fd5ea5028ca9c342e15291d7fd60' (length=128)
  'date' => string '1356827615' (length=10)
  'uid' => string '0' (length=1)
  'urlID' => string '2' (length=1)
  'id' => string '2' (length=1)
  'decryptedText' => string 'hello woaaaaaaaaarld������������' (length=32)
                                                 ^^^^^^^^^^^^ This

If I add more than 32 characters, it pads to 64, etc...
Here's how I'm decrypting it:
        $cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_256, '', MCRYPT_MODE_CBC, '');

        if (mcrypt_generic_init($cipher, $key, $result_set['IV']) != -1) {
            $decrypted = mdecrypt_generic($cipher, $result_set['cryptedText']);
            mcrypt_generic_deinit($cipher);
            mcrypt_module_close($cipher);
            $result_set['decryptedText'] = $decrypted;
        }

The Rijndael-256 encrypted data is being stored in my database on LONGBLOB (binary) data type, aswell as the IV.

A: http://php.net/manual/en/function.mcrypt-encrypt.php

data
The data that will be encrypted with the given cipher and mode.
  If the size of the data is not n * blocksize, the data will be padded
  with '\0'.
The returned crypttext can be larger than the size of the data that
  was given by data.

A: base64_encoding my data before encrypting it solved this problem. Yay!


text:
Q: Irregular expressions I've dictionary (word's name : word's points).
dict = {"fe": 1, "je": 2, "jee": 3, "ain": 3, "dai": 5, "ne": 2, "ai": 2}

Any character that does not create a word in the dictionary is minus 1 point
Example: fejeain - 1+2+3 = 6 feje**b**ain - 1+2-**1**+3 = 5
Here is my string
string = "feaineai"

I would like to award points for individual parts of a word. Their sum will be the result.
But there are several ways to calculate the result:
fe-ai-ne-ai = 1+2+2+2=7
fe-ain-e-ai = 1+3-1+2=5

Is there any algorithm that will help me?
The algorithm should find the highest possible result.

A: Consider the following as the direct recursive solution, a tabled solution would use less time:
a_dict = {"fe": 1, "je": 2, "jee": 3, "ain": 3, "dai": 5, "ne": 2, "ai": 2}

string = "feaineai"

def p(w):
    if not w:
        yield 0
        return
    for word in a_dict:
        if w.startswith(word):
            for v in p(w[len(word):]):
                yield a_dict[word] + v
    for v in p(w[1:]):
        yield -1 + v

print max(p(string))

Prints 7 for feaineai and 5 for fejebain and 12 for aidaidai.

A: first of all, don't call your variable dict. This is how I'll do it:

Edit

Finally reading the answer of user @Dan D., wich is correct, I had nothing to add, just a subprocess calling the max function over all the results.
a_dict = {"fe": 1, "je": 2, "jee": 3, "ain": 3, "dai": 5, "ne": 2, "ai": 2}

def words_points(w):
  return max(sub_points(w))

def sub_points(w):
    if not w:
        yield 0
        return
    for word in a_dict:
        if w.startswith(word):
            for v in sub_points(w[len(word):]):
                yield a_dict[word] + v
    for v in sub_points(w[1:]):
        yield -1 + v

for s in ("feaineai", "fejebain", "fejeain", "aiaiai", "aiaiaije"):
  print(words_points(s))

A: This is a great example of a problem where you want to use dynamic programming. There's a lot of ways to implement the algorithm, let me sketch one below (not an optimal one).
For each prefix length (0 to N), you can remember the best score you can achieve for that prefix. Obviously the best score for a prefix of length 0 is 0. You can initialize the other prefixes with minus their length (-1 point for each character).
Now, you iterate over the positions and you try to match all dictionary words at that position (let's call it K). If there's a match, you update the best score at position (K + length of the matched word, let's call it L) to max(scores[L], scores[k] + word_score). The end result will be at position scores[len(string)].
def get_score(dct, to_score):
    dp = [-i for i in xrange(len(to_score) + 2)]
    for i in xrange(len(to_score)):
        for word in dct:
            lw = len(word)
            if lw <= len(to_score) - i:
                if word == to_score[i:i + lw]:
                    dp[i + lw] = max(dp[i+lw], dp[i] + dct[word])
        dp[i + 1] = max(dp[i + 1], dp[i] - 1)
    return dp[len(to_score)]

dct = {"fe": 1, "je": 2, "jee": 3, "ain": 3, "dai": 5, "ne": 2, "ai": 2}

for s in ("feaineai", "fejebain", "aidaidai"):
    print "%s -> %d" % (s, get_score(dct, s))


text:
Q: CPropertyPage dialogue OnOk should not close the dialogue if there is an error I have a class which inherits from CPropertyPage class. I have a OnOk() method and a OnKillActive() method.
Whenever I press Ok on the dialogue. OnKillActive() gets called but OnOk() is never called.
The problem is depending on a condition I do not want to close the dialogue on pressing Ok. But the dialogue is closing on pressing Ok.
How do I prevent the dialogue from closing when I press Ok?
Code:
In MyClass.h:
    class MyClass : public CPropertyPage {
    }

In MyClass.cpp:
    void MyClass::OnOK(){
        if (condition true) {
            return; // This should prevent the dialogue from closing but still      the dialogue closes
        }
        return CPropertyPage::OnOk();
    }

    BOOL MyClass::OnKillActive() {
        if (condition true) {
            CDialog::DoModal();
            return FALSE; // This should prevent the dialogue from closing but   still the dialogue closes
        }
        return CPropertyPage::OnKillActive();
    }

A: I am not sure if you can call CDialog::DoModal(); as your property page is  not closed yet.
When this event(OnKillActive()) occurs your property page is inactive. But your property page still exists and the data in the property page also exists for validation.
To bring your page back, just set the focus in one of the dialog item. Use "GetDlgItem" to get an object and set the focus using "SetFocus"
An example is available here.
https://msdn.microsoft.com/en-us/library/2122ct0z.aspx

A: Actually in the OnClickedOk() function of the PropertySheet class, there was an EndDialog(IDOK). This is why it was closing everytime when Ok was pressed.
I just gave a condition check before EndDialog() and it worked.
Thanks for your reply.


text:
Q: Connect Shopify store specific page or path to your subdomain How to connect a specific page of your Shopify store page to your domain?
Important, not the shop itself, just a specific path/page.
For example:
https://the-landing-test.myshopify.com/blogs/news -> https://journal.landing.com

A: The only solution I found so far is to use Stealth Forwarding.
Although it has few drawbacks it was the only way of accomplishing what I needed.
1 way of doing it is here, with Nginx.


text:
Q: Need to replace 0 with 1 in LINQ? let value2 = Grp.Count(x => x.Column1 <= 2 && x.Column2== "studentName") * 100 / Grp.Count(x => x.Column2== "studentName")
in this the Bold is zero sometimes and it give me infinity i want to replace it with 1 if value is zero.

A: Using a C# Extension you can do something like this. Add this class into your namespace.
 public static class DataFormatter
 {
    public static int CheckForZero(this int value)
    {
       return value == 0? 1 : value;
    }
 }

And then you can do this.
 let value2 = Grp.Count(x => x.Column1 <= 2 && x.Column2== "studentName") * 100 /
   Grp.Count(x => x.Column2== "studentName").CheckForZero(); //add this check

Else you can use the usual ternary operator like below..
 var initialCount = Grp.Count(x => x.Column2== "studentName");
 var refinedCount = initialCount == 0?  1: initialCount;

A: Use an external variable or if you don't mind the performance hit, just use an Any() with a ternary operator. Linq's Any will return true if the predicate matches atleast one value, so if you find a match, it will find the count. Otherwise it will just return 1 in the denominator.
let value2 = Grp.Count(x => x.Column1 <= 2 && x.Column2== "studentName") * 100 / (Grp.Any(x => x.Column2 == "studentName") ? Grp.Count(x => x.Column2== "studentName") : 1)

Using an external variable would look like:
let valueStudentName = Grp.Count(x => x.Column2== "studentName")
let value2 = Grp.Count(x => x.Column1 <= 2 && x.Column2== "studentName") * 100 / valueStudentName != 0 ? valueStudentName : 1


text:
Q: TikZ: Place different elements of a same path on various layers I have different elements (say, a node and a filled circle) defined using a single path:
\path (0,0)
    node [blue] {some text}
    [fill, red] circle [radius = 1];

Issue: I would like to put one of these elements (the circle) on a given layer (that is the background layer).
I have tried [fill, red, on background layer] as option but it doesn't work. I cannot open/close a scope environment in the middle of a path neither.

MWE
The example below is constructed as following:

*

*some elements (here a black line),

*a path containing a node with text and a circle.

Resulting layers are thus (considering first bullet = top layer) :

*

*text + circle,

*some elements.

However, I'd like to have:

*

*text,

*some elements,

*circle.

\documentclass[margin=10pt]{standalone}
    \usepackage{tikz}
        \usetikzlibrary{positioning, fadings, backgrounds}
\begin{document}
    \begin{tikzpicture}
            \draw [very thick] (-1,-1) -- (1,1);
            \path (0,0)
                node [red!20, font=\sffamily\bfseries] {some text}
                [fill, red, on background layer] circle [radius=1];

            \node at (0,2) {actual trial};

        \begin{scope}[xshift=-3cm]
            \path (0,0) [fill, red, on background layer] circle [radius = 1];
            \draw [very thick] (-1,-1) -- (1,1);
            \path (0,0) node [red!20, font=\sffamily\bfseries] {some text};

            \node at (0,2) {expected};
        \end{scope}
    \end{tikzpicture}
\end{document}

Edit:
For a better understanding, here is my real problem that is abstracted hereinabove. In following picture, I want the text to be above the axes (as it is now), and the shading below (it is not the case)... and I want to draw both of them using on unique command.

A: You can use the decorations.markingslibrary, along with the preaction key, so that the decoration is added "before" the path is drawn. Basically this is like the second solution you posted, but all in one.
This code provides a style with two arguments decred={ <pos> }{ <text> }. The colored node will be behind the line, the text in front of it.
Output

Code
\documentclass[margin=10pt]{standalone}
\usepackage{tikz}

\usetikzlibrary{decorations.markings, backgrounds}

\tikzset{
    decred/.style 2 args={%
        decoration={markings, mark = at position #1 with {
            \begin{scope}[on background layer]
            \node[fill=red, circle, font=\sffamily\bfseries] {\phantom{#2}};
            \end{scope}
            \node[circle, text=red!20, font=\sffamily\bfseries] {#2};
        }}, postaction={decorate},
        thick,
    }
}

\begin{document}
\begin{tikzpicture}
\draw[decred={.5}{some text}] (-1,-1) -- (1,1);
\end{tikzpicture}
\end{document}

A: You could try with a pic. It's possible to define foreground code and background code which are drawn in front or behind the path.

\documentclass[margin=10pt]{standalone}
    \usepackage{tikz}
        \usetikzlibrary{positioning, fadings, backgrounds}

\tikzset{
    pics/mypic/.style = {
        foreground code = {\node [red!20, font=\sffamily\bfseries]{sometext};},
        background code = {\draw[fill, red] circle [radius=1];}
        }
}

\begin{document}
    \begin{tikzpicture}
       \draw [very thick] (-1,-1) -- pic{mypic} (1,1);
   \end{tikzpicture}

   \begin{tikzpicture}
       \draw [very thick] (-2,0) -- (2,0) (0,-2)--(0,2) (.5,.5) pic{mypic};
   \end{tikzpicture}
\end{document}

A: Here is a solution, based on LoopSpace's suggestion and on his work for implementing Z levels (i.e. layers) in TikZ.
The tricky part of the initial problem is the following: an object can be easily send to the background using [on background layer] option of the backgrounds TikZ-library. However, this apply to the whole path.
Yet, in my question, I wanted one part of a single path to be put on foreground, and another on the background.
Hence, the trick is to use several backgrounds (cf. LoopSpace work) and to apply them with pre/postactions. (Here, the text is first written with the [on layer=top] option, and then, using a postaction, we switch to the background and fill the circle).
The benefit of this solution compared to the other, is that you can put as many elements as you want in the middle ground (here symbolized with the black rule).
Furthermore, the "text+circle" element is independent of those middle-ground elements. Moreover, giving only one coordinate for the whole path, you have one of its component (text) on foreground, and one other on background (circle).

\documentclass[margin=10pt]{standalone}
    \usepackage{tikz}
        \usetikzlibrary{positioning, fadings, backgrounds}

    %-- see tex.stackexchange.com/a/20426/86
    \pgfdeclarelayer{back}
    \pgfdeclarelayer{front}
    \pgfsetlayers{back,main,front}

    \makeatletter
    \pgfkeys{%
        /tikz/on layer/.code={
            \pgfonlayer{#1}\begingroup
            \aftergroup\endpgfonlayer
            \aftergroup\endgroup
        },
        /tikz/node on layer/.code={
            \gdef\node@@on@layer{%
                \setbox\tikz@tempbox=\hbox\bgroup\pgfonlayer{#1}\unhbox\tikz@tempbox\endpgfonlayer\egroup}
            \aftergroup\node@on@layer
        },
        /tikz/end node on layer/.code={
            \endpgfonlayer\endgroup\endgroup
        }
    }

    \def\node@on@layer{\aftergroup\node@@on@layer}

    \makeatother
  %-- end see, many thanks to LoopSpace

\begin{document}
    \begin{tikzpicture}
            \node at (0,2) {solution};

            \draw [very thick] (-1,-1) -- (1,1);
            \path (0,0)
                [postaction={on layer = back, fill, red}] % <=== here is the trick: for the postaction, another layer is selected, and instructions are given for drawing the circle.
                node [%
                    red!20, font=\sffamily\bfseries,%
                    on layer = front % <==== It puts the text on foreground
                ] {some text}
                [radius = 1] circle % <==== note that the circle is defined, but without any information about "how to draw it"
            ;

        \node at (4.5,2) {not working};
        \draw (3,1.8) -- +(3, 0);
        \begin{scope}[xshift=3cm]
            \draw [very thick] (-1,-1) -- (1,1);
            \path (0,0)
                [postaction={on background layer, fill, red}] % <=== here is the trick: for the postaction, another layer is selected, and instructions are given for drawing the circle.
                node [%
                    red!20, font=\sffamily\bfseries,%
                    %on layer = front % <==== It puts the text on foreground
                ] {some text}
                [radius = 1] circle % <==== note that the circle is defined, but without any information about "how to draw it"
            ;
        \end{scope}

        \begin{scope}[xshift=6cm]
            \draw [very thick] (-1,-1) -- (1,1);
            \path (0,0)
                node [on layer = front, red!20, font=\sffamily\bfseries] {some text} % <== here the layer is set to front, but...
                [on layer = back, fill, red, radius = 1] circle % <== there, we set the layer to back, and this apply *to the whole* path!
            ;
        \end{scope}
    \end{tikzpicture}
\end{document}


text:
Q: Oracle and optional stored procedure parameter in where clause I have a stored procedure with an optional parameter like this
create or replace
PROCEDURE "my_stored_procedure" (param1 int, param2 int default null)
IS

BEGIN

[select some fields from some tables]
...

I need a where clause with a if on the default parameter (if it is set), but I don't even know if it's possible...
Something like
where param1=123 and (if param2 is not null then some_value != param2)

The select clause it's pretty long and complex, so I'll prefer to have a "flexible" WHERE rather than a structure like
if param2 is not null then
    [long and complex select] where param1=123 and some_value != param2
else
    [long and complex select] where param1=123

Is this possible?

A: In this case you can do:
where param1=123 and (param2 is null or param2 != some_value)

If param2 is not null - then it's true only if param2 != some_value - as expected
If param2 is null - then it returns true no matter what some_value is

A: Initially we used this syntax:
WHERE (pParameter = COLUMN OR pParameter IS NULL)

until a database tuning specialist found out that this causes Oracle to perform full table scans and ignore the indexes, because of using OR.
Now we use
WHERE decode(pParameter,
             null, 1, --if parameter is null, then return 1
             COLUMN, 1, -- if parameter matches the value in the column, then return 1
             0) --else return 0
             = 1

this construct allows an easy and readable way to add special handling for special values
WHERE decode(pParameter,
     null, 1, --if parameter is null, then allow the row
     'abc', 1, --if parameter is 'abc', then always allow the row
     'xyz', 1, --if parameter is 'xyz', then always reject the row
     COLUMN, 1, -- if parameter matches the value in the column, then allow
         0) --else return 0 to reject the row
         = 1

Alternatively, you can rewrite this with COALESCE or with CASE:
WHERE COALESCE(pParameter, COLUMN, 'ok') = COALESCE(COLUMN, 'ok')

or, sample using CASE:
THEN    (
            case
            when pParameteris null then 1
            when pParameter= COLUMN then 1
            else 0
            end
        ) = 1


text:
Q: SQL Query - Combine rows based on multiple columns
On the image above, I'd like to combine rows with the same value on consecutive days.
Combined rows will have the earliest date on From column and the latest date on To column.
Looking at the example, even if Rows 3 and 4 have the same value, they were not combined because of the date gap.
I've tried using LAG and LEAD functions but no luck.

A: You can try below way -
DEMO
    with c as
    (
    select *, datediff(dd,todate,laedval) as leaddiff,
    datediff(dd,todate,lagval) as lagdiff
    from
    (
    select *,lead(todate) over(partition by value order by todate) laedval,
    lag(todate) over(partition by value order by todate) lagval
    from t1
    )A
    )

select * from
(
select value,min(todate) as fromdate,max(todate) as todate from c
    where coalesce(leaddiff,0)+coalesce(lagdiff,0) in (1,-1)
    group by value
    union all
    select value,fromdate,todate from c
    where coalesce(leaddiff,0)+coalesce(lagdiff,0)>1 or coalesce(leaddiff,0)+coalesce(lagdiff,0)<-1
)A order by value

OUTPUT:
value   fromdate            todate
1       16/07/2019 00:00:00 17/07/2019 00:00:00
3       21/07/2019 00:00:00 26/07/2019 00:00:00
2       18/07/2019 00:00:00 18/07/2019 00:00:00
2       20/07/2019 00:00:00 20/07/2019 00:00:00

A: I am going to recommend the following approach:

*

*Find where each new group begins.  You can do this by comparing the previous maximum todate with the fromdate in this row.

*Do a cumulative sum of the starts to define a group.

*Aggregate the results.

This can be handled using window functions and aggregation:
select value, min(fromdate) as fromdate, max(todate) as todate
from (select t.*,
             sum(case when prev_todate >= dateadd(day, -1, fromdate)
                      then 0   -- overlap, so this does not begin a new group
                      else 1   -- no overlap, so this does begin a new group
                 end) over
                 (partition by value order by fromdate) as grp
      from (select t.*,
                   max(todate) over (partition by value
                                     order by fromdate
                                     rows between unbounded preceding and 1 preceding
                                    ) as prev_todate
            from t
           ) t
     ) t
 group by value, grp
 order by value, min(fromdate);

Here is a db<>fiddle.


text:
Q: correct sintaxis of json with laravel I have a problem with a Controller because I have this code:
public function index()
{
    $all = Nodes::all();
    return Response::json($all);
}

My problem is that I need realize a count about this response and I don't know how to express this because in the view I have the following error.

Undefined variable: all (View: C:\xampp2\htdocs\copiaAngus\app\views\nodes\index.blade.php)

PHP
foreach ($all as $user)
{
    var_dump($user->id);
}

A: Don't use Response::json($all) as it is not the way of passing data into a view.
Instead, use:
return View::make('nodex/index')->with('all', $all);

Then in the view your code should work.


text:
Q: How to rewrite the ast to use cache value for function in Python? I would like to write a Fibonacci program in Python and it will rewrite the AST to use a cache to avoid intermediate calculation if possible.
My current implementation will find all ast.Call and transform them to ast.Constant node. However, I cannot get the correct result from the code below. I suspect it's due to I am not using func args properly.
Really appreciate your help! Thanks.
Code in Python3.9.7
    import ast
    import inspect
    import types

    class Rewrite(ast.NodeTransformer):
        def visit_Call(self, node):
            func_name = node.func.attr
            if (func_name, self._func_args) in self._cache:
                print(
                    f"Hitting cache: {self._func_args} to get {self._cache[(func_name, self._func_args)]}"
                )
                return ast.Constant(self._cache[(func_name, self._func_args)])
            return node

    def dag(f):
        def wrapper(*args, **kwargs):
            _self = args[0]
            func_args = args[1:]
            source = inspect.getsource(f)
            lines = source.splitlines()[1:]
            lines[0] = lines[0].lstrip()
            source = "\n".join(lines)
            old_code_obj = f.__code__
            old_ast = ast.parse(source)
            rewriter = Rewrite()
            rewriter._cache = _self._cache
            rewriter._func_args = func_args
            new_ast = rewriter.visit(old_ast)
            ast.fix_missing_locations(new_ast)
            new_code_obj = compile(new_ast, old_code_obj.co_filename, "exec")
            print(ast.dump(new_ast))
            print("dumped")
            new_f = types.FunctionType(new_code_obj.co_consts[0], f.__globals__)
            value = new_f(*args, **kwargs)
            print(f"args: {args}, kwargs:{kwargs}")
            print("value", value)
            if (f.__name__, func_args) not in _self._cache:
                _self._cache[(f.__name__, func_args)] = value
            print(f"cache_after", _self._cache)
            return value

        return wrapper

    class Rick:
        def __init__(self):
            self._cache = {}

        @dag
        def fibonacci(self, n):
            return 1 if n < 2 else self.fibonacci(n - 1) + self.fibonacci(n - 2)

    Rick().fibonacci(4)


text:
Q: PDFLatex tables are covering up text I have a series of images that I'm displaying using a table environment. However, pdflatex places my table over the references portion of my paper.

I've tried [htb!] options for the table, and it doesn't seem to make much of a difference. I've also tried to use:
\usepackage{float}
\restylefloat{table}

with the [H] option, but that hasn't worked either.
Any ideas on how to prevent this from happening?

A: Found this just a second ago - just my luck...
latex-fullpage picture in two column layout
The solution is to use the figure* environment. It had everything to do with the two-column layout, and nothing to do with the image placement specifiers [htb].
\begin{figure*}[ht]
\centering
...
\end{figure*}


text:
Q: How to move the image to top of page in pdf using simpledoctemplate reportlab package? //This uses simpledoctemplate to create pdf. Im not able to bring the image to top of the page. Please give a solution
def report_creator():
    styles = getSampleStyleSheet()
    styleN = styles['Normal']
    styleH = styles['Heading1']
    elements = []
    im = Image("C:\\Images\photo.jpg")
    elements.append(im)
    doc = SimpleDocTemplate("C:\\report_image.pdf", pagesize=letter)
    doc.build(elements)
if __name__ == "__main__":
    report_creator()
    print "main"

A: The width and height of reportlab's letter page size is (612.0, 792.0).
So you can get the the starting position for your input image by dividing ((page's width/2) - (input image's width/2)).
In this example
page's width = 612.0
input image width = 100
So starting position(x) for input image would be:
>>> int((612.0/2) - (100/2))
256

Note :- Image size is passed as argument in drawInlineImage method of Canvas.
from PIL import Image
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter

def generate_pdf(c):
    """
    letter :- (612.0, 792.0)
    """
    im = Image.open("so.png")
    c.drawInlineImage(im, 256, 720, width=100, height=60)

c = canvas.Canvas("report_image.pdf", pagesize=letter)
generate_pdf(c)
c.save()

Generated PDF looks like this:

A: From source code, when drawing, Image try to get _offs_x, _offs_y attributes
def draw(self):
    lazy = self._lazy
    if lazy>=2: self._lazy = 1
    self.canv.drawImage(    self._img or self.filename,
                            getattr(self,'_offs_x',0),
                            getattr(self,'_offs_y',0),
                            self.drawWidth,
                            self.drawHeight,
                            mask=self._mask,
                            )
    if lazy>=2:
        self._img = self._file = None
        self._lazy = lazy

To position the image using SimpleDocTemplate, you can overwrite the _offs_x and _offs_y attributes of Image object before adding it into story.
im.__setattr__("_offs_x", 0)
im.__setattr__("_offs_y", 0)


text:
Q: Python : find substring1 and if it does not exist then find substring2 For Example:
my string looks like this:
1.1.0-feature
1.1.0-feature
1.1.0-feature
1.1.0-feature
1.1.0-feature
1.1.0-mainline
1.1.0-feature
1.1.0-feature
1.1.0-feature
1.1.0-mainline
1.1.0-mainline
v1.5.0-mainline
substring1 = mainline
substring2 = feature
if substrin1 exist in string:
 print string and do not enter to else statement

else check if substring2 exist in string
 print string

Output should be:
1.1.0-mainline

A: Since you want to do the same thing under both conditions, there's no need for two if statements, a single one will do.  The or is short circuiting so if the first condition is True the second won't be checked.
if substring1 in string or substring2 in string:
    print(string)


text:
Q: Adding a row to database if it doesn't exist I have a databaste, visitorsCounter, and I want to add a new row everytime someone visits the page. I'm getting their IP, and then I check if there isn't a row in the databaste with their IP. If there isn't, I add a new row.
$visitor_ip = getUserIP();
if(!isset($db)) $db = connect_db(); // connecting to the databaste with PDO
$userName = $_SESSION['username'];

$query = "SELECT entries from visitorsCounter WHERE ip=:ip";
$stmt = $db->prepare ( $query );
$stmt->bindParam ( ":ip", $visitor_ip);
$stmt->execute ();
$result = $stmt->fetch ( PDO::FETCH_ASSOC );

if($result != null){ // **** if there isn't a row with that IP ****
$addEntryQuery = "UPDATE visitorsCounter SET entries = entries + 1 WHERE ip=:ip";
$stmt = $db->prepare ( $addEntryQuery );
$stmt->bindParam ( ":ip", $visitor_ip);
$stmt->execute ();
}

EDIT: adding a row with user code:
    $userName = $_SESSION['username'];
$query = "INSERT INTO visitorsCounter(ip, entries, user)
    VALUES (:ip, 1,:user)
    ON DUPLICATE KEY UPDATE entries = entries + 1;
        ";
$stmt = $db->prepare ( $query );
$stmt->bindParam ( ":ip", $visitor_ip);
$stmt->bindParam ( ":user", $userName);
$stmt->execute ();

if(isset($_SESSION['username'])){
$addEntryQuery = "UPDATE visitorsCounter SET user = :user WHERE ip=:ip";
$stmt = $db->prepare ( $addEntryQuery );
$stmt->bindParam ( ":ip", $visitor_ip);
$stmt->bindParam ( ":user", $userName);
$stmt->execute ();
}

A visitor come in the website, and the user is null in the database. But when he logins, it stays null. Any idea why?

A: You should be doing this as one statement.  The key idea is on duplicate key update.
So, add a unique index to your table so the database enforces one row per ip:
create unique index unq_visitorscounter_ip on visitorsCounter(ip);

Then, update/insert the value as:
INSERT INTO visitorsCounter(ip, entries)
    VALUES (ip, 1)
    ON DUPLICATE KEY UPDATE entries = entries + 1;

In addition to simplifying your code, this is the more correct way of expressing the logic.  You code can have race conditions if the same ip is being inserted at the same time by different applications/threads.

A: I think the reason you never get inside the "update" if-statement is that you shouldn't check for null, but instead check for a false value.
According to the documentation for PDOStatement::fetch() you will get false returned on failure.
So your code should work better with a
if($result !=== false) {
    ...
}


text:
Q: RecyclerView onDoubleClick and onClick After reading Jacob's solution at RecyclerView onClick question   I tried to extend his solution for the "Double Click" event. When I register the recyclerview to both click and double click listeners, onDoubleClick() is correctly called but onClick() is also called when the user double click, which I want to avoid. I want that if the double click event is detected, no single click event be detected.
Below is the code of my double click listener adapted from  Jacob's solution :
 public class RecyclerItemDoubleClickListener implements RecyclerView.OnItemTouchListener {
    private OnItemDoubleClickListener doubleClickListener;

    public interface OnItemDoubleClickListener {
        public void onItemDoubleClick(View view, int position);
    }

    GestureDetector mGestureDetector;

    public RecyclerItemDoubleClickListener(Context context, OnItemDoubleClickListener listener) {
        doubleClickListener = listener;
        mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override public boolean onDoubleTap(MotionEvent e) {
                return true;
            }
        });
    }

    @Override public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
        View childView = view.findChildViewUnder(e.getX(), e.getY());
        if (childView != null && doubleClickListener != null && mGestureDetector.onTouchEvent(e)) {
            doubleClickListener.onItemDoubleClick(childView, view.getChildPosition(childView));
        }
        return false;
    }

    @Override public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { }
}

And I simply register like that :
    recyclerView.addOnItemTouchListener(new RecyclerItemDoubleClickListener(
            this, new RecyclerItemDoubleClickListener.OnItemDoubleClickListener() {
        @Override
        public void onItemDoubleClick(View view, int position) {
            Toast.makeText(ActivityMain.this, "double click " + position, Toast.LENGTH_SHORT).show();
        }
    }));

    recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(
            this, new RecyclerItemClickListener.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {
            Toast.makeText(ActivityMain.this, "single click " + position, Toast.LENGTH_SHORT).show();
        }
    }));

How would you handle this?
PS : I also would like to detect "longClick", "swipe left", "swipe right" on the same recyclerview item independently. But I guess that's maybe too much to code by myself. I will wait for libraries or Google to provide it.

A: use onSingleTapConfirmed() method of the GestureListener to differentiate between the singleTap and DoubleTap.
http://developer.android.com/reference/android/view/GestureDetector.SimpleOnGestureListener.html#onSingleTapConfirmed%28android.view.MotionEvent%29
To detect swipe left and right use onFling() of GestureListener
inside onFling use the following code
if(motionEvent.getX() - motionEvent.getX() > SWIPE_MIN_DISTANCE ) {
    onSwipeRightToLeft();
    }  else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE ) {
    onSwipeLeftToRight();
    }

A: you can use ItemTouchHelperto add swipe to dismiss and drag & drop support to RecyclerView.


text:
Q: ASP.NET MVC3 Hand coding IoC Ninject, Sprint.NET, Unity, Autofac, Castle.Windsor are all examples are IoC frameworks that are available.  However, I like the learning curve and control of writing my own.  It is definitely common practice to not "re-invent the wheel" and just use pre-existing structures.  If your comment is along those lines please be gentle.
Can IoC be implemented without the use of XML? It seems to me most, if not all, of the aforementioned frameworks use XML but I would much rather just write mine in C# instead of using XML to load a .dll.  The C# is all converted into one .dll eventually anyway.
From my understanding, if wrong please correct, IoC can be used with DI to make the functionality of classes be based off of their definition and implementation while allowing for a separation of concerns.
This is accomplished in C# using microsoft's library System.ComponentModel.IContainer by having a class which inherits it.  A class, such as Product, would have an interface IProduct. A generic constructor would then inherit from IContainer and in the constructor, allow a repository to be passed in, an instantiated object to be passed in, and a function to be passed in.  This would allow a controller action to then instantiate an interface (IProduct), instantiate the generic constructor with the current repository instance, and then pass it the interface and function.
Is this setup accurate?
I am still trying to learn more about this topic, and have read the wiki articles on IoC, DI, and read about Castle.Windsor, ninject, Unity, and looked over multiple definitions from the MSDN regarding C# libraries which are used.  Any assistance, corrections, or suggestions, are greatly appreciated.  Thanks

A:
Can IoC be implemented without the use of XML?

Yes, Ninject, Unity, Castle Windsor and Autofac can be configured without using any XML at all. (not sure about Spring.NET, last time I used it it was impossible, version 1.3)

From my understanding, if wrong please correct, IoC can be used with
  DI to make the functionality of classes be based off of their
  definition and implementation while allowing for a separation of
  concerns.

If under "IoC" you mean "IoC container" then yes, it can be used with DI, but since DI is a particular case of Inversion Of Control your IoC container will be just a container for you dependencies. By just having it your will not magically get any DI-friendly types. It's just a support for managing your inverted dependencies.
Edit
As Mystere Man pointed in his answer you need to improve you understanding of the IoC containers. So I would recommend to read this wonderful book (from Mark Seeman) about all that stuff.

A: I think it is a great exercise to start without a DI container. Before focusing on using a DI framework, focus on best patterns and practices. Especially, design all classes around Dependency Injection and make sure your code follows the SOLID principles. Both sounds pretty easy, but this takes a shift in mindset and a lot of practice before you will get this right (but is well worth it).
When you do this, and do this well, you will quickly notice that your application will evolve in amazing ways. Your code will be testable and extendable in ways that you never imagined before, without your code to rot over time (however, it keeps constant focus to prevent code from rotting).
Still, when you do all this right (which –again- takes a lot of practice), you will still have one part of your application that, despite your best efforts, will get more complex and harder to maintain, as the application grows. This is the part of the application where you wire all dependencies together: the Composition Root.
And this is where DI containers come in. They have fancy names and compete with each other over features, but their goal can be stated in a single sentence:

The goal of a DI container is to keep the Composition Root
  maintainable.

Although you can write your own simple DI container to wire up your dependencies, to prevent your Composition Root to become a big fragile, ever changing ball of mud, the container must at least have one crucial feature: Automatic Constructor Injection (a.k.a. auto-wiring). With auto-wiring, the container will look at the constructor arguments of a type that it needs to create, and it will inject the dependencies in it based on the types of those arguments. This feature will make the difference between a maintenance nightmare and a healthy Composition Root. Although creating your own container that supports auto-wiring isn't that hard (with expression trees it takes about 20 lines of code), the moment you start needing auto-wiring is the time to start using one of the existing DI frameworks.
So in conclusion, if you feel it helps you in the learning experience by doing this by hand, please do, as long as you stick to SOLID, DI, DRY, and TDD. When the burden of changing your Composition Root for each change in the application gets too big (which will be sooner than you might expect), switch to an established framework.

A: I would suggest using an existing DI container first, to understand how it works from the end user perspective.  Then you can go about re-designing the wheel.  My favorite saying is "You have to know the rules before you can break them".
Some of what you've said doesn't make a lot of sense.  you don't have to use System.ComponentModel.IContainer in any framekwork i know of.  Maybe Unity requires that (Microsoft's container) but none of the others do.  I'm not familiar with Unity thogh.


text:
Q: Consuming SOAP and REST WebServices at the same time in PHP My objective is consume various Web Services and then merge the results.
I was doing this using PHP cURL, but as the number of Web Services has increased, my service slowed since the process was waiting for a response and then make the request to the next Web Service.
I solved this issue using curl_multi and everything was working fine.
Now, I have a new problem, because I have new Web Services to add in my service that use Soap Protocol and I can't do simultaneous requests anymore, because I don't use cURL for Soap Web Services, I use SoapClient.
I know that I can make the XML with the soap directives and then send it with cURL, but this seems to me a bad practice.
In short, is there some way to consume REST and SOAP Web Services simultaneously?

A: I would first try a unified, asynchronous guzzle setup as others have said.  If that doesn't work out I suggest not using process forking or multithreading.  Neither are simple to use or maintain.  For example, mixing guzzle and threads requires special attention.
I don't know the structure of your application, but this might be a good case for a queue.  Put a message into a queue for each API call and let multiple PHP daemons read out of the queue and make the actual requests.  The code can be organized to use curl or SoapClient depending on the protocol or endpoint instead of trying to combine them. Simply start up as many daemons as you want to make requests in parallel.  This avoids all of the complexity of threading or process management and scales easily.
When I use this architecture I also keep track of a "semaphore" in a key-value store or database.  Start the semaphore with a count of API calls to be made.  As each is complete the count is reduced.  Each process checks when the count hits zero and then you know all of the work is done.  This is only really necessary when there's a subsequent task, such as calculating something from all of the API results or updating a record to let users know the job is done.
Now this setup sounds more complicated than process forking or multithreading, but each component is easily testable and it scales across servers.
I've put together a PHP library that helps build the architecture I'm describing.  It's basic pipelining that allows a mix of synchronous and asynchronous processes.  The async work is handled by a queue and semaphore.  API calls that need to happen in sequence would each get a Process class.  API calls that could be made concurrently go into a MultiProcess class.  A ProcessList sets up the pipeline.

A: Yes, you can.
Use an HTTP client(ex: guzzle, httpful) most of them are following PSR7, prior to that you will have a contract. Most importantly they have plenty of plugins for SOAP and REST.
EX: if you choose guzzle as your HTTP client it has plugins SOAP. You know REST is all about calling a service so you don't need extra package for that, just use guzzle itself.
**write your API calls in an async way (non-blocking) that will increase the performance. One solution is you can use promises
Read more

A: its not something php is good at, and you can easily find edge-case crash bugs by doing it, but php CAN do multithreading - check php pthreads and pcntl_fork. (neither of which works on a webserver behind php-fpm / mod_php , btw, and pcntl_fork only works on unix systems (linux/bsd), windows won't work)
however, you'd probably be better off by switching to a master process -> worker processes model with proc_open & co. this works behind webservers both in php-fpm and mod_php and does not depend on pthreads being installed and even works on windows, and won't crash the other workers if a single worker crash. also you you can drop using php's curl_multi interface (which imo is very cumbersome to get right), and keep using the simple curl_exec & co functions.  (here's an example for running several instances of ping https://gist.github.com/divinity76/f5e57b0f3d8131d5e884edda6e6506d7 - but i'm suggesting using php cli for this, eg proc_open('php workerProcess.php',...); , i have done it several times before with success.)

A: You could run a cronjob.php with crontab and start other php scripts asynchronously:
// cronjob.php
$files = [
    'soap-client-1.php',
    'soap-client-2.php',
    'soap-client-2.php',
];

foreach($files as $file) {
    $cmd = sprintf('/usr/bin/php -f "%s" >> /dev/null &', $file);
    system($cmd);
}

soap-client-1.php
$client = new SoapClient('http://www.webservicex.net/geoipservice.asmx?WSDL');

$parameters = array(
    'IPAddress' => '8.8.8.8',
);
$result = $client->GetGeoIP($parameters);
// @todo Save result

Each php script starts a new SOAP request and stores the result in the database. Now you can process the data by reading the result from the database.

A: This seems like an architecture problem. You should instead consume each service with a separate file/URL and scrape JSON from those into an HTML5/JS front-end. That way, your service can be divided into many asynchronous chunks and the speed of each can been tweaked separately.


text:
Q: how to stop ABP from querying EMPTY AbpUserOrganizationUnits TABLE We  use ABP with a  MSSQL database hosted on Azure.
in scope of Cost optimization we need to make as less requests to DB as possible.
during investigation i found out that  ABP does  around 50 millions of requests to table  AbpUserOrganizationUnits per month and we don't this table at all
I would like to disable all calls to this table.
making 50 millions requests to database to receive an empty set is not what a normal product should do.
i woudl like to know if there is a way to stop this requests or if redirect them to a redis Cache or even  stop them inside the API


text:
Q: Probability from a random pick. A test was given to a group of students. The grades and gender are summarized below

If one student is chosen at random from those who took the test,
Find the probability that the student got a 'C' GIVEN they are female.

The total females is 43, total C's are 19
  The total females who have a C is 5 of 19
  So my answer is 5/19, is this wrong?

A: AHHH, I was reading it wrong.
The answer is 5/43.
I was reading, the probability that a student is female given they got a C.
which is 5/19


text:
Q: javascript reload only once I don't know javascript and I have tried to find an answer on this before posting.
$(function(){
    $('body').fadeIn(1000);
    setTimeout(function(){
        $('body').fadeOut(2000, function(){
            location.reload(true);
        });
    }, 5000); // 5 seconds for demo
});

See the code in work here: http://jsfiddle.net/7duedzkb/5/
This code reloads a page every 5 seconds. I'd want to modify it to reload a page only once, basically it will reload the page after 5 secs and then stops the reload loop. I need this on a aggregator type of site where at first page opening the feeds are loaded from cache for speed issues.
Can you help? Much appreciated.
Thank you

A: You must reload only if a certain condition is true. For example, you can save in sessionStorage a flag and read if exists don't reload.
var store = window.sessionStorage;
$(function(){
    $('body').fadeIn(1000);
    if(!store.getItem("reloaded")) {
       setTimeout(function(){
           $('body').fadeOut(2000, function(){
               store.setItem("reloaded", "true");
               location.reload(true);
           });
       }, 5000); // 5 seconds for demo
    }
});

It's better session storage instead of localstorage, because the next time user comes to the page the flag will be setted.
EDIT
Solution storing the URL of the page (assuming the URLs are unique):
var store = window.sessionStorage;
var page = window.location.href;
$(function(){
    $('body').fadeIn(1000);
    if(!store.getItem("reloaded-"+page)) {
       setTimeout(function(){
           $('body').fadeOut(2000, function(){
               store.setItem("reloaded-"+page, "true");
               location.reload(true);
           });
       }, 5000); // 5 seconds for demo
    }
});

A: Use localStorage for this purpose,
$(function(){
    $('body').fadeIn(1000);
    if(localStorage.getItem("reloaded") !== "true") {
    //Check the flag in localStorage before begin the reload.
      setTimeout(function(){
        $('body').fadeOut(2000, function(){
            localStorage.setItem("reloaded","true");
            //set a flag during the first reload in localStorage
            location.reload(true);
        });
      }, 5000); // 5 seconds for demo
    }
});

DEMO
Or Use SessionStorage as pointed in the below comments, based on your req :-
var storage = window.sessionStorage;
$(function(){
    $('body').fadeIn(1000);
    if(!storage.getItem("reloaded")) {
    setTimeout(function(){
        $('body').fadeOut(2000, function(){
            location.reload(true);
            storage.setItem("reloaded", "true");
        });
    }, 5000); // 5 seconds for demo
    }
});

A: set the flag in a cookie and check it everytime before doing a reload
$(function(){
    $('body').fadeIn(1000);
    setTimeout(function(){
        $('body').fadeOut(2000, function(){
            if ( getCookie("reload") != "true" )
            {
               setCookie("reload", "true");
               location.reload(true);
            }
        });
    }, 5000); // 5 seconds for demo
});

    function setCookie(key, value) {
        var expires = new Date();
        expires.setTime(expires.getTime() + (1 * 24 * 60 * 60 * 1000));
        document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
    }

    function getCookie(key) {
        var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
        return keyValue ? keyValue[2] : null;
    }

A: $(function(){
    $('body').fadeIn(1000);
    if (localStorage.reloaded !== 'true') {
        setTimeout(function(){
            $('body').fadeOut(2000, function(){
                localStorage.reloaded = 'true';
                location.reload(true);
            });
        }, 5000); // 5 seconds for demo
    }
});

A: Use SessionStorageto achieve the result, please see the below sample:-
var storage = window.sessionStorage;
$(function(){
    $('body').fadeIn(1000);
    if(!storage.getItem("reloaded")) {
    setTimeout(function(){
        $('body').fadeOut(2000, function(){
            location.reload(true);
            storage.setItem("reloaded", "true");
        });
    }, 5000); // 5 seconds for demo
    }
});

Sample


text:
Q: JQuery DataTables - Style Child Rows So I'm recreating the solution from this post.
JQuery Datatable with parent child relationship in same dataset. How to display it as parent child rows in the table?
Take a look at the accepted answer and run the code.
You have a table like this, with child rows.

Those child <tr> and <td> elements are created inside of another <table> which is embedded inside of another <tr> and <td> tag.  If you have FireBug installed, click on Inspect Element to see this.

Take a look at the <tr> line in dark blue and the <td> below it.  It looks like those are automatically created by something.  I can't see where those are coming from.  I want to have my child <tr> and <td> elements (currently inside the table in the light blue line) in the same order as the parent columns.  I can strip out the <table> element, but I don't see why this is all embedded in a <td>.  Can anyone see a way to have my child elements appear in a row just like any other?
One final thought.  Is there any chance these rows would show up on an export?
https://datatables.net/extensions/buttons/examples/initialisation/export.html


text:
Q: Finding the string or substring within nth occurrence in a line I would like to find the third occurrence of string inside quotes in order to replace this string or part of this string. This is a typical line I have to deal with:

"/activities/absenceactivity/lang/#LANG_ID#/prop_dialog.php";"BA2_PD_SCR";"Opis
  dogodka";"Event description";"Descrição do Evento";"ÐпиÑ
  подÑÑ";"";"č®vykio aprašymas";"Descripción del evento";"";

I know that "([^"]*)" shows every occurrence of text and quotes but I would like to get just the third one, in this example "Opis dogodka" in order to perform Search & Replace in Sublime Text.
Problem is to find the third occurrence of string within the quotes, replace it entirely or just partially and make sure that the Regex provides also a solution for an empty

""

strings.
Thank you.

A: I'm sure there are ways to simplify this further, but if you're ok with brute force:
Sublime command:
 Find: "[^"]*";"[^"]*";"([^"]*)".*
 Replace: $1

NP++:
 Find what: "([^"]*)";"([^"]*)";"([^"]*)".*
 Replace with: $3

sed:
 sed 's/"\([^"]*\)";"\([^"]*\)";"\([^"]*\)".*/\3/'

A: You can use {} pattern repetition:
/(?:"([^"]*)";){3}/   # first match group will be 'Opis dogodka'

Demo
Or, use a global type match and then take the third match. This might require logic such as slicing or looping:
/"([^"]*)";/g

Demo 2
Or, just manually put in the first two patterns to skip:
 /^"[^"]*";"[^"]*";("[^"]*";)/

Demo 3
Or combine repetition to skip the first n-1 then capture the nth match:
/^(?:"[^"]*";){2}("[^"]*";)/

Demo 4


text:
Q: parse json data using python i have this json data that i want to parse using python code
{
   "_class":"com.cloudbees.plugins.credentials.CredentialsStoreAction$DomainWrapper",
   "credentials":[
      {
         "description":"",
         "displayName":"guest",
         "fingerprint":null,
         "fullName":"system/_/3fad6c4d-3f3a-48e1-9d7c-0f165e105907",
         "id":"3fad6c4d-3f3a-48e1-9d7c-0f165e105907",
         "typeName":"SSH Username with private key"
      },
      {
         "description":"",
         "displayName":"guest",
         "fingerprint":null,
         "fullName":"system/_/9c078a40-bfce-44bb-96df-9014ac129036",
         "id":"9c078a40-bfce-44bb-96df-9014ac129036",
         "typeName":"SSH Username with private key"
      },
      {
         "description":"",
         "displayName":"guest",
         "fingerprint":null,
         "fullName":"system/_/199b1b42-62a6-4859-ae94-c6ba832af693",
         "id":"199b1b42-62a6-4859-ae94-c6ba832af693",
         "typeName":"SSH Username with private key"
      },
      {
         "description":"",
         "displayName":"guest",
         "fingerprint":null,
         "fullName":"system/_/35abdef0-c727-49c9-830a-8acb940a92cc",
         "id":"35abdef0-c727-49c9-830a-8acb940a92cc",
         "typeName":"SSH Username with private key"
      },...

and this data goes on.
I got this data from aJSON API and i want the values of display name, id and typeName from here but i am not sure how to proceed.
I am relatively new to python and could come up with this code
response = requests.get(url, verify=False, auth=(user, api_token))
  response.status_code
#  print response.text
  json_data = response.json()
  print json_data
  resp_data = json.loads(credentials)
  resp_data['displayName']

A: You were very close. You just need to iterate over the resp_data.
response = requests.get(url, verify=False, auth=(user, api_token))
response.status_code
json_data = response.json()
resp_data = json_data['credentials']

for credential in resp_data:
    print(credential['displayName'], credential['id'], credential['typeName'], sep='---')

This should print out this response :
guest---SSH Username with private key---3fad6c4d-3f3a-48e1-9d7c-0f165e105907
guest---SSH Username with private key---9c078a40-bfce-44bb-96df-9014ac129036
guest---SSH Username with private key---199b1b42-62a6-4859-ae94-c6ba832af693
guest---SSH Username with private key---35abdef0-c727-49c9-830a-8acb940a92cc

In order to know more about working with JSON, you can reference this:
Working With JSON Data in Python
and also this JSON library official doc reference.

A: You need to iterate over the credentials array and print the values you want.
response = requests.get(url, verify=False, auth=(user, api_token))
response.status_code
json_data = response.json()
#iterate over credentials array
for credentials in json_data['credentials']:
    print(credentials['displayName'])
    print(credentials['id'])
    print(credentials['typeName'])


text:
Q: Add a new button to siebel list applet I have a requirement to add a new button to a List Applet with the caption 'TEST'. I have added a new control to the specific list applet with HTML Type 'MiniButton' and Caption as 'TEST'. The button displayed as follows. what could be the reason for this and how to correct it?

A: Have you check the location where you added the button in the list applet? If you add the control to the specific control location like "new","query" they might appear odd. Check also the button's property "HTML Bitmap" - it should be empty.

A: *

*As Pirkka mentioned, with post-IP17 Siebel the applet "edit weblayoyut" is only in WebTools and it doesn't work well. If you are using this version of Siebel, you might want to remove check the applet webtemplate item and ensure the SEQUENCE number assigned to it is correct. Just edit it in that list reference. My experience with the latest Siebel versions is that just adding the applet webtemplate item record directly is the best approach.

*Check the underlying webtemplate that is used for your applet. Make sure that the sequence number assigned at the applet webtemplate item level for your control is actually corresponding to a control section in the underlying list applet webtemplate.

*Is the applet and/or webtemplate custom? If it is OOTB, can you share the names?


text:
Q: Android Studio: separate package with subpackage
When you create a package in Android Studio, and then create subpackage, in a while it transforms to the form, you can see in attachment. So when I want to create another subpackage of acctocard with the help of
right button click -> new -> package,
my newly created package will be a subpackage of acctocard.activities.
Please, tell me, how to separate this packages, to have them displayed as a tree.
Thanks in advance!

A: As Sachin Bahukhandi adviced in the comments, I took a look at the post.
So what you need to do, is to click Project Bar -> Settings and uncheck Compact Empty Middle Packages item.

A: Just do something like that, actually I was struggling to find project bar


text:
Q: Appium : Element not identified during test run I have obtained locators using appium inspector . The obtained element works well during recording in appium inspector. But when I run the test case, appium fails to identify the element.
Below is the log in the server
    [JSONWP Proxy] Proxying [POST /session] to [POST
    http://127.0.0.1:8000/wd/hub/session] with body: {"desiredCapabilities":{"chromeOptions":{"androidPackage":"com.android.chrome","androidDeviceSerial":"3208c623a27f61e9"}}}
[Chromedriver] Webview version: 'Chrome/63.0.3239.111'
[JSONWP Proxy] Got response with status 200: {"sessionId":"a577f16ef658470ccbc8066131f27b70","status":0,"value":{"acceptSslCerts":true,"applicationCacheEnabled":false,"browserConnectionEnabled":false,"browserName":"chrome","chrome":{"chromedriverVersion":"2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f)"},"cssSelectorsEnabled":true,"databaseEnabled":false,"handlesAlerts":true,"hasTouchScreen":true,"javascriptEnabled":true,"locationContextEnabled":true,"mobileEmulationEnabled":false,"nativeEvents":true,"pageLoadStrategy":"normal","platform":"ANDROID","rotatable":false,"setWindowRect":false,"takesHeapSnapshot":true,"takesScreenshot":true,"unexpectedAlertBehaviour":"","version":"63.0.3239.111","webStorageEnabled":true}}
[Chromedriver] Changed state to 'online'
[Appium] New AndroidDriver session created successfully, session 9aa0ede8-867f-41a1-b4c9-61416598aaf0 added to master session list
[BaseDriver] Event 'newSessionStarted' logged at 1542707446213 (15:20:46 GMT+0530 (India Standard Time))
[MJSONWP] Responding to client with driver.createSession() result: {"platform":"LINUX","webStorageEnabled":false,"takesScreenshot":true,"javascriptEnabled":true,"databaseEnabled":false,"networkConnectionEnabled":true,"locationContextEnabled":false,"warnings":{},"desired":{"browserName":"chrome","platformName":"Android","deviceName":"3208c623a27f61e9"},"browserName":"chrome","platformName":"Android","deviceName":"3208c623a27f61e9","deviceUDID":"3208c623a27f61e9","platformVersion":"6.0.1","deviceScreenSize":"1080x1920","deviceModel":"SM-G900H","deviceManufacturer":"samsung"}
[HTTP] <-- POST /wd/hub/session 200 33062 ms - 584
[HTTP] --> POST /wd/hub/session/9aa0ede8-867f-41a1-b4c9-61416598aaf0/url {"url":"https://www.google.com"}
[MJSONWP] Driver proxy active, passing request on via HTTP proxy
[JSONWP Proxy] Proxying [POST /wd/hub/session/9aa0ede8-867f-41a1-b4c9-61416598aaf0/url] to [POST http://127.0.0.1:8000/wd/hub/session/a577f16ef658470ccbc8066131f27b70/url] with body: {"url":"https://www.google.com"}
[JSONWP Proxy] Got response with status 200: {"sessionId":"a577f16ef658470ccbc8066131f27b70","status":0,"value":null}
[JSONWP Proxy] Replacing sessionId a577f16ef658470ccbc8066131f27b70 with 9aa0ede8-867f-41a1-b4c9-61416598aaf0
[HTTP] <-- POST /wd/hub/session/9aa0ede8-867f-41a1-b4c9-61416598aaf0/url 200 4603 ms - 76
[HTTP] --> POST /wd/hub/session/9aa0ede8-867f-41a1-b4c9-61416598aaf0/element {"using":"xpath","value":"/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.view.ViewGroup/android.widget.FrameLayout[1]/android.widget.FrameLayout[2]/android.webkit.WebView/android.view.View/android.view.View[3]/android.view.View[1]/android.view.View/android.view.View[2]/android.view.View[3]"}
[MJSONWP] Driver proxy active, passing request on via HTTP proxy
[JSONWP Proxy] Proxying [POST /wd/hub/session/9aa0ede8-867f-41a1-b4c9-61416598aaf0/element] to [POST http://127.0.0.1:8000/wd/hub/session/a577f16ef658470ccbc8066131f27b70/element] with body: {"using":"xpath","value":"/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.view.ViewGroup/android.widget.FrameLayout[1]/android.widget.FrameLayout[2]/android.webkit.WebView/android.view.View/android.view.View[3]/android.view.View[1]/android.view.View/android.view.View[2]/android.view.View[3]"}
[JSONWP Proxy] Got response with status 200: {"sessionId":"a577f16ef658470ccbc8066131f27b70","status":7,"value":{"message":"no such element: Unable to locate element: {\"method\":\"xpath\",\"selector\":\"/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.view.ViewGroup/android.widget.FrameLayout[1]/android.widget.FrameLayout[2]/android.webkit.WebView/android.view.View/android.view.View[3]/android.view.View[1]/android.view.View/android.view.View[2]/android.view.View[3]\"}\n  (Session info: chrome=63.0.3239.111)\n  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.14393 x86_64)"}}
[JSONWP Proxy] Replacing sessionId a577f16ef658470ccbc8066131f27b70 with 9aa0ede8-867f-41a1-b4c9-61416598aaf0
[HTTP] <-- POST /wd/hub/session/9aa0ede8-867f-41a1-b4c9-61416598aaf0/element 200 205 ms - 733
[HTTP] --> DELETE /wd/hub/session/9aa0ede8-867f-41a1-b4c9-61416598aaf0 {}
[MJSONWP] Calling AppiumDriver.deleteSession() with args: ["9aa0ede8-867f-41a1-b4c9-61416598aaf0"]
[BaseDriver] Event 'quitSessionRequested' logged at 1542707451117 (15:20:51 GMT+0530 (India Standard Time))
[Appium] Removing session 9aa0ede8-867f-41a1-b4c9-61416598aaf0 from our master session list
[AndroidDriver] Shutting down Android driver
[AndroidDriver] Stopping chromedriver for context CHROMIUM
[Chromedriver] Changed state to 'stopping'
[JSONWP Proxy] Proxying [DELETE /] to [DELETE http://127.0.0.1:8000/wd/hub/session/a577f16ef658470ccbc8066131f27b70] with no body
[JSONWP Proxy] Got response with status 200: "{\"sessionId\":\"a577f16ef658470ccbc8066131f27b70\",\"status\":0,\"value\":null}"
[Chromedriver] Changed state to 'stopped'

A: I think the issue is that your screen's element is not available when you tried to interact with that element. If you tried to use implicit wait, it didn't work for me.
You can use explicit wait or Thread.sleep().

Thread.sleep() is not recommended way.

you can use explicit wait using following method:
 public void ExplicitWait(MobileElement element,int timeOutInSeconds) {
        (new WebDriverWait(driver, timeOutInSeconds)).until(ExpectedConditions
                .visibilityOf(element));
    }


text:
Q: remote: error: insufficient permission for adding an object to repository database objects - why is this happening? While trying to push into git (using source tree) I got the following output:
Pushing to ssh://USERNAME@DEVGROUP.local/git/PROJECTNAME
remote: error: insufficient permission for adding an object to repository database objects
remote: fatal: failed to write object
error: unpack failed: unpack-objects abnormal exit

(I used USERNAME & PROJECTNAME & DEVGROUP instead of the real output cause... copyrights...).
After a while, I tried pushing again and this time got the same output as well as this:
! [remote rejected] develop -> develop (unpacker error)

I found more then one answer to a similar problem, such as
 this, but everything I was able to find stated that I need to use chmod & chgrp commands, which I really don't want to use without good reason. So my question is - why is this problem appearing even if I was able to "git push" before, and how can it be fixed safely, without fear of messing with the settings?


text:
Q: Keyboard shortcut to select some text in a cell in Excel I'd like to know the shortcut I must use to do a multiple selection of some text (not adjacent words) in a unique cell.
The reason is because I need to highlight some text of the same cell, and I currently have to do it selecting the text individually.
So it would be very helpful to find the shortcut to multiple select, as Ctrl + click usually works.
I used it time ago, but I don't remember how I did.
Please, could you help me
Thanks & regards
Susana

A: AFAIK, there is no way to select non-adjacent words in a cell in Excel. If you need to format several non-adjacent words, you need to process them one at a time.

A: I think that the cmd key is your best bet.
I can't try it, i'm not in front of a computer now, but in most OS X programs and also in Word for Mac, the cmd key allows you to select different nonconsecutive strings of text.


text:
Q: Map NAS drive ip address to name I have a NAS drive on my local network at a static IP. i can browse this drive at \\10.0.0.x\
However, I would like to alias this ip to a more human readable name: \\server\
how do I accomplish this in Windows (10)?

A: Edit HOSTS file and add name record for your NAS.
location:

C:\Windows\System32\Drivers\etc

For example, if you wanted to use the HOSTS file to translate a host name of a computer called "printserver" into the IP address of 192.168.0.1, you would add this line:

192.168.0.1 printserver

You can add more than one host name to the same IP address. For example, if the computer called "printserver" also acts as a scanner called "scanserver", you could use this line:

192.168.0.1 printserver scanserver

(Edit using elevated prompt / save to other location and overwrite ... )
info : https://www.petri.com/easily-edit-hosts-file-windows-10


text:
Q: android onClick change fragment I want to change the Fragment when i click the button. The fragments are in the same adapter/viewpager.
FROM THIS FRAGMENT:
public class LoginFragment extends Fragment {

TextView linkToRegister;

public static final LoginFragment newInstance()
{
    LoginFragment mf = new LoginFragment();
    Bundle bd = new Bundle(1);
    mf.setArguments(bd);
    return mf;
}

public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState )
{
    View v = inflater.inflate(R.layout.fragment_login, container, false);

    linkToRegister = (TextView) v.findViewById(R.id.link_to_register);

    linkToRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Change Fragment
        }
    });

    return v;
}

}

TO THIS FRAGMENT:
public class RegisterFragment extends Fragment {

public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";

public static final RegisterFragment newInstance()
{
    RegisterFragment mf = new RegisterFragment();
    Bundle bd = new Bundle(1);
    mf.setArguments(bd);
    return mf;
}

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState )
{
    View v = inflater.inflate(R.layout.fragment_register, container, false);
    return v;
}
}

PagerAdapter:
public class WelcomePagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> Welcomefragments;

public WelcomePagerAdapter(FragmentManager fm, List<Fragment> Welcomefragments) {
    super(fm);
    this.Welcomefragments = Welcomefragments;
}

@Override
public Fragment getItem(int position) {
    return this.Welcomefragments.get(position);
}

@Override
public int getCount() {
    return this.Welcomefragments.size();
}
}

Activity:
public class WelcomeActivity extends AppCompatActivity {
ViewPager welcomeViewPager;
WelcomePagerAdapter welcomePagerAdapter;
List<Fragment> welcomeFragments;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_welcome);

    welcomeViewPager = (ViewPager) findViewById(R.id.viewPagerWelcome);
    welcomeFragments = getWelcomeFragments();
    welcomePagerAdapter = new WelcomePagerAdapter(getSupportFragmentManager(), welcomeFragments);

    welcomeViewPager.setAdapter(welcomePagerAdapter);

}

public List<Fragment> getWelcomeFragments() {
    List<Fragment> newFragment = new ArrayList<Fragment>();
    newFragment.add(LoginFragment.newInstance());
    newFragment.add(RegisterFragment.newInstance());
    return newFragment;

}

}

A: Step 1: Define a callback interface in the Fragment and hook in the Activity when the Fragment attaches to it.
public class MyFragment extends Fragment {

    public interface OnInteractionListener {
        void doAction(); // Can include parameters here if needed
    }

    private OnInteractionListener listener;

    @Override
    public void onAttach(Context context) {
        if (context instanceof OnInteractionListener) {
            listener = (OnInteractionListener) context;
        } else {
            throw new ClassCastException(context + "must implement " + OnInteractionListener.class.getSimpleName());
        }
        super.onAttach(context);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_layout, container, false);
        // ...
        return v;
     }
}

Step 2: Make sure your Activity implements that Interface
public class MyActivity extends AppCompatActivity implements MyFragment.OnInteractionListener {

    @Override
    public void doAction() {
        // TODO: Implement this... e.g. switch fragments
    }

    ...
}

Step 3: Inside the Fragment, you can invoke the callback whenever you want to perform some action
if (listener != null) {
    listener.doAction();
}

A: From MainActivity(), get the navController and then use the navigate() function:
NavController navController = Navigation.findNavController(this,R.id.nav_host_fragment);
navController.navigate(R.id.nav_grid);