text:
Q: Как расспарсить формулу в текстовом формате? Добый день, подскажите пожалуйста! Функция draft создает график по формуле (в данном случае y = np.sin(t)), функция работает, но есть одна проблема! Для полной реализации нужно вводить формулу вручную и передавать в функцию в виде строки, где в последующем нужно ее распарсить и применить для построения графика.
Пробывал реализовать через алгоритм сортировочной станции, ругается на переменную t, тк она не является числом, она диапазон значений (как я это понял)
Если кто то встречался, отпишитесь, буду очень благодарен за помощь!
PS Формула может быть абсолютно произвольная
import datetime
import matplotlib.pyplot as plt
import numpy as np

def draft(interval, step, formula):
    start = datetime.datetime.now().day - datetime.timedelta(days=interval).days
    end = datetime.datetime.now().day

    t = np.linspace(start, end, 500)
    # ???
    y = np.sin(t)

    plt.grid()
    plt.xticks(np.arange(start, end, step))
    plt.plot(t, y)
    plt.show()

draft(interval=6, step=2, formula="sin(t)")

A: Регулярные выражения - сила. r'(?P<func>[\w\d]+)\((?P<arg>[\w\d]+)\)' и считать найденные группы. должны увидеть 'sin' и 't'
Проверить можно тут https://regex101.com/r/Nso1sr/1


text:
Q: Which procedures/functions/views refer to a particular table I have a table and would like to know which all procedures/views/functions refer to that table. How do I do that in SQL?

A: If you are using MS SQL:
SELECT
    referencing_schema_name, referencing_entity_name, referencing_id,
    referencing_class_desc, is_caller_dependent
FROM
    sys.dm_sql_referencing_entities ('mySchemaName.myTableName', 'OBJECT');
GO

Replace mySchemaName and myTableName with your actual schema name and table name and run the above query

redpajama_set_name: RedPajamaStackExchange


text:
Q: get model.predict values in python I am running a random forest model. I am predicting values using below code
prediction = model.predict(test_x)
I want the predicted values in a list or dataframe from below output.
array([1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1,
       0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1,
       0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0,
       1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1,
       1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0,
       0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1,
       1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 1, 0, 1, 0, 0, 1, 0, 1, 0], dtype=int64)
How to do it in Python

A: The predict function returns an array object so you can covert it into dataframe as follows.
import pandas as pd
prediction = model.predict(test_x)

cols = prediction[0].keys()
df = pd.DataFrame([[getattr(i,j) for j in cols] for i in prediction], columns = cols)

For your particular case :
import pandas as pd
prediction = model.predict(test_x)
df = pd.DataFrame(prediction, columns = ['ouput'])


text:
Q: How to create a schema in mysql using nodejs? I am very new to nodejs and trying to create a registration API using nodejs, I search for it and got some code but the problem is developer is using MongoDB but I am using MYSQL. So my question is how to create a schema in MYSQL using nodejs, I got the code where developer created the schema in MongoDB.
Here is the code:
const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const userSchema = new Schema({
    email: String,
    password: String,
});

module.exports = mongoose.model('user', userSchema, 'users');

Also Why we need schema in the first place can't I just create table in my database manually and Insert data using Insert Query.
Thanks.

A: You don´t need a specific schema if you are using mySQL. The database itself has a schema and won´t give you the chance to store malformed data if configured correctly. Mongoose provides a schema for mongoDB, because mongoDB is schema-less. You can store any kind of data and you won´t get an error back if malformed data was stored.
But of course if you are using TypeScript, you can build an interface or a class and validate data before storing without the use of any kind of third-party package


text:
Q: Copy yaml formatting (indent) from one file to another A translator completely messed up a yaml file by copying everything into word (don't ask).
I have already cleaned up the file using regexes, but the indent (spacing) is now missing; everything starts at the first character:
es:
default_blocks:
thank_you_html: "thank you text"

instead of
en:
  default_blocks:
    thank_you_html: "thank you text"

Do you have a good idea on how to automatically copy the format/structure/indent from the correct file (say en.yml) to the corrupt one (say es.yml)? (I'm using textmate 2.0 as editor)
Thanks!

A: Assuming the original and the translation contain exactly the same strings per line (except for the indentation problem), a quick&dirty script scanning the leading whitespace may solve this:
#!/usr/bin/env ruby
# encoding: UTF-8

indented = File.readlines(ARGV[0]).map do |l|
  l.scan(/^\s+/)[0]
end.zip(File.readlines(ARGV[1])).map { |e| e.join }.join

File.open(ARGV[1], "w") { |io| io.write(indented) }

Save it, make it executable and call
./script_name.rb en.yml es.yml

Wouldn't mess with Textmate if this is not a regular task, but you could easily transform this to a command and either prompt for the two files via a dialog or select both in the file browser, open one of them in the current tab and differentiate them via environment variables ($TM_FILEPATH, $TM_SELECTED_FILES)


text:
Q: How create a jwt signature using a private key and a rsasha256 algorithm (.net)? I am trying to sign a JWT with a private key and the rsasha256 algorithm. Everytime a try to create the tokenHandler, it goes into the Catch part.
The exception that I get is:

System.Exception: 'Erro ao obter ID do processo: IDX10634: Unable to create the SignatureProvider.
Algorithm: 'System.String', SecurityKey: 'Microsoft.IdentityModel.Tokens.SymmetricSecurityKey'
is not supported. The list of supported algorithms is available here: https://aka.ms/IdentityModel/supported-algorithms'

        var privateKey = File.ReadAllText(@"C:\Cencosud\Git\APIs\Api_Unico\Unico.Infra.Data\API.Services\Implementations\.key.pem");
        privateKey = privateKey.Replace("-----BEGIN PRIVATE KEY-----", string.Empty).Replace("-----END PRIVATE KEY-----", string.Empty);
        privateKey = privateKey.Replace(Environment.NewLine, string.Empty);
        var privateKeyBytes = Encoding.UTF8.GetBytes(privateKey);

        var tokenHandler = new JwtSecurityTokenHandler();
        var key = privateKeyBytes;
        var token = tokenHandler.CreateToken(new SecurityTokenDescriptor
        {
            Issuer = "service_account_name@tenant_id.iam.acesso.io",
            Audience = "https://identityhomolog.acesso.io",
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.RsaSha256)
        });

        var jwt = tokenHandler.WriteToken(token);

A: A couple problems here:

*

*The code is converting the private key as if it's a UTF8 string using Encoding.UTF8.GetBytes. Use Convert.FromBase64String instead.

*The code is attempting to initialize SigningCredentials as a symmetric key but a private RSA key isn't symmetrical and needs to be created differently.

See my changes below:
var privateKey = File.ReadAllText(@"C:\Cencosud\Git\APIs\Api_Unico\Unico.Infra.Data\API.Services\Implementations\.key.pem");
privateKey = privateKey.Replace("-----BEGIN PRIVATE KEY-----", string.Empty).Replace("-----END PRIVATE KEY-----", string.Empty);
privateKey = privateKey.Replace(Environment.NewLine, string.Empty);

// CHANGE CONVERSION TYPE
var privateKeyBytes = Convert.FromBase64String(privateKey);

// INITIALIZE RSA
using var rsa = RSA.Create();
// Since the private key starts with "BEGIN PRIVATE KEY" it's PKCS8 encoded
rsa.ImportPkcs8PrivateKey(privateKeyBytes, out _);

var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(new SecurityTokenDescriptor
{
    Issuer = "service_account_name@tenant_id.iam.acesso.io",
    Audience = "https://identityhomolog.acesso.io",
    // CREATE SIGNING CREDENTIALS WITH THE RSA INITIALIZED ABOVE
    SigningCredentials = new SigningCredentials(new RsaSecurityKey(rsa), SecurityAlgorithms.RsaSha256)
});

var jwt = tokenHandler.WriteToken(token);


text:
Q: How to change the src of multiple ImageButtons on a single ImageButton click I know how to change the src of an ImageButton when clicked, however I want to also change the src of another ImageButton at that time. I have no clue how to go about accessing the ImageButton that was NOT clicked. I know it's ID.
Edit: It may be good to mention that I will have multiple buttons, so it's not just a certain button that I need to change. Both the ones I need to change will differ.

A: Ok lets think we have two ImageButton like ImageButtonA and ImageButtonB. When user click ImageButtonA we have to change the src of ImageButtonB. Lets make two class variable for ImageButtonA and ImageButtonB.
public class MyActivity extends Activity{

private ImageButton imageButtonA,ImageButtonB;

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

        imageButtonA= (ImageButton ) findViewById(R.id.image_button_a);
        imageButtonB= (ImageButton ) findViewById(R.id.image_button_b);

        imageButtonA.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
             imageButtonB.setBackgroundResource(R.drawable.mysourceImage);
            }
        });

    }
}

I think it will solve your problem. And if you want to change multiple ImageButton src then you can make multiple ImageButton class variable.


text:
Q: MultiThreadedHttpConnectionManager with each HttpClient needing unique cookies and host I've been reading the Apache javadocs and have concluded that the correct way to handle a heavily multithreaded application which involves HttpClient is to use a static singleton MultiThreadedHttpConnectionManager with a global HttpClient, with each thread having its instance of HttpState for its cookies and HostConfiguration. Is this correct? Obviously I want to avoid each thread interfering with the others' states.
Also, one of the problems I've been noticing is that when these threads end the socket associated with the HttpClient remains (checking /proc/###/fd), even after RequestMethod.releaseConnection() is called in the finally block. This is a problem as the default limit for fd is 1024 and this will be breached after a few days. What's the best way to kill with these left over sockets?
The only applicable method I can see for killing these sockets is MultiThreadedHttpConnectionManager.closeIdleConnections(timeout)- is this correct?
This means I'm going to have to either instantiate another thread to periodically call this method, or just call it every time the threads are killed manually, which seems quite clunky. Any advice?
Thanks a lot


text:
Q: Perform mutually exclusive Read & Write operations on a mongoDB? I've a program which needs to have two processes doing mutually exclusive reads and writes to a mongodb document.
One part (lets call it "process_a") reads and updates (adds) to the document. The other (lets call it "process_b") reads and updates (deletes) all the values to the document.
So in an ideal scenario, process_a's read and writes never overlaps with process_b's read and writes.
Otherwise, if the process_b's reads right before the process_a updates the document with new values. Process_b would delete (set it to zero) the document without realizing the update from process_a every happened. Thus failing to record the transaction.
Is there any way to lock the document/collection while one process performs its read and update task.

A: I found no way of doing it with 100% certainty. So I ended up modifying code somewhere  else to prevent it from happening.


text:
Q: Explanations on the proof that the sequence $b_k={\tbinom {n}{k}}$ is increasing on $0\le k\le\left\lfloor\frac{n+1}{2} \right\rfloor$
Let $n \in \mathbb{N}$ et $f_n$ is a function defined by  :
  $${\displaystyle {\begin{aligned}f_n\colon [|0,n|] &\longrightarrow \mathbb {N} \\k&\longmapsto {\displaystyle {\tbinom {n}{k}}}\end{aligned}}} $$
  Show that $f_n$ is increasing on $\left [\left|0,\lfloor\dfrac{n+1}{2} \rfloor \right|\right]$

I don't understand the following proof :

*

*why the author took $k \in \mathbb{N}$ and not in $\left [\left|0,n \rfloor \right|\right]$ because if $k\in \mathbb{N}$ we could be have $k>n$ then $f_{n}(k)=0$ vanished so the expression $\dfrac{f_{n}(k+1)}{f_{n}(k)}$ will have no sense

