text:
Q: Error: could not assemble transaction: ProposalResponsePayloads do not match (base64): i run this function in chaincode under hyperledger fabric:
func (c *SmartContract) InitiateUser(ctx contractapi.TransactionContextInterface, userID string) error {
    // Generate a new ECC key pair
    curve := elliptic.P256() // Use P-256 curve
    privateKey, err := ecdsa.GenerateKey(curve, rand.Reader)
    if err != nil {
        return fmt.Errorf("failed to generate private key: %v", err)
    }

    // Hash the public and private keys using SHA-256
    publicKeyHash := sha256.Sum256(elliptic.MarshalCompressed(curve, privateKey.PublicKey.X, privateKey.PublicKey.Y))
    privateKeyHash := sha256.Sum256(privateKey.D.Bytes())

    // Create a new User object from the input arguments and the ECC key pair
    user := &User{
        ID:         userID,
        PublicKey:  hex.EncodeToString(publicKeyHash[:]),
        PrivateKey: hex.EncodeToString(privateKeyHash[:]),
    }

    // Convert the User object to a JSON-encoded byte array
    userBytes, err := json.Marshal(user)
    if err != nil {
        return fmt.Errorf("failed to marshal user data to JSON: %v", err)
    }

    // Store the JSON-encoded byte array in the ledger using PutState
    err = ctx.GetStub().PutState(userID, userBytes)
    if err != nil {
        return fmt.Errorf("failed to put user data on the ledger: %v", err)
    }

    // Return a success response with the user data
    return nil
}

As result a get this error:
Error: could not assemble transaction: ProposalResponsePayloads do not match (base64): 'CiD6XpjbMfvrXmPkeykGv7m1q8cRn02P8hBq3yi+yuNIBxKUAwr/AhI3CgpfbGlmZWN5Y2xlEikKJwohbmFtZXNwYWNlcy9maWVsZHMvZmFiY2FyL1NlcXVlbmNlEgIIBxLDAgoGZmFiY2FyErgCChYKEAD0j7+/aW5pdGlhbGl6ZWQSAggIGp0CCjF7ImlkIjoiMSIsInB1YmxpY19rZXkiOiJBdWRpIiwicHJpdmF0ZV9rZXkiOiJSOCJ9GucBeyJpZCI6IntcImlkXCI6XCIxXCIsXCJwdWJsaWNfa2V5XCI6XCJBdWRpXCIsXCJwcml2YXRlX2tleVwiOlwiUjhcIn0iLCJwdWJsaWNfa2V5IjoiZmE1MTI4Mjc5ZTVjMmY5Zjg2N2M0ZmZiMWI3MTJjNTlhZGFjMWE4M2ZjMGQ3NDA0OTI0MDY2MWY3NDE3YTk2YSIsInByaXZhdGVfa2V5IjoiMjk1M2Q2YzAzNDIzZWYxZTg5ODI3MmM5ZDZhZDNmYWFlZjcxMDM5MmMzOWM3OTZlYjg5OWRkMmMyNmM4ZGJkNiJ9GgMIyAEiCxIGZmFiY2FyGgEx' vs 'CiD6XpjbMfvrXmPkeykGv7m1q8cRn02P8hBq3yi+yuNIBxKUAwr/AhI3CgpfbGlmZWN5Y2xlEikKJwohbmFtZXNwYWNlcy9maWVsZHMvZmFiY2FyL1NlcXVlbmNlEgIIBxLDAgoGZmFiY2FyErgCChYKEAD0j7+/aW5pdGlhbGl6ZWQSAggIGp0CCjF7ImlkIjoiMSIsInB1YmxpY19rZXkiOiJBdWRpIiwicHJpdmF0ZV9rZXkiOiJSOCJ9GucBeyJpZCI6IntcImlkXCI6XCIxXCIsXCJwdWJsaWNfa2V5XCI6XCJBdWRpXCIsXCJwcml2YXRlX2tleVwiOlwiUjhcIn0iLCJwdWJsaWNfa2V5IjoiMzA5ZjI0Mjg5YmI0ZWJkZGRmZGNmZWVmYTMzYjFiYzU4ZWRlMzAyNTY1NWM5MzU1ZmEwMjBhMTcxNjQxYzEwNSIsInByaXZhdGVfa2V5IjoiZWFjZWVlODMwNWRkOTRjODI0MWFhZDQwNzZiMTViNzdjYWUyYTU4ZWI0OGJhZDYyMGY3MWQyZjY3MDFmMzI3MSJ9GgMIyAEiCxIGZmFiY2FyGgEx' - proposal response: version:1 response:<status:200 > payload:"\n \372^\230\3331\373\353^c\344{)\006\277\271\265\253\307\021\237M\217\362\020j\337(\276\312\343H\007\022\224\003\n\377\002\0227\n\n_lifecycle\022)\n'\n!namespaces/fields/fabcar/Sequence\022\002\010\007\022\303\002\n\006fabcar\022\270\002\n\026\n\020\000\364\217\277\277initialized\022\002\010\010\032\235\002\n1{\"id\":\"1\",\"public_key\":\"Audi\",\"private_key\":\"R8\"}\032\347\001{\"id\":\"{\\\"id\\\":\\\"1\\\",\\\"public_key\\\":\\\"Audi\\\",\\\"private_key\\\":\\\"R8\\\"}\",\"public_key\":\"309f24289bb4ebdddfdcfeefa33b1bc58ede3025655c9355fa020a171641c105\",\"private_key\":\"eaceee8305dd94c8241aad4076b15b77cae2a58eb48bad620f71d2f6701f3271\"}\032\003\010\310\001\"\013\022\006fabcar\032\0011" endorsement:<endorser:"\n\007Org1MSP\022\315\007-----BEGIN CERTIFICATE-----\nMIICojCCAkigAwIBAgIUDWYC5bxEYnHpgCznJRsqC+kZ6/MwCgYIKoZIzj0EAwIw\naDELMAkGA1UEBhMCVVMxFzAVBgNVBAgTDk5vcnRoIENhcm9saW5hMRQwEgYDVQQK\nEwtIeXBlcmxlZGdlcjEPMA0GA1UECxMGRmFicmljMRkwFwYDVQQDExBmYWJyaWMt\nY2Etc2VydmVyMB4XDTIzMDIyMDExMzQwMFoXDTI0MDIyMDExNDAwMFowWzELMAkG\nA1UEBhMCVVMxFzAVBgNVBAgTDk5vcnRoIENhcm9saW5hMRQwEgYDVQQKEwtIeXBl\ncmxlZGdlcjENMAsGA1UECxMEcGVlcjEOMAwGA1UEAxMFcGVlcjAwWTATBgcqhkjO\nPQIBBggqhkjOPQMBBwNCAAT+Wtt2RO/bZw+HOEmT2XpB43cSZFIoN4C7oHzsQXwn\nuUH33ewhZoXdd8OU/FOVZgClCTYVUF/muq1/arF74rZMo4HcMIHZMA4GA1UdDwEB\n/wQEAwIHgDAMBgNVHRMBAf8EAjAAMB0GA1UdDgQWBBT8T2I8s+PEojCgOQyE6MMA\nIc/U+DAfBgNVHSMEGDAWgBRZL2wM0bLnKnTrOyTnVcZN6GzQsTAhBgNVHREEGjAY\nghZwZWVyMC5vcmcxLmV4YW1wbGUuY29tMFYGCCoDBAUGBwgBBEp7ImF0dHJzIjp7\nImhmLkFmZmlsaWF0aW9uIjoiIiwiaGYuRW5yb2xsbWVudElEIjoicGVlcjAiLCJo\nZi5UeXBlIjoicGVlciJ9fTAKBggqhkjOPQQDAgNIADBFAiEAipyoKYkGNE03TKOz\nE5RBQj2C2gZybIsrGxb15Wm+2zwCIE2DQxPSnK7saifTPEzSJdMXTL0sJY3uacor\n3udX8ot2\n-----END CERTIFICATE-----\n" signature:"0D\002 \tG[\331@\373\333\005\323\265oL\242\252\025x[\221\304\026:\036h\003\322\322\311\271\021\t\021\246\002 Fn\362\267C\315j\3176g\255\320\002\222g\026\317\217\342*\311~fS5\016\34753\006\002\014" >

What should I do to fix the problem ?
I use Linux mint. Tutorial is enter link description here I met this problem is the first step at "Invoking the chaincode"
link

A: Your smart contract transaction function implementation is invalid since it will not return the same read/write sets and transaction result on multiple invocations for the same set of inputs and ledger state. Each invocation generates a new (unique) public/private key pair and stores this on the ledger. See the description of the transaction flow in the Fabric documentation for details:
https://hyperledger-fabric.readthedocs.io/en/latest/txflow.html
As an aside, storing user private encryption keys on a blockchain makes those private keys publicly visible to all the collaborating organizations using that blockchain. Typically private keys are intended to remain private so blockchain probably is not the best place to store them.


text:
Q: Proving a sequence of step functions converges pointwise to a function $f$. Question: Suppose $f: [0,1] \rightarrow \mathbb{R}$ is continuous on $(0,1)$. Prove there is a sequence of step functions $\left\{f_{n}\right\}$ which converges pointwise to $f$ on $[0,1]$.
I saw the same question was asked here but I was still confused regarding the solution to the question.
I had attempted a solution but I now realize this solution is wrong:
Proof:
Since $f$ is continuous on $(0,1)$, then for every $x \in (0,1)$ and for every $\epsilon>0$, there exists a $\delta(x)$ such that $|f(x)-f(y)|<\epsilon$ whenever $y \in (0,1)$ and $|y-x|<\delta(x)$. In particular, let $\epsilon_{n} = 1/2^{n}$ and let $\delta_{n}(x)$ be the corresponding $\delta$ which is guaranteed by the continuity of $f$. Fix a value of $n$ and choose a partition $x_{0}=0 < x_{1} < x_{2} < \ldots < x_{m} = 1$ such that $x_{i}-x_{i-1} < \delta_{n}(x)$. Let $f_{n}(x):= f(x_{i-1})$ for all $x \in (x_{i-1}, x_{i})$. Clearly $f_{n}(x)$ is a step function and hence $\left\{f_{n}\right\}$ is a sequence of step functions. Observe that $f_{n}(x)=f_{n}(x_{i-1})=f(x_{i-1})$. Finally, by the continuity of $f$ and by the fact that $x_{i}-x_{i-1} < \delta_{n}(x)$, we may conclude that
\begin{align*}
|f(x)-f_{n}(x)| \leq |f(x)-f(x_{i-1})| < \epsilon_{n}
\end{align*}
and so the sequence converges pointwise to $f$.
End of proof.
I was hoping someone can shed some light on the correct solution to this problem. Any hints would be appreciated. Thanks!

A: Since $f$ is continuous on $(0,1)$, for all $n\in \mathbb N$, consdier $I_n = [2^{-(n+1)}, 1-2^{-(n+1)}]$. Then $f$ is continuous on $I_n$. Let $s_n$ be a step function on $I_n$ so that $|f(x) - s_n(x)|<2^{-n}$ for all $x\in I_n$. That can be found as $I_n$ is a closed and bounded interval and so $f$ is uniformly continuous on $I_n$.
Now define a step function $f_n$ on $[0,1]$, where
$$f_n(x) = \begin{cases} s_n(x)  &\text{if } x\in I_n \\ f(0) & \text{if }x \in [0,2^{-(n+1)}), \\ f(1) & \text{if } x\in (1-2^{-(n+1)},1]. \end{cases}$$

Claim: $f_n$ converges to $f$ pointwisely on $[0,1]$.