*what is the reason that let author deduced from
$$f_n\left(\lfloor \dfrac{n-1}{2} \rfloor \right)\leq f_n\left(\lfloor \dfrac{n+1}{2} \rfloor \right) $$
that $f_{n}$ is increasing on $\left [\left|0,\lfloor\dfrac{n+1}{2} \rfloor \right|\right]$

Update:
Is the following remark true ?

To show that a map $f$ is increasing on $[|n,n + p|]$ where $n$ is an integer and $p$ a non-zero natural integer, it suffices to show that $f(k)\leq f(k +1)$ All $k$ between $n$ and $n+p-1$.

A: It's true that the ratio $\frac{f_n(k+1)}{f_n(k)}$ should have been considered for $k \in [\![0,n-1]\!]$ and not for all $k \in \mathbb N,$ for exactly the reasons you point out, so let's just pretend that the proof does that instead.
The proof actually considers all $k$ in that interval, though, not just $k = \left\lfloor \frac{n-1}{2}\right\rfloor.$ The argument runs: since $\frac{f_n(k+1)}{f_n(k)} = \frac{n-k}{k+1},$ we have $$f_n(k+1) \ge f_n(k) \iff \frac{f_n(k+1)}{f_n(k)} \ge 1 \iff \frac{n-k}{k+1} \ge 1,$$ and the final inequality simplifies to $k \le \frac{n-1}{2}.$ The author of the proof just wants to take extra care to make sure that at the highest value we consider, $k = \left\lfloor \frac{n-1}{2}\right\rfloor,$ the inequality $k \le \frac{n-1}{2}$ still holds, I guess?


text:
Q: Node.js + Discord.js - YouTube 24/7 Radio Voice Streaming I've created a bot to stream in discord channel some youtube videos (only sound).
I'm using dispatcher to pause/ stop/ play some videos, but it wont play youtube radio.
When bot connecting to my channel with link to radio - it keeps playing only about 2-3 seconds and stops (and dispatcher not triggering by 'finish' event).
I've tested video with 15h. duration and all works fine, but 12h livestreams is a trouble for bot.
Nothing special in my code, I think, but anyways:
const connection = await client.channels.cache
  .find(channel => channel.name === musicVoiceChannelName).join();

dispatcher = connection.play(ytdl(message.content.split(" ")[1], { filter: 'audioonly' }));

What should I do to play 24/7 livestreams on YouTube? Appreciate any thoughs.

A: In the case of youtube live stream, using the audioonly option will not succeed.
I don't know further details, but anyway, if you remove the audioonly option, it will play.


text:
Q: Difference between two lists in Java I started learning data structures and algorithms with Java.
I started with list and the first concept which I learnt is difference between array and list.
Now in list I learn how to insert and element in to list and displaying on the screen. I got two pieces of code. The first one I understood very well; where the second one is confusing.
My confusion is what is the Node here? In the beginning we declare Node head;. So basically what is Node here?
Is it predefined datatype or something? Also, how does the second program flow? How is the second program different from the first? And what is the difference?
Also I understood that we are using util here, but still I want to know because how people use it in the industry.
The first method:
import java.util.*;

public class TestCollection7 {
    public static void main(String args[]) {

        LinkedList<String> al = new LinkedList<String>();
        al.add("Ravi");
        al.add("Vijay");
        al.add("Ravi");
        al.add("Ajay");

        Iterator<String> itr = al.iterator();
        while(itr.hasNext()) {
            System.out.println(itr.next());
        }
    }
}

Second method:
package javaapplication3;

public class LIstTEst {
    Node head;

    static class Node {
        int data;
        Node next;
        Node(int d) {
            data = d;
            next = null;
        }
    }

    public void PrintList() {
        Node n = head;
        while(n != null){
            System.out.print(n.data+" ");
            n = n.next;
        }
    }

    public static void main(String args[]) {
        LIstTEst llist = new LIstTEst();
        llist.head = new Node(1);
        Node second = new Node(2);
        Node third = new Node(7);

        llist.head.next = second;
        second.next = third; = third;

        llist.PrintList();
    }
}

A: Node is a class nested inside LIstTEst.
You have its definition:
static class Node {
    int data;
    Node next;
    Node(int d) {
        data = d;
        next = null;
    }
}

It represents a link in a linked list. It contains a numeric value (data) and a reference to the next Node in the list.
Node head;

is a member of the LIstTEst which refers to the first link in the list.
Note that the posted implementation of LIstTEst is lacking. It should use an add method instead of the main creating Nodes and directly manipulating the links.

A: That
public class LIstTEst

is nothing else but the first step towards self-implementing a list. Whereas your first piece of source code makes use of the linked list implementation that comes as part of the "standard" Java collection classes.
A "linked list" (in generic terms) is nothing else but, well, a list of connected thingies (of the same type). Those "thingies" are expressed using that internal Node class.
Thus, the real answer is: avoid mixing up concepts and implementation. In order to understand how Java is dealing with "linked lists"; you should first step back and understand the concept "linked list" itself. For example, by reading its Wikipedia entry:

In computer science, a linked list is a linear collection of data elements, called nodes, each pointing to the next node by means of a pointer. It is a data structure consisting of a group of nodes which together represent a sequence. Under the simplest form, each node is composed of data and a reference (in other words, a link) to the next node in the sequence. This structure allows for efficient insertion or removal of elements from any position in the sequence during iteration. More complex variants add additional links, allowing efficient insertion or removal from arbitrary element references.

In other words: programming languages are about implementing common algorithms and data structures for that given language. Therefore it is very much advised to start your research by learning about those common concepts.
Beyond that: the reason why you might find the second example confusing:

*

*probably you have not learned about inner classes yet

*the example is incomplete; important methods to add or remove list elements are still missing!

A: First example
LinkedList is an implementation of a linked-list data structure in Java.
Second example
It is manually written implementation of the same data structure. Node is you class, which describes one cell in this linked list.
Both implementations are not the same. Java's implementation provides a bunch of convenient methods to work with list, while yours do not. You can start with an implementation of add method.
// Appends the specified element to the end of this list.
public void add(int data) {

    // Create Node only in case of first element
    if (head == null) {
        head = new Node(data);
    }

    Node temp = new Node(data);
    Node current = head;

    // Check if there is first element
    if (current != null) {

        // Starting at the head node, iterate to the end of the list and then add element after last node
        while (current.getNext() != null) {
            current = current.getNext();
        }

        // The last node's "next" reference set to our new node
        current.setNext(temp);
    }
}

What is a linked list?
Long story short: a linked list is a chain of cells. Each cell knows about the next one. The last cell knows that there is no next cell. A linked-list class (which manipulates those cells (nodes)) contains reference for the first node.

Look at this interactive demo: https://visualgo.net/list

A: public class LIstTEst {
    Node head; // ==> Declaring a Class level variable.

    static class Node { // Create a static class
        int data; // Integer data type variable.
        Node next; // Class refrernce.

        Node(int d) { // Create a constructor.
            data = d; // Holding the current value.
            next = null;
        }
    }

    public void PrintList() {
        Node n = head;
        while (n != null) {
            System.out.print(n.data + " ");
            n = n.next;
        }
    }

    public static void main(String args[]) {
        LIstTEst llist = new LIstTEst(); // Creating a object of the mentioned
                                         // class.

        llist.head = new Node(1);        // Creating the Node class object by Class
                                         // level refrence.

        Node second = new Node(2);       // As this is static class, inside one class,
                                         // so we created directly to object of Node
                                         // class by passing the parameter to the
                                         // constructor.
        Node third = new Node(7);

        llist.head.next = second; // Just transfering the current reference to
                                  // next level reference before that
                                  // constructor is making null for each
                                  // executions.
        llist.head.next = third;

        llist.PrintList(); // Finally for printing purpose it is calling.
    }
}


text:
Q: Flutter how can i print just a value from an array Flutter i need to print a simple data but dont know what is an issue its showing null but it have a value.
my code
  var url =
        'http://api.igiinsurance.com.pk:8888/drive_api/location.php?imei=358480081983837';
    print(url);
    http.Response res = await http.get(
      url,
      headers: <String, String>{
        'token': 'c66026133e80d4960f0a5b7d418a4d08'
      },
    );
    var data = json.decode(res.body);
      print(data);

    if (data['status'].toString() == "success") {
      print(data['location']);
    }

if i run api in postman it looks like this
 {
    "origin": {
        "id": "b733bc40-aafe-421d-8fed-4067bcdb5afc",
        "name": "358480081983837"
    },
    "date": "2020-12-22T10:10:40.000Z",
    "received": "2020-12-22T10:11:39.000Z",
    "active": false,
    "linked": [
        {
            "id": "73f0516a-76ff-4abb-bf78-7b2493b6c94a",
            "name": "APL-Muhammad Saleem Ahmed",
            "type": "asset"
        }
    ],
    "zones": [
        {
            "id": "8ea7dd50-b00d-4880-aaf2-3f924c1ae503",
            "name": "Pakistan",
            "type": "keepin"
        },
        {
            "id": "bd90ec5b-2da8-4022-bca0-7a9e7603c2fc",
            "name": "Karachi",
            "type": "keepin"
        },
        {
            "id": "4087d332-5277-48bc-a23e-400d2c15ea31",
            "name": "Sindh",
            "type": "keepin"
        },
        {
            "id": "4ca687c6-9d25-47b5-8f2f-9117dab39cea",
            "name": "Sindh Province",
            "type": "keepin"
        },
        {
            "id": "3c73b284-498d-4661-989b-ee6401708c85",
            "name": " Karachi",
            "type": "keepin"
        },
        {
            "id": "b5c0d124-c1ba-495d-9c62-6bc766639731",
            "name": "International Boundary",
            "type": "keepin"
        },
        {
            "id": "a0f7186a-42e5-4eec-b529-a933a5cdb0e1",
            "name": "Pakistan",
            "type": "keepin"
        },
        {
            "id": "a9a4ec02-f0a0-40c7-8a00-c1cea582a9ca",
            "name": "Sindh",
            "type": "keepin"
        },
        {
            "id": "e57df14d-191e-4c31-bd3c-78fa1ac2e2d7",
            "name": "Karachi",
            "type": "keepin"
        }
    ],
    "routes": [],
    "state": {},
    "spd": null,
    "location": {
        "lon": 67.036763,
        "lat": 24.827595,
        "speed": 0,
        "altitude": 25,
        "heading": 1,
        "accuracy": 13,
        "age": 0,
        "gc": {
            "rd": "Khayaban-e-Rumi",
            "sb": "Clifton Block 9",
            "tw": "Clifton",
            "ct": "Pakistan"
        },
        "address": "Khayaban-e-Rumi, Clifton Block 9, Clifton, Pakistan"
    },
    "telemetry": {
        "priority": 0,
        "eventId": 0,
        "ignition": 0,
        "moving": 0,
        "motion_end": 1,
        "gsm_signal": 3,
        "digital_01": 0,
        "output_01": 0,
        "power_voltage": 12.73,
        "gps_speed": 0,
        "gsm_cell": 10283,
        "gsm_lac": 727,
        "battery_voltage": 3.996,
        "battery_current": 0,
        "analog_01": 173,
        "fuel_rate": 18.95,
        "x": -0.02,
        "eco_score": 10,
        "gsm_code": 41004,
        "odo_diff": 0,
        "odometer": 20403.945,
        "fuel_counter": 3839.767,
        "movement": 0,
        "hours_00_counter": 1177.310307,
        "idle_counter": 0
    },
    "counters": {
        "odometer": 20403.945,
        "hours": 1177.310307
    },
    "io": {
        "output_01": {
            "type": "output",
            "input": "output_01",
            "name": "Immobilizer",
            "value": 0,
            "text": "Off",
            "unit": ""
        }
    },
    "meta": {
        "dsid": "deviceserver2@b314b24a22c6",
        "wshost": "dws.eu1.kt1.io",
        "wsport": 80,
        "ecsid": "69ebf0b0b87645318ec79d2cc883a5f3",
        "tpsq": 0
    },
    "object": {
        "id": "73f0516a-76ff-4abb-bf78-7b2493b6c94a",
        "name": "APL-Muhammad Saleem Ahmed",
        "type": "asset"
    },
    "lastMovement": "2020-12-22T04:20:08.000Z"
}

i just want to print lon and lat values. but dont know why in flutter its showing null.

you can see my console its showing value in lon but its cut dont know why. I am stuck on this point and i know its very basic in flutter. But can any one please help how can i print just a value ?
i already try multiple ways like
print(data['location']['lon']);

but its showing null

A: Doing my own investigation, I found that the actual structure of your data is
{
  "status": "success",
  "data": {
    "origin": {
      // ...
    },
    "date": "2020-12-22T12:49:55.000Z",
    "location": {
      "lon": 67.036763,
      "lat": 24.827595,
      // ...
    },
  }
}

So to access the location longitude you have to do
print(data["data"]["location"]["lon"]);

A: Try the following:
final locationMap = Map<String,dynamic>.from(data['location']);
print(locationMap['lon']);


text:
Q: Testing React Component with Jest/Enzyme I am trying to use Enzyme's shallow wrapper to get the instance of my component and calling my class function over it. It shows me this error:
TypeError: tree.instance(...).onCampaignSelected is not a function
class ToolbarPage extends Component {
  constructor(){
    super();
    this.onCampaignSelected = this.onCampaignSelected.bind(this);
    this.state = {
      item: null
    }
  }

  onCampaignSelected (item) {
     this.setState({item})
  }

  render () {
    return (
      <MyComponent onItemSelected={this.onCampaignSelected} />
    )
  }
}
function mapStateToProps(state){
  buttons: state.toolbar.buttons
}
export default connect(mapStateToProps)(ToolbarPage);

My test case looks like this
import { shallow, mount } from 'enzyme';
import ToolbarPage from './ToolbarPage';
import configureStore from 'configureStore';

const store = configureStore();

const props = {
 store,
 isLoggedIn: false,
 messageCounter: 0
}

describe('<ToolbarPage />', () => {
  it('allows to select campaign', () => {
    const tree = shallow(<ToolbarPage {...props}/>);
    tree.instance().onCampaignSelected();
  })
})

I also figured out that it is a wrapped component, so I won't get this function on the wrapped component. How do I access this function?

A: shallow does not render the full set of components with all of their properties & methods. It is intended for basic "did this thing render what I expected?" testing.
mount will give you everything and should allow you to test whatever you need. It is very useful for testing event handling & manipulating the state of components to test the interactions between components.


text:
Q: GET https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js net::ERR_ABORTED 404 (Not Found) My html uses "jquery.min.js"  by https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js.
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title>xxxx</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>

Today it suddenly doesn't work, chrome console show:
GET https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js net::ERR_ABORTED 404 (Not Found)

What should i do for the url? Can i change another one? Or download jquery.js(3.4.1) and put it on my service? This web only services for about 1000 people.

A: We download this file from other source, deploy it to our server.
And change the  <script src="xxxx" address to our domain.


text:
Q: Issue in Hive-0.14.0 Integration in HBase-0.98.8-hadoop2 I have hive 0.14.1 hbase 0.98.8 and hadoop 2.5.0 I am trying to integrate hive with hbase and put zookeeper-3.4.6.jar,hbase-common-0.98.8-hadoop2.jar file from HBase/lib to Hive/lib. Steps Followed are as follows:
1.hive --auxpath $HIVE_HOME/lib/hive-hbase-handler-0.14.1.jar,$HIVE_HOME/lib/hbase-common-0.98.8-hadoop2.jar,$HIVE_HOME/lib/zookeeper-3.4.6.jar,$HIVE_HOME/lib/guava-11.0.2.jar -hiveconf hbase.master=masternode:60000

2.CREATE TABLE hbase_table_1(key int, value string)
STORED BY 'org.apache.hadoop.hive.hbase.HBaseStorageHandler'
WITH SERDEPROPERTIES ("hbase.columns.mapping" = ":key,cf1:val")
TBLPROPERTIES ("hbase.table.name" = "xyz");

This Command does not works for me.It give me error.
FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. MetaException(message:org.apache.hadoop.hbase.DoNotRetryIOException: java.lang.NoSuchMethodError: org.apache.hadoop.hbase.protobuf.generated.ClientProtos$Scan$Builder.setCaching(I)Lorg/apache/hadoop/hbase/protobuf/generated/ClientProtos$Scan$Builder;
    at org.apache.hadoop.hbase.client.RpcRetryingCaller.translateException(RpcRetryingCaller.java:216)
    at org.apache.hadoop.hbase.client.RpcRetryingCaller.callWithRetries(RpcRetryingCaller.java:125)
    at org.apache.hadoop.hbase.client.RpcRetryingCaller.callWithRetries(RpcRetryingCaller.java:93)
    at org.apache.hadoop.hbase.client.ClientScanner.nextScanner(ClientScanner.java:283)
    at org.apache.hadoop.hbase.client.ClientScanner.initializeScannerInConstruction(ClientScanner.java:188)
    at org.apache.hadoop.hbase.client.ClientScanner.<init>(ClientScanner.java:183)
    at org.apache.hadoop.hbase.client.ClientScanner.<init>(ClientScanner.java:110)
    at org.apache.hadoop.hbase.client.HTable.getScanner(HTable.java:745)
    at org.apache.hadoop.hbase.catalog.MetaReader.fullScan(MetaReader.java:542)
    at org.apache.hadoop.hbase.catalog.MetaReader.tableExists(MetaReader.java:310)
    at org.apache.hadoop.hbase.client.HBaseAdmin.tableExists(HBaseAdmin.java:307)
    at org.apache.hadoop.hbase.client.HBaseAdmin.tableExists(HBaseAdmin.java:321)
    at org.apache.hadoop.hive.hbase.HBaseStorageHandler.preCreateTable(HBaseStorageHandler.java:182)
    at org.apache.hadoop.hive.metastore.HiveMetaStoreClient.createTable(HiveMetaStoreClient.java:602)
    at org.apache.hadoop.hive.metastore.HiveMetaStoreClient.createTable(HiveMetaStoreClient.java:595)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.invoke(RetryingMetaStoreClient.java:90)
    at com.sun.proxy.$Proxy8.createTable(Unknown Source)
    at org.apache.hadoop.hive.ql.metadata.Hive.createTable(Hive.java:670)
    at org.apache.hadoop.hive.ql.exec.DDLTask.createTable(DDLTask.java:3959)
    at org.apache.hadoop.hive.ql.exec.DDLTask.execute(DDLTask.java:295)
    at org.apache.hadoop.hive.ql.exec.Task.executeTask(Task.java:160)
    at org.apache.hadoop.hive.ql.exec.TaskRunner.runSequential(TaskRunner.java:85)
    at org.apache.hadoop.hive.ql.Driver.launchTask(Driver.java:1604)
    at org.apache.hadoop.hive.ql.Driver.execute(Driver.java:1364)
    at org.apache.hadoop.hive.ql.Driver.runInternal(Driver.java:1177)
    at org.apache.hadoop.hive.ql.Driver.run(Driver.java:1004)
    at org.apache.hadoop.hive.ql.Driver.run(Driver.java:994)
    at org.apache.hadoop.hive.cli.CliDriver.processLocalCmd(CliDriver.java:247)
    at org.apache.hadoop.hive.cli.CliDriver.processCmd(CliDriver.java:199)
    at org.apache.hadoop.hive.cli.CliDriver.processLine(CliDriver.java:410)
    at org.apache.hadoop.hive.cli.CliDriver.executeDriver(CliDriver.java:783)
    at org.apache.hadoop.hive.cli.CliDriver.run(CliDriver.java:677)
    at org.apache.hadoop.hive.cli.CliDriver.main(CliDriver.java:616)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:212)
Caused by: java.lang.NoSuchMethodError: org.apache.hadoop.hbase.protobuf.generated.ClientProtos$Scan$Builder.setCaching(I)Lorg/apache/hadoop/hbase/protobuf/generated/ClientProtos$Scan$Builder;
    at org.apache.hadoop.hbase.protobuf.ProtobufUtil.toScan(ProtobufUtil.java:879)
    at org.apache.hadoop.hbase.protobuf.RequestConverter.buildScanRequest(RequestConverter.java:488)
    at org.apache.hadoop.hbase.client.ScannerCallable.openScanner(ScannerCallable.java:303)
    at org.apache.hadoop.hbase.client.ScannerCallable.call(ScannerCallable.java:164)
    at org.apache.hadoop.hbase.client.ScannerCallable.call(ScannerCallable.java:59)
    at org.apache.hadoop.hbase.client.RpcRetryingCaller.callWithRetries(RpcRetryingCaller.java:117)
    ... 40 more
)

A: You may need to add the hbase-protocol JAR to the classpath.  The symbol that could not be resolved per your stack trace appears to come from there, at least based on cursory inspection only.


text:
Q: How to pass stripe token to the server, create a user account, charge the credit card and have it all show up on the dashboard So I'm trying to get stripe setup on my server but I'm having a problem.
I'm using checkout v2 on my page and the form works perfectly, however the token never passes through to my php file. the card is charged but the information does not show up on the dashboard, it is in the log though.
here's what I have:
<form action="assets/php/slingshot.php" method="POST">
 <button id="customButton">Purchase</button>
 <script>
    $('#customButton').click(function(){
    var token = function(res){
    var $input = $('<input type=hidden name=stripeToken />').val(res.id);
    $('form').append($input).submit();
    };

  StripeCheckout.open({
    key:         'pk_live_*************************',
    address:     true,
    amount:      2500,
    currency:    'usd',
    name:        'test',
    description: 'A bag of test',
    panelLabel:  'Checkout',
    token:       token
  });

  return false;
  });
  </script>
</form>

and then for slingshot.php:
<?php
require_once(dirname(__FILE__) . '/config.php');

$token = $POST['stripeToken']; //get the creditcard details from the form
try {
$charge = Stripe_Charge::create(array(
        'card' => $token,
        'amount'   => 2500,  //amount in cents
        'currency' => 'usd',
        'description' => 'Get Bacon Direct, LLC'
        ));

        } catch(Stripe_CardError $e) {
// The card has been declined
}
echo '<h1>Successfully charged $25.00 </h1>';
}
?>

and my config.php file:
<?php
require_once('stripe-php/lib/Stripe.php');
// Set your secret key: remember to change this to your live secret key in production
// See your keys here https://manage.stripe.com/account

$stripe = array(
"secret_key"        => "sk_live_************************************",
"publishable_key"   => "pk_live_************************************"
);

Stripe::setApiKey($stripe['secret_key'] );