Fix $x\in [0,1]$. We need to show that $f_n(x) \to f(x)$ as $n\to \infty$. By definition of $f_n$, this is obvious for $x=,0,1$. If $x\in (0,1)$, then there is $N_x\in \mathbb N$ so that $x\in I_n$ for all $n\ge N_x$. Thus
$$|f_n(x) - f(x)| = |s_n(x) - f(x)| \le 2^{-n},\ \ \ \forall n\ge N_x.$$
This implies $f_n(x) \to f(x)$ as $n\to \infty$. Thus the claim is shown.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to sync gradle with terminal Android studio sync build.gradle is so slow,
this is a part of log:
:app:incrementalApkFlavorReleaseUnitTestJavaCompilationSafeguard UP-TO-DATE
:app:preApkFlavorReleaseUnitTestBuild UP-TO-DATE
:app:prepareApkFlavorReleaseUnitTestDependencies
:app:compileApkFlavorReleaseUnitTestJavaWithJavac UP-TO-DATE
:app:processApkFlavorReleaseUnitTestJavaRes UP-TO-DATE
:app:compileApkFlavorReleaseUnitTestSources UP-TO-DATE
:app:assembleApkFlavorReleaseUnitTest
:app:testApkFlavorReleaseUnitTest UP-TO-DATE
:app:incrementalPluginFlavorDebugUnitTestJavaCompilationSafeguard UP-TO-DATE
:app:prePluginFlavorDebugUnitTestBuild UP-TO-DATE
:app:preparePluginFlavorDebugUnitTestDependencies
:app:compilePluginFlavorDebugUnitTestJavaWithJavac UP-TO-DATE
:app:processPluginFlavorDebugUnitTestJavaRes UP-TO-DATE
:app:compilePluginFlavorDebugUnitTestSources UP-TO-DATE
:app:assemblePluginFlavorDebugUnitTest
:app:testPluginFlavorDebugUnitTest UP-TO-DATE
:app:incrementalPluginFlavorReleaseUnitTestJavaCompilationSafeguard UP-TO-DATE
:app:prePluginFlavorReleaseUnitTestBuild UP-TO-DATE
:app:preparePluginFlavorReleaseUnitTestDependencies
:app:compilePluginFlavorReleaseUnitTestJavaWithJavac UP-TO-DATE
:app:processPluginFlavorReleaseUnitTestJavaRes UP-TO-DATE
:app:compilePluginFlavorReleaseUnitTestSources UP-TO-DATE
:app:assemblePluginFlavorReleaseUnitTest
:app:testPluginFlavorReleaseUnitTest UP-TO-DATE
:app:test UP-TO-DATE
:app:check
:app:build

BUILD SUCCESSFUL

it will build all flavor ,do check , etc..  I was very hurt, you never know how hard one gay from China want to build a project.  the slow DNS, the netwok limit.. Pzzzz.. my heart..oh..
So, what can i do with terminal , is there a task do sync ?  I don't want do any  redundant task.
By the way , can I see the source code of android studio sync ? can i configure it?

A: With command line in your root project
./gradlew build
It will sync and build your app
To see all available gradle task, use ./gradlew tasks

A: If you have
apply plugin: 'eclipse'

You can do gradle eclipse cleanEclipse. It sets up the project for eclipse and downloads all dependencies. Then cleanEclipse to remove the eclipse files.
I haven't tested, but I think this should allow gradle sync to run those two tasks. Adapted from this stackoverflow post
task sync(type: GradleBuild) {
     tasks = ['eclipse', 'cleanEclipse']
}


text:
Q: Codeigniter 3 textarea I have tried to limit number of rows in textarea to 4 but its giving error
Message: Array to string conversion

this is my code of textarea using helper class
$textarea_options = array('class' => 'form-control','rows' => 4,   'cols' => 40);

echo form_textarea('vc_desc', set_value('vc_desc'),  $textarea_options);

A: setup a $data array instead with all the options
    $data = array(
        'name'        => 'vc_desc',
        'id'          => 'vc_desc',
        'value'       => set_value('vc_desc'),
        'rows'        => '50',
        'cols'        => '10',
        'style'       => 'width:50%',
        'class'       => 'form-control'
    );

    echo form_textarea($data);

A: Use rows and cols to get change the height and length of text area in code ignitor.
$data = array('name' => 'SupAddress','value' =>set_value('SupAddress'), 'id'=>'SupAddress',  'class' => 'form-control' ,'readonly' => 'true' ,'rows' => '3', 'cols' => '40');

 echo Form_textarea($data);


text:
Q: My API cannot read the passed data array using Curl I have a previous question here recently that has no answer at all. I tired everything I can but to no avail. NOw, I'm asking for another question since I figured something was not right in my code. Take a look at my code.
My URL for the API with parameters
http://localhost/sample/index.php/2/users/mil/minoza/09876543212

** The Array**
if ($request[0] == 2) {
$data = array(
  "table" => $request[1],
  "fname" => $request[2],
  "lname" => $request[3],
  "cntct" => $request[4]
);

The code for the CURL and URL
if ($request[0] == 2) {
   $str_data = json_encode($data);
   $post_elements = array('data'=>$str_data);
   echo $url_send;
   echo "</br>";
   print_r($post_elements);
   die();
   sput($url_send, $post_elements);
   echo sput($url_send, $post_elements);
}

The sput function (CURL)
function sput($url, $fields)
{

    $ch = curl_init($url);

    $post_field_string = http_build_query($fields);

    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");

    curl_setopt( $ch, CURLOPT_POSTFIELDS, $post_field_string);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    $response = curl_exec($ch);

    curl_close ($ch);

    return $response;
}

Scenarios:
You notice that in The code for the CURL and URL I have a echo, echo, print_r and a die. This i placed because I want to check if there's a data in the variables I'm going to use for the fucntion. And it does have data.
Result
http://localhost/api.php/
Array ( [data] => {"table":"users","fname":"mil","lname":"minoza","cntct":"09876543212"} )

MY API.PHP
$method = $_SERVER['REQUEST_METHOD'];
if ($method == 'PUT') {
   $data = preg_replace('/[^a-z0-9_]+/i','',array_shift($_POST));
   echo $data."AMF";
   die();
}

When I'm in api.php I dont know how will I get the data array I passed using the index.php Curl. Here's the result
AMF

is it right that I asked for the $_POST since in my CUrl in index.php there's a line in curl that states,
curl_setopt( $ch, CURLOPT_POSTFIELDS, $post_field_string);

Please someone helpme please. My previous question was totatlly ignored.
Thanks.


text:
Q: Как с помощью классов создать html-элемент и вставить на страницу? Например, нужно создать input разного типа (email, password, text) и вставить на страницу. Я так понимаю один метод на определенный тип нужно делать. Что в конструктор писать?
class Input {
  constructor() {
    ///
  }
  createPassInput() {
    //
  }
createEmailInput() {
    //
  }
createTextInput() {
    //
  }
}

let inputpass = new Input("input");
inputpass.createPassInput()

A: Для каждого тега создавать отдельный класс? Сомнительная идея. Не удобнее ли пользоваться new Elem("input", {type: "password", placeholder: "moo"}); примерно такими вызовами? Можно всё передавать в виде параметров.
Собственно, как и тип инпута, в вашем случае:

class Input {
  constructor(type) {
    this.elem = document.createElement("input");
    if (type) this.elem.type = type;
  }

  appendTo(parent) {
    parent.appendChild(this.elem);
  }
}

new Input("number").appendTo(document.body);
new Input("checkbox").appendTo(document.body);
new Input("password").appendTo(document.body);

По разному можно фантазировать на эту тему, например:

let input = create("input", {type: "password", placeholder: "moo"});
let div = create("div", {class: "bubu"}, {children: [input]});

document.body.appendChild(div);
document.body.appendChild( create("div", {class: "bubu"}, {text: "bubu"}) );

/***/
function create(tagName, attributes, contents) {
  let elem = document.createElement(tagName);

  if (contents) {
    if (contents.children) {
      contents.children.forEach(el => elem.appendChild(el));
    } else if (contents.text) {
      elem.textContent = contents.text;
    }
  }

  if (!attributes) return elem;

  for (let [attr, value] of Object.entries(attributes) ) {
    elem.setAttribute(attr, value);
  }

  return elem;
}
.bubu { border: 2px solid orange; padding: 4px; margin: 4px; }

Если хочется в виде класса: Как-раз домашнее задание!)
P.s. При этом, спорно, что все эти телодвижения будут лучше, чем банально собирать HTML из строки. Но "набить руку" и попробовать как вариант - вполне годятся.


text:
Q: refer or extract the elements of a particular level Say I applied the cut function on seq(15) like this cut(seq(15), 5)
I would get a list of bins in which each element would fall.  What if I want to extract the members or elements of the third level?  How can I refer to the elements that would fall in the 3rd bin after cutting the sequence?
Addressing Arun's comment:I will provide the cut function a vector like this:  temp <- cut(seq(15), c(.9,4,8,12,15)).  I am looking for the elements of the seq(15) that would fall in the 3rd level. They are 9,10,11,12. There is already an answer that worked bellow.

A: You can use labels=F to get
 cut(seq(15),5,labels=F)