?>

could you please help me out?

A: I'm not entirely sure how the charge is being made, but I'm fairly confident that the reason you aren't getting the token, is because of this line
$token = $POST['stripeToken']; //get the creditcard details from the form

When accessing POST data in PHP, the global variable is prefixed with an underscore, so you'd need to do
$token = $_POST['stripeToken']; //get the creditcard details from the form

That should fix it.
-- UPDATE ---
Just for readability, in your javascript, I would specify the input field as follows
var $input = $('<input type="hidden" name="stripeToken" />').val(res.id);

I've also checked out the stripe documentation again, and it looks like the card attribute is optional, as is customer, but it does state that one must be provided. Chances are, it's not throwing an error because of an issue with their code that doesn't catch the eventuality of neither being provided.


text:
Q: Python Multithreaded Processing Clogging Up Memory I am new to multithreaded processing in Python, but have been using the following code to run a multithreaded download, but after running this for several hours it eats up my memory over time and then stalls due to lack of free memory. I'm trying to figure out an alternative method that will allow me to run this process for several hours without having to worry about memory consumption:
def worker()
    while True:
        item = jq.get()
        download_stuff(item)
        jq.task_done()

input_list = [1,2,3,4,5,6,7,8,9...]
num_threads = 8
q = Queue
jq = JoinableQueue()
for i in range(num_threads):
    t = Thread(target=worker)
    t.daemon = True
    t.start()

for item in input_list:
    jq.put(item)

jq.join()


text:
Q: python regex to calculate vowel/consonant ratio in English I've embarked on a reasonably dumb linguistics project to learn regular expressions in Python. I'm pretty sure I could avoid the multiple passes over the same string, and find a more "compact" and "pythonic" way to do what I'm trying to do, which is: calculate using regex whether 'Y|y' in a word is a vowel or a consonant. At the bottom of the code segment, I've put in a comment block 20 words containing 12 vowel y's and 9 consonant y's. Seems like the code could be simplified and the re.compile lines merged together.
import re
vowelRegex = re.compile(r'[aeiouAEIOU]')
consoRegex = re.compile(r'[b-df-hj-np-tv-xzB-DF-HJ-NP-TV-XZ]')
yconsRegex = re.compile(r'[aeiou]y[aeiou]')
ycon2Regex = re.compile(r'\bY')
yVowlRegex = re.compile(r'[b-df-hj-np-tv-xzB-DF-HJ-NP-TV-XZ]y[b-df-hj-np-tv-xz]')
yVow2Regex = re.compile(r'y\b')

#thestring = 'Sky Family Yurt Germany Crypt Day New York Pennsylvania Myth Hungry Yolk Year Bayou Yak Silly Beyond Dynamite Mystery Yacht Yoda'
#thestring = 'Crypt Pennsylva Myth Dynamite Mystery'
#thestring='RoboCop eats baby food. Pennsylvania Baby Food in the bayou. And, New York is where I\'d Rather be!'
thestring='violent irrational intolerant allied to racism and ' \
    'tribalism bigotry invested in ignorance and hostile to free '\
    'inquiry contemptuous of women and coercive towards children ' \
    'organized religion ought to have a great deal on its conscience ' \
    'Yak yacht beyond mystery'
fun=vowelRegex.findall(thestring)
nofun=consoRegex.findall(thestring)
funny = yVowlRegex.findall(thestring)
foony = []
for f in funny:
    foony.append (f[1])
fun += foony
fun += yVow2Regex.findall(thestring)
notfunny = yconsRegex.findall(thestring)

foony = []
for f in notfunny:
    foony.append (f[1])
nofun += foony
nofun += ycon2Regex.findall(thestring)

print(thestring)
print('Vowels:',''.join(fun), len(''.join(fun)))
print('Consos:',''.join(nofun), len(''.join(nofun)))

'''
Sky         Vowel; endswith 1
Family      Vowel; endswith 2
Yurt        Consonant; begswith 1
Germany     Vowel; endswith 3
Crypt       Vowel; sandwiched 1
Day         Vowel; endswith 4
New York    Consonant; begswith 2
Pennsylva   Vowel; sandwiched 2
Myth        Vowel; sandwiched 3
Hungry      Vowel; endswith 5
Yolk        Consonant; begswith 3
Year        Consonant; begswith 4
Bayou       Consonanwich 1
Yak         Consonant; begswith 5
Silly       Vowel; endswith 6
Beyond      Consonanwich 2
Dynamite    Vowel; sandwiched 4
Mystery     Vowel; sandwiched, Vowel; endswith!
Yacht       Consonant; begswith 6
Yoda        Consonant; begswith 7
'''

A: You can use an or operator in regex, that could reduce it a bit. For example:
yVowlRegex = re.compile(r'[b-df-hj-np-tv-xzB-DF-HJ-NP-TV-XZ]y[b-df-hj-np-tv-xz]|y\b')

now includes both yVowl and yVow2

A: @Joshua-Lewis answer led me to the following way to streamline the code above:
import re
vowelRegex = re.compile(r'[aeiouAEIOU]|[b-df-hj-np-tv-xzB-DF-HJ-NP-TV-XZ]y[b-df-hj-np-tv-xz]|y\b')
consoRegex = re.compile(r'[b-df-hj-np-tv-xzB-DF-HJ-NP-TV-XZ]|[aeiou]y[aeiou]|\bY')
vowelRescan = re.compile(r'[aeiouyAEIOUY]')
consoRescan = re.compile(r'[b-df-hj-np-tv-xyzB-DF-HJ-NP-TV-XYZ]')
thestring='any and every religion is violent irrational intolerant '\
    'allied to racism and tribalism bigotry invested in ignorance and '\
    'hostile to free inquiry contemptuous of women and coercive towards '\
    'children organized religion ought to have a great deal on its '\
    'conscience why it continues toward the 22nd century ACE is a mystery '\
    'known only to New Yorkers and lovers of the bayou'
fun=vowelRegex.findall(thestring)
funn=''.join(fun)
fun = ''.join(vowelRescan.findall(funn))
nofun=consoRegex.findall(thestring)
nofunn=''.join(nofun)
nofun=''.join(consoRescan.findall(nofunn))

print(thestring)
print('Vowels:',fun, len(fun))
print('Consos:',nofun, len(nofun))

'''
Sky         Vowel; endswith 1
Family      Vowel; endswith 2
Yurt        Consonant; begswith 1
Germany     Vowel; endswith 3
Crypt       Vowel; sandwiched 1
Day         Vowel; endswith 4
New York    Consonant; begswith 2
Pennsylva   Vowel; sandwiched 2
Myth        Vowel; sandwiched 3
Hungry      Vowel; endswith 5
Yolk        Consonant; begswith 3
Year        Consonant; begswith 4
Bayou       Consonanwich 1
Yak         Consonant; begswith 5
Silly       Vowel; endswith 6
Beyond      Consonanwich 2
Dynamite    Vowel; sandwiched 4
Mystery     Vowel; sandwiched, Vowel; endswith!
Yacht       Consonant; begswith 6
Yoda        Consonant; begswith 7
'''


text:
Q: The operation CreateSession failed due to an internal error: Could not initialize class mono.android..D3DImageFactory Click this image to show error
I am new to Xamarin . I want tO learn xamarin. I have following installation on my machine.
1. Visual Studio Community 2017
2. Xamarin latest
I have updated the Android SDK 25 but still getting the error.

A: Make sure that Visual Studio is pointing to the 64-bit version of the JDK rather than 32-bit.
Select Tools > Options from the top menu and scroll all the way to the bottom on the left hand side list and open Xamarin > Android Settings. In there you should change the first item, "Java Development Kit Location" as highlighted in the picture below.

In your case it's probably pointing to a folder in Program Files (x86). Try to find the Java\jdkx.x.x_xxx folder in Program Files\ instead like you can see in the picture.
After making the change, close the axml designer and reload the file. It should work after that.


text:
Q: How to set month and day from one table to new stored procedure declare
    @pm_WeekEndDate DATETIME,
    @lp_Day VARCHAR(10),
    @intDate DATETIME

set @pm_WeekEndDate = MONTH(@pm_WeekEndDate)
set @lp_Day = day(@pm_WeekEndDate)
set @intDate = (@pm_WeekEndDate & @lp_Day)

This code should take month january then = 1 because other table has all in numbers like month 1 to 12 and day 1 to 7.
But I am getting this error:

Msg 402, Level 16, State 1, Procedure PRO, Line60
  The data types datetime and varchar are incompatible in the '&' operator.

A: This is purely a guess by on extremely vague details and having this kind of poor table design in the past. Is something like this what you are looking for?
declare @pm_WeekEndDate DATETIME = getdate()

select @pm_WeekEndDate

declare @DateVal char(4)

select @DateVal = right('00' + convert(varchar(2), MONTH(@pm_WeekEndDate)), 2) + right('00' + convert(varchar(2), DAY(@pm_WeekEndDate)), 2)

select @DateVal

Please notice that you can't have the result be a date because it doesn't make sense. I am guessing that your table has dates stored as either strings or ints??


text:
Q: How to add BBC podcasts to Rhythmbox? I copied link address from RSS feed here http://www.bbc.co.uk/podcasts/series/comedy. Then clicked ADD button in Rhythmbox podcast and added http://downloads.bbc.co.uk/podcasts/radio4/comedy/rss.xml
It gave the error that "The feed does not contain any downloadable items".
How to fix this problem?
Thanks.

A: It looks like you're adding the wrong URL.  Here is what I did.
Opened Rhythmbox, clicked on Podcasts, and then right click choose New Podcast Feed, as shown in the image below.