[1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5

Then
x <- seq(15)
> x[cut(x,5,labels=F)==3]
[1] 7 8 9

A: Your question is poorly worded and somewhat ambiguous, but can use basic indexing for this:
temp <- cut(seq(15), 5)
temp[temp == levels(temp)[3]]
# [1] (6.6,9.4] (6.6,9.4] (6.6,9.4]
# Levels: (0.986,3.79] (3.79,6.6] (6.6,9.4] (9.4,12.2] (12.2,15]

Or, if you wanted the relevant values from seq(15):
seq(15)[temp == levels(temp)[3]]
# [1] 7 8 9


text:
Q: bokeh plotting second axis - how to get limits of primary axis? I have a bokeh plot with date on the x-axis (data["obs_date"]) and I want another x-axis at the top covering the same range but shown in a different format (mjd below).
I have tried to add the second axis with:
plot.extra_x_ranges = {"MJD":
                           Range1d(start=Time(min(data["obs_date"])).mjd,
                                   end=Time(max(data["obs_date"])).mjd)}
plot.add_layout(LinearAxis(x_range_name="MJD", axis_label="MJD",
                               axis_label_text_font_size="16pt"),
                               "above")

However, because bokeh adds a small buffer to the limits of the plot, using min max of data["obs_date"] as the limits for this new axis gives me a small offset - in the image below 16 Jan 2018 should align with 58134. It also causes it to break when I only have one point to plot.
How can I set the limits of my  new axis so that it is 'aware' of the limits of the primary axis? Coming form a matplotlib background, I suppose the equivalent I am looking for is ax.get_xlim().

A: Bokeh implicitly uses DataRange1d that computes the padded bounds based on its range_padding, range_padding_units, and follow_interval fields, and whether the underlying scale is linear or logarithmic. But it does not store the computed values.
So, your only options at this point are either to set the boundaries explicitly for both ranges or to compute the boundaries for the extra range based on the aforementioned DataRange1d fields and the scale type.


text:
Q: Simulate onclick to get dynamic img src with javascript I am trying to parse data from a website
var inputs = document.getElementsByClassName('parentClass');
for (var i = 0; i < inputs.length; i++) {
    inputs[i].click();
    var someimage = document.getElementsByClassName('class-img');
    var myimg = someimage[0].getElementsByTagName('img')[0];
    var mysrc = myimg.src;
    console.log(mysrc);
}

The website has this behavior, whenever you click the div, it triggers to onclick and as a result, different image will be shown. I am writing this javascript to get all the image in order from top to bottom. That is why i am simulating the click. The problem with this is that it somehow does not grasp the new link but the last link.
There are 19 images and it is printing the last image src 19 times. Any clue?
I ended up have to go through the page source and manually get the onclick argument so I can use AJAX to send the post request
var inputs = document.getElementsByClassName('parentClass');
    for (var i = 0; i < inputs.length; i++) {
        var str = (inputs[i].getAttribute('onclick'));
        var params = str.split("nameOfFunction(")[1].split(',');
        params[params.length - 1] = params[params.length - 1].replace(');');
        $.ajax({
            method: "POST",
            url: "request.php",
            data: {
                id: parseInt(params[0]),
                name: params[1],
                belongsys: params[2],
                type: params[3],
                rep: params[4],
                set: params[5],
                mass: ' kg'
            }
        }).done(function(result){
            $(".class-img").html(result).show();
            var someimage = document.getElementsByClassName('class-img');
            var myimg = someimage[0].getElementsByTagName('img')[0];
            var mysrc = myimg.src;
            console.log(mysrc)
            array.push(mysrc);
        });
    }


text:
Q: ChangeNotifierProxy Provider & ChangeNotifier Provider loses value when app is refreshed I am using a ChangeNotifierProxyProvider to provide a class called DatabaseService. The provider is shown below
 ChangeNotifierProxyProvider<AuthService, DatabaseService>(
    create:(_)=> DatabaseService() ,
    update: (_,AuthService authService, DatabaseService databaseService)=> databaseService..update(authService.currentUserId),
    ),

Here is the update function in DatabaseService
void update (String uid)async {

if(uid==this.uid) return;
this.uid=uid;
notifyListeners();
print("USER ID IS : " + uid); }

When a user logs in, the Database class successfully gets the uid, and calling Provider.of(context).uid works fine. The problem is that when I refresh the app, the uid resets back to its default value. How can I prevent the value from resetting after refreshing the app.

A: So I came to a conclusion that provider does not persist data. Meaning that when the app is killed or refreshed in the emulator, the provider values will reset. To solve my problem, I used share preferences to solve my data persistency problem.


text:
Q: OpenWRT: failed to connect to ubus I have a WNDR3800, flashed trunk version of OpenWRT, and then did a sysupgrade -r from previous working backup on the same machine. After reboot everything is normal (since many packages are not installed), but Once I try to connect to it via SSH it reports:
Aiee, segfault! You should probably report this as a bug to the developer
Connection to 192.168.3.1 closed.

After that I put it in failsafe mode, connected via telnet and tried severial commands:
root@(none):/# /etc/init.d/dropbear start
root@(none):/# mv: can't remove '/etc/dropbear/dropbear_dss_host_key': Read-only file system
mv: can't remove '/etc/dropbear/dropbear_rsa_host_key': Read-only file system
chown: /etc/dropbear: Read-only file system
chmod: /etc/dropbear: Read-only file system
Failed to connect to ubus

root@(none):/# mount_root
root@(none):/# /etc/init.d/dropbear start
Failed to connect to ubus
Failed to parse json data: unexpected end of data
interface lan has no physdev or physdev has no suitable ip
Failed to connect to ubus
root@(none):/# ifconfig
eth0      Link encap:Ethernet  HWaddr 46:94:FC:XX:XX:XX
          inet addr:192.168.1.1  Bcast:192.168.1.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:2059 errors:0 dropped:531 overruns:1 frame:0
          TX packets:188 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:371693 (362.9 KiB)  TX bytes:18693 (18.2 KiB)
          Interrupt:4

Also I tried firstboot with or without mount_root, in both cases it stucks and does nothing.
Since dropbear refuse to start, I am unable to configure anything. Is there any way I can revert to default settings or flash another version of firmware?

A: You can try the recovery method using TFTP as described for the WNDR3700 here (it also applies to the WNDR3800). If this does not work, you can use the serial console as a last resort to directly talk to the U-Boot bootloader and instruct it to load a firmware image using TFTP. Hope this helps.
Unfortunately, the recent OpenWRT distributions seem to be broken in many ways. They change too many things too fast. Actually, I found your question while looking for known errors of the json parser of this ubus thing in latest "stable" 15.05 (couldn't find anything in the OpenWRT forum/ticket system related to that particular error), which breaks something trivial as the firewall start/stop script and other commands like for example mount.
As for me, I will go back to 12.09 for now, which is the latest really stable version for my platforms (Netgear WNDR3700, TP-Link WDR4300, PCEngines Alix). As a long-time user of OpenWRT (10 years) I usually try to fix errors first before reverting back to older versions, but due to the lack of documentation of the new features it does take much too much time to dig into this new and (IMHO) very complex framework.


text:
Q: how to merge branch into master by PyGithub For example, I have a file t.json, the content is:
{
  "a": "abcdefg"
}

And file t.json is pushed to to master branch. Then I add some content to the file, and checkout to a new branch so the file looks like this now:
{
  "a": "abcdefg",
  "b": "mkjuujj"
}

Now I can compare two commits by using PyGithub. Codes are like this:
WORKING_BRANCH = "my_new_branch"
new_branch_ref_str = "refs/heads/%s" % WORKING_BRANCH
branch_ref = None
all_ref = repo.get_git_refs()

for ref in all_ref:
    if ref.ref == new_branch_ref_str:
        branch_ref = ref
        break

if not branch_ref:
    # create branch from this commit
    b = repo.get_branch("master")
    branch_ref = repo.create_git_ref(ref=new_branch_ref_str,
                                 sha=b.commit.sha)

    last_head = repo.get_branch(WORKING_BRANCH)
    fc = repo.get_file_contents("/t.json", ref=WORKING_BRANCH)
    file = 't.json'
    commit_message = "create a new branch with changes"
    input_file = open(file, 'rb')
    data = input_file.read()

    result = repo.update_file("/t.json",
                          commit_message,
                          data,
                          fc.sha, branch=WORKING_BRANCH)

    diff_url = repo.compare(last_head.commit.sha,
                        result['commit'].sha)

    print diff_url.diff_url

this is what I got:
diff --git a/t.json b/t.json
index ef03bf5..b775e51 100644
--- a/t.json
+++ b/t.json
@@ -1,3 +1,4 @@
 {
-  "a": "abcdefg"
+  "a": "abcdefg",
+  "b": "mkjuujj"
 }

What should I do to merge my_new_branch into master branch by using PyGithub. Thank you very much. Really appreciate it.

A: try:
    base = repo.get_branch("master")
    head = repo.get_branch(WORKING_BRANCH)

    merge_to_master = repo.merge("master",
                        head.commit.sha, "merge to master")

except Exception as ex:
    print ex


text:
Q: For loop in a package function I have this for loop, meant to search through a list of URLs and calls a function to scrape off the web and return a list of recipes where a match occurs. It works great on its own.
for (recipe_url in recipe_urls) {
  if ("allrecipes.*" %rin% recipe_urls){
    scrape_allrecipes(recipe_url)
  }
  if("foodnetwork.*" %rin% recipe_urls){
    scrape_foodnetwork(recipe_url)
  }
}

Note: %rin% is a custom function to search for a partial string of text.
`%rin%` = function (pattern, list) {
  vapply(pattern, function (p) any(grepl(p, list)), logical(1L), USE.NAMES = FALSE)
}

However, the problem is that when I tried to put it inside of a function in a package, it gives me this error:
Error in for (recipe_url in recipe_urls) { : invalid for() loop sequence

Version I converted to a function in a package:
scrape <- function(scrape) {
for (recipe_url in recipe_urls) {
  if ("allrecipes.*" %rin% recipe_urls){
    scrape_allrecipes(recipe_url)
  }
  if("foodnetwork.*" %rin% recipe_urls){
    scrape_foodnetwork(recipe_url)
  }
}
}

I sense that it's either to do with it now being in a function, or something to do with how a package works (never made a package before so I am unfamiliar).
Any advice is appreciated!


text:
Q: Styling selected TreeItem inside a TreeView I'm trying to override the style of the selected TreeItem inside a Material-UI TreeView component. According to the CSS API docs, there is a selected selector, but when I use that, I see the entire subtree getting styled, and not just the selected item.
What is the correct selector to use to only style the selected tree item?
Code Sandbox: https://codesandbox.io/s/nostalgic-flower-e85cd?file=/src/App.js
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import TreeView from "@material-ui/lab/TreeView";
import ExpandMoreIcon from "@material-ui/icons/ExpandMore";
import ChevronRightIcon from "@material-ui/icons/ChevronRight";
import MuiTreeItem from "@material-ui/lab/TreeItem";
import { withStyles } from "@material-ui/core/styles";

const useStyles = makeStyles({
  root: {
    height: 240,
    flexGrow: 1,
    maxWidth: 400
  }
});

const TreeItem = withStyles({
  selected: {
    color: "red"
  }
})(MuiTreeItem);

export default function FileSystemNavigator() {
  const classes = useStyles();

  return (
    <TreeView
      className={classes.root}
      defaultCollapseIcon={<ExpandMoreIcon />}
      defaultExpandIcon={<ChevronRightIcon />}
    >
      <TreeItem nodeId="1" label="Applications">
        <TreeItem nodeId="2" label="Calendar" />
        <TreeItem nodeId="3" label="Chrome" />
        <TreeItem nodeId="4" label="Webstorm" />
      </TreeItem>
      <TreeItem nodeId="5" label="Documents">
        <TreeItem nodeId="10" label="OSS" />
        <TreeItem nodeId="6" label="Material-UI">
          <TreeItem nodeId="7" label="src">
            <TreeItem nodeId="8" label="index.js" />
            <TreeItem nodeId="9" label="tree-view.js" />
          </TreeItem>
        </TreeItem>
      </TreeItem>
    </TreeView>
  );
}

A: When you have questions about how to override the default Material-UI styles, the best resource is to look at how the default styles are defined.
Below are the most relevant portions of the default styles for TreeItem:
export const styles = (theme) => ({
  /* Styles applied to the root element. */
  root: {
    '&$selected > $content $label': {
      backgroundColor: fade(theme.palette.primary.main, theme.palette.action.selectedOpacity),
    },
    '&$selected > $content $label:hover, &$selected:focus > $content $label': {
      backgroundColor: fade(
        theme.palette.primary.main,
        theme.palette.action.selectedOpacity + theme.palette.action.hoverOpacity,
      ),
      // Reset on touch devices, it doesn't add specificity
      '@media (hover: none)': {
        backgroundColor: 'transparent',
      },
    },
  },
  /* Pseudo-class applied to the root element when selected. */
  selected: {},
  /* Styles applied to the tree node content. */
  content: {
    width: '100%',
    display: 'flex',
    alignItems: 'center',
    cursor: 'pointer',
  },
  /* Styles applied to the label element. */
  label: {
    '&:hover': {
      backgroundColor: theme.palette.action.hover,
      // Reset on touch devices, it doesn't add specificity
      '@media (hover: none)': {
        backgroundColor: 'transparent',
      },
    },
  },
});

The overall structure of TreeItem (which can also be found by looking at the source code) is as follows (simplified slightly):

         {icon}

      <Typography component="div" className={classes.label}>
         {label}
      </Typography>

   {children}

In the structure above, you can see that the selected class is on the root element which is an
 which surrounds both the content specific to this TreeItem as well as its children. The TreeItem's own content is in the
 with the content class and that div contains the icon and label.
You can target the content div as follows:
const TreeItem = withStyles({
  root: {
    "&.Mui-selected > .MuiTreeItem-content": {
      color: "red"
    }
  }
})(MuiTreeItem);

which is equivalent to:
const TreeItem = withStyles({
  root: {
    "&$selected > $content": {
      color: "red"
    }
  },
  selected: {},
  content: {}
})(MuiTreeItem);

If you don't want to include the icon in the styling, then you can just target the label within the content:
const TreeItem = withStyles({
  root: {
    "&.Mui-selected > .MuiTreeItem-content .MuiTreeItem-label": {
      color: "red"
    }
  }
})(MuiTreeItem);

which is equivalent to:
const TreeItem = withStyles({
  root: {
    "&$selected > $content $label": {
      color: "red"
    }
  },
  selected: {},
  content: {},
  label: {}
})(MuiTreeItem);

If you want to change the background color, you need to pay attention to a few more details in the default styling (since the default styling does a lot with background color) in order to deal appropriately with the hover and focused states.

A: import MuiTreeItem from "@material-ui/lab/TreeItem";
import { withStyles } from "@material-ui/core/styles";

const TreeItem = withStyles({
  root: {
    "&.Mui-selected > .MuiTreeItem-content": {
      background: "#89CFF0"
    },
    "&.MuiTreeItem-root > .MuiTreeItem-content:hover": {
      background: "gray",
    },
    "&.MuiTreeItem-root > .MuiTreeItem-content:hover > .MuiTreeItem-label": {
      background: "#89CFF0",
    },
    '@media (hover: none)': {
      backgroundColor: 'transparent',
    }
  }
})(MuiTreeItem);

A: The answers so far use withStyles from MUI v4 because that was the current version when they were posted. I'm pretty sure there is a MUI v5 approach, but I gave up on trying to get that to work.
The technique used doesn't really matter as much, anyway: The problem is getting all the selectors right.
I ended up adding this to index.css which seems to disable any most focused / hover / selected styles (some edge cases seem to persist):
.MuiTreeItem-root:hover {
  background: transparent
}

.MuiTreeItem-root > .MuiTreeItem-content:hover {
  background: transparent
}

.MuiTreeItem-root > .MuiTreeItem-content:hover > .MuiTreeItem-label {
  background: transparent
}

.MuiTreeItem-root > .MuiTreeItem-content.Mui-selected {
  background: transparent
}

.MuiTreeItem-root > .MuiTreeItem-content.Mui-selected:hover {
  background: transparent
}

.MuiTreeItem-root > .MuiTreeItem-content.Mui-selected > .MuiTreeItem-label {
  background: transparent
}

.MuiTreeItem-root > .MuiTreeItem-content.Mui-selected.Mui-focused {
  background: transparent
}

Yes, as far as I can tell, they are all required. Probably still a few more.
NOTE: That's focused (with one s), using e.g. MUI-focussed fails silently.


text:
Q: BOOT FAILURE Prtition Change Stressed user here.  Last week I could not boot into my Ubuntu 5.04. I have now got the 14.04 installed via DVD. though I can not restore my backups and I have made matters even worse since I have changed the partitions which have stopped me using the FSCK command in the terminal. I can't get Ubuntu 15.04 back either.
I'm blind in both senses that I can't see what I'm doing and have to use my poor wife to carry out the operations and in the sense that I know little or nothing of restoring Ubuntu after boot failure and partition changing.  Totally, my fault about partition change.
Help before I damage the computer and ruin my marriage LOL
Andy :-(

A: A few steps you can take. First install a fresh copy of Ubuntu 14.04.3LTS on a disk. http://www.ubuntu.com/download/desktop boot from this disk, install on a flash drive! (recommend 32gb or above) You may need to partition the drive you can do this in the try Ubuntu link and use Gparted. Once install is complete reboot system. System comes with a update manager, run this after reboot or go into terminal and type "sudo apt-get update" then "sudo apt-get autoclean". You may also re-partition the systems hard-drive in gparted and install Ubuntu, but this must be done from flash not DVD! Hope this helps

A: Hi There I now have a new situation where I cannot even boot into my Labtop via the Boot repair CD or the live Ubuntu DVD.  I momentary get a Booting page for a second or so that goes blank.  IS this the end? Is there life after blank screen? @DnrDevil


text:
Q: Flash messages in Rails 3.2.3 and json There is an action in a controller. It can be called only with json format via ajax.
def update
    @article = Article.find_by_id params[:id]
    respond_to do |format|
      if @article.update_attributes(params[:article])
        flash[:message] = "good"
      else
        flash[:error] = @article.errors.full_messages.join(", ")
      end
          format.json { render :json => flash}
  end

end

the part of a page
<% unless flash[:error].blank? %>
   <%= flash[:error] %>
<% end %>

<% unless flash[:message].blank? %>
  <%= flash[:notice] %>
<% end %>
<!-- page content goes -->

Of course, a page contains a button_to with :remote=>true that calls the method update.
The bottom line is that it shows nothing after updating. JSON object definitely returns, I can see it in fireBug.
The question is, am I using flash correctly? And how do I use it to show a message on a page? Please don't forget about ajax.

A: Why do you have an if/else statement in your respond_to block?
def update
  @article = Article.find_by_id params[:id]
  if @article.update_attributes(params[:article])
    flash[:notice] = "Good"
  else
    flash.now[:notice] = "Bad"
    render "edit"
  end
  respond_to do |format|
    format.html {redirect_to @article}
    format.js
  end
end

Then create update.js.erb
$("#notice").text("<%= escape_javascript(flash[:notice]) %>")
$("#notice").show()

Code above might not be 100% correct.
For flash, I'd have something like:
<div id="notice">
  <% flash.each do |key, value| %>
    <%= content_tag(:div, value, :class => "flash #{key}") %>
  <% end %>
</div>

A: This posting has all the code you'll need. It saved my hide:
https://gist.github.com/linjunpop/3410235
Here's a fork of it that makes a few minor modifications:
https://gist.github.com/timothythehuman/5506787

A: I think
You have to bind ajax:success call back which will display flash message by replacing message or placing message to dom.


text:
Q: JSON and Web API - how do I receive a simple JSON object into a Web API using built in types (without JQuery)? I'm working on a system that sends a simple JSON object to a C# .NET Web API in the form:
{property1: "string1", property2: "string2"}
I want to receive this JSON into the web api. I can't initially use a custom object when I receive the JSON into the web API (because the system I'm working writes stuff into the DB automagically, and for this to work, only the built-in C# types can be used at the point that data reaches the web api).
The system doesn't utilise JQuery, so that's not an option. How can I accept this JSON into the Web API?

A: You could make use of dynamic type:
[Route("your route")]
[HttpPost]
public IHttpActionResult Post([FromBody]dynamic properties)
{
    var property1 = properties["property1"];

    var property2 = properties["property2"];

    //your code
}

or
[Route("your route")]
[HttpPost]
public IActionResult Post([FromBody]object properties)
{
    var property1 = (properties as dynamic)["property1"];

    var property2 = (properties as dynamic)["property2"];

    //your code
}


text:
Q: Separate each alphabet by using preg_match PHP i know that this is a beginner level question, but i am stuck here and  i need help.
i want to store each alphabet in an array. (Only Alphabets not integers)
let me show you the previous code that i am using
$str = "ab c45 d123ef";
preg_match_all('/./us', $str, $ar);
echo '<pre>';
print_r($ar);

its output
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
            [2] =>
            [3] => c
            [4] => 4
            [5] => 5
            [6] =>
            [7] => d
            [8] => 1
            [9] => 2
            [10] => 3
            [11] => e
            [12] => f
        )

)

But it also separate integers... what i have to change in the preg_match expression, i want this output.
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
            [2] =>
            [3] => c
            [4] => 45
            [5] =>
            [6] => d
            [7] => 123
            [8] => e
            [9] => f
        )

)