Once you get the screen shown below, add the URL (http://www.bbc.co.uk/podcasts/series/comedy), and press Search.  That will get you all the feeds, and then just choose the one you want.


text:
Q: Are "kind" and "sort" synonym in "all kinds and sorts of people"? I am reading Norman Lewis's book Word power made easy. At one place the author says,

"Words that describe all kinds and sorts of people..."

Here if "kind" and "sort" mean the same thing then the above sentence literallg means,

"Words that describe all kinds and kinds of people.."

This is quite confhsing. Please explain.

A: Kind and sort (and variety, and type, etc.) are names for groupings (typically of noun phrases),
according to some shared criterion.

*

*It's the most common/expensive kind/sort/type/variety/model of positronic brain defibrillator.
Etymologically, kind is a noun from the Proto-Indo-European root *gen- 'give birth to, be born, offspring', along with words like king, kin, gonad, and gentle, while sort is a verb from sors, sortis- 'lot, condition.' It refers to the common activity of sorting objects (and by extension, events) and features in many idioms and phrasal verbs.
From a kind/sort of cookie to kind/sort of a cookie is not much of a jump in meaning, but the grammar is different for kind and type, and for them alone.  Sort and kind have each developed quantifier-like idiomatic extensions with of (sort of and kind of), both meaning 'close to; approximately'. And these constructions can modify anything at all, even verbs. These are both so common that they have their own eye-dialect spelling contractions  -- sorta and kinda.

*

*She got sort of mad ~ She sort of got mad ~ She got sorta mad ~ She sorta got mad.

*She got kind of mad ~ She kind of got mad ~ She got kinda mad ~ She kinda got mad.

Naturally, when you're dealing with classifiers and other operators, it matters where you put them. In the sentences above, kinda and sorta can go before mad, meaning 'somewhat mad', or they can go before got mad, meaning 'did something that was close to getting mad'. These may in fact refer to precisely the same behavior, depending on the speaker's judgement about others' emotions.
This extension, by the way, doesn't happen with type, model, or variety:

*

*It's a type of cookie, but *It's type of a cookie ~ *She got type of mad ~ *She type of got mad.

So in this regard, kind and sort are synonymous.

A: For the phrase

all kinds and sorts of people  =  all kinds and all sorts of people

all kinds means "a great number of"

and

all sorts means a "wide variety of"

as in

so the rephrasing of your original sentence would be

Words that describe many different kinds of people.

This is different than @JohnLawler's answer since

She got kind of mad = She was mildly angry

whereas

She was all kinds of mad = She was furious


text:
Q: Communicating from/to usercontrol in tabcontrol in form I thought C# was hard. Try posting a question in stackoverflow.
I have a listbox and a button in a usercontrol, itself in a tabpage of a tabcontrol, itself on a form. I need to populate the listbox from the form when the button is clicked.
form > tabcontrol > tabpage > usercontrol > listbox & button
So, how do you notify the form that a deeply buried button has been clicked and then fill the listbox from the form (or call the usercontrol from the form to populate the listbox)?
Thank you guys.

A: Assuming that your question is about WinForms.
For notification:
   Expose an event on the userControl and link it to the event of the button, form knows it's children.
public class MyUserControl {
    private Button myButton;
    public event EventHandler MyControlButtonClicked;

    public MyUserControl() {
         ...
         myButton.Click += OnMyButtonClicked;
    }

    private void OnMyButtonClicked(object sender, EventArgs arguments) {
        if (MyControlButtonClicked != null) {
           MyControlButtonClicked(this, arguments);
        }
    }
}

In your form:
public class MyForm {
   private MyUserControl userControl;

   public MyForm() {
     ...
     userControl.MyControlButtonClicked += OnUserControlButtonClicked;
   }

   private void OnUserControlButtonClicked(object sender, EventArgs arguments) {
      // handle the button click here
   }
}

For population:
   The same pattern, use your user control as a mediator. Add a public method on userControl that will do the listBox population and call it from your form.


text:
Q: Drag formulas in excel from C# I have a feeling that this question is very simple, but I just can't find the answer.
I want to apply a column of formulas in column "C" based on information in col "A" and "B". I want the formula to work as it would in excel when you write a formula, and then drag, creating row-relative formulas all the way down.
The method below works, but it's very slow, since it writes each formula separately. I'm sure there's a more efficient method out there somewhere.
Thanks
        using Excel = Microsoft.Office.Interop.Excel;

        ...

        object oOpt = System.Reflection.Missing.Value; //for optional arguments
        Excel.Application oXL = null;
        Excel.Workbook oWB = null;
        Excel.Worksheet oSheet = null;
        Excel.Range oRng = null;

        try
        {
            //Start Excel and get Application object.
            oXL = new Excel.Application();
            oXL.Visible = true;

            //Get a new workbook.
            oWB = (Excel.Workbook)(oXL.Workbooks.Add(Missing.Value));
            oSheet = (Excel.Worksheet)oWB.ActiveSheet;

            ...
            //Set numberOfRows
            //Load information to column A and B
            ...

            //Write the column of formulas
            for (int r = 2; r < numberOfRows + 2; r++)
            {
                oRng = oSheet.get_Range("C" + r, "C" + r);
                oRng.Formula = "= IF(AND(A" + r + "<> 0,B" + r + "<>2),\"YES\",\"NO\")";
            }

        }
        catch (Exception theException)
        {
            String errorMessage;
            errorMessage = "Error: ";
            errorMessage = String.Concat(errorMessage, theException.Message);
            errorMessage = String.Concat(errorMessage, " Line: ");
            errorMessage = String.Concat(errorMessage, theException.Source);

            MessageBox.Show(errorMessage, "Error");
        }
        finally
        {

            // Cleanup
            GC.Collect();
            GC.WaitForPendingFinalizers();

            Marshal.FinalReleaseComObject(oRng);
            Marshal.FinalReleaseComObject(oSheet);

            oWB.Close(Type.Missing, Type.Missing, Type.Missing);
            Marshal.FinalReleaseComObject(oWB);

            oXL.Quit();
            Marshal.FinalReleaseComObject(oXL);
       }

A: Use R1C1 formula, and replace :
    for (int r = 2; r < numberOfRows + 2; r++)
    {
        oRng = oSheet.get_Range("C" + r, "C" + r);
        oRng.Formula = "= IF(AND(A" + r + "<> 0,B" + r + "<>2),\"YES\",\"NO\")";
    }

with
    oRng = oSheet.get_Range("C2").get_Resize(100, 1);
    oRng.FormulaR1C1 = "=IF(AND(RC[-2]<> 0,RC[-1]<>2),\"YES\",\"NO\")";

A: I am posting this code for Drag formulas in excel from C# using Microsoft.Office.Interop.Excel Library
class Program
{
    static void Main(string[] args)
    {
        Program p = new Program();
        p.Excel();
    }

    public void Excel()
    {
        Application xlApp = new Application();
        Workbook xlWorkBook;
        Worksheet xlWorkSheet;
        object misValue = Missing.Value;

        xlWorkBook = xlApp.Workbooks.Add(misValue);
        xlWorkSheet = (Worksheet)xlWorkBook.Worksheets.get_Item(1);

        for (int r = 1; r < 5; r++) //r stands for ExcelRow and c for ExcelColumn
        {
            // Its a my sample example: Excel row and column start positions for writing Row=1 and Col=1
            for (int c = 1; c < 3; c++)
            {
                if (c == 2)
                {
                    if (r == 1)
                    {
                        xlWorkSheet.Cells[r, c].Formula = "=SUM(A1+200)";
                    }
                    continue;
                }
                xlWorkSheet.Cells[r, c] = r;
            }
        }
        Range rng = xlWorkSheet.get_Range("B1");

        //  This is the main code we can Drag our excel sheet formulas in range
        rng.AutoFill(xlWorkSheet.get_Range("B1", "B4"), XlAutoFillType.xlLinearTrend);

        xlWorkBook.Worksheets[1].Name = "MySheetData";//Renaming the Sheet1 to MySheet

        xlWorkBook.SaveAs(@"E:\test.xlsx");

        xlWorkBook.Close();

        Marshal.ReleaseComObject(xlWorkSheet);
        Marshal.ReleaseComObject(xlWorkBook);
        Marshal.ReleaseComObject(xlApp);

    }
}


text:
Q: How to get a Java Object from JNI call (C++)? I've been researching a bit on how to make JNI calls from C++ to Java, and so far I haven't had any issue, I managed to call almost any type of function.
I say ALMOST, because right now I'm facing this situation:
In Java, I have this function:
public static Object getJObject(int id){
    Object st = null;
    switch (id){
        case 0: st = "hello"; break;
        case 1: st = "bye"; break;
        case 2: st = 1; break;
        case 3: st = 2; break;
        case 4: st = 3; break;
    }
    return st;
}

As you can see, this function returns a different type of value given the ID received as a parameter.
The problem comes when trying to get that object from C++. Here's the function that makes the JNI call:
bool check(){
    JniMethodInfo methodInfo;
    jobject jobj;

    bool b = getStaticMethodInfo(methodInfo, "org.example.act.activity", "getJObject", "()Ljava/lang/Object;");

    if (!b){
        CCLog("getJObject method not found");
        return false;
    }else{
        jobj = methodInfo.env->CallStaticObjectMethod(methodInfo.classID, methodInfo.methodID, 0);
        return true;
    }
}

NOTE: (Although I think it is obvious) note that the
  getStaticMethodInfo method sets the whole process of identifying a method in a Java class. It works with every other function that I
  call, except for this one.

That's the only thing that I want to do...I'm pretty sure it's something about the signature specifying the type of method it is, but maybe I'm wrong.
So far I've found answered questions about getting a class object or strings, but I haven't found anything on a proper Java Object...

A: The signature that you are providing to getStatiticMethodInfo does not match the method.  For a method that takes an int argument and returns an Object, the signature should be: (I)Ljava/lang/Object;
IIRC, the method signature syntax is described in a couple of places including:

*

*the JNI specification, and

*the JVM specification

A: Double check that you have the package and class name correct, and that the signature agrees with the output of javap -s.
But it's a terrible design.


text:
Q: Postfix rewrite sender: why doesn't this work I have server A with an IP address only and a dummy FQDN (on the basis all machines should have a FQDN): pants.net.invalid.  All mail is relayed through another server elsewhere, which works fine.
On server A, Postfix rewrites the sender address with smtp_generic_maps = hash:/etc/postfix/generic.  According to the Rewrite manual at http://www.postfix.org/ADDRESS_REWRITING_README.html#remote, this should rewrite all outgoing external mail's Sender address:
$ cat /etc/postfix/generic
@pants.net.invalid     nick+pants@my.other.server.net

but it does not.  postmap -q nick@pants.net.invalid returns nothing.
This works:
nick@pants.net.invalid     nick+pants@my.other.server.net

It seems as though it is doing regex matching even though I specify type hash:. Clearly I am misunderstanding the manual.
I don't want to use regex or pcre expressions because there are only a couple of users (root and two others) and I don't want the overhead.
I can specify the users exactly and it works.  But, I would like to know what I am misunderstanding for future reference.
Thanks.

A: It works. According to the manual http://www.postfix.org/generic.5.html
But your postmap command is faulty. It should read:
postmap -q nick@pants.net.invalid hash:/etc/postfix/generic


text:
Q: Submitting eCommerce analytics to Google Analytics prior to completing transaction We're using Google Analytics to track transactions, products, browser data, etc on our shopping cart. I am interested in pushing some data to GA prior to completing the transaction. Normally I push data to GA on the success/order confirmation page.
My Question: If I push custom variables to Google Analytics prior to completing an order, will GA be able to associate that session with my completed transaction - allowing me to cross reference my custom variables with the transaction IDs?
Background: We use an address validation service and sometimes the address that the validation service submits to us isn't correct. It can "over correct" and completely strip vital details from certain addresses. Happens less than 1% of the time but when that is multiplied against 1000 - 2000 orders a day it can really become a problem for our fulfillment department. Yes, we have reported this to the address validation service and they tell us they are investigating it. I plan to use jQuery to grab the form data in the billing and shipping fields and when the user fills out all necessary fields, do a push to GA.

A: Yeah, you should be able to set a session-level custom variable (a unique id or any other value that isn't PII) prior to the transaction, and then create a custom report in GA that looks at that custom variable against the transaction Id. Because it's a session-level variable, it will associate anything that happens for that session.
More info on session-level variables here - Custom Variables - Web Tracking (ga.js)


text:
Q: ELF x86 executable entry point void  *entrypoint;
/*virtual address of process*/
fscanf(debuggedfile, "%p", &entrypoint);

where debuggedfile is the stream to an elf file at the offset where int entry point is.
when i use ptrace(PTRACE_PEEKTEXT, 0, entrypoint, 0) it returns -1

A: ELF is a binary file format. fscanf is for reading from text files. Try fread instead.

A: If you are writing code that parses ELF files, I would suggest
using a standard library like libelf instead of coding your
own ELF parser by hand.
That way you would let libelf handle the corner cases that arise
occasionally, for example, ELF objects that use extended section numbering.
There are active open-source projects developing BSD licensed
and GPL'ed implementations of libelf---take your pick.


text:
Q: Extjs Clickable tooltip I have a situation where I roll over a row in a grid, I want to display a menu. I put the menu in a tooltip. But can't click on a menu unless I make the tooltip closable. If I make the tooltip closable, I can't provide the use the autohide functionality and I have to click to close the tooltip. Is there any way to mouseover rows in a grid, show a tooltip that includes clickable items and then have the tooltip goaway when you scroll off of it?

A: you may need extend your own component from tooltip.


text:
Q: Sort chained objects with parent we have Lists of categories where each category can has parent field which is reference to parent category of current category. Can you tell me what is the best algorithm in java to sort categories, for instance from top to bottom category? Thank you.
@Table
@Entity
public class Category {
     @Id
     Long id;
     @ManyToOne
     Category parent;
}

Sample:
List of:

*

*Category(id=3, parent=Category(id=11))

*Category(id=4, parent=Category(id=3))

*Category(id=11, parent=Category(id=20, parent=null))

will sorted from top to bottom like that:
Category(id=20) -> Category(id=11) -> Category(id=3) -> Category(id=4)

A: Supposing you've List. You can sort that list using Collections.sort();
But your class has to change a little bit, because you've to implement Comparable and override compareTo() method. This is an example,  I hope it helps you.
public class Category implements Comparable<Category>{
    Long id;
    Category parent;
    // Constructors getters setters
    public int compareTo(Category aux){
       // Assuming you want to sort by parent's id, and I understand a category
       // maybe doesn't have parent it may be null
       if(aux.getParent() != null && this.parent != null){
           if(aux.getParent().getId() > this.parent.getId()) return -1;
           else if(aux.getParent().getId() < this.parent.getId()) return ;
           return 0;
       }
       if(aux.getParent() == null && this.parent.getId() == null) return 0;
       if(aux.parent() == null) return 1;
       return 0;
    }
}

A: I cannot see how sorting is involved here.

*

*Search for the category that has no parent

*search for the child of it

*goto 2

This gives you the list you want.
Remark:
If every parent has only one or no child you get a list like in your example. (or more than one list) otherwise you get a tree (or more than one tree).
In case of "one or no child" you can extend your category by a field child which makes it a double linked list. In this case "search for the child of it" gets trivial since you have a direct reference to it.


text:
Q: Infinity groupoid objects I was wondering if there is a model-theoretic way of defining the infinity category of infinity-groupoid objects in a category $C$ (more generally, if $C$ is an infinity category itself, but, right now a 1-category is enough). Is there a model structure on $C^{\Delta^{op}}$ such that those objects which are fibrant and cofibrant correspond to "internal Kan-complexes" in the correct way? So e.g. I want the C-enriched nerve of an actual groupoid object of C to be fibrant and cofibrant in this model structure. If you don't know the answer in general, for now I am mostly interested in the case that $C$ is the 1-category of topological spaces (here I DO NOT want to think of $C$ as being the same thing as infinity-groupoids or simplicial sets, I actually care about the topology).
More generally, if $C$ is an infinity-category associated to a model category $D$, does this correspond to the Reedy-model structure on $D^{\Delta^{op}}$?
EDIT: I should really be asking for a SIMPLICIAL model category structure.

A: I don't have an answer which includes the category of topological spaces, but the two remarkable papers "Sheafifiable Homotopy Model Categories I and II" by Tibor Beke together give you a big class of categories with good model structures on their simplicial objects. They are available on his homepage. I think your requirement for internal groupoids is satisfied for these, but better check it out yourself.

A: There is not a model category on simplicial smooth manifolds which gives the data you're looking for, but there is a structure of category of fibrant objects such that nerves of groupoids are fibrant.  The fibrations are Kan maps (a la Henriques, but with the additional requirement that the maps on vertices be submersions), and the weak equivalences are maps which induce isomorphisms on all simplicial homotopy groups (again, as Henriques defines them).  Nerves of groupoids are fibrant in this sense, hypercovers are trivial fibrations, and morphisms qua principal bibundles are equivalent to morphisms via spans where the source leg is a hypercover.
This category of fibrant objects structure doesn't extend to a model structure on simplicial manifolds because there aren't any positive dimensional cofibrant objects (e.g. hypercovers are trivial fibrations, but given any positive dimensional manifold, you can build a hypercover on it which doesn't admit a section).
If you still want to work in a model category capturing this, the natural thing is to use Yoneda and pass to the local model structure on simplicial presheaves.  You can show that this is a fully faithful embedding on the level of homotopy categories.

A: Did you check math.AT/0603563 (``integrating $L_\infty$ algebras" by André Henriques)? I am not an expert, but I think he does a construction close to what you are looking for in the category of smooth manifolds.


text:
Q: incorrect value after casting double to a float I have some C code performing high precision arithmetic compiled by gcc(gcc (GCC) 4.4.4 20100726 (Red Hat 4.4.4-13)).The final result of the calculation is a double which has a value of 622.07999995861189.I am casting the double to a float.
frequency_value = (float)current_freq;
where current_freq is a double and frequency_value is a float.The value of frequency_value after the cast is 622.080017.I would expect the value to be 622.079956 as calculated in gdb by
(gdb) p (float)current_freq
$1 = 622.079956
Can anyone explain the large difference in values between that calculated by gcc and gdb.

A: A float has much less precision than a double; you lose about half the digits. So at best you'd be seeing the 622.0799 portion (rounded up to 622.0800). The difference you see is probably caused by the rounding mode in use.
Here are the actual numbers:

*

*As double: 622.0799999586118929073563776910305023193359375

*As float: 622.08001708984375 (internal representation: 1142654239)

*Immediately-preceding float: 622.0799560546875 (internal representation: 1142654238)

The internal representations are values generated using Java's Float.floatToIntBits. You can also use Float.intBitsToFloat to get back a floating-point number.

A: Floating-point values are usually stored in the machine in some binary format, not in some decimal format. For this reason, when you are truncating/rounding the number, it is unreasonable to expect that it will be truncated/rounded in therms of its decimal digits. I.e. it is unreasonable to expect that 622.07999995861189 will turn into something that necessarily begins with 622.07999.... Some leading decimal digits should "survive" unchanged, but since the truncating/rounding is performed on binary representation (and what you see on the screen is the result of conversion the original binary format onto ASCII string) it is quite possible that the number of decimal digits affected by the process will be much greater than one might expect. In your case the change propagated all the way to the second digit after the dot. Which is why you got 622.08... instead of 622.07....
As for the different result from GDB... It is quite possible that GDB's floating-point computation model is different from that of the compiler. For example, GDB might be truncating the result, while the compiler is rounding it. Or the compiler might be optimizing the computations, which often leads to a slightly different result.


text:
Q: Alexa simulator does not recognise number as slot value this is my utterance - "when do the may holidays start for boarders in 2018",
which "may" and "2018" are my required slot values. However alexa is not picking up "2018" as a slot value already fulfilled but only "may" as fulfilled. i realised this is only happening because 2018 is a number. is there anyway to go around this?
See screenshot in the link

A: You can use AMAZON.FOUR_DIGIT_NUMBER. I think you're typing your request in the Alexa simulator, so maybe Alexa is not able to recognize that as a year. But when a user SAYS(voice) the content in the screenshot above, Alexa interprets it as:

When do the may holidays start for boarders in two thousand eighteen

Then the built-in slot AMAZON.FOUR_DIGIT_NUMBER will convert two thousand eighteen to 2018 automatically and 2018 will be available to you to use it in your code.
Alternatively, you can use AMAZON.DATE, but this didn't recognize my years properly sometimes. So, for year recognition, I had to ignore AMAZON.DATE.


text:
Q: How do I move files whose name changes daily to AWS S3 bucket using AWS CLI? I have script that runs daily and saves a CSV file with daily time stamp below is the AWS CLI command for moving a file to S3 bucket and then delete it from source I am using.
aws s3 mv /path/NW_test_Export_03_05_2020_14_37_24.csv s3://bucekt-name/folder/ --acl public-read-write

I want to automate this daily moving of file to S3 bucket using a Cron job. How do I make the file name variable in the AWS CLI command?

A: Ok by trial and error the below command is working perfectly for me.
aws s3 mv /path-to-file/ s3://bucekt-name/folder/ --exclude "*" --include "*.csv" --recursive


text:
Q: OnClick Javascript Ajax Toolkit, Custom button update a field I have a custom object: Ticket__c
In that object I added a custom button, and I want to update an attribute of the object (Escalate__c) from false to true, I am not sure how to do this right now I have something like this:

{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}
  {!REQUIRESCRIPT("/soap/ajax/29.0/apex.js")}
  var result = sforce.apex.execute("evticket__c" : true);
  alert(result);
  window.location.reload();

Thanks

A: Your JavaScript isn't quite right, but unless you've written a method for this, it'd be easier to update the record directly:
{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}
var record = new sforce.SObject("Ticket__c");
    record.Id = "{!Ticket__c.Id}";
    record.Escalate__c = true;
var result = sforce.connection.update([record]);
// check the result here
window.location.reload();


text:
Q: Array.prototype without modifying original array I want to create a new Array method without modifying the original array.
my_array.push('foo') //modifies my_array
my_array.slice(2) //returns a new array without modifying my_array

I'd like to make a new Array.prototype method that returns an array without modifying the array it was called upon. So this would be possible:
//[define new method here] Array.prototype.add_foo = function() {...
var my_array = ['poo'];

my_array.add_foo(); //would return ['poo', 'foo'];
my_array; //would return ['poo'];

A: my_array.concat('foo');

concat doesn't alter the original array.

A: Array.prototype.add_foo = function(){
    var ret = this.slice(0); //make a clone
    ret.push("foo"); //add the foo
    return ret; //return the modified clone
}


text:
Q: scoping concern when dealing with coupling I'm learning ruby (and OOP in the process) and I find keep having to write the same patterns when logging progress so I want to wrap this up in a logging library that my other code can then just pass data to - say a string, a file name and a log level. This of course couples the logging library with other code - other code still has to be aware of how the logging library works (that it wants the string, name, & level). I tend not to like coupling like this but it seems like I can't really prevent it, but rather have to deal with it by consciously deciding to scope the library's use to an area of concern "ie: snoweagle's personal tech projects"
Is this good design or is there a better way to approach coupling?

A: I don't think what you're describing is necessarily tightly coupled

This of course couples the logging library with other code - other code still has to be aware of how the logging library works (that it wants the string, name, & level)

Not exactly.  The consuming code won't need to know how the logging library works.  It'll simply need to know what is expected of a logging library.  In other words, consuming code only needs to know about the logging library's public interface.
If your language supports it, you can guarantee looser coupling by forcing the consuming code to work against a Logger Interface (as opposed to the Logger implementation).
This is considered loosely coupled because there is only one --clearly defined-- point of contact between the Logger library and the consuming code.  This is the Logger Interface.
If in the future you decided to swap out your Logger for a new-fangled modern logger, then all you would need to do is code a compatibility layer between your new Logger lib and your existing Logger Interface.  Loose coupling to the max ;)
In C#:
Your logger interface:
public interface ILogger
{
    void Log(String filename, String message, Level level);
    void Log(String filename, Exception exception, Level level);
    void Log(String message, Level level);
    void Log(Exception exception, Level level);
    void LogInfo(String message);
    void LogWarning(String message);
    void LogError(String error);
    void LogError(Exception error);
    // etc...
}

A specific implementation of ILogger
public class AbcLogger : ILogger
{
    // Implements all of ILogger

    public void LogWarning(String message)
    {
        this.abcTarget.Write(message, AbcLevelsEnum.Warning)
    }
}

Code consuming a Logger
public void SomeMethod(int a)
{
    if (a < 1000)
    {
        String message = "Quantities of fewer than 1000 bananas are not accepted";

        ILogger logger = ServiceLocator.GetMeMyLogger();
        logger.LogWarning(message);

        throw new BananaException(message);
    }

    // do more...
}

As you can see, the consuming code isn't aware it's dealing with AbcLogger.  All it knows is that a logger is available and that it can be used by going throw the ILogger interface.
And this way, if you ever want to switch to another logger like this one...
public class XyzLogger : ILogger
{
    // Implements all of ILogger

    public void LogWarning(String message)
    {
        this.xyzTarget.Flush();
        this.xyzTarget.OtherPreRequisites();

        this.xyzTarget.Write(message, XyzLevel.NonCritical)

        this.xyzTarget.Flush();
        this.xyzTarget.OtherPostRequisites();
    }
}

...it's just a matter of changing your application's bootstrapping code to use XyzLogger instead of AbcLogger.
public Bootstrapping()
{
    ServiceLocator.SetLogger(new XyzLogger());
    ServiceLocator.SetBananaManager(new BananaManaga());
    // ... etc
}


text:
Q: Flutter Multiple Scoped Models I have a flutter app I am working on, and I want to have multiple scoped models.  The example given at https://pub.dev/packages/scoped_model#-readme-tab- shows how to listen to the models, but it doesn't show how to instantiate them.  I found this example online, where one is made to be the child of the other,
() => Navigator.push(context,
      MaterialPageRoute(builder: (context) => ScopedModel<ModelA>
          model: ScopedModel.of<AppModel>(context).a,
          child: ScopedModel<ModelB>(
             model: ScopedModel.of<AppModel>(context).b,
             child: PageAB())))))),