A: preg_match_all('/[\d.]+|./us', $str, $ar);

[\d.] matches a digit or decimal point, the + quantifier after it matches a sequence of them.
Result:
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
            [2] =>
            [3] => c
            [4] => 45
            [5] =>
            [6] => d
            [7] => 123
            [8] => e
            [9] => f
        )

)

A: A way with preg_split:
$result = preg_split('/(?=\pL)|(?<=\pL)/', $str, -1, PREG_SPLIT_NO_EMPTY);

You obtain:
Array
(
    [0] => a
    [1] => b
    [2] =>
    [3] => c
    [4] => 45
    [5] => d
    [6] => 123
    [7] => e
    [8] => f
)

The current pattern matches two kind of positions, positions followed by a letter (?=\pL), and positions preceded by a letter (?<=\pL).


text:
Q: Average torque on a Projectile of mass $m$ with initial speed $u$ and angle of projection $θ$ between initial ($P$) and final ($Q$) positions is Question is as follows:
Average torque on a Projectile of mass $m$ with initial speed $u$ and angle of projection $θ$ between initial $(P)$ and final $(Q)$ positions is
I researched a lot but wherever I saw they used the following way
$$\vec{r}=ucos\theta.t$$
$$\vec{F}=mg$$
$$t=\frac{2usin\theta}{g}$$
This implies
$$\vec{\tau_{avg}}=\frac{\vec{r}×\vec{F}}{t}$$
But I want to solve this using integration but I'm not able to.
Kindly help me

A: Find torque($\tau$) as a function of time. I am assuming you can do it. If not, let me know.
For averaging it find $$\frac{\int{\tau{dt}}}{t}$$