My question is, is this the proper way to instantiate and listen to scoped models?  Thanks!

A: You can use the package "provider" (https://pub.dev/packages/provider) with it's MultiProvider instead of package "scoped_model".


text:
Q: Which should I close first, the PreparedStatement or the Connection? When using a PreparedStatement in JDBC, should I close the PreparedStatement first or the Connection first? I just saw a code sample in which the Connection is closed first, but it seems to me more logical to close the PreparedStatement first.
Is there a standard, accepted way to do this? Does it matter? Does closing the Connection also cause the PreparedStatement to be closed, since the PreparedStatement is directly related to the Connection object?

A: The following procedures should be done (in order)

*

*The ResultSet

*The PreparedStatement

*The Connection.

Also, it's advisable to close all JDBC related objects in the finally close to guarantee closure.
//Do the following when dealing with JDBC. This is how I've implemented my JDBC transactions through DAO....

Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;

try {
  conn = ....
  ps = conn.prepareStatement(...);

  //Populate PreparedStatement
  rs = ps.executeQuery();

} catch (/*All relevant exceptions such as SQLException*/Exception e) {
  logger.error("Damn, stupid exception: " , e);
} finally {
if (rs != null) {
            try {
                rs.close();
                rs = null;
            } catch (SQLException e) {
                logger.error(e.getMessage(), e.fillInStackTrace());
            }
        }

        if (ps != null) {
            try {
                ps.close();
                ps = null;
            } catch (SQLException e) {
                logger.error(e.getMessage(), e.fillInStackTrace());
            }
        }

        try {
            if (conn!= null && !conn.isClosed()){
                if (!conn.getAutoCommit()) {
                    conn.commit();
                    conn.setAutoCommit(true);
                }
                conn.close();
                conn= null;
            }
        } catch (SQLException sqle) {
            logger.error(sqle.getMessage(), sqle.fillInStackTrace());
        }
}

You can see I've checked if my objects are null and for connection, check first if the connection is not autocommited. Many people fail to check it and realise that the transaction hasn't been committed to DB.

A: The statement. I would expect you to close (in order)

*

*the result set

*the statement

*the connection

(and check for nulls along the way!)
i.e. close in reverse order to the opening sequence.
If you use Spring JdbcTemplate (or similar) then that will look after this for you. Alternatively you can use Apache Commons DbUtils and DbUtils.close() or DbUtils.closeQuietly().


text:
Q: Having trouble with array being overwritten I'm trying to load a scrabble dictionary to memory, but when I print out the contents of the dictionary, it seems to have rewritten every string in my data array with the last string seen by the buf, for example, when I print out the data array at the very end, every entry in the array is 'zzz' because its the last entry in scrabble.txt. I don't understand why it is being overwritten? What am I doing wrong?
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>

#define LEN 100

struct data_t {
    int nval;       /* current number of values in array */
    int max;        /* allocated number of values */
    char **data;        /* the data array */
};

enum {INIT = 1, GROW = 2};

int main(void)
{
    FILE *fp = fopen("scrabble.txt", "r");
    char buf[LEN];
    int i = 0;
    struct data_t *data = malloc(sizeof(struct data_t));
    data->nval = INIT;
    data->max = INIT;
    data->data = NULL;
    while (fgets(buf, LEN, fp)) {
            if (data->data == NULL) {
                    data->data = malloc(LEN);
                    assert(data->data);
            }
            else if (data->nval > data->max) {
                    data->data = realloc(data->data, GROW * data->max * LEN);
                    assert(data->data);
                    data->max = GROW * data->max;
            }
            //printf("%s\n",buf);
            data->data[i] = buf;
            //printf("data->data[%d] = %s ", i, data->data[i]);
            i++;
            data->nval++;
    }
    /* overcounted */
    data->nval--;

    for(i = 0; i < data->nval; i++)
            printf("data->data[%d] = %s", i, data->data[i]);

    fclose(fp);
    free(data->data);
    return 0;
}

A: You write:
data->data[i] = buf;

This makes the pointer data->data[i] point at the buffer buf.  You do this every time around the loop, so you end up with all of your pointers pointing to buf.  So when you output what each pointer is pointing to, it outputs the contents of buf that many times.
You probably wanted to use a different buffer for each line. You will have to use malloc or related to allocate those buffers. For example, replace data->data[i] = buf; with:
data->data[i] = strdup(buf);

(strdup is not a Standard C function, but if your system doesn't have it, you can malloc(strlen(buf)+1) followed by strcpy).


text:
Q: MySQL and php connection error I created a form using php, mysql and xampp server. The problem is that whatever I write in this form it shows that the "message failed to send" and even when I check my db using http://localhost/phpmyadmin/ the message is not there. Here is the code.
P.S I followed a video tutorial and it is exactly the same that made me totally lost. Please help.
The Connection code is:
<?php

$db_host = 'localhost';
$db_user= 'root';
$db_pass= 'the password';

$db_name= 'chat';

if ($connection= mysql_connect($db_host, $db_user, $db_pass)) {

    echo "Connected to Database Server...
";

    if ($database= mysql_select_db($db_name, $connection)) {
        echo "Database has been selected...
";
    } else {
        echo "Database was not found.
";
    }
} else {
    echo "Unable to connect to MYSQL server.
";
}
?>

And the function code is:
<?php

    function get_msg() {

        $query = "SELECT 'Sender', 'Message' FROM 'chat' . 'chat'";

        $run = mysql_query($query);

        $messages= array();

        while($message = mysql_fetch_assoc($run)) {
            $messages[]= array ('sender' =>$message['Sender'],
                                'message'=>$message['Message']);
        }

        return $messages;

    }

    function send_msg($sender, $message) {

        if(!empty($sender) && !empty($message)){

            $sender  = mysql_real_escape_string($sender);
            $message  = mysql_real_escape_string($message);

            $query = "INSERT INTO 'chat'.'chat' VALUES (null, '{$sender}', '$message')";

            if($run = mysql_query($query)) {
                return true;
            } else {
                return false;
            }

        } else {
            return false;
        }
    }
?>

A: I have found the problem in your SQL query:
$query = "INSERT INTO 'chat'.'chat' VALUES (null, '{$sender}', '$message')";

You have to specify the fields there, the SQL query is invalid. Also you have used the wrong escape characters. This works:
$query = "INSERT INTO `chat`.`chat` (`ID`, `sender`, `message`) VALUES (null, '{$sender}', '$message')";

You do not have to specify a null value if you use AUTO_INCREMENT:
$query = "INSERT INTO `chat`.`chat` (`sender`, `message`) VALUES ('{$sender}', '$message')";

And please use MySQLi instead of MySQL because it is deprecated. Furthermore, the database should not be specified twice, simple use:
$query = "INSERT INTO `chat` (`sender`, `message`) VALUES ('{$sender}', '$message')";

A: $query = "INSERT INTO `chat`.`chat` VALUES (null, '{$sender}', '$message')";
Note the ` and it's not '

A: I am a novice in PHP and MySQL so I tend to always explicitly exit or die on MySQL on errors.
<?php
$db = new mysqli('host', 'username', 'password', 'db');
if($db->connect_errno > 0){
    die('Unable to connect to database [' . $db->connect_error . ']');
    // no reason to continue, no db connection
}

$statement="SELECT * from `bufferlines` WHERE `beloeb` >'-400' AND `tekst` LIKE 'Dankort-nota SuperB%'";
if(!$res=$db->query($statement)){
        printf("Error: %s\n", $db->error); //show MySQL error
        echo "
".$statement; // show the statement that caused that error
        exit("Error 4");//no reason to continue, show where in code
}

?>

This way I get it thrown in my face and cannot get any further until I have pinned down and corrected the error.
The number in exit("Error 4") is only to find the place in the code where it went wrong and thus is unique.
I know this is counter productive when you know your stuff, but for me it's an invaluable learning tool together with php.net dev.mysql.com and stackoverflow.com


text:
Q: Nexus 4 v4.3 Facebook connect I'm trying to develop a application integrate with Facebook connect, it work fine on other device (Note 2 v4.1.2) but same code unable to login to Facebook on Nexus 4 v4.3.
Is it a bug? is there a known issue regarding this?
Following is log shown by facebook sdk
10-05 10:59:29.864: D/FacebookSDK.WebDialog(7727): Webview loading URL: https://m.facebook.com/login.php?skip_api_login=1&api_key=623266737691185&signed_next=1&next=https%3A%2F%2Fm.facebook.com%2Fdialog%2Foauth%3Fredirect_uri%3Dfbconnect%253A%252F%252Fsuccess%26display%3Dtouch%26type%3Duser_agent%26client_id%3D623266737691185%26ret%3Dlogin&cancel_uri=fbconnect%3A%2F%2Fsuccess%3Ferror%3Daccess_denied%26error_code%3D200%26error_description%3DPermissions%2Berror%26error_reason%3Duser_denied&display=touch&_rdr

Thanks

A: Facebook Connect used OAuth as authentication method, and part of OAuth param include timestamp. If the time of the device is not correctly set, it will produce incorrect timestamp and result in the error above.
Hope Facebook can be more clear about their error message.


text:
Q: Get Palette (IntPtr) pointer from Bitmap I need to convert a System.Drawing.Bitmap to System.Windows.Media.Imaging.BitmapSource.
The problem is that my bitmap has a custom palette and I need to pass it to CreateBitmapSourceFromHBitmap method.
How can obtain the pointer (IntPtr) of the bitmap palette?
Thanks.
IntPtr hBitmap = bitmap.GetHbitmap();

BitmapSource bmpSrc = CreateBitmapSourceFromHBitmap(hBitmap,
                                                    ????,
                                                    Int32Rect.Empty,
                                                    BitmapSizeOptions.FromEmptyOptions());


text:
Q: opencv_createsamples command it is not recognized in pycharm I just started fiddling with opencv and python using pycharm. I followed a tutorial on how to create a Haar Cascade file, but when I reached the step where I had to use 'opencv_createsamples' command, it returned:

"is not recognized as an internal or external command"

I searched for a solution. Most of them said to add opencv to path in the enviroment variables, so I downloaded opencv, extracted it in the C directory and added it to the path, but it still did not work. Could someone help me?

A: I tried this a quickie and I got the same message. I also use PyCharm. Are you sure you're using the right version of opencv? I'm on 2.4 which is quite old. Maybe this is a method that's been added in a later version. If you can import cv2 it shouldn't be the pythonpath.


text:
Q: python-Levenshtein.ratio calculation I have two strings:
>>> a= '@ROAD INC'
>>> b = 'WYETH'
>>> Levenshtein.ratio(a, b)
0.0

Now I understand the calculation behind it, but not the intuition:
>>> ldist = sum([2 for item in Levenshtein.editops(a,b) if item[0] == 'replace'])
              + sum([1 for item in Levenshtein.editops(a,b) if item[0] != 'replace'])
>>> ln = len(a) + len(b)
>>> ldist - ln
0

Isn't the result counter-intuitive? Shouldn't lower Levenshtein.ratio be interpreted as string match instead of complete string difference?


text:
Q: file permissions for php scripts which runs as apache user I don't think I fully understand groups and users. I have determined that php runs as user apache
I have 2 files on my server, but of which I can run without any problems. Below are the file permissions.
-rwxrwxr-x  1 staging staging     2100 Sep  6 14:47 hardware.php
-rwxrwxr-x  1 staging apache        69 Dec  5  2012 ipn.php

Is the only reason hardware.php can run is because it has read and execute permissions for everyone. What does php need to run?
Also I have a folder migrations with below permissions.
drwxrwxr-x  2 staging apache      4096 Dec 17 12:45 migrations

Is the reason I can write to this because the group is apache and the group has write permissions?
I am still a bit confused by users and groups. I know that groups can contain a collection of users, but I am not sure where to lookup the information.
Is apache a user or a group?

A:
What does php need to run?

It needs one of these:

*

*Read access for everyone (chmod o+r)

*File belongs to the user apache (chown apache)

*File belongs to the group apache (chgrp apache)

Is the reason I can write to this because the group is apache and the group has write permissions?

Yes.

Is apache a user or a group?

There usually is a group and a user with the same name.

A: I set all of my Apache web files to 644 and my directories to 755. Check out this useful guide: http://www.cyberciti.biz/faq/how-linux-file-permissions-work/
644 means that files are readable and writeable by the owner of the file and readable by users in the group owner of that file and readable by everyone else.
755 is the same thing, it just has the execute bit set for everyone. The execute bit is needed to be able to change into the directory. This is why directories are commonly set to 755.
Apache is a user, in a group called apache.


text:
Q: Numerical approximations of $2^x$ where $x$ is between $0$ and $1.0$? I've been looking everywhere for this.  I've found a billion ways to approximate e^x, and ln(x), and I know I could combine those, what I'm looking for here is an independent numerical method to calculate $2^x$ with $0.0 < x < 1.0$.  there is one here but it appears to be using an auto generated polynomial coefficients for numerical approximation, and doesn't really go into detail of how they were chosen.
I figured there would be some series approximation or a analytically derived polynomial expansion, but it seems like that isn't the case (though in that event I'd like to know why, or at least why e^x does and 2^x doesn't).
When I say independent, I mean that the method isn't for say, $e^x$, and then uses some transformation to get to $2^x$. Here's what I don't want, some derivation that comes down to $exp(x * ln(2))$.  Constant log terms like $ln(2)$ are fine, and if it some how helped, an $e^c$ constant would be fine as well. It just can't rely on needing an numerical approximation for $ln(x)$ or $e^x$ or $log_{10}$ etc...

A: The Chebyshev series for $2^x$ on the interval $[0,1]$ is $\sum_{n=0}^\infty c_n T_n(2x-1)$
where $$c_n = \frac{2}{\pi} \int_0^1 \frac{2^x T_n(2x-1)}{\sqrt{x-x^2}}\; dx$$ (except $c_0$ has $1/\pi$ instead of $2/\pi$) where $T_n$ are the Chebyshev polynomials of the first kind.  The first few terms are
$$\eqalign{& 1.45699987501296291\,T_0 \left(2\,x-1 \right) + 0.497524867810441862
\,T_1 \left( 2\,x-1 \right) \cr +& 0.0428931119896796484\,T_2 \left( 2\,x-1
 \right) + 0.00247142816399587408\,T_3 \left( 2\,x-1 \right)\cr +&
 0.000106906116358177253\,T_4 \left( 2\,x-1 \right) +
 0.00000370138142770695859\,T_5 \left( 2\,x-1 \right)\cr +&
 0.000000106823753743946597\,T_6 \left( 2\,x-1 \right) +
 0.00000000264303276285357833\,T_7 \left( 2\,x-1 \right)}
$$
which has maximum error less than $6 \times 10^{-11}$.

A: Write $2=\frac{\frac32}{\frac34}=\frac{1+\frac12}{1-\frac14}$ or similarly $2=\frac{1+\frac13}{1-\frac13}$ and apply the binomial series with a sufficiently large number of terms
$$
2^x=\frac{\sum_{k=0}^\infty \binom{x}{k}2^{-k}}{\sum_{k=0}^\infty \binom{x}{k}(-1)^k4^{-k}}
~~\text{ or }~~
2^x=\frac{\sum_{k=0}^\infty \binom{x}{k}3^{-k}}{\sum_{k=0}^\infty \binom{x}{k}(-1)^k3^{-k}}
$$
This of course suffers the fate of all Taylor expansions in that it has very small errors at the development point and large errors at the other end of the interval under consideration. One could reduce that a little by using $2^x=2/2^{1-x}$ for $x$ closer to $1$, or suitably combine both approximations.

A: Note that $$2^x=e^{\ln(2)x}$$  you can approximate like before (using taylor series or linear approximation etc). $$1+x\ln(2)+\frac{(x\ln(2))^2}{2}...$$

A: Starting from Robert Israel's answer, we have
$$c_n=2 \sqrt{2}\, I_n\left(\frac{\log (2)}{2}\right)$$ where $I_n$ is   the modified Bessel function of the first kind and,as Robert Israel wrote
$$2^x= \sqrt{2}I_0\left(\frac{\log (2)}{2}\right)+2 \sqrt{2}\sum_{n=1}^\infty I_n\left(\frac{\log (2)}{2}\right)\, T_n(2x-1)$$
Computing the maximum error $\Delta$ for the partial sum up to $p$, a quick and dirty linear regression gives $(R^2=0.9986)$
$$\log_{10}(|\Delta|)=0.90352 -1.60856 \,p$$
If you accept $\color{blue}{a=\log(2)}$ to be part of the approximation and assuming that you are noot too much requiring about accuracy, you could use an $[n,n]$ Padé approximant built at $x=\frac 12$ and get, for example,
$$\color{blue}{2 ^x \sim \sqrt 2\,\frac {1+\frac{a }{2}t+\frac{a^2 }{10}t^2+\frac{a^3 }{120}t^3 } {1-\frac{a }{2}t+\frac{a^2 }{10}t^2-\frac{a^3 }{120}t^3 }}\qquad \text{where} \qquad \color{blue}{t=x-\frac 12}$$ which leads to a maximum error equal to $1.2 \times 10^{-8}$.
Edit
If we use the $[n,n]$ Padé approximant built at $x=\frac 12$,we have $(R^2=0.9981)$
$$\log_{10}(|\Delta|)=1.23774 -3.13141  \,n$$ For $n=5$, it would be
$$\color{blue}{2^x\sim \sqrt 2\,\frac{30240+15120 y+3360 y^2+420 y^3+30 y^4+y^5} {30240-15120 y+3360 y^2-420 y^3+30 y^4-y^5 }}$$
 where $\color{blue}{y=\left(x-\frac{1}{2}\right) \log (2)}$ and the maximum error is $2.44\times 10^{-15}$.
In fact, the general $[n,n]$ Padé approximant built at $x=\frac 12$ can write as
$$\color{red}{2^x \sim \sqrt 2\,\frac{\sum_{k=0}^n \frac{(k+n)! }{k! (n-k)!}y^{n-k}} { \sum_{k=0}^n (-1)^{k-1} \frac{(k+n)! }{k! (n-k)!}y^{n-k}}}\qquad \text{where} \qquad \color{red}{y=\left(x-\frac{1}{2}\right) \log (2)}$$


text:
Q: Handle Click Event Masterpage Control on content Page I Have a LinkButton on my master page, and want to do with it in my content page,
so I write a code like this on my page load :
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If Session("UserID") Is Nothing Then
            Session("UserID") = Request.ServerVariables("LOGON_USER").Replace("INA\", "")
        End If

        Me.lbleMessage.Text = ""
        Dim lblUaname As Label = DirectCast(Master.FindControl("lblUname"), Label)
        lblUaname.Text = Session("UserID").ToString

        Dim testlinkbutton As LinkButton = DirectCast(Master.FindControl("LinkButton1"), LinkButton)
        testlinkbutton.Click += New EventHandler(AddressOf LinkButton1_Click)

        If Not IsPostBack Then
            Me.lbleMessage.Text = ""
            If Session("UserID") <> "svaldano" Then
                'If CAuth.AuthUser(Session("UserID"), "20") Then

                'Else
                '     Response.Redirect("login.aspx")
                'End If
                FillDataWO()
                FillDataTC()
            ElseIf Not (Session("Username") Is Nothing) Then
                'If CAuth.AuthUser(Session("Username"), "20") Then

                'Else
                '     Response.Redirect("login.aspx")
                'End If
                If Session("Username") = "sv" Then
                    FillDataWO()
                    FillDataTC()
                Else
                    Response.Redirect("login.aspx")
                End If

            ElseIf Session("Username") Is Nothing Then
                Session("UserID") = Request.ServerVariables("LOGON_USER").Replace("BMJAKARTA\", "")
                Response.Redirect("login.aspx")
            End If

        End If
    End Sub

but the line testlinkbutton.Click += New EventHandler(AddressOf LinkButton1_Click) of gimme an Error ,
Public Event Click(sender As Object, e As System.EventArgs)' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event.
so is it true that I couldn't use my code? because I just know about raiseevent

A: Instead of
    testlinkbutton.Click += New EventHandler(AddressOf LinkButton1_Click)

you may try
    AddHandler testlinkbutton.Click, AddressOf LinkButton1_Click

See How to: Add an Event Handler Using Code


text:
Q: Access screen height and width in a service worker I want my service worker to get the height and width of the screen.
I've tried screen.height, self.innerHeight, window.innerHeight, but it seems service workers run on a different context where these are undefined.
Is there a way to access device information like height and width within the context of a service worker?

A: Service Workers (and all workers in general) can't access the DOM.
I can see two ways to achieve what you want:

*

*Store those values in IndexedDB (or in a Cache) in your page and access them in the worker;

*Send those values from the page to the service worker using postMessage.

Obviously, you can use the first solution always, you can't use the second solution when your service worker is running and there isn't any page open.