text:
Q: C# highest string This seems so trivial but I'm not finding an answer with Google.
I'm after a high value for a string for a semaphore at the end of a sorted list of strings.
It seems to me that char.highest.ToString() should do it--but this compares low, not high.
Obviously it's not truly possible to create a highest possible string because it would always be lower than the same thing + more data but the strings I'm sorting are all valid pathnames and thus the symbols used are constrained.
In response to the comments:
In the pre-unicode days in Delphi I would simply have used #255.  I simply want a string that will compare higher than any possible pathname.  This should be trivial--why isn't it??
Response #2:
It's not the sorting that requires the sentinel, it's the processing afterwards.  I have multiple lists that I am sort-of merging (a simplistic merge won't do the job.) and either I duplicate code or I have dummy values that always compare high.

A: A string representation of the highest character will only be one character long.
Why don't you just append it as a semaphore after sorting, rather than trying to make it something that will sort afterwards?
Alternatively, you could specify your own comparator that sorts your token after any other string, and calls the default comparator otherwise.

A: I had the same problem when trying to put null values at the bottom of a list in a LINQ OrderBy() statement.  I ended up using...
Char.ConvertFromUtf32(0x10ffff)

...which worked a treat.

A: Something like this?
public static String Highest(this String value)
{
    Char highest = '\0';
    foreach (Char c in value)
    {
        highest = Math.Max(c, highest);
    }
    return new String(new Char[] { highest });
}


text:
Q: Creating Entity Relationship Diagram I created the ERD of my system and now I would like to create a SQL Code.

So should a SQL Code look like this?:
CREATE TABLE Student
(
    StudentID    INT NOT NULL IDENTITY PRIMARY KEY,
    FirstName    VARCHAR(255),
    LastName     VARCHAR(255),
    ADDRESS      VARCHAR(255),
    PhoneNumber  VARCHAR(255),
    Email        VARCHAR(255),
    GroupID      INT NOT NULL FOREIGN KEY
);

A: Your problem is with the FOREIGN KEY part of your query, you are not defining the foreign key there. If you now remove that, your query will work, but without a defined FK:
CREATE TABLE Student
(
    StudentID    INT NOT NULL IDENTITY PRIMARY KEY,
    FirstName    VARCHAR(255),
    LastName     VARCHAR(255),
    ADDRESS      VARCHAR(255),
    PhoneNumber  VARCHAR(255),
    Email        VARCHAR(255),
    GroupID      INT NOT NULL
);

If you want to create the foreign key, you need to do something like this (with the correct table and column):
CREATE TABLE Student
(
    StudentID    INT NOT NULL IDENTITY PRIMARY KEY,
    FirstName    VARCHAR(255),
    LastName     VARCHAR(255),
    ADDRESS      VARCHAR(255),
    PhoneNumber  VARCHAR(255),
    Email        VARCHAR(255),
    GroupID      INT NOT NULL REFERENCES Group(Group_ID)
);

A: Your "FOREIGN KEY" declaration is incomplete - you need to say which table/column the foreign key references.
If you just want to get the table built,
CREATE TABLE Student
(
    StudentID    INT NOT NULL IDENTITY PRIMARY KEY,
    FirstName    VARCHAR(255),
    LastName     VARCHAR(255),
    ADDRESS      VARCHAR(255),
    PhoneNumber  VARCHAR(255),
    Email        VARCHAR(255),
    GroupID      INT NOT NULL);

should work.


text:
Q: Writing code in javadoc comment Is it possible to write a short code inside a java doc comment?
I don't mean a simple line of code, I mean a short method like:
public static void main() {
    doSomething();
}

A: You can put your code in Multiple line comments like this.
/*
*  public static void main() {
*    doSomething();
*  }
/

If you want to be in Java documentation comment,then it would be with two * after slash
/**
*  public static void main() {
*    doSomething();
*  }
/


text:
Q: Foreign Key Not Outputting Query Data try {
    Statement s = conn.createStatement();
    ResultSet result2 = s.executeQuery("Select Distinct * From Poem p,Recording r Where r.PoemTitle = p.PoemTitle AND r.poemTitle = 'poem1'");
    System.out.print("Result (Select with Join): ");
    while (result2.next()) {
        System.out.println(result2.getString(1)+ " " + result2.getString(2)+ result2.getString(3));
    }
} catch(Exception e) {
    System.out.print(e.getMessage());
}

I am trying to output the poemtitle and the date it was recorded. When this runs it outputs the poemtitle and then gives the date the poem was created instead of recorded? Is this because of the relationship?

A: Most likely it's because of the * in the SELECT list.
Specify the columns that you want returned, in the order you want them returned.
We're just guessing at the name of the column that contains "date recorded" and which table it's in:
SELECT p.PoemTitle
     , r.dateRecorded
     , r.readBy
  FROM Poem p
  JOIN Recording r
    ON r.PoemTitle = p.PoemTitle
 WHERE r.poemTitle = 'poem1'
 GROUP
    BY p.PoemTitle
     , r.dateRecorded
     , r.readBy
 ORDER
    BY p.PoemTitle
     , r.dateRecorded DESC
     , r.readBy

Notes:
Ditch the old-school comma syntax for the join operation and use the JOIN keyword instead, and relocate the join predicates from the WHERE clause to an ON clause.
Avoid using * in the SELECT list. Explicitly list the columns/expressions to be returned. When we read the code, and that SQL statement, we don't know how many columns are being returned, what order the columns are in, or what the datatypes are. (We'd have to go look at the table definitions.)
Explicitly listing the columns/expressions being returned only takes a little bit of work. If code was only ever written, then it would be fine, save the time writing. But code is READ ten times more than it is written. (And the SQL statement with the * makes the SQL statement virtually indecipherable in terms of which column is being referenced by getString(1).
Listing the columns columns can also make it more efficient on the database, to prepare a resultset with a few columns vs a resultset of dozens of columns, and we also transfer a smaller resultset from the database to the client. With a subset of columns, its more likely we can use a covering index for the query.


text:
Q: Django ajax form, choicefields dependancy models.py
class Book(models.Model):
    title = models.CharField()
    genre = models.ManyToManyField(Genre)

class Genre(models.Model):
    name = models.Charfield()

class ReadBook(models.Model):
    genre = models.ForeignKey(Genre)
    books = models.ManyToManyField(Book)

Also I have one ModelForm:
class ReadBookForm(ModelForm):
    class Meta:
        model = ReadBook

template.html
<form action="/add_report/" method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Submit" />
</form>

The purpose:
By default to show a visitor only one field - genre. When he is with done this choice - show other fields from books model, related to selected genre.

A: inside form tag:
{{ form.genre }}

<input type="submit" value="Submit" disabled="yes" />

then in javascript (jQuery is great for this stuff):
$('#{{ form.genre.id }}').change(function(){
    $('#books').load('{% url get_genre_books %}', {genre: $(this).value()})
});

you must create a view that will return a html that should be placed in this div:
def get_genre_books(request):
    genre = get_object_or_404(pk=request.GET.get('genre', None))
    # here render a template or something that shouls be multiple selector of the books)
    resp = ", ".join(genre.book_set.values_list('title', flat=True))
    return HttpResponse(resp)

and of course add this view to the urls.py.
One of many solutions :) didnt' test it (written only here, so maybe small bugs somewhere) :)


text:
Q: Каким образом получить новый массив из текущего? Через переменную получаю такой массив вывода продукта
array(4) {
  [0]=>
  array(3) {
    ["name"]=>
    string(58) "Адаптер прямоугольного сечения"
    ["price"]=>
    string(8) "300 руб."
    ["catID"]=>
    string(1) "7"
    ["catName"]=>
    string(60) "Воздуховоды квадратного сечения"
  }
  [1]=>
  array(3) {
    ["name"]=>
    string(43) "Воздуховод прямошовный"
    ["price"]=>
    string(8) "500 руб."
    ["catID"]=>
    string(1) "8"
    ["catName"]=>
    string(54) "Воздуховоды круглого сечения"
  }
  [2]=>
  array(3) {
    ["name"]=>
    string(51) "Врезка круглая в воздуховод"
    ["price"]=>
    string(8) "60 руб."
    ["catID"]=>
    string(1) "8"
    ["catName"]=>
    string(54) "Воздуховоды круглого сечения"
  }
  [3]=>
  array(14) {
    ["name"]=>
    string(56) "Заглушка воздуховода торцевая"
    ["price"]=>
    string(8) "900 руб."
    ["catID"]=>
    string(1) "7"
    ["catName"]=>
    string(60) "Воздуховоды квадратного сечения"
  }
}

В данном примере 3 продукта относиться к категории №7 ( catID) а один к №8
Задача, вывести по категориям, что бы на странице формировалась такая структура

Названия категории №1

Имя продукта

Цена продукта

Имя продукта

Цена продукта

Названия категории №2

Имя продукта

Цена продукта

Я подумал сделать следующим образом. Пройтись по массиву, и сравнивать ID категории, создавая новые массивы , где каждый массив будет иметь названия категории, ид, и внутри массив с продукции которые относяться к данной категории. По логике понимаю как сделать но возникли трудности с реализации. Буду очень признателен за помощь.

A: $items =[
    ['name'=>'Адаптер прямоугольного сечения1','price'=>12,'catID'=>'7','catName'=>'Воздуховоды квадратного сечения'],
    ['name'=>'Адаптер прямоугольного сечения2','price'=>13,'catID'=>'7','catName'=>'Воздуховоды квадратного сечения'],
    ['name'=>'Адаптер прямоугольного сечения3','price'=>14,'catID'=>'7','catName'=>'Воздуховоды квадратного сечения'],
    ['name'=>'Врезка круглая в воздуховод1','price'=>15,'catID'=>'8','catName'=>'Воздуховоды круглого сечения'],
    ['name'=>'Врезка круглая в воздуховод2','price'=>16,'catID'=>'8','catName'=>'Воздуховоды круглого сечения'],
    ['name'=>'Врезка круглая в воздуховод3','price'=>17,'catID'=>'8','catName'=>'Воздуховоды круглого сечения'],
];

$result = [];
foreach($items as $item){
    $catId = $item['catID'];
    $result[$catId]['catID'] = $item['catID'];
    $result[$catId]['catName'] = $item['catName'];
    unset($item['catID'],$item['catName']);
    $result[$catId]['items'][] = $item ;
}
var_dump($result);


text:
Q: What hardware devices do you test your Android apps on? The emulator that comes with ADK for use under Eclipse is fine for testing basic Android application functionality, but:

*

*it's not very performant

*it doesn't reflect real-world hardware and software configurations

*it doesn't support varying input devices such as d-pads, touch screens, trackballs or even Bluetooth/USB controllers.

Android Developer posts some very helpful rolling graphs of Platform versions, Screen sizes and densities, and OpenGL ES versions as extracted from Android Market:

*

*http://developer.android.com/resources/dashboard/platform-versions.html

*http://developer.android.com/resources/dashboard/screens.html

*http://developer.android.com/resources/dashboard/opengl.html
Those really help to narrow the scope of some of the choices, but I find myself really wanting to know what the proportions of input methods various devices support are... is touch represented by 90% of the market, or only 5%? What proportion of those support multi-touch?
For example... anyone who has played the free and open source game Replica Island ( http://replicaisland.net/ ) will know that how you control the game varies between devices because it supports multiple input methods. I think Chris and Genki have done a fantastic job here, but if you use touch screens you know that the game is much more playable on 5-7 inch devices than it is on 10+ inch devices. This is because the left-right slide control doesn't maintain the same physical size as the screen size increases - meaning that you have to move too far on large touch screen devices (such as Honeycomb tablets) to be comfortable.
These are the sorts of issues you only find out when you start using various hardware devices to do your testing on. Or you can wait until users do your testing for you and start bringing your app ratings down.
So after my long introduction, here are my questions to you:

*

*What collection of hardware devices have you bought to use in your software development and have you found those choices to have been beneficial or detrimental?

*Do you instead use 3rd party testing services and just tolerate the long turnaround times between test reports (hours/days instead of instant gratification)?

A: For me test devices are sort of like pickup trucks:  I'll make friends just to get access to their phones ;-)
Seriously, I do tap friends and family as resources.  I'm a small shop and can't afford to buy a lot of test devices.  Yet even with this limited pool of resources I've go the following devices available and it seems to have served me well:

*

*Original Moto DROID (seems like such a dog now).

*DROID Pro (broken screen but still good for testing).

*Asus eTransformer

*Samsung Galaxy Tab (7")

*HTC Rezound (my personal phone--it rocks)

*Samsung Charge (my wife's phone)

*DROID X (son-in-law)

*HTC-something I can't remember right now (daughter & son)

*Amazon Kindle Fire (father).

So, as you can see, without spending a fortune I've got a pretty good set of test devices, not counting all the friends I press into service as beta-testers.  With all those I really haven't had many problems with platform specific issues.  I hear a lot of grumbling about fragmentation (perhaps mostly from iOS developers), but if you develop your app intelligently it isn't a huge issue.

A: I have own collection of devices:

*

*tablet with 10" screen (Motorola Xoom);

*Nexus S as reference smartphone;

*device with hardware keyboard (Motorola Droid);

*one device from HTC (HTC Desire HD). I need it because it has slightly different UI (HTC Sense) and HTC phones are quite popular in my country. It is the least useful device in the collection;

*a pair of devices with non standard screen resolutions.

A: At this stage I'm just testing with two phones:

*

*HTC Magic (3.5" touchscreen)

*Samsung Galaxy S II (4.3" touchscreen)

There's a pretty big difference in the perceived density between these phones, so it's been helpful for comparison in testing my own games. The major omission at this stage is a tablet - just haven't been able to justify the cost yet.
I'm also playing around at the moment with LCDDensity for Root which allows you to change the screen resolution on-the-fly. Interesting to see what the same sized screen would look like with more pixels stuffed in (i.e. closer to Retina display)


text: Q: How to test different media queries for a javascript I have below javascript written, I would like to add tooltip on a button for  every desktop device of different sizes. Can anyone advise how can I mention different media screen in my javascript and how could I test it in my laptop for every media screen I included in style.


text:
Q: how to display data from a table in php using checkbox? I have multiple themes in my database and my query is to fetch the common info of these themes by selecting check boxes in php?
suppose there are four themes 'a', 'b', 'c' and 'd' I have separate tables too containing there common data i.e. a table of a intersect b, a intersect c and a intersect d and so on.
now what i have tried is first user have to select the theme form a drop box , then will select the multiple comparing themes using check box. When i check two themes it displays the data of last theme only.
<form method="GET" action="abc.php" name="form">
    Select Theme >>
   <select name ="table[]">
     <option value="ab">a</option>
     <option value="bc">b</option>
     <option value="cd">c</option>

     Show Common Genes of Selected Theme with

   <input type="checkbox" name="search" value = "a"/>
    a
   <input type="checkbox" name="search" value = "a"/>
    b
   <input type="checkbox" name="search"/ value = "c">
    c
   <input type= "submit" value= "Search" name="sub" />
</form>

can any one suggest me what should be my action.php?
i am trying this but it is giving no results:
    <?php
    require("config.php");

    $table=$_POST['table'];
    $search=$_POST['search'];

  echo"

Theme
Id
Symbol
Name
Synonyms
Chromosome
New_Id

";

        foreach($search as $key)
        {

switch($key)
            {
      case"cancer":
   $sql = mysql_query("select * from $table where theme = 'cancer'", $con);
    $num_row=mysql_num_rows($sql);

    for($i=0;$i<$num_row;$i++)
{

$result=mysql_fetch_assoc($sql);

  echo"
";
  echo"" . $result['theme'] ."	";

    $strName2 = $result["Locus_id"];
   echo"" . $result['id'] ."	";
  echo"" . $result['symbol'] ."	";
  echo"" . $result['name'] ."	";
  echo"" . $result['Synonyms'] ."	";
  echo"" . $result['Chromosome'] ."	";
  echo"" . $result['new_id'] ."	";
  echo"
";
}
    break;

    case"diabetes":
   $sql = mysql_query("select * from $table where theme = 'diabetes'", $con);
    $num_row=mysql_num_rows($sql);

    for($i=0;$i<$num_row;$i++)
{

$result=mysql_fetch_assoc($sql);

echo"
";
  echo"" . $result['theme'] ."	";

    $strName2 = $result["Locus_id"];
   echo"" . $result['id'] ."	";
  echo"" . $result['symbol'] ."	";
  echo"" . $result['name'] ."	";
  echo"" . $result['Synonyms'] ."	";
  echo"" . $result['Chromosome'] ."	";
  echo"" . $result['new_id'] ."	";
  echo"
";
}
}
    break;

            case"tubersulosis":
   $sql = mysql_query("select * from $table where theme = 'tuberculosis'", $con);
    $num_row=mysql_num_rows($sql);

    for($i=0;$i<$num_row;$i++)
{

$result=mysql_fetch_assoc($sql);

echo"
";
  echo"" . $result['theme'] ."	";

    $strName2 = $result["Locus_id"];
   echo"" . $result['id'] ."	";
  echo"" . $result['symbol'] ."	";
  echo"" . $result['name'] ."	";
  echo"" . $result['Synonyms'] ."	";
  echo"" . $result['Chromosome'] ."	";
  echo"" . $result['new_id'] ."	";
  echo"
";
}
}
    break;
            case"hiv":
   $sql = mysql_query("select * from $table where theme = 'HIV'", $con);
    $num_row=mysql_num_rows($sql);

    for($i=0;$i<$num_row;$i++)
{

$result=mysql_fetch_assoc($sql);

echo"
";
  echo"" . $result['theme'] ."	";

    $strName2 = $result["Locus_id"];
   echo"" . $result['id'] ."	";
  echo"" . $result['symbol'] ."	";
  echo"" . $result['name'] ."	";
  echo"" . $result['Synonyms'] ."	";
  echo"" . $result['Chromosome'] ."	";
  echo"" . $result['new_id'] ."	";
  echo"
";
}
}
    break;
        }
            }

mysql_close($con);
    ?>

A: As suggested by @manoj change the name to search[] instead of search. And make the form method to POST.
Now in abc.php you can get the checkbox value by
$search = $_POST['search'];//this will be an array

The rest i think you can do. right ?

A: Your form code should be:
<form method="POST" action="abc.php" name="form">

     Select Theme >>

   <select name="table">
    <option value="ab">a</option>
    <option value="bc">b</option>
    <option value="cd">c</option>
   </select>

     Show Common Genes of Selected Theme with

   <input type="checkbox" name="search[]" value="a" />
    a
   <input type="checkbox" name="search[]" value="b" />
    b
   <input type="checkbox" name="search[]" value="c" />
    c
   <input type="submit" value="Search" name="sub" />
</form>

In your PHP file, you can access values:
$search = $_POST['search']; // checkbox values
print_r($search);

$table = $_POST['table']; // select value
echo $table;


text:
Q: Ruby incorrectly interpreting class namespace I have code that looks like the following snippet:
require_relative 'class/foo'
require_relative 'class/bar'
require_relative 'class/baz'

class MyClass
  def initialize(arg)
    ...

    %w(wordone wordtwo).each do |word|
      Foo.public_send(word.to_sym, arg)
      Bar.public_send(word.to_sym, arg)
      Baz.public_send(word.to_sym, arg)
    end
  end
end

In each of those three requires is code like this template:
class Foo
  def self.wordone(arg)
    # do stuff
  end

  def self.wordtwo(arg)
    # do stuff
  end
end

This works perfectly fine for Foo and Bar, but once it hits Baz:
NameError: uninitialized constant MyClass::Baz
Did you mean?  Baz

I clearly specified Baz and not MyClass::Baz. Why is Ruby randomly misinterpreting the namespace for the third object method invocation and not the first two?
I should also mention that if I change:
Baz.public_send(word.to_sym, arg)

to:
Baz.wordone(arg)

then it works perfectly for that one method invocation, but I obviously need to loop over multiple method invocations for that class. So Ruby's namespace misinterpretation seems to be linked to the use of public_send on the object method.
This is occurring on Ruby 2.3.1p112.

A: It seems some characters are being escaped in the string passed into the block
Upon inspection,
$('wordone wordtwo').each {|word| p word}
gives
"\"wordone\"" and "\"wordtwo\""
Removing the extra escaped string quotes and forward slash gets it working for me.
class MyClass
  def initialize(arg)
    ...

    %w(wordone wordtwo).each do |word|
      word = word.tr('\"', '');
      Foo.public_send(word.to_sym, arg)
      Bar.public_send(word.to_sym, arg)
      Baz.public_send(word.to_sym, arg)
    end
  end
end

You could check that, let's see how it goes

A: Codifying my (apparently helpful) comment from the OP:
Basically what's happening here is Ruby can't find class Baz at the top-level, so it's looking under MyClass (it actually tries looking under MyClass first, then checks the top-level; the error message tells you that it couldn't find it in either namespace).


text:
Q: Bean definition in spring integration I am new to spring. I want to write a bean definition for the code below.
package com.abc.common.filter;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

public class RegexFilter implements Filter<String> {

   Logger logger = Logger.getLogger(RegexFilter.class);
   private Pattern regex;
   private String lastMatch;

   public RegexFilter(String regexString) {
      this.lastMatch = null;
      regex = Pattern.compile(regexString, Pattern.UNICODE_CHARACTER_CLASS);
   }

   @Override
   public boolean matches(String text) {
      text = text.toLowerCase();
      if (text == null) {
         logger.error("No text set for matching!");
         return false;
      }

      Matcher matcher = regex.matcher(text);
      if (matcher.find(0)) {// always start at index 0
         this.lastMatch = matcher.group();
         if (logger.isDebugEnabled()) {
            logger.debug(matcher.group() + " found!");
         }
         return true;
      }

      return false;
   }

   public String getLastMatch(){
      return this.lastMatch;
   }

}

I am stuck after this line, i dont know how to include index or name? A little more clarification on index and values would be more than helpful.
<bean id="regexfilter" class="com.abc.common.filter.RegexFilter" />
    <constructor-arg name="regexString"  />
        </bean>

A: You can define your bean
<bean id="regexfilter" class="com.abc.common.filter.RegexFilter" />
    <constructor-arg type="java.lang.String" value="valueforregexstring"/>
</bean>

You can see more about bean definitions here
http://www.tutorialspoint.com/spring/constructor_based_dependency_injection.htm

A: in annotation based manor with pure java you can do something like this:
@Configuration
public class ApplicationConfig {

    @Bean
    public Filter regexFilter() {
        return new RegexFilter("value_for_the_regex_filter");
    }
}

or simply:
@Service
public class RegexFilter implements Filter<String> {
    ...
}


text:
Q: Does Lubuntu have a future? I have some old, lower-end hardware (P4, 2.0 GHz, 1 GB RAM) onto which I have installed Lubuntu 13. 10 as my first venture into Linux. For the most part, everything has been fine and the learning curve hasn't yet been too bad to overcome.
The machine is mostly being used for web browsing and basic office type functions using LibreOffice.
After reading this post, https://wiki.ubuntu.com/Lubuntu/Testing/14.04, I'm wondering about the future of Lubuntu and whether I should stick with it. My plan for this particular machine was to upgrade it to Lubuntu 14.04 (hopefully it will released as a LTS version) and then give this machine to a relative who needs something for basic tasks.
Is it worth sticking with Lubuntu for something like this (a LTS release will probably outlive the machine's usefulness) or does it look like there isn't a future for Lubuntu and I should look into one of the other minimal distros.

A: Lubuntu just started releasing LTS versions so why should the project end? As long as there is Ubuntu, there will be Lubuntu.
In fact, Lubuntu is Ubuntu, but uses the desktop environment LXDE and its software instead of the default DE called Unity.
Basically you can use every Linux system with the Xorg graphics server and install LXDE, which would look the same as Lubuntu, but would be have a bit differently.
Another lightweight environment would be XFCE (which is also available as Xubuntu)
Basically you can choose any distro- and desktop-combo. But for an older PC you should stay with LXDE or XFCE.


text:
Q: Use of *this as a return value One example from Sutter & Alexandrescu's coding standards caught my eye
"Example 2: std::string::append (postcondition error). When appending a character to a string, failure to allocate a new buffer if the existing one is full prevents the operation from performing its documented function and achieving its documented post-conditions, and is therefore an error."
I can't imagine that in any normal conditions one would check the return value from an append, but was curious what that value is and it turns out to be *this (which can only be used inside a nonstatic member function).  I suppose one could check the string length before and after the append,
but how might one go about accessing *this?
For example:
std::string::s = "Hello World";
for (int i=0; i<many millions; ++i) {
  s.append(s);
}
s.append(".");  //  Which we assume fails due to a buffer error.

A: Error checking in facilities like string as well as most of the standard library is done via exceptions, not via return values.
If append fails, it will exit via an exception, otherwise, the operation succeeded and you get a valid return value.  So checking for errors in the returned value is neither necessary nor possible.
As pointed out in the comments, said return value can then be used to e.g. chain operations.

A: If you really wanted to, you could cache the return value in a local variable in the loop and check it's contents, but it would be redundant:
std::string s = "Hello World";
for (int i=0; i<many millions; ++i)
{
  std::string s2 = s.append(s);
  if (s2.size() == 42)
  {
    break;  // or some kind of check
            // but as others said, exceptions are better
  }
}


text:
Q: How to compute the result of 8086 IDIV instruction? Instructions (numbers in hex):
mov ax, 0832
mov cx, 008a
idiv cl

Documentation says:
when operand is a byte:
AL = AX / operand
AH = remainder (modulus)

Source: http://www.electronics.dit.ie/staff/tscarff/8086_instruction_set/8086_instruction_set.html#IDIV
As far as I understand, I have to check if the leftmost bit isn't 1:
0832 -> 0000.1000.0011.0010
008a -> 0000.0000.1000.1010

Since there's no 1's in highest bits, by using calculator I should get:
0832 mod 008a as remainder and 0832 div 008a as div part. Mod goes to AH and div should go to AH, but I can't get the correct answer. The correct answer is 5CEF. What am I doing wrong?

A: +1 for reading the documentation :)
Note that you need to check the leftmost bit according to the effective operand size. Since you are dividing by CL, which is a 8 bit value, you need to check bit #7, which is 1. As such, the number in CL is negative, namely -118. So,
AL = 0832h / -118 = 2098 / -118 = -17 = EFh
AH = 2098 - (-17 * -118) = 92 = 5Ch


text:
Q: Why can't my php document read in a different folder? I'm developing a PostgreSQL based site.
If I begin my index.php like
<?php
(...)
?>

it shows normally on the browser. But if I begin like
<?php session_start();
include("../includes/databaseLogin.php");
?>

it doesn't show anything at all. I wonder if that's because of 'includes' folder's permission. If I type ls -la at the .. folder, it gives:
drwxr-xr-x  4 root root 4096 Ago  9 20:21 .
drwxr-xr-x 14 root root 4096 Jul 23 11:30 ..
drwxr-xr-x  2 root root 4096 Ago  9 20:47 html
drwxr-xr-x  2 root root 4096 Ago  9 20:46 includes

The permissions on the file includes/databaseLogin.php are
-rw-r--r--

There are 3 R's which means my folder can be READ by myself, by other users on my group, and by other users on other groups, right? Or not? What am I doing wrong here? I'm using Ubuntu 14.04 with Apache server.
Thanks in advance.


text:
Q: Loading sub reports in main reports in java jasper netbeans I want to load sub reports 14th1 to the main report 15th.. but through this code i am getting errors.. can anyone help me out through this code?
but when i dont attach sub reports it works fine with this code.
JasperDesign jd = JRXmlLoader.load("C:\\Users\\Neetesh\\Documents\\NetBeansProjects\\labproject\\src\\13th.jrxml");

String sql="select main_test, sub_test, item, patient_id, normal_value, unit, results, remarks, date_v from tbl_report where patient_id='"+Patients+"' order by main_test ";
JRDesignQuery newQuery = new  JRDesignQuery();
newQuery.setText(sql);
jd.setQuery(newQuery);
JasperDesign sub = JRXmlLoader.load("C:\\Users\\Neetesh\\Documents\\NetBeansProjects\\labproject\\src\\14th1.jrxml");
           Map para=new HashMap();
        para.put("Sub1", sub);

JasperReport jr=JasperCompileManager.compileReport(jd);
JasperPrint jp=JasperFillManager.fillReport(jr, null,con);
JasperViewer.viewReport(jp);

A: I had got a similar issue. What I did was that, I previewed the sub report in Jasper iReport Designer. After that i run the code and it worked fine.
I believe when we preview the report it is compiled correctly and works for us through java code.
Whereas without previewing when we try to run it from the code, the code is not able to compile it at runtime.
That is the code only loads a precompiled report successfully.
See if this works for you. Thanks.


text:
Q: Make Portage install non-free software after confirmation So, in my make.conf I have ACCEPT_LICENSE="@FREE" variable set up, but I still want to use some proprietary software. Best case scenario would be Portage warning that the software I'm going to install is not free and then ask for a confirmation to proceed. Is that possible?

A: I have ACCEPT_LICENSES="-* @FREE", yet sadly need some proprietary software for school once in while. I solved this using the optional file in /etc/portage, package.license, where you can instruct portage to make exceptions for certain licenses on certain packages.
The format of package.license is similar to package.use: you supply one package per line, in the format of category/package license. You can use # to start comments as well.
You can also make /etc/portage/package.license a directory, like the other configuration files in there. In that case, it will read all files inside this directory.
Using this configuration, when you try to install software with licenses not included in @FREE, portage will complain about it. It will inform you which packages require which licenses to be accepted, which you can then add to your package.license configuration.

A: *

*Add ACCEPT_LICENSE="-* @FREE" in the /etc/portage/make.conf

*Add ACCEPT_LICENSE="*" in the /etc/portage/env/accept_license.conf
Then you can allow specific packages you want creating a file on /etc/portage/package.env.
E.g (/etc/portage/package.env/non-free):
<category>/<some-software> accept_license.conf


text:
Q: How to migrate Schema to ISchema in aws cdk 2.61.1 Hi since the new aws cdk version (2.61.1) the Schema does no longer exist :/
So it's now impossible to import it from appsync:
import { Schema } from "@aws-cdk/aws-appsync-alpha"
Vscode suggest me to use ISchema instead :
https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.ISchema.html
So i try to use SchemaFile but i didn't manage to reproduce my previous comportment
const apiSchema: SchemaFile = SchemaFile.fromAsset("../../playbook-api-schema/schema.graphql")
// const apiSchema = new Schema()
// apiSchema.addToSchema(appSyncCompatibleSchema)

Someone know whot to replace my old code ?

A: As of 2.55, the "code-first" schema generation functionality was moved out of the CDK repo and to a separate package, @cdklabs/awscdk-appsync-utils:
import { CodeFirstSchema } from 'awscdk-appsync-utils';

const schema = new CodeFirstSchema();

schema.addType(new ObjectType('demo', {
  definition: { id: GraphqlType.id() },
}));

By the way, as of 2.60, the "schema-first" SchemaFile construct and the other remaining AppSync L2 constructs were promoted from "alpha" to "stable".  They are now available in aws-cdk-lib like all stable APIs.  The -alpha package is deprecated.


text:
Q: Google+ Auth in AWS Cognito and API Gateway is unauthorized AWS Wizards,
I've created a POC web app to test AWS Cognito and Federated Identities for a project.
I extended the POC with Google+ authentication. When a user authenticates via Google the counter for the Google Signin is increasing in Federated Identities, they are obviously being verified.
Now I am trying to use the credentials with a secured AWS API Gateway endpoint with no luck. The user will remain unauth'ed according to the gateway. I've tried the test feature in the API Gateway authorizers config, if I test with a Cognito user CognitoUserSession.idToken the test returns the claims.
If I do the same test with a Google user's idToken it is unauthenticated. After a successful Google sign in the same AWS Javascript SDK code is executed (as the Cognito user login). The credentials are updated with an identity ID and a session token but no ID token.
As I am a total noob on AWS I am probably missing something here. What should I do to get a valid idToken? Should it be done in a different way?
(GoogleLogin is a React component)
render() {
    return (
        <GoogleLogin
            clientId="44xxx11.apps.googleusercontent.com"
            buttonText="Google Login"
            onSuccess={this.responseGoogle}
            onFailure={this.responseGoogle}
        />
    )
}

responseGoogle(response) {
    console.log(response.tokenId)
    cognitoIdentityCredentials(response.tokenId)
}

cognitoIdentityCredentials(idToken) {

    const loginsObj = {
        ['accounts.google.com']: idToken
    }

    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
        IdentityPoolId: IDENTITY_POOL_ID, // your identity pool id here
        Logins: loginsObj
    })

    AWS.config.credentials.get(function(err) {
        if ( err ) {
            console.log(err);
        } else {
            console.log("---- AWS credentials ----")
            console.log(AWS.config.credentials)
            // Got credentials, but no valid idToken
        }
    })
}

A: The solution to this problem is that you can't really use AWS Security the way I assumed. In AWS API Gateway a generated library can be downloaded to access that API specifically and when using the lib we found that there are more fields added to the request, and yes they are signed. All of them.
It will be a pain to use different SDK libraries for different environments and apps, so we simply took one of the SDKs and made it into a general library that we can use for all requests in all web projects. There are similar projects already on Github, but they are unfortunately only working with Cognito users, not Federated Identities.
Happy Panda again.


text:
Q: Open a webpage in flex application How can I open a web (example www.cnn.com) in a Flex application?

A: I understand that you are trying to open an url in the default system browser.Please try this.
var urlRequest:URLRequest = new URLRequest("http://www.adobe.com/");
            //To open in a new tab
            navigateToURL(urlRequest,_blank);
            //To open on top of the same page
            navigateToURL(urlRequest,_top);

If you are looking to open an url within a Flex application you check here


text:
Q: CUDA Driver API equivalent to cudaDeviceSetCacheConfig Comparing the CUDA (latest, v11.3 as of writing) driver API with the runtime API reveals that the runtime API has function
__host__ cudaError_t cudaDeviceSetCacheConfig ( cudaFuncCache cacheConfig )
    Sets the preferred cache configuration for the current device.

and it seems the driver API has no equivalent function. Any insight to why that is and is there a way to set the device-wide cache configuration with the driver API?

A: The corresponding function is cuCtxSetCacheConfig  documented here.
The reason for the difference is that the driver API focuses on context behavior.  The runtime API generally posits that for a particular process owner, there is only one context per device.  (Therefore it generally has a "device" in view instead of a context.)  The same is not necessarily the case for the driver API. So you you are given the ability to set it per-context.
If you only have one context per device, that control is effectively "device-wide".


text:
Q: How to override ctl-tab keybinding in textmate.el minor mode I'm playing around with textmate.el: https://github.com/defunkt/textmate.el. A little confusing at first if you've never tried textmate, but pretty cool!
I'd like to override a binding in the minor mode.
Here is a snippet from the source that does the binding:
(defvar *textmate-mode-map*
  (let ((map (make-sparse-keymap)))
    (cond ((featurep 'aquamacs)
       ....
(t ;; Any other version
 (define-key map [(control tab)] 'textmate-shift-right)
 (define-key map [(control shift tab)] 'textmate-shift-left)

Rather than modifying the source I got from github, I'd like to override in my .emacs.

A: All it should take is
(eval-after-load 'textmate
  '(progn
     (define-key *textmate-mode-map* [(control tab)] 'my-cool-function)))

replacing of course my-cool-function with whatever you actually want it to do.  If you want to use a lambda function, don't forget to make it interactive or you will get an error:
(eval-after-load 'textmate
  '(progn
     (define-key *textmate-mode-map* [(control tab)]
       (lambda () (interactive)
         ...))))


text:
Q: How to validate dynamic rules with dynamic form elements created with ng-repeat and using ng-form? I have a dropdown that dynamically generates any number of text inputs, all of which have different validation rules (min/max length, pattern etc.). According to several other stackoverflow questions ie. (How to validate inputs dynamically created using ng-repeat, ng-show (angular)) using the ng-form module can allow you to create dynamic form elements with dynamic validation.
I've done this, but the problem is the validation rules do not update accordingly when the number of text fields are changed based off the selection in the dropdown. For example, the first dropdown option will generate 1 text input with a minlength of 3. And the second option may also generate 1 text input, but it's minlength will be 1. Even though the minlength rule is 1, angular ends up validating a minlength of 3, from the original selection's text field.
My question is, is this possible in angular without creating some kind of custom directive? An alternative solution would be to just output all of the possible text elements for each dropdown selection up front, and use ng-show based off of the dropdown selection to show/hide each set. But I'd like to keep the template clean and use ng-repeat to dynamically generate them like I already am.
I've set up a minimal example:
var validationApp = angular.module('validationApp', []);

validationApp.controller('ValidationCtrl', ['$scope', function($scope) {
    $scope.textChoices = [
        { label: "1 line", validation: [ { minLength: 3 } ] },
        { label: "2 lines", validation: [ { minLength: 1 }, { minLength: 3 } ] },
        { label: "3 lines", validation: [ { minLength: 2 }, { minLength: 2 }, { minLength: 3 } ] }
    ];
    $scope.choice = $scope.textChoices[0];
    $scope.text = [];
}]);

Please view the html and full example here: http://jsfiddle.net/anpsince83/kBVR2/

A: As mentioned in the other Stack Overflow question it's not possible with the current  AngularJS form validation. However here is a method using ngChange:
AngularJS:
validationApp.controller('ValidationCtrl', ['$scope', function($scope) {
$scope.chkLength = function(i) {
    $scope.minBad[i] = ($scope.text[i].length < $scope.choice.validation[i].minLength);
};
$scope.minBad = {};
}]);

HTML:
        <ng-form name="textForm">
            Enter Text
            <input type="text"
                   name="text"
                   ng-model="text[$index]"
                   ng-change="chkLength($index)">

            Min {{ rules.minLength }} Chars

                Please enter min amount of characters.

        </ng-form>

Fiddle code: http://jsfiddle.net/kBVR2/61/

A: Unfortunately it just doesn't look like it's possible using the built-in validation directives, so as others have suggested, I implemented a custom directive.
validationApp.directive('myMinlength', [function() {
    return {
        require: 'ngModel',
        scope: {
            myMinlength: '@',
            ngModel: '='
        },
        link: function(scope, elem, attrs, ctrl) {
            var minLengthValidator = function(value) {
                if (attrs.myMinlength) {
                    var minlength = attrs.myMinlength;
                    if (!ctrl.$isEmpty(value) && value.length < minlength) {
                        ctrl.$setValidity('myMinlength', false);
                    } else {
                        ctrl.$setValidity('myMinlength', true);
                    }
                } else {
                    ctrl.$setValidity('myMinlength', true);
                }
            };

            // validate when minlength attr changes
            scope.$watch('myMinlength', function() {
                minLengthValidator(scope.ngModel);
            });

            // validate when model changes
            scope.$watch('ngModel', minLengthValidator);
        }
    }
}]);


text:
Q: Replace For and If to make code faster I'm new with VBA and I wrote multible little makros to compare to sheets for changes. One sheet has 40000 rows and I used For and If conditions. is it possible to replace them, to make the makro work faster. now my makro ist workin for 100 rows but for more excel does not respond.
It would be glad if someone coul help me, I dont know what to do.
Sub OldT() 'Time

Worksheets("Old").Activate

For zOld = 2 To 100
    For zNew = 2 To 100
        If Worksheets("Old").Cells(zOld, 5) = Worksheets("New").Cells(zNew, 5) And Worksheets("Old").Cells(zOld, 12) = Worksheets("New").Cells(zNew, 12) Then
            Worksheets("Old").Cells(zOld, 18) = Worksheets("New").Cells(zNew, 8)
        Exit For
        End If
    Next zNew
Next zOld
End Sub


text:
Q: Center div elements I have a few elements inside a div. i want to align them center
vertically and horizontally. as if they where in one line like this
I've tried following several stackoverflow samples margin auto and many
other as you will see on my css file but no luck if you can please just put the answer and explain how is working it will help a lot. thanks.

*{margin:0px;
padding: 0px;
}

nav{
position:absolute;
left:0px;
width:100%;
background-color: #3333ff;
height: 40px;
text-align: center;
}
nav ul{
margin: 0;
padding:0;
display: inline-block;
}
.nav li{
  text-align: center;
  list-style-type: none;
  float: left;
  width: 150px;

}
.nav li a{
text-decoration: none;
text-align: center;
font-size: 150%;
color: yellow;
line-height: 40px; /*set same as height in nav to center line
vertically.*/
display:block;
}
.nav li a:hover{
background-color: chartreuse;
color:black;
}
#logo{
width:20%;
border-radius: 35%;
margin-top: auto;
margin-bottom: auto;
}

#mainImg{
height: 65vh;
width: 50vw;
border: 3px solid black;
margin-left:auto;
margin-right:  auto;
}

.tirita{
/*display:block;*/

margin: 0 auto;
height: 105px;
width:400px;

}
#gallery img{
display: none;
}
.tiritas img{
height:100px;
width: 100px;
border: 3px solid blue;
float:left;

}
.tiritas:hover{
cursor: pointer;
border-color: red;
transform: scale(1.5);
}
center{
padding:2%;
}
.prev,.next{

vertical-align: middle;

}
.prev{

float:left;
margin: 0 auto;
}
.next{
float:right;

}
#tiritaContainer{
display: inline-blockblock;
margin-left: auto;
margin-right: auto;
margin-top: auto;
margin-bottom: auto;
}

i want to have the left and right arrow in the same row aligned center
both vertical and horizontally

A: You can use flexbox to make a layout easily. What you need here is display:flex and justify-content:center for horizontal alignment and align-items:center for vertical alignment.

*{box-sizing:border-box}
.container{width:100%;display:flex;justify-content:center;align-items:center;border:1px red solid}

img{display:block;width:100px;margin:10px}


text:
Q: How to make user's turn end when certain type of card is randomly generated? If-else statement not working I'm fairly new at coding and I'm making a game in which the user plays a random card drawing game against the computer. The goal is to reach 50 points first and you reach that by drawing the cards.
For example, a 2 of Clubs should have a value of 2 and a King of Hearts should have a value of 13. The user and computer take turns drawing cards and you may continue your turn as long as you want and accumulate points, unless you draw any type of Ace or Jack, in which you lose all points for that turn and your turn ends.
In my code, I'm not sure why the user doesn't lose points and their turn doesn't end when they draw an Ace or Jack, even though there's a section of code that specifically includes an if-else statement acknowledging it. Can anyone help me?
Btw, this is as minimal as I can make the code so that you can understand how it works at its basics, while making sure that the if-else statement in question still has the same steps leading up to it.
# Useful Definitions
user_score = 0
computer_score = 0
user_turn_score = 0
computer_turn_score = 0
type = "user"
import random

class Card:
    suits = {'c': '♣','h': '♥','s': '♠','d': '♦'}
    faces = {
        1: 'Ace',
        11: 'Jack',
        12: 'Queen',
        13: 'King'
    }
    def __init__(self, rank, suit):
        self.rank = rank
        self.suit = suit
    def __repr__(self):
        face = self.faces.get(self.rank, self.rank)
        return f'{face}{self.suits[self.suit]}'
    def __add__(self, other):
        if isinstance(other, int):
            return self.rank + other
        return self.rank + other.rank
    def __radd__(self, other):
        if isinstance(other, int):
            return other + self.rank
        return self.rank + other.rank

sorted_deck = [Card(n, s) for s in Card.suits for n in range(1, 14)]

if type == "user":
    user_turn_score = 0
    random_drawn_card = random.choice(sorted_deck)
    print("Your card: " + str(random_drawn_card))
    sorted_deck.remove(random_drawn_card)
    if random_drawn_card == "Ace♣" or random_drawn_card == "Ace♥" or random_drawn_card == "Ace♦" or random_drawn_card == "Ace♠" or random_drawn_card == "Jack♣" or random_drawn_card == "Jack♥" or random_drawn_card == "Jack♦" or random_drawn_card == "Jack♠":
        user_turn_score = 0
        print("You drew an Ace or a Jack. You will not gain any points this turn.")
        type = "computer"
    else:
        value = random_drawn_card.rank
        user_turn_score = user_turn_score + value
        user_score = user_score + user_turn_score
        print("Your points this round: " + str(user_turn_score))

A: Consider the following code:
class MyClass:
    def __repr__(self):
        return "foo"

instance = MyClass()
print(instance == "foo") # False
print(str(instance) == "foo") # True

A: The Issue Seemed to be you using an else statement, I changed it to an elif doing the opposite conditions of the other if statement for the aces and stuff. I also am forcing the card to be an ace for debugging purpose since it never seemed to drawn a loosing card, so you may want to re-work you card picking system, I added a couple of print lines for it to print the type and score, you now loose points when you draw a loosing card hope this helps!
# Useful Definitions
user_score = 0
computer_score = 0
user_turn_score = 0
computer_turn_score = 0
type = "user"
import random

class Card:
    suits = {'c': '♣','h': '♥','s': '♠','d': '♦'}
    faces = {
        1: 'Ace',
        11: 'Jack',
        12: 'Queen',
        13: 'King'
    }
    def __init__(self, rank, suit):
        self.rank = rank
        self.suit = suit
    def __repr__(self):
        face = self.faces.get(self.rank, self.rank)
        return f'{face}{self.suits[self.suit]}'
    def __add__(self, other):
        if isinstance(other, int):
            return self.rank + other
        return self.rank + other.rank
    def __radd__(self, other):
        if isinstance(other, int):
            return other + self.rank
        return self.rank + other.rank

sorted_deck = [Card(n, s) for s in Card.suits for n in range(1, 14)]

if type == "user":
    user_turn_score = 0
    random_drawn_card = random.choice(sorted_deck)
    print("Your card: " + str(random_drawn_card))
    sorted_deck.remove(random_drawn_card)
    random_drawn_card = "Ace♣" # Just Forcing it to be an ace
    if random_drawn_card == "Ace♣" or random_drawn_card == "Ace♥" or random_drawn_card == "Ace♦" or random_drawn_card == "Ace♠" or random_drawn_card == "Jack♣" or random_drawn_card == "Jack♥" or random_drawn_card == "Jack♦" or random_drawn_card == "Jack♠":
        user_turn_score -= 1 # Now Subtracts points
        print("You drew an Ace or a Jack. You will not gain any points this turn.")
        type = "computer"
        print(type) # Debugging
        print(user_turn_score) # Debugging
    elif random_drawn_card != "Ace♣" or random_drawn_card != "Ace♥" or random_drawn_card != "Ace♦" or random_drawn_card != "Ace♠" or random_drawn_card != "Jack♣" or random_drawn_card != "Jack♥" or random_drawn_card != "Jack♦" or random_drawn_card != "Jack♠":
        value = random_drawn_card.rank
        user_turn_score = user_turn_score + value
        user_score = user_score + user_turn_score
        print("Your points this round: " + str(user_turn_score))

A: This should point you in the right direction. Just below sorted_deck.remove(random_drawn_card) I added
print(random_drawn_card == str(random_drawn_card))

# False

In other words, the way it's displayed is not the same as what it is.


text:
Q: SQL Server 2017 on RHEL Linux with IDM for AD authentication We are using Red Hat IDM to authenticate AD users to SQL Server. Users can login successfully to SQL Server with SSMS and SQL CMD with AD Authentication. But running some elevated commands from SSMS or SQL CMD can run only once in session and it kick out AD authenticated users from SQL Server with the following error:
Error 15404 'Could not obtain information about Windows NT group/user '%ls', error code 0x80090304'

A: I had similar experience. I believe this was due to a limitation in IDM. There is currently a bugzilla filed for this issue. I believe Red Hat is working on addressing this issue.


text:
Q: how to filter the shape by text and delete selected shapes (In the example, I'm trying to filter shapes with text "No" and delete) Sub delete_shapes()
    Dim i As Integer

    ActiveSheet.Shapes.SelectAll

    For i = 1 To 4 Step 1
    If i < 5 Then

    For Each shape In ActiveSheet.Shapes
     'it has to match with shapes of text "NO"

      If Selection.ShapeRange(i).TextFrame2.TextRange.Characters.Text = "No" Then

     shape.Select
        Selection.Delete

     Else
     Debug.Print Selection.ShapeRange(i).TextFrame2.TextRange.Characters.Text
  ' running through the range of index
    i = i + 1
      End If

    Next shape

    End If

    Next i
End Sub

A: When deleting items from a collection it's often a good idea to go "backwards" so that deleted items don't affect the indexes of later items.
Sub delete_shapes()
    Dim i As Long, ws As Worksheet, txt, shp As Shape

    Set ws = ActiveSheet
    Application.ScreenUpdating = False
    For i = ws.Shapes.Count To 1 Step -1
        Set shp = ws.Shapes(i)
        txt = shp.TextFrame2.TextRange.Characters.Text
        Debug.Print shp.Name, txt
        If txt = "No" Then shp.Delete
    Next i
    Application.ScreenUpdating = True
End Sub


text:
Q: I am contributing to an repository but " fatal: will not add file alias " is been shown while commit As the problem is while commit,
fatal: will not add file alias 'src/Components/Button.js' ('src/components/Button.js' already exists in index)
The above error shows up, as haven't even opened the file and is working fine.

A: Read the text carefully and closely:

fatal: will not add file alias 'src/Components/Button.js' ('src/components/Button.js' already exists in index)

(note: I had to retype this, because you used an image instead of cutting-and-pasting text; please read the How do I ask a good question? help page).
Perhaps this might help:
src/Components/Button.js
src/components/Button.js

Can you see the difference between two letter c-s here?  One is UPPERCASE and one is lowercase.

*

*To Git, these are two different file names.

*To your operating system, these are the same file name.
Git can easily store both files.  But if you make it do that, you won't be able to work with this repository any more—or at least, not in a sensible way, with this particular commit.  Git is carefully keeping you from shooting yourself in the foot.
Because your system doesn't distinguish between uppercase and lowercase in file and folder names, but Git does, you must be particularly careful when working with a repository that uses MixedCapItALIzaTIOn in file names for whatever crazy reason.  You should do one or more of the following before proceeding:

*

*Switch to a system that does think these are different file names.  The problem is now gone: Git and your OS agree that src/Components/Button.js and src/components/Button.js are two completely different files, and it's easy to store and work with both.

*Figure out why, despite Git's thinking that files should be named src/Components/*, your actual checkout has them as src/components/*.  Perhaps you should rename your components folder to Components.

*Dedicate yourself to stamping out this particular craziness: why do we have uppercase and lowercase in the first place?  Invent a time machine, go back in time to the invention of alphabets, and make sure the mistake never happens in the first place.

*Convert your software so that everything everywhere always uses lowercase whenever possible, so that the problem never occurs.  (YOU COULD USE ALL UPPERCASE, BUT THIS FEELS VERY SHOUTY.)
This whole area of file name craziness in certain OSes is a minefield.  Watch out!


text:
Q: Ember issue with setting attribute value I have an Ember Route class defined as below;
export default Ember.Route.extend({
    model: function() {
        var compObj = {};
        compObj.gridPara = this.get('gridPara');
        return compObj;
    },
    gridPara: function() {
        var self = this;
        var returnObj = {};
        returnObj.url = '/myService';
        // setting some other returnObj attributes
        var summaryObj = {
            total: {
                label: "Total 1",
                value: "100"
            },
            additional: [{
                label: 'Label 2',
                value: 'val2'
            }, {
                label: 'Label 3',
                value: 'val3'
            }]
        };
        returnObj.summary = summaryObj;
        return returnObj;
    },
    actions: {
        dataLoaded: function(resp) {
            // Here I get the service response and want to set (or overwrite) the summaryObj values
            this.get('gridParams').summary.total.value = resp.numRows;
        }
    }
});

My template looks like
{{my-grid params=this.gridPara dataLoaded="dataLoaded"}}

Now I want to set the "summary" on returnObj
I have verified that I get "resp" inside dataLoaded callback.
But I get the following error when trying to do
this.get('gridParams').summary.total.value = resp.numRows;

Uncaught Error: Assertion Failed: You must use Ember.set() to set the value property (of [object Object]) to 100.
Also how do I set/push for "additional" array inside summaryObj

A: As the error states, you must use set to the the value (Im assuming you have gridParams defined somewhere?):
this.set('gridParams.summary.total.value', resp.numRows);

In order to push a new object, try this:
var additional = this.get('gridParams.additional');
additional.push({label: ..., value: ....});
this.set('gridParams.additional', additional);

A: not 100% sure, but give it a try:

*

*Watch out the property names. I suppose it's a wording error to declare 'gridPara' and trying to get 'gridParams'

*You should retrieve the value like this
this.get('gridParams.summary.total.value')

*What you are trying with the last sentence is a setting, but like it was plain JS. In Ember you should do it this.set('gridParams.summary.total.value',resp.numRows)

A: Just adding to @Remi answers ,the best practice would be to use
Ember.set('gridParams.summary.total.value', resp.numRows);

To answer the question in your comment
Say you want to update additional  array at index i.Just do
var updateItem = additional[i];
Ember.set(updateItem.propertyname,newValue)
//Here propertyname would be the property you want to update and new Value is the new value which you want to set to that property