text:
Q: Can't send volley post request from android phone to my database I'm using volley to make my android communicate with my database by using PHP as bridge to get through database.
Below here are my Login code on android studio which work perfectly fine using emulator Nexus 4 API 23, but when i'm trying to run the App using my smartphone Samsung A5-2017 it only works on interface but the data are not send/function as it should. Btw i'm using SDK version 29 on this application
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

EditText editTextNoPelajar,editTextPassword;
TextView link_register;
Button btnLogin;
private static String URL_LOGIN = "http://10.1.19.2/attendance/Login.php";
SessionManager sessionManager;

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

    sessionManager = new SessionManager(this);

    editTextNoPelajar = (EditText)findViewById(R.id.editTextNoPelajar);
    editTextPassword = (EditText) findViewById(R.id.editTextPassword);
    link_register = (TextView) findViewById(R.id.textViewRegister);
    btnLogin = (Button) findViewById(R.id.buttonLogin);

    btnLogin.setOnClickListener(this);
}

private void userLogin(){
   final String NoPelajar = editTextNoPelajar.getText().toString().trim();
   final String Password = editTextPassword.getText().toString().trim();

    if(NoPelajar.isEmpty() || Password.isEmpty()){
        Toast.makeText(this,"Please fill up all the requirement",Toast.LENGTH_LONG).show();
    }

    else{

        StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_LOGIN,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            System.out.println(response);
                            JSONObject jsonObject = new JSONObject(response);
                            String success = jsonObject.getString("error");
                            JSONArray jsonArray = jsonObject.getJSONArray("login");

                            if(success.equals("0")){

                                for(int i = 0 ; i < jsonArray.length();i++){
                                    JSONObject object = jsonArray.getJSONObject(i);

                                    String name = object.getString("Name").trim();
                                    String KodProgram = object.getString("KodProgram").trim();

                                    sessionManager.createSession(name,KodProgram);

                                    Intent intent = new Intent(LoginActivity.this,HomeActivity.class);
                                    intent.putExtra("Name",name);
                                    intent.putExtra("KodProgram",KodProgram);
                                    startActivity(intent);
                                    finish();
                                }

                            }

                        } catch (JSONException e) {
                            e.printStackTrace();

                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(),error.getMessage(),Toast.LENGTH_LONG).show();
            }
         })
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> params = new HashMap<>();
                params.put("NoPelajar",NoPelajar);
                params.put("Password",Password);

                return params;
            }
        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

}

@Override
public void onClick(View view) {
    if(view == btnLogin){
        userLogin();
    }

}

}

Plus i have enable all the internet permission at Manifest as i shown below
   <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />

Once i click button Login its display this
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
D/ViewRootImpl@8b8d06[Toast]: setView = android.widget.LinearLayout{9070fc7 V.E...... ......I. 0,0-
0,0} TM=true MM=false
D/ViewRootImpl@8b8d06[Toast]: dispatchAttachedToWindow
V/Surface: sf_framedrop debug : 0x4f4c, game : false, logging : 0
D/ViewRootImpl@8b8d06[Toast]: Relayout returned: old=[0,0][0,0] new=[462,1596][618,1728] result=0x7
surface={valid=true 536733736960} changed=true
D/ViewRootImpl@8b8d06[Toast]: MSG_RESIZED_REPORT: frame=Rect(462, 1596 - 618, 1728) ci=Rect(0, 0 -
0, 0) vi=Rect(0, 0 - 0, 0) or=1
D/ViewRootImpl@8b8d06[Toast]: dispatchDetachedFromWindow
D/InputEventReceiver: channel '630e1a0 Toast (client)' ~ Disposing input event receiver.
D/InputEventReceiver: channel '630e1a0 Toast (client)' ~NativeInputEventReceiver.
I/zygote64: Do full code cache collection, code=250KB, data=195KB
I/zygote64: After code cache collection, code=247KB, data=157KB
I/zygote64: Do partial code cache collection, code=248KB, data=160KB
I/zygote64: After code cache collection, code=248KB, data=160KB
Increasing code cache capacity to 1024KB

Where did i do wrong guys?.. Please help me solve this problem, its been 2 days already trying to figured out the solution. Thank you


text:
Q: How to send background gmail immediately? I wrote some application ( marshmallow sdk ) that in some action i need to send mail with some file attached using the default device account to well know user.
When i trying to use my sending action ( code attached ) i getting some dialog that tell me to choose the application that i want to use for this shared this file attached.
I want to skip this dialog somehow and just make this sending action be done without give the user that use this application to choose the gmail and press the 'send' button.
( like sending the mail in the background )
The code:
 public void SendToMail(String filePath)
{
    Intent emailIntent = new Intent(Intent.ACTION_SEND);

    emailIntent.setType("text/plain");
    emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {"somemailAddress@gmail.com"});
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Reminder");
    emailIntent.putExtra(Intent.EXTRA_TEXT, "Null");

    File file = new File(filePath);
    if (!file.exists() || !file.canRead()) {
        return;
    }

    Uri uri = Uri.fromFile(file);
    emailIntent.putExtra(Intent.EXTRA_STREAM, uri);

    final PackageManager pm = _context.getApplicationContext().getPackageManager();
    final List<ResolveInfo> matches = pm.queryIntentActivities(emailIntent, 0);
    ResolveInfo best = null;
    for(final ResolveInfo info : matches)
        if (info.activityInfo.packageName.endsWith(".gm") || info.activityInfo.name.toLowerCase().contains("gmail"))
            best = info;

    if (best != null)
        emailIntent.setClassName(best.activityInfo.packageName, best.activityInfo.name);

    _context.startActivity(emailIntent);
}

A: You can do this from android using javamail api
You can try this link
Send email in android using JavaMail API with smtp but without SSL
But after some time gmail may gives error on your account because your location may vary as user from different countries access your gmail using your application.

redpajama_set_name: RedPajamaStackExchange


text:
Q: CIDR security group in aws ec2 configuration My website seems to be under heavy bandwidth which is hosted in EC2 AWS.
May I know how to determine CIDR for an area/country so that traffic can be limited in the security group configuration for aws ec2.
My current IP from my internet provider is this:
124.13.126.1
Is it possible to limit it to this area/country ?

A: You can allow your ISP Ip range by adding this 124.13.126.1/32. to inbound security group
Or you can use aws WAF to only allow users in your region https://docs.aws.amazon.com/waf/latest/developerguide/web-acl-geo-conditions.html


text:
Q: Setting feature weights for KNN I am working with sklearn's implementation of KNN. While my input data has about 20 features, I believe some of the features are more important than others. Is there a way to:

*

*set the feature weights for each feature when "training" the KNN learner.

*learn what the optimal weight values are with or without pre-processing the data.

On a related note, I understand generally KNN does not require training but since sklearn implements it using KDTrees, the tree must be generated from the training data. However, this sounds like its turning KNN into a binary tree problem. Is that the case?
Thanks.

A: kNN is simply based on a distance function. When you say "feature two is more important than others" it usually means difference in feature two is worth, say, 10x difference in other coords. Simple way to achive this is by multiplying coord #2 by its weight. So you put into the tree not the original coords but coords multiplied by their respective weights.
In case your features are combinations of the coords, you might need to apply appropriate matrix transform on your coords before applying weights, see PCA (principal component analysis). PCA is likely to help you with question 2.

A: The answer to question to is called "metric learning" and currently not implemented in Scikit-learn. Using the popular Mahalanobis distance amounts to rescaling the data using StandardScaler. Ideally you would want your metric to take into account the labels.


text:
Q: Xcode поиск строки вызывающей исключение Как в отладчике Xcode найти (перейти) к строке objective-c на которой падает программа?
Ассемблерный  код остановки программы мне непонятен, в логе информация о недопустимом индексе обращения к массиву, но искать в каком месте это происходит долго. Может есть простой цивилизованный способ?

A: Способы есть, конечно. Подозреваю, что не один. Я пользуюсь следующим приёмом:
перейдите в breakpoint navigator

выберите пункт add exception breakpoint

все опции оставьте по умолчанию. запускайте приложение.
вот таким будет итог данных манипуляций:


text:
Q: Put multiple data sorted into one variable (like HashMap just with more rows) I am trying to receive data from my MySQL database and save all of the rows with multiple variables in them and put them into one variable.
My database:
############################################
#192.168.1.1 | Instance1 | 19.988 | 0 | 20 #
############################################

############################################
#192.168.1.2 | Instance2 | 19.878 | 1 | 19 #
############################################

and so on...

From this database I receive the data which is contained in the entries/rows (unique key is the IP address [first entry])
Now my goal is it to store all of this data in one variable so I can list all of my instances and show the according data to them.

Question:
Is there a way to store this data in one variable (something like a HashMap just with more rows) or is there maybe even a better way to store the data?

A: You can use a single HashMap object to store the multiple records that come from your SQL query.
After setting up your database connection and performing your query, just go through the ResultSet object, create an object using a model class and add it to the HashMap using the IP as the key. The code below shows an example of how to do it:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

public class Example {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection connection = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/my_database", "db_user", "db_password");

            Statement stmt = connection.createStatement();
            ResultSet resultSet = stmt.executeQuery("SELECT * FROM my_table");
            HashMap<String, DBRecord> results = new HashMap<>();
            while (resultSet.next()) {
                results.put(resultSet.getString(1), new DBRecord(
                        resultSet.getString(1),
                        resultSet.getString(2),
                        resultSet.getFloat(3),
                        resultSet.getInt(4),
                        resultSet.getInt(5)
                ));
            }
            connection.close();
            printHashMap(results);
        } catch (Exception e) {
            System.out.println("Error: " + e);
        }
    }

    public static void printHashMap(HashMap<String, DBRecord> records) {
        for (Map.Entry pair : records.entrySet()) {
            System.out.println(pair.getKey() + " = " + pair.getValue());
        }
    }

    public static class DBRecord {

        private String ip, instance;
        private double firstValue;
        private int secondValue, thirdValue;

        public DBRecord(String ip, String instance, double firstValue, int secondValue, int thirdValue) {
            this.ip = ip;
            this.instance = instance;
            this.firstValue = firstValue;
            this.secondValue = secondValue;
            this.thirdValue = thirdValue;
        }

        //Gets and sets...

        @Override
        public String toString() {
            return ip + " | " + instance + " | " + firstValue + " | " + secondValue + " | " + thirdValue;
        }
    }

}

Using the HashMap you can retrieve the results from the object using the key (IP), but you could also use an ArraList or some other data structure to store your records, although you would need to change how you go through them.
I hope this helps you.


text:
Q: differentiating between post requests I have this jquery function which sends a POST request to the server
function loadInfo() {
    jQuery(function($) {
        $.ajax({
            method: "POST",
            url: "/admin.php",
            dataType: "json",
            success: function(data) {
                console.log(data);
                for (var i = 0; i < data.length; i++) {
                    setMarker(data, i, "red");
                    printInfo(data, i);
                }
            }
        })
    });
}

This is how the request gets handled
if($_SERVER['REQUEST_METHOD'] === 'POST'){
    header('Content-Type: application/json');
    require 'private/database.php';

    $sql = "SELECT * FROM form";
    $result = mysqli_query($conn, $sql);

    $data = array();
    if (mysqli_num_rows($result) > 0) {
        while ($row = mysqli_fetch_assoc($result)) {
            $data[] = $row;
        }
    }
    die(json_encode($data));
}

The code works, but what if I have send multiple POST requests to the same server? Is there a way to differentiate between them like how you would when handling HTML forms?
e.g. If the of the button that submits the form is "submit_button"...
if (isset($_POST['submit_button'])) {
   ...
}

A: You have to send some parameter to differentiate the request.
eg:     $.post( "test.php", { name: "John", time: "2pm", method:"formSubmit" } );

A: There are a number of ways to send post by AJAX with data (multiple data items). One of the ways is:
 $.ajax({
                url: 'process.php',
                type: 'POST',
                data: {status: "ok", name: "Richard"},
                success: function (result) {
                    alert('success');
                }
})

In the above case, you have sent status and name data to the php script by POST method. Hope that it can answer your question.


text:
Q: Frequency Hopping 900MHz -- Noise Floor Mitigation and Algorithim Design I've built a few baremetal fixed frequency RF systems, and am working on a long range frequency hopping product using a ARM Cortex M3.  So we got some horsepower here!
I've got the the TX FCC Part 15.247 compliant hopping across 60 channels and using an extremely narrowband signal to hit our range requirements. Average message time is 190ms (~50ms pre-amble, 140ms sync word + packet).
Product market is USA, so everything is being done to be FCC compliant.
It's an odd system because the goal is to simply deliver one single packet and take advantage of the increased transmit limit.
If the system were more bursty, I would just start on Hopping Channel 1, and go through all 60.  But we have a very tight latency requirement.
We need the system to respond within 300ms of a transmit.  If we loop through all 60 channels, that takes nearly 10 seconds. If we change the bit rate, we won't hit our distance.
I've got the RX cycling ~800us per channel to an asynchronous scan of all 60 channel, taking an RSSI read, and than dwelling on the strongest channel.
On my desktop, I'm getting about 80% of the packets through.
I did some more digging, and it seems like I am getting a lot of ambient noise in the 900MHz range that trips up my detector.
I added an RSSI limit, and that improved the system to about 90% of the packets.
But this is simply on my desktop!  From my experience I know this system isn't going to go far, this narrowband signal blends into the noise floor quickly but somehow the receiver is so sensitive it goes quite far (800 meters +).
I have thought about averaging the noise floor which might help (take your pick simple moving average or something more microcontroller friendly [I'm more of an 8 bit guy, so I have to see if the M3 really needs an MCU friendly scheme).
System mechanical really are one unit is TX, and one is the RX.  So I haven't really digested a re-transmission scheme yet.  The latency timing probably wouldn't work from a user perspective either.
Has anyone tackled a frequency hopping scheme like this?  Any ideas how to mitigate the amount of 900MHz noise out there but still get our signal through?

A: You can send a short packet on a beacon frequency once a second or so and hop through the other 59 frequencies with payload on a predetermined schedule.  The short beacon packet has the current position in the hopping sequence.
If you want to implement a "cognitive" system, you can look at the noise floor across all frequencies on the main transceiver and send a mask indicating which frequencies will be used in the hopping sequence in the beacon frame (you will need more than 60 total frequencies so you can skip high noise channels).
This scheme requires the use of a single, unchanging beacon frequency, but you can design the system to have secondary beacons on a variable frequency in the hop sequence.  This will give you one second lock-on as remote transceivers are connected to the network and no additional latency for transmitting once you have acquired the sequence.
If you have multiple transceivers and need to allocate timeslots for remote transmission you'll have to design this into your protocol.  If you provide information in your question on the number of transceivers, frequency of packets, etc I can refine this answer to your particular situation.
If you are occasionally sending a single packet from/between a large number of remote stations, LORA is probably a better solution than building something from scratch.  LORA has an extremely high link budget, so you will probably be able to meet your range goals without going over the 250mW regulatory threshold and using external PAs on your transceivers.  In a suburban (high noise floor) environment we achieved >1 mile range (LOS) with Semtech LORA transceivers without external PA (but with a decent antenna on each end).  Note that some of the Chinese LORA boards are terrible (mostly low tolerance crystals, but also generally bad RF layout).

A: Quick calculation:
Free space path loss at f=900 MHz for d=1 km in dB:
\begin{align}
a(d,f) & = 20\log_{10}(d)+ 20\log_{10}(f) +20\log_{10}\frac{4\pi}{c}\\
& = 20\log_{10}(10^3)+ 20\log_{10}(9\cdot10^8) +20\log_{10}\frac{4\pi}{3\cdot10^8}\\
&=60+ 160 +20\log_{10}9 +20 \log_{10}\frac{4\pi}{3} - 160\\
&\approx 92
\end{align}
Compare the sensitivities of less spartanic OOK transceivers than the SX1211; something like GFSK is way cleverer than OOK, here, because probability of detection and false alarm are just not on your side when using OOK in an AWGN channel with uncertainty about noise floor. Much, much less even in a Rayleigh channel.
So, the solution here really isn't smart estimation of the noise floor – it's using something less prone to noise than OOK.
Since you said you're happy that you have a proper ARM Cortex-M3 at hand, I did a quick check at the "usual suspects" when it comes to producing ARM MCUs with integrated RF frontend.
SILabs has the rather interesting Flex Gecko family:
https://www.silabs.com/products/wireless/proprietary/efr32-flex-gecko-2-4-ghz-sub-ghz
which can talk multiple bands at once, but really, we only care for 900 MHz, right? (If you run the same numbers as above for 2.4 GHz, you'll notice that you could even use that if you have more than 0 dBm TX power, and you do have that with these chips.)
So, what do they promise for 900 MHz?

-126.2 dBm @600 bps, GFSK, 916 MHz

Sounds a lot like your application, right?
So, does that work out in our scenario?
Ok, let's consult the datasheet (p. 54) about TX powers:

Maximum TX Power

*

*PAVDD connected directly to external 3.3V supply, 20 dBm output power setting: \$POUT_\text{max, minimal specified}=18\,\text{dBm}\$

*PAVDD connected to DC-DC output, 14 dBm output power setting: \$POUT_\text{max, minimal specified}=12.6\,\text{dBm}\$

So, because we're grumpy and know that matching circuitry is more exhausting that it should be, we just say: Ok, we emit 10 dBm.
With a TX power of 10 dBm (I think you can do that much without hopping, but I'm not in FCC-land), you'd still receive -82 dBm.
That's (-82)-(-126) dB = 44 dB above sensitivity.
I'd call that a reliable buffer against fading.
So, call off your hopping efforts. Just use an ARM microcontroller that integrates the frontend and can do a little more than OOK.


text:
Q: Transfer data from ashx to aspx. Make asp image control identify which image to show - asp.net c# page.aspx.cs code:
HttpContext.Current.Session["id1"] = id1.ToString();
Server.Transfer("Handler.ashx"); //Getting error
Image1.ImageUrl = "~/Handler.ashx?ID=" + id1.ToString();

HttpContext.Current.Session["id2"] = id2.ToString();
Server.Transfer("Handler.ashx"); //Getting error
Image2.ImageUrl = "~/Handler.ashx?ID=" + id2.ToString();

Handler.ashx code:
public void ProcessRequest(HttpContext context)
{
    int id = Convert.ToInt32(context.Session["id1"]);
    byte[] IMG = class.ReadImg(id);
    context.Response.ContentType = "image/jpg";
    context.Response.BinaryWrite(IMG);
}
public void ProcessRequest2(HttpContext context2)
{
    int id = Convert.ToInt32(context2.Session["id2"]);
    byte[] IMG2 = class.ReadImg(id);
    context2.Response.ContentType = "image/jpg";
    context2.Response.BinaryWrite(IMG2);
}

page.aspx code:
<asp:Image ID="Image1" runat="server" />//How to define thats gonna show image of id1
<asp:Image ID="Image2" runat="server" />//How to define thats gonna show image of id2

Question:

*

*I'm not able to transfer data from page.aspx to Handler.ashx

*I dont know how to make Image element to identify which image it should show according to the id (maybe some request.queryString magic I don't understand)

Help!!
Thanks :]

A: Server.Transfer() does what it says - transfer the request on the server-side, without returning a HTTP 301 re-direct to the client.
Your problem can be solved by simply reading the querystring in the ashx file:
string id = context.Request.Querystring["ID"];
context.Response.ContentType="image/jpeg";
......

Then in your aspx page:
Image1.ImageUrl = "/Handler.ashx?ID="+id.ToString();


text:
Q: yeoman generator-angular-cordova errors I have a problem installing an angular cordova app with yeoman. (more specifically this generator.)
Here's what happens:
$ yo angular-cordova

     _-----_
    |       |
    |--(o)--|   .--------------------------.
   `---------´  |    Welcome to Yeoman,    |
    ( _´U`_ )   |   ladies and gentlemen!  |
    /___A___\   '__________________________'
     |  ~  |
   __'.___.'__
 ´   `  |° ´ Y `

Out of the box I include Ionic and some AngularJS recommended modules.

[?] What is the name of your app? (Spaces aren't allowed) HelloCordova
[?] What would you like the package to be? io.cordova.hellocordova
[?] What platforms would you like to add support for? Android, iOS
[?] What plugins would you like to include by default?
[?] Would you like to copy some sample icons for cordova? Yes
Creating cordova app: helloCordova

/usr/lib/node_modules/generator-angular-cordova/node_modules/cordova/node_modules/q/q.js:126
                    throw e;
                          ^
Error: ENOENT, no such file or directory '/home/leoha/projects/mobile-app-v2/www/js/index.js'
    at Object.fs.unlinkSync (fs.js:760:18)
    at /usr/lib/node_modules/generator-angular-cordova/app/index.js:246:16
    at _rejected (/usr/lib/node_modules/generator-angular-cordova/node_modules/cordova/node_modules/q/q.js:808:24)
    at /usr/lib/node_modules/generator-angular-cordova/node_modules/cordova/node_modules/q/q.js:834:30
    at Promise.when (/usr/lib/node_modules/generator-angular-cordova/node_modules/cordova/node_modules/q/q.js:1079:31)
    at Promise.promise.promiseDispatch (/usr/lib/node_modules/generator-angular-cordova/node_modules/cordova/node_modules/q/q.js:752:41)
    at /usr/lib/node_modules/generator-angular-cordova/node_modules/cordova/node_modules/q/q.js:821:14
    at flush (/usr/lib/node_modules/generator-angular-cordova/node_modules/cordova/node_modules/q/q.js:108:17)
    at process._tickCallback (node.js:419:13)

If someone knows how to solve this, I'd be really grateful.

A: Ok, here is what I did on MacOS 10.10 (Yosemite) to get this to work, and it's a bit different from others. Note that I do not use sudo, but use the approach John Papa recommends.

*

*npm -g uninstall generator-angular-cordova

*mkdir ~/projects/node

*git clone https://github.com/wangshijun/generator-angular-cordova.git && cd $_

*npm link

*mkdir ~/projects/my-new-project && cd $_

*yo angular-cordova

It ends up asking some questions about dependencies on my machine, but I don't always see them, so the generator appears to hang.

A: The issue is described (and a solution provided) here: https://github.com/wangshijun/generator-angular-cordova/issues/2

A: I got it and fixed it.
I just installed the generator (locally and not globally)
C:\PhoneGap\Workspace\Demos\cordovayeoman>npm install generator-angular-cordova

after the successful installation of the package. When I ran:  "yo angular-cordova"  I got the same exception (see snapshot)

then I created another folder (MyCordovaApp) inside "the folder" where I installed/configured the generator plugin i.e.
From:   C:\PhoneGap\Workspace\Demos\cordovayeoman\

To:   C:\PhoneGap\Workspace\Demos\cordovayeoman\MyCordovaApp

Now here I ran again: "yo angular-cordova" and it worked well :)  (see snapshot)

Note:- I had selected iOS platform that's why it given me excetion while generating stuff for iOS on Windows machine.
and here is the generated stuff.


text:
Q: How do you configure a Camunda process specific datasource? I have Camunda 7.10 running on Tomcat 9.0.12.
The process engine datasource is configured in
/[tomcat-home]/conf/server.xml

and, by necessity, is available to all deployed web-apps.
I wish to configure a process specific datasource that is only available to that process.
For a normal web app, there is typically a
[tomcat-home]/webapps/[web-app-name]/META-INF/context.xml

configuration file that defines the datasource and the locator code that returns a  javax.sql.DataSource using a javax.naming.InitialContext etc
Looking at the deployment of the specific process, there are two META-INF folders
[tomcat-home]\webapps\[process-name]\META-INF
[tomcat-home]\webapps\[process-name]\WEB-INF\classes\META-INF

The first has maven specific items.
The second is where the process.xml file resides.
Using proven datasource locator code and putting a proven context.xml file here fails with
javax.naming.NameNotFoundException: Name [jdbc/recruitDS] is not bound in this Context. Unable to find [jdbc].

Searching for this only leads to information on the main Camunda process engine datasource configuration which is well covered in the manual, forums etc.

A: The following configuration works for Camunda 7.10 running on Tomcat 9.0.12 accessing SQL Server 2012 using a Maven build project as per the Camunda Java Process Get-Started example.
In the exploded WAR file, in the folder:
[tomcat-home]\webapps\[process-name]\META-INF

there must be a context.xml file with these fields:
<?xml version="1.0" encoding="UTF-8"?>
<Context>
  <Resource
    name="jdbc/myDatasource"
    global="jdbc/myDatasource"
    auth="Container"
    type="javax.sql.DataSource"
    driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
    url="jdbc:sqlserver://127.0.0.1:1433;databaseName=myDatabaseName"
    username="myUsername"
    password="myPassword"
    maxTotal="50"
    maxIdle="0"
    maxWaitMillis="-1"
    removeAbandonedOnBorrow="true"
    removeAbandonedOnMaintenance="true" />
</Context>

The important field is the global tag - missing this causes the above exception. For a normal JSP/servlet web-app, this field is not necessary as the scope is limited to that web-app. For Camunda, the task listeners etc run in the scope of the main Camunda web-app.
Using a Maven build, it is just a case of adding the META-INF folder & file to the project file structure.
Then, in a Camunda JavaDelegate or TaskListener, it is possible to use the DataSource to obtain a connection in the usual manner via an InitialContext with a URL of the form:
java:/comp/env/jdbc/myDatasource

Using a process specific data-source avoids polluting the main tomcat server.xml configuration file with process specific items.


text:
Q: Unfold a notation within a scope This answer provides a simple useful trick: unfold ">=" is the same as unfold ge but does not require you to know that >= is the notation for ge.
Can you do the same for notations within a scope?
Require Import NArith.
Goal forall x, (x >= x)%N.
unfold ">=".

Here unfold ">=" does not do anything because it tries to unfold ge, not N.ge.
I have found the following solution:
Open Scope N.
unfold ">=".

But is there a syntax allowing to unfold this notation without first opening the scope?

A: Yes, you can use the template unfold string % scope as follows:
Require Import NArith.
Goal forall x, (x >= x)%N.
  unfold ">=" % N.

This gives us the goal forall x : N, (x ?= x)%N <> Lt with unfolded >=.


text:
Q: Where are the private lists stored when you are saving lists in "My Lists" Where are the private lists stored when you are saving lists in "My Lists"?
Found this explenation:
"User profile pictures are stored in the My Site Host site collection. The My Site Host site collection is created from the SPSMSITEHOST#0 template. When the SharePoint Online tenant is provisioned, a My Site Host site collection is created. The profile pictures are stored in a document library that's named "User Photos." The pictures are stored in a folder inside the User Photo document library by having a .jpg filename extension".
But how can i access My Site?
Greetings, P

A: Microsoft Lists are stored in your personal site. These are good old SharePoint lists, in a good old SharePoint site.
You can verify it by navigating your the MS List service and then replacing /Lists.aspx with /ViewLsts.aspx in the URL:


text:
Q: What can we infer from (x|y)=(x|z) in a real inner product space? $(x|y) = (x|z)$
I think the vectors $y$ and $z$ are parallel to each other.
What else can be said?

A: I think you are talking about
$$
\langle x,y \rangle=\langle x,z \rangle
$$
being true for any $x,y,z \in (V, \langle\cdot,\cdot\rangle)$, then you can not infer $y$ and $z$ being parallel to each other.
A counterexample would be $V=\mathbb{R}^3$ and $x=(1,0,0)^t, y=(0,1,0)^t$ and $z=(0,0,1)^t$. Even though with the standard inner product
$$
\langle x,y \rangle=1\cdot0+0\cdot1+0\cdot0=0=1\cdot0+0\cdot0+0\cdot1=\langle x,z \rangle
$$
your identity holds, it is obviously not true that $y$ is parallel to $z$.
However, the following holds because of the bilinearity of the inner product:
$$
\langle x,y \rangle=\langle x,z \rangle \Leftrightarrow \langle x,y-z \rangle=0
$$
which means that $x \perp y-z$.


text:
Q: Finding all keys that match a value in a nested dictionary and creating a new dictionary with the values as keys I've got the following dictionary (much larger obviously):
{
'file1': {'parameter1': value,
          'parameter2': value}

'file2': {'parameter1': value,
          'parameter2': value}
}

I need to turn it into:
{
'parameter1': {value1 : [list of all matching files],
               value2 : [list of all matching files]}

'paramemer2': {value1 : [list of all matching files],
               value2 : [list of all matching files]}
}

The number of files and values is arbitrary, the number of parameters is fixed and relatively low.
I'm kinda able to do it, but it requires a lot of intermediate steps, generating sets of all parameters' values etc. Is there a quick pythonic way to invert it? Maybe I should use a different data structure?

A: You can use a collections.defaultdict:
from collections import defaultdict

data = {
    'file1': {'parameter1': 'value1',
              'parameter2': 'value2'},
    'file2': {'parameter1': 'value1',
              'parameter2': 'value3'}
}

dd = defaultdict(lambda: defaultdict(list))
for file, pv_dict in data.items():
    for para, value in pv_dict.items():
        dd[para][value].append(file)

print(dd)
# defaultdict(<function <lambda> at 0x7fb4d89c3c80>,
#     {
#         'parameter1': defaultdict(<class 'list'>, {'value1': ['file1', 'file2']}),
#         'parameter2': defaultdict(<class 'list'>, {'value2': ['file1'],
#                                                    'value3': ['file2']}),
#     }
# )


text:
Q: Hive to GCP BigQuery Sync We need to move data from Hive tables (Hadoop) to GCP (Google Cloud Platform) BigQuery at regular intervals (hourly/daily/any). There are multiple tables and the volume of data is huge. Can you please let me know if Cloud Data Flow (CDF) can be used in this situation? Any alternatives?
Thanks in advance!
Regards,
Kumar

A: There are umpteen number of solutions depending on the timescales you have but any or all of them will involve using gsutil to copy data from HDFS (to the local file system) and then to GCS. Alternatively, you may also develop a solution using MySQL backup and restoring them back on GCP


text:
Q: Django admin site adding "city object" instead of "City" I'm trying to create a basic weather forecast site on Django and this error arises. I successfully made a "Cities" section but when adding any city name, "City Object 1" is added. This then creates errors when reading JSON from the API key.
from django.db import models

class City(models.Model):
    name = models.CharField(max_length=25)

    def _str_(self): #show the actual city name on the dashboard
        return self.name

    class Meta: #show the plural of city as cities instead of citys
        verbose_name_plural = 'cities'

admin.py
from django.contrib import admin
from .models import City

admin.site.register(City)

A: two undersccore
def __str__(self):

https://docs.djangoproject.com/en/3.0/ref/models/instances/#other-model-instance-methods


text:
Q: Form Won't Pass Value Pair In Get Request Url After Submission I'm familiarizing myself with API's Get & Post Request in Laravel. I have a form where an admin can send Points to an external API. Unfortunately, in the documentation the request has to be a GET request and the data which is being submitted has to append to the url
ie: myurl.com/my-end-point?platform_id=value&auth=value...
The issue is, whenever i fill the form and submit the url remains the same:
ie: myurl.com/my-end-point?platform_id=platform_id&auth=auth...
It does not pass the data in the get request.
Controller
public function sendCpdPoints(Request $request)
{
$response = Http::asForm()->get('myurl.com/my-end-point', [
            'platform_id' => 'platform_id',
            'auth' => 'auth',
            'cpd_id' => 'cpd_id',
            'registration_number' => 'registration_number',
            'certificate' => 'certificate',
]);

dd($response);

}

View (Blade)
<form action="{{url('admin/rewards/points/manual_update/dashboard/store/participants-points') }}" method="POST">

                {{ csrf_field() }}

                            Platform Id
                            <input type="text" name="platform_id" id='platform_id' class="form-control" value="123" readonly>

                            Authentication Key
                            <input type="text" name="auth" id='auth' class="form-control" value="123456789" readonly>

                            Cpd Id
                            <input type="text" name="cpd_id" id='cpd_id' class="form-control" placeholder=".ie 587">

                            Registration Number
                            <input type="text" name="registration_number" id='registration_number' class="form-control" placeholder=".ie MDC/PA/RNXXXX">

                            Certificate Serial Number
                            <input type="text" name="certificate" id='certificate' class="form-control" placeholder=".ie 2022-03/001">

                        <button type="send" class="btn btn-primary">Send</button>

            </form>

Help is greatly appreciated. As i really want to get better.

A: You need to pass the value from the form . You can use $request-> from the request facade
You can try this
 public function sendCpdPoints(Request $request)
 {
   $response = Http::asForm()->get('myurl.com/my-end-point', [
        'platform_id' =>  $request->platform_id,
        'auth' => $request->auth,
        'cpd_id' => $request->cpd_id,
        'registration_number' => $request->registration_number,
        'certificate' => $request->certificate,
  ]);

  dd($response);
 }

A: Let me see if I understand. Does your backend that handles the request call an external API? If that's the case, the problem is that you're passing strings as an argument. To retrieve the form values try something like:
$request->auth or
$request->get('auth')
If this is not the case, and you simply want to get the form data in your backend, I advise you to do it with JS using AJAX. You can use Fetch or install an external lib like axios to do this.
NOTE: the type of your submit button is incorrect, change it to type="submit"
https://www.w3schools.com/tags/att_button_type.asp


text:
Q: Can't use any programs in full-screen mode on Ubuntu 19.10 When I try to use full screen mode on any program, be it sites under Firefox, games with Lutris/wine or VLC, the screen starts to flicker and switches between full-screen mode and a smaller resolution of the screen in the top left corner of my monitor.
Would be grateful for any ideas that could help me tackle this major problem.
I am using a 4K monitor and have fractional scaling enabled as an experimental feature. This seems to cause the problem, but I can't go without it since at 100% scaling everything is just too tiny to read and 200% doesn't look very good, so I keep everything at 150%.
Also this problem only started recently after I updated one of my Lutris games. I didn't have this problem before.

A: I'm using the same distribution (19.10) with 4k display scaled by factor 2 and i didn't face such issue for all applications, but any browser which is based on Chromium (Chrome, Opera, Chromium itself etc.) behaves exactly as you describe, even on Youtube with full-screen mode.
As a workaround i'm running google-chrome --force-device-scale-factor=1 with default page zoom at 200% for all websites (Chrome -> Settings -> Page Zoom).
P.S.
Advise you to check Gnome Extensions if you have, since i faced somehow similar weird bugs with applications scale in case of hidden Gnome top bar or left sidebar.


text:
Q: Detecting the character entered into an input field on keydown The Question: How can I detect the character that is going to be inserted into an input field after keypress / keydown?
The Background: I'm creating an input field that is dynamically expanding and shrinking as the user types.  In order to do this fluidly I need to redraw immediately before the character is rendered. In order to redraw to the correct width, I need to know the character that is about to be inserted.  Using keyup and then .val() creates a jittery interface because the width isn't changed until after the text shifts to the right.
Explored Approaches:
This is what I'm using now, but it doesn't do the trick simply because it is not an accurate mapping, especially for special characters.
        // Convert the keypress to the appropriate letter
        self.lastLetter = String.fromCharCode(e.keyCode);
        self.lastLetter = e.shiftKey?self.lastLetter:self.lastLetter.toLowerCase();

A: I wrote a module called keysight that translates keypress, keydown, and keyup events into characters and keys respectively.
Keysight retruns an object that has a char property, and a key property. The char property represents the character being typed, which takes into account uppercase. The key property represents the key on the keyboard and doesn't represent upper or lower case - just the key.
Example:
 element.addEventListener("keydown", function(event) {
    var character = keysight(event).char
    if(character === 'w') {
      console.log("got lower case w")
    } else if(character === 'W') {
      console.log("got upper case W")

      var key = keysight(event).key
      console.log("keysight(event).key is still lower case "+key)
    }
 })

A: It's hard to be sure from the small snippet you've posted, but it looks like you're trying to map character codes to characters. The keypress event does indeed pass character codes. The keydown (and keyup) events, however, pass scan codes instead of character codes. That's so they can pass key strokes that don't represent characters (such as arrow keys, hot keys, etc.). You can find a table of scan codes in this blog post, but note that they're browser and OS specific.


text:
Q: have multiple users belong to one record in rails 5 app I am building out a rails 5 ruby 2.4.0 app.
I have a Truck model, and a User model.
I would like to reference several users to the truck.. the person who created the truck, the owner of the truck and the driver of the truck if it differs from that of the owner. I want it to reference only the user because I don't want to have may types of user models.
Is this theoretically possible?
im thinking about this:
Truck has_many_users
user belongs_to truck (not sure how to work this?)
when a truck is created it logs the current user id, then the user can select system users for the driver association and owner association...
Please help i'm burning my brain trying to map this out..

A: So what you're looking for is associating Truck to User multiple times, with each association playing a different role.
It's definitely possible, and quite a common way to set up associations.
However, I would definitely set it up so that the Truck model is the child ("belongs to") the User model, for two reasons -

*

*A truck model should be self-contained in its knowledge. It should know who its creator, driver, and owner are. So you want those id's (foreign key references) stored on the Truck and not the User. Also in your case each truck can have 1 and only 1 creator, driver, or owner. (Side note: If you did have a case where a Truck could have numerous creators, drivers, and owners then this wouldn't work and you'd have to rely on a many-to-many relationship like an intermediary joining table.)

*A user can inherently be associated with multiple trucks. A user could own 3 different trucks or they could own 1 truck but drive another. It makes more sense that a User would have the has_many relationships here.
The trick is that ActiveRecord lets you name associations anything you want. So you can try -
class Truck < ApplicationRecord
  belongs_to :creator, class_name: "User", foreign_key: :creator_id
  belongs_to :owner, class_name: "User", foreign_key: :owner_id
  belongs_to :driver, class_name: "User", foreign_key: :driver_id
end

class User < ApplicationRecord
  has_many :created_trucks, class_name: "Truck", foreign_key: :creator_id
  has_many :owned_trucks, class_name: "Truck", foreign_key: :owner_id
  has_many :driven_trucks, class_name: "Truck", foreign_key: :driver_id
end

In each line we override -

*

*The class_name, because if we didn't specify it Rails would use the associated name to guess it. So belongs_to :creator would look for a Creator model, instead of a User model

*The foreign_key, because if we didn't specify it Rails would use the associated name to guess it. So belongs_to :creator would look for for a creator_id on this model (since it belongs to the other model). Similarly if we had has_one :creator it would look for a creator_id on the foreign Creator model (or whatever is specified via class_name).


text:
Q: Marginal density knowing joint density I have a probability density function:
$f_{X,Y}(x,y) = \begin{cases}24xy, & 0 \le x < 1, \ 0 \le y < 1, \ x+y<1, \\
0 & \text{otherwise} \end{cases}$
I have to find the marginal density $f_X(x)$ and the conditional probability of $X$ given Y=1/2.
$$f_X(x)= \int_{x=0}^{x=1} f_{X,Y}(x,y), dx= \int_{x=0}^{x=1} 24 x y, dx=   24 [x^2/2]_{x=0}^{x=1}=12y$$
$$f_{X|Y}(x|y= \frac{1}{2})= \frac{f(x,y= \frac{1}{2})}{f_Y(y= \frac{1}{2})}= \frac{24x \frac{1}{2}}{12* \frac{1}{2}}=2x$$
but I'm not sure.  Could someone check my solution?

A: For the marginal density you have to also consider the bound $x+y<1$:
$$
f_X(x) = \int_{0}^{1-x} f_{X,Y}(x,y) \;dy = 24x \int_0^{1-x}y \;dy = 12x(1-x)^2, \quad x \in [0,1).
$$
I am not 100% sure what you mean by the conditioned probability of $X$ but I assume you mean the conditional density of $X$ given $Y=\frac 12$. Therefore you first need the marginal density of $Y$ which is given by
$$
f_Y(y) = \int_{0}^{1-y} f_{X,Y}(x,y) \;dx = 12y(1-y)^2, \quad y \in [0,1)
$$
Then
$$
f(x|Y=\frac12) = \frac{f_{X,Y}(x,\frac12)}{f_Y(\frac 12)} = \frac{12x}{\frac 32} = 8x, \quad x \in [0,\frac 12).
$$


text:
Q: Did Instagram change API rate limits on Mar 30, 2018? I use some self developed script to get info about my posts and followers. Recently I discovered that Instagram changed rate limits for my app. I see following info in headers:
x-ratelimit-limit: 200

I learned Instagram blog and page with changes but found no mentions about any changes since Oct 1, 2017.
Is this new limit related only to my token or to entire platform? Could you check your token?

A: Some perspective:
This 200 per hour call has been in the Graph API documentation for at least a month (according to wayback machine).
Facebook must have panicked over the weekend and pressed the "require Graph API permissions" button, thus our current situation. :\

A: Yes,
The limit has been reduced.
Here are some reference links for detailed documentation:
Instagram API limit reduced to 200 from 5000
https://techcrunch.com/2018/04/02/instagram-api-limit/
https://developers.facebook.com/docs/instagram-api/overview/#rate-limiting
Hope it helps
Thanks

A: Here's our answer:  https://www.instagram.com/developer/changelog/
The API deprecated immediately. So really the limits probably don't matter that much anymore. I really don't see myself building another app based on their API...

A: Here is  The New Instagram's Public Api Update , unfortunately Limit rates are worthless for some Features in Instagram .
   April 4, 2018
The following endpoints are deprecated immediately:
Follows and Relationships
GET /users/self/follows
GET /users/self/followed-by
GET /users/self/requested-by
GET /users/{user-id}/relationship
POST /users/{user-id}/relationship
Commenting on Public Content
GET /media/{media-id}/comments (Deprecation not relevant when fetching comments for self media)
POST /media/{media-id}/comments
DEL /media/{media-id}/comments/comment-id
Media
GET /media/{media-id}
GET /media/shortcode/{shortcode}
Likes
GET /media/{media-id}/likes
POST /media/{media-id}/likes
DEL /media/{media-id}/likes
User Search
GET /users/{user-id}
GET /users/{user-id}/media/recent
GET /users/self/media/liked
GET /users/search
Subscriptions - to receive notifications when media is posted
Some information on Public Content returned through hashtag and location search will be removed - Name, Bio, Comments, Commenters, Follower Count, Following Count, Post Count, and Profile Picture

A: Yes It is, Although no official communication.
I also experienced that.
I found this in their documentation.
The Instagram API uses the same rate limiting as the Graph API (200 calls per user per hour) with one exception: the /media/comments edge limits writes to 60 writes per user per hour. Please refer to the Graph API's rate limiting documentation for more information.
https://developers.facebook.com/docs/instagram-api/overview/#rate-limiting
https://techcrunch.com/2018/04/02/instagram-api-limit/
Hope this will be helpful.
Update:-
Further on 4th April few more APIs deprecated by Instagram.
https://www.instagram.com/developer/changelog/


text:
Q: Updating dictionaries to append file data I want to make a function that updates two dictionaries with data from a open file. The first dict one would be a "person to countries" dict and the second one would be a "person to people" dict.
For example, the "person to countries" would be something like {'Greg Van' : ['Canada', 'America'], 'Tori Mars' : ['Thailand']} and the "person to people" dict would be be {'Greg Van' : ['Mike Wu', 'Emily Salt'], 'Mia Tan' : ['Sandy Bay', 'Dan Hamilton']}.
The parameters of the function would be
(file, dict of {string : list of strings}, dict of {string : list of strings}) -> NoneType
The text file would be something like:
Chan, Ferah
Canada
Pritchett, Mitchell
Pritchett, Jay

Rad, Sarah
France
America
MacKenzie, Corey

Delgado, Manny
Luong, Sam

Vu, Linda
China
Khan, Jane

where the first line of each list is a person and then it would list 0 or more countries that they have lived in, along with 0 or more people. There would also be a blank line space between each person. Each list/paragraph here in the file is related to each other.
I don't know how to update the two existing dicts("person to countries" and "person to people") with the data from the given file (which includes a person, countries, and/or people). So basically I want to append the data to the two dicts.
All I know is that I can differentiate the countries and the people by the comma since countries don't have them.

A: Taking the pattern I see, I can tell that the difference between the countries and the animals is that Countries are Capitalized, so, you could do a variety of things: you can have a dict where each letter is the key and a tuple that is the value, inside the value (the tuple) you would have two lists, one for countries and the other for pets. The other approach is to have one dict instead of the tuple and the dict would have two elements, I'll show you the structure of this dict:
    people = {'A': {'countries':['Canada',], 'pets':['dog', 'cat']}}

That would be the mapping in the dict of the first element. The code would be something like:
    people = {}
    file_read = open("asdf.in", "r")

    current_person = file_read.readline().strip()

    while current_person:
        people[current_person] = {}
        line = file_read.readline().strip()
        people[current_person]['countries'] = []
        people[current_person]['pets'] = []
        while line:
            if line.istitle(): people[current_person]['countries'].append(line)
            elif line.islower(): people[current_person]['pets'].append(line)
            line = file_read.readline().strip()

        current_person = file_read.readline().strip()

    print people


text:
Q: Define icon for flatpak application I am using gnome builder. I saw that in gnome music it is installed with
install_data(
    join_paths('icons/hicolor/scalable/apps', APPLICATION_ID + '.svg'),
    install_dir: join_paths(get_option('prefix'), get_option('datadir'), 'icons/hicolor/scalable/apps')
)

but it is not working doing only this.


text:
Q: Javascript - missing ; before statement I'm studying with a tutorial for a "drawing app". When I launch my app on Firefox, Firebug tells me "missing ; before statement" where I call my function on line 9. I just don't get where I'm supposed to put these ";".
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

var radius = 10;

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

var putPoint = Function(e){
    context.beginPath();
    context.arc(e.clientX, e.clientY, radius, 0, Math.PI*2);
    context.fill();
}

canvas.addEventListener ('mousedown', putPoint);

/* ligne 15 context.arc(x, y, radius, start, end) */

A: *

*var putPoint = Function(e) ---> var putPoint = function(e)

*contint.fill(); } ---> contint.fill(); };


text:
Q: WPF datagrid binding complex type property back I have a simple Datagrid binded to an ObservableCollection from the ViewModel. This ObservableCollection is composed by a Custom Type, say ObservableCollection.
The ComplexType only have 2 properties, and only one is editable on the screen. The other one is a bool type that depends on the first.
When I edit the first property, it gets reflected to the ComplexType and it also change the second property. But the second property is not changed on the screen.
How can I update the second property on the screen?

A: Try this:
public class ComplexType:INotifyPropertyChanged
{
    private object someProperty1;
    public object SomeProperty1
    {
        get{return someProperty1;}
        set
        {
            someProperty1=value;
            SomeProperty2=somefunc(someProperty1);

            If(PropertyChanged!=null){PropertyChanged(this, new PropertyChangedEventArgs(SomeProperty1));}
        }
    }

    private object someProperty2;
    public object SomeProperty2
    {
        get{return someProperty2;}
        set
        {
        someProperty2=value;

        If(PropertyChanged!=null){PropertyChanged(this, new PropertyChangedEventArgs(SomeProperty2));}
        }

    public event PropertyChangedEventHandler PropertyChanged;
}

A: An observable collection provides notification only when items are added, removed, or the whole collection is refreshed.  You need to make sure that each property either raises the PropertyChanged event or is a dependency property if you want your UI to refresh when it changes.


text:
Q: Using python to scrape push data? I'm trying to scrape the left side of this news site (= SENESTE NYT):
https://www.dr.dk/nyheder/
But it seems the data isn't anywhere to be found? Neither in the html or related api/json etc. Is it some kind of push data?
Using Chrome's Network console I've found this api but it doesn't contain the news items on the left side:
https://www.dr.dk/tjenester/newsapp-content/teasers?reqoffset=0&reqlimit=100
Can anyone help me? How do I scrape "SENESTE NYT"?

A: I first loaded the page with selenium and then processed with BeautifulSoup.
from selenium import webdriver
from bs4 import BeautifulSoup

url = "https://www.dr.dk/nyheder"
driver = webdriver.Chrome()
driver.get(url)
page_source = driver.page_source

soup = BeautifulSoup(page_source, "lxml")
div = soup.find("div", {"class":"timeline-container"})
headlines = div.find_all("h3")

print(headlines)

And it seems to find the headlines:
[
Puigdemont: Debatterede spørgsmål af interesse for hele Europa
,

Afblæser tsunami-varsel for Hawaii
,

56.000 flygter fra vulkan i udbrud
,

Pence: USA offentliggør snart plan for ambassadeflytning
,

Østjysk motorvej genåbnet
]

Not sure if this is what you wanted.
-----EDITED----
More efficient way would be to create request with some custom headers (already confirmed this is not working)
import requests
headers = {
        "Accept":"*/*",
        "Host":"www.dr.dk",
        "Referer":"https://www.dr.dk/nyheder",
        "User-Agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"

    }

r = requests.get(url="https://www.dr.dk/tjenester/newsapp-content/teasers?reqoffset=0&reqlimit=100", headers=headers)

r.json()


text:
Q: Ack — Ignoring multiple directories without repeating the flag Is it possible to ignore multiple directories in Ack, without repeating the flag?
e.g. I know the following works (i.e. setting multiple flags):
ack --ignore-dir=install --ignore-dir=php 'teststring'

I was hoping that I could separate directories with commas, like I can do with the extensions as follows:
ack --ignore-file=ext:css,scss,orig 'teststring'

However, the following comma separated ignore flag doesn't work:
ack --ignore-dir=install,php 'textstring'

Is it possible to use some short-hand equivalent, so I don't have to repeatedly type out the --ignore-dir flag?

A: It's actually similar to how you would specify the include patterns for grep:
ack <term> --ignore-dir={dir_a,dir_b}
However, This format does not work with a single directory. So
ack <term> --ignore-dir={log}
will not work.

A: Since you're using ack 2, you can put --ignore-dir=install and --ignore-dir=php in a .ackrc file in the root of your project.  Then, every ack invocation in that tree will use those flags.

A: So to ignore single directory use
ack <term> --ignore-dir=dir_a

and to ignore multiple directories use
ack <term> --ignore-dir={dir_a,dir_b}

A: One approach could be to select those directories to exclude with a regular expression in -G option complemented with the option --invert-file-match. Based in your question, something like the following:
ack -a -G 'install|php' --invert-file-match 'textstring' .


text:
Q: How can I use Include method in entity framework 4.3 for an abstract type? I have an Order class which links to a list of OrderLine, which is an abstract type.
I want to issue an Include on one of the sub-classes of OrderLine, such as ProductOrderLine which has a Product property on it:
Something like:
data.Orders.Include(x=>x.Lines).Include("Lines.Product");

Obviously that causes a failure, so I need a way of specifying sub-types I guess.
Thanks

A: Including on inheritance hierarchies is not supported. You can only include properties from the base type.


text:
Q: How to integrate paypal payment gateway in Grails 3.3.0 I am beginner in Grails. I want to integrate paypal payment gateway in my application. I have install Grails 3 plugin but after that i don't know what to do. i want step by step process to implement paypal payment in Grails 3.3.0 web application. Any suggestion will be appreciated.

A: You don't necessarily need a plugin. Just refer to the REST documentation if any, then write a wrapper for it then.


text:
Q: Docbook Dblatex - how to omit header on first page of chapter? I'm using dblatex to convert a book formatted using Docbook into a PDf, and everything is working great, however for the life of me I can't figure out how to suppress the inclusion of a header on the first page of each chapter? Of course I want that page to "count" in terms of the overall page count, however I don't want the book title nor page number to appear on that first page.
Any ideas?
Thank you!
Jason

A: In latex this is often done using a combo of the fancyhdr package and the \thispagestyle{} command. I would look through your dsssl stylesheet for references to these packages.


text:
Q: How do I convert a single char in string to an int Keep in mind, if you choose to answer the question, I am a beginner in the field of programming and may need a bit more explanation than others as to how the solutions work.
Thank you for your help.
My problem is that I am trying to do computations with parts of a string (consisting only of numbers), but I do not know how to convert an individual char to an int. The string is named "message".
for (int place = 0; place < message.size(); place++)
        {
            if (secondPlace == 0)
            {
                cout << (message[place]) * 100 << endl;
            }
        }

Thank you.

A: If you mean that you want to convert the character '0' to the integer 0, and '1' to 1, et cetera, than the simplest way to do this is probably the following:
int number = message[place] - '0';

Since the characters for digits are encoded in ascii in ascending numerical order, you can subtract the ascii value of '0' from the ascii value of the character in question and get a number equal to the digit.


text:
Q: How to execute instructors in order with ruby net ssh channel? As the net-ssh manual book says the method "exec" executes a command asynchronously on channel.http://net-ssh.github.io/ssh/v1/chapter-3.html#s6
But when I hope to execute some instructors in order, for example:
def work(session, instructor )
  session.open_channel do |channel|
    channel.on_data do |ch, data|
      puts data.strip
    end
    channel.exec instructor
  end
end

Net::SSH.start( 'host' ) do |session|
  work session, "touch a.file"
  work session, "mv a.file b.file"
  work session, "rm b.file"
  session.loop
end

Executing a command asynchronously really makes such code doesn't work.
Can anybody help me to solve this problem?
Thanks!

A: Use sync shell service for it, do something like:
Net::SSH.start( 'localhost' ) do |session|
  shell = session.shell.sync
  shell.touch 'a.file'
  shell.mv 'a.file', 'b.file'
  shell.send_command("rm", 'b.file')
  shell.exit
end

or just organize the commands on-a-line:
work session, "touch a.file; mv a.file b.file; rm b.file"


text:
Q: Is there an immutable and read-only collection type in .NET? In .NET we have both read-only and immutable collection types.
For instance:

*

*ReadOnlyCollection<T> is a read-only wrapper around a list. Instances of this type cannot be modified by the client code (so this type is read-only), but if the underlying list changes, then those changes are reflected on the ReadOnlyCollection<T> instance (so, this type is not immutable).

*ImmutableList<T> is an immutable type (once you have an instance of the type, there is no way to modify it by changing the object state), but it's public interface is not a read-only interface: the client code can call methods (such as the Add method) whose purpose is creating new instances of the type, without modifying the current instance.
Sometimes I feel the need for a concrete type which is both immutable and read-only.
Based on my knowledge, there is no existing type in the .NET base class library having both of these characteristics. Am I missing anything ?
The closest you can get is by using interface types, such as in the following example:
public IReadOnlyCollection<string> GetItems()
{
  // the returned collection is an immutable object and is seen as read-only by the client code
  return new List<string>{ "foo", "bar" }.ToImmutableList();
}

A: Immutability implies read only.
The ImmutableList<T>.Add method does not modify the object. It is just a shortcut for creating a new object. It is very similar to something like Enumerable.Concat, something that is also available on ReadOnlyCollection<T>. So the object itself remains immutable and read only.
The distinction between read only and immutable in this context is if someone else can modify the collection. ReadOnlyCollection<T> is just a wrapper around a list, so it is still possible for someone else to change the list. ImmutableList<T> promises that no one can change the list. But this distinction is not 100% consistent in the language. The readonly keyword is for example used to mark structs as immutable.

A: Let's take a step back and agree on what the terms readonly and immutable means.

*

*A ReadOnlyCollection<T> cannot be modified. However, the list of objects that it refers to can be modified (unless those objects are immutable).

*An immutable list cannot be modified. The list of objects that it refers to, cannot be modified either. That's the difference.
In other words, all immutable collections are readonly. You're getting exactly what you're asking for.
From docs:

... When you add or remove items from an immutable list, a copy of the
original list is made with the items added or removed, and the
original list is unchanged...
ImmutableList<T> Implements
IReadOnlyCollection<T>...

https://learn.microsoft.com/en-us/dotnet/api/system.collections.immutable.immutablelist-1?view=net-7.0


text:
Q: CircleCI configuration to deploy to server Question:
Could anyone tell me why the below configuration is not working?
Error:
Error: orb not found: scp _r * shinedom@shinedome.com:
Config:
# PHP CircleCI 2.0 configuration file
#
# Check https://circleci.com/docs/2.0/language-php/ for more details
#
version: 2
jobs:
  build:
    docker:
      # specify the version you desire here
      - image: circleci/php:7.1.5-browsers

      # Specify service dependencies here if necessary
      # CircleCI maintains a library of pre-built images
      # documented at https://circleci.com/docs/2.0/circleci-images/
      # - image: circleci/mysql:9.4

    working_directory: ~/repo
    steps:
      - checkout
      - scp -r * shinedom@shinedome.com:/home/shinedom/public_html


text:
Q: uninitialized constant for module included in model I've read a bunch of other SO posts on this and it seems the convention is to place the module in lib (lib/my_module.rb) and name it CamelCase (module MyModule) and then include it in the model (include MyModule). I did all this and still get "uninitialized constant Model::MyModule". I was wondering if something changed in Rails 4 or if I have to do something in my config/environment.rb file. Here is my code:
app/models/comment.rb
class Comment < ActiveRecord::Base
    include KarmaExtension # error at this line

    belongs_to :user
    belongs_to :post
    belongs_to :parent, class_name: "Comment"

    ...
end

lib/karma_extension.rb
module KarmaExtension
    def karma_recieved_from?(sender)
        sender ? !karmas.where("sender_id = ?", sender.id).empty? : true
    end
end

and my config/environment.rb just in case (have not touched this file)
# Load the Rails application.
require File.expand_path('../application', __FILE__)

# Initialize the Rails application.
RailsHnClone::Application.initialize!

A: Add /lib to your load_path:
# in config/application.rb
config.autoload_paths += %W(#{config.root}/lib)

And require your lib:
# in config/initializers/karma_extension.rb
require 'karma_extension'

Found the answer here: http://blog.chrisblunt.com/rails-3-how-to-autoload-and-autorequire-your-custom-library-code/


text:
Q: get row number of an NSManagedObject in core data i want to know if there is a function in core data to get the row number of a NSManagedObject with a specific id?

A: There is no row number. Don't think in terms of tables, it's an (unordered) object store. The data is often backed in an SQLite store, but not necessarily.
If you need to specify some ordering then you should store and maintain your own order attribute on the entity and use that.


text:
Q: Porting from Code::Blocks to Visual Studio 2010 Say I have a open source C::B C++ (non-C++11, perfectly compatible with the 1998 ISO standard) project I've downloaded which is using MinGW/GCC (TDM-1 4.7.1 or 4.7.2 - doesn't work with newest version),; can I port the source files from it to Visual Studio 2010 and be able to make it work without massive code rewriting? Or there are certain cases in which it won't be possible? Or it depends on various things?
EDIT:
The code relies on additional external utilities and libraries such as:

*

*Lua

*SDL 2.0 + SDL Image 2.0

*OpenGL

A: If the project was written using portable C++98 code you shouldn't have too much trouble. First, I would check you can compile in GCC with -std=c++98 -pedantic flags and fix any warnings to ensure you are not relying on any GCC extensions.
It also depends on the portability of any required libraries.

A: The most General and correct response is: It depends on various things.
What kind of project are you refering to? Is it wxWidget, QT4, GTK+, OpenGL?
How much do you use c++11?
Assuming that we are talking about a simple Console Application the easiest way to verify whether you can migrate to MSVC2010 is to switch compiler inside Code::Blocks project.
Select Project->Build Option... and under Selected compiler choose Microsoft Visual Studio C++ 2010. Afterwards try to recompile. The warning and errors will show you how easy will be the porting.
Of course you have to install Code::Blocks with MSVC2010 too.
EDIT: The OpenGL library is supported by MSVC2010 and libsdl has VC development libraries. However, things seem to be more complex with Lua. My guess is that you might start a substantial porting work here.

A: Try it!
If your code is standard-compliant and does not rely on any GCC extensions or GCC-specific libraries, then you should be fine out-of-the-box.
Note though that different compilers support C++ in different ways; for example, even Visual Studio 2013 has only passing C++11 support so if your program is a C++11 program with things like ranged-for and initializer lists in it then, depending on the version you're using, it's just not going to work without those pieces of code being rewritten to look more like C++03.

A: I actually made a mistake:
C::B indeed told me there were multiple errors in the compilation attempt with the MSVC2010 compiler, because the code included many Unix-only libraries, too intricately so to be easily avoided. Thus, I'm thinking of either making MinGW/GCC work in Visual Studio itself or sticking with C::B.
(Continues here: POSIX Headers (from MinGW project) in Visual Studio 2013)


text:
Q: Unspecified GSS failure, No Kerberos credentials available I tried to ssh to a server and get this error:
"Unspecified GSS failure. Minor code may provide more information No Kerberos credentials available"
I am not exactly sure what it means. (Still try to Google it)
; ssh -vT -p 1234 root@mysite.com
OpenSSH_6.6.1, OpenSSL 1.0.1f 6 Jan 2014
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug1: Connecting to mysite.com [1.2.3.4] port 1234.
debug1: Connection established.
debug1: identity file /home/kenpeter/.ssh/id_rsa type 1
debug1: identity file /home/kenpeter/.ssh/id_rsa-cert type -1
debug1: identity file /home/kenpeter/.ssh/id_dsa type -1
debug1: identity file /home/kenpeter/.ssh/id_dsa-cert type -1
debug1: identity file /home/kenpeter/.ssh/id_ecdsa type -1
debug1: identity file /home/kenpeter/.ssh/id_ecdsa-cert type -1
debug1: identity file /home/kenpeter/.ssh/id_ed25519 type -1
debug1: identity file /home/kenpeter/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-8
debug1: Remote protocol version 2.0, remote software version OpenSSH_5.3
debug1: match: OpenSSH_5.3 pat OpenSSH_5* compat 0x0c000000
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr hmac-md5 none
debug1: kex: client->server aes128-ctr hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<3072<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Server host key: RSA xxxxx....xxxxxx....
debug1: Host '[mysite.com]:1234' is known and matches the RSA host key.
debug1: Found key in /home/kenpeter/.ssh/known_hosts:1
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password
debug1: Next authentication method: gssapi-keyex
debug1: No valid Key exchange context
debug1: Next authentication method: gssapi-with-mic
debug1: Unspecified GSS failure.  Minor code may provide more information
No Kerberos credentials available

debug1: Unspecified GSS failure.  Minor code may provide more information
No Kerberos credentials available

debug1: Unspecified GSS failure.  Minor code may provide more information

debug1: Unspecified GSS failure.  Minor code may provide more information
No Kerberos credentials available

debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/kenpeter/.ssh/id_rsa
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password
debug1: Trying private key: /home/kenpeter/.ssh/id_dsa
debug1: Trying private key: /home/kenpeter/.ssh/id_ecdsa
debug1: Trying private key: /home/kenpeter/.ssh/id_ed25519
debug1: Next authentication method: password
root@mysite.com's password:

When I type my password, I get "permission denied".

A: The remote server did allow root remote access, but the password was changed and it is different from the documentation I have.


text:
Q: React Router - Mapping routes with 404 error page I am currently using React Router. I prefer the syntax of a routes config file and mapping over the array of routes to render the Route, as opposed to the <Switch> option.
{routes.map(route => {
        return (
          <PrivateRoute
            key={route.path}
            path={route.path}
            exact
            component={route.component}
          />
        );
      })}

Is there a way with the above use case to have a 404 component for all non-exact matching routes.
I have seen the <Switch> approach like this: https://reacttraining.com/react-router/web/example/no-match. As mentioned I prefer declaring all routes in a route config file, with the path, component and breadcrumb name. If I go down the Switch route then the route config is only used for breadcrumbs and becomes less useful

A: If you are going to be defining your routes in a config file, then you should probably use react-router-config (which is also part of react-router)
If you have a peek at the implementation of renderRoutes, then you will notice that it internally uses a Switch component, which means that you can put your "404" routes at the end of the list and it should fallback to that one if there is no other match, for instance:
const routes = [
  {
    component: Root,
    routes: [
      {
        path: "/",
        exact: true,
        component: Home
      },
      {
        path: "/child/:id",
        component: Child,
        routes: [
          {
            path: "/child/:id/grand-child",
            component: GrandChild
          }
        ]
      },
      {
        path: "*",
        component: NotFound,
      },
    ]
  }
]

You could also implement a component like this RedirectToNotFound:
const RedirectToNotFound = () => <Redirect to="/404" />;

And then setup your config file like this:
const routes = [
  {
    component: Root,
    routes: [
      {
        path: "/",
        exact: true,
        component: Home
      },
      {
        path: "/child/:id",
        component: Child,
        routes: [
          {
            path: "/child/:id/grand-child",
            component: GrandChild
          }
        ]
      },
      {
        path: "/404",
        component: NotFound
      },
      {
        path: "*",
        component: RedirectToNotFound,
      },
    ]
  }
]

Full disclosure: I've never used react-router-config and unless you have a very specific need I wouldn't recommend its usage.


text:
Q: applyTransaction to add a row fails Adding row using applyTransaction
this.agGridOptions.api.applyTransaction({ add: [value], addIndex: this.rowData.length - 1 })

is failing for ag-grid (27.3.0/28.1.1) with the following stack -
ERROR TypeError: Cannot read properties of undefined (reading 'some')
at SortService.sort (ag-grid-community.auto.esm.js:50571:35)
at SortStage.execute (ag-grid-community.auto.esm.js:50361:26)
at ClientSideRowModel.doSort (ag-grid-community.auto.esm.js:50011:24)
at ClientSideRowModel.refreshModel (ag-grid-community.auto.esm.js:49767:22)
at ClientSideRowModel.commonUpdateRowData (ag-grid-community.auto.esm.js:50205:14)
at ClientSideRowModel.updateRowData (ag-grid-community.auto.esm.js:50182:14)
at GridApi.applyTransaction (ag-grid-community.auto.esm.js:32024:43)
at GridApi.updateRowData (ag-grid-community.auto.esm.js:32041:21)

I could not find any reported issues for the above stack.
Any pointers on how to debug the issue?


text:
Q: Word or phrase for "seeing meaning where none exists" Is there a word or a phrase to describe an instance where meaning is ascribed to something where there is no such meaning or where the interpretation is particularly fanciful?
For example, when reading Shakespeare in English class or when viewing modern visual art in Art Appreciation class, someone mentions the 'phallic imagery or symbolism' of anything cylindrical in what is being read or viewed.

A: Pareidoilia is seeing meaning in random stimulus, such as seeing faces or animals in cloud patterns.

A: The expression "Wishful thinking" comes to my mind. There's also a quirky word, "eisegesis" (the link is to the Wikipedia article on it, there's some useful related terms to be gleaned there, like "confirmation bias").
The word "exegesis", being a term with a long history, is also sometimes used to imply "wishful, crafty extrapolation", as in this beautiful poem by J.C.Ransom, Prometheus in Straits:

To the library then to view the masterpieces?
   Not now, though I risk the damage of your inference,
   For before their alterations respect ceases:
   Their glowing centers you have laid over with absurd circumference,
   Indeed you have undone them with exegesis,
   And provoke me to a gesture not of deference.

There's also an idiom to read into.

A: pervert, v: 4. To interpret incorrectly; misconstrue or distort: an analysis that perverts the meaning of the poem.; 5. to misconstrue or misinterpret, esp. deliberately; distort.
slant, n: to have or be influenced by a subjective point of view, personal feeling or inclination, etc; bias.
bias, n, v: 1. mental tendency or inclination, esp an irrational preference or prejudice
stretch, n,v: 13. (tr) Informal to expand or elaborate (a story, etc.) beyond what is credible or acceptable that's stretching it a bit
warp n,v: 3. to pervert or be perverted
[src: TFD]

A: The technical term for this phenomenon is apophenia.
Name for cognitive bias suggesting a person is special or important.
Here's an article that explains the phenomenon:
http://lostpedia.wikia.com/wiki/Apophenia
Urban dictionary dictionary defines brain fact as follows:

A thought that you believe to be true. The "facts" are completely fabricated and are supported by zero empirical evidence whatsoever. The only qualifier is that you believe the fact to be true.

A: It's a phrase, not a word, but there's the expression reading too much into something, as in:

Matt, I think you're reading too much into it.

TFD lists read into as a phrasal verb, meaning:

to attach or attribute a new or different meaning to something; to presume inferences as one reads something.

That seems to be pretty close to what you're after.

A: The word you are see
king is: Eisegesis often confused with: Exegesis.

A: One word I can think of is
connotation
an idea or feeling which a word invokes for a person in addition to its literal or primary meaning.

A: This one's a little more folksy, but "painting a bullseye on a barn" refers to the Texas Sharpshooter Fallacy, which

refers to the tendency in human cognition to interpret patterns where none actually exist.
  The name comes from a joke about a Texan who fires some shots at the side of a barn, then paints a target centered on the biggest cluster of hits and claims to be a sharpshooter.

See also: Clustering illusion


text:
Q: Does 'git branch -u (or --set-upstream-to)' lose tracking information of all the existing remote tracking branches? I was in my 'master' branch when I thought of creating a new branch and did it by:
$ git checkout -b od_newstructure
Switched to a new branch 'od_newstructure'

The I committed few changes and added this new branch to remote and started tracking
$ git commit
$ git branch -u origin/od_newstructure
Branch od_newstructure set up to track remote branch od_newstructure from origin.
$ .. some other work including git pull and git push

I now wanted to switch back to master. So I did
git checkout master
Switched to branch 'master'

But then, master seemed not be tracking origin/master anymore!
$ git branch -vv
* master          d1db2e3 Subdivided into several namespaces
  od_newstructure d1db2e3 [origin/od_newstructure] Subdivided into several namespaces

It was also verified by a git pull
$ git pull
There is no tracking information for the current branch.
Please specify which branch you want to merge with.
See git-pull(1) for details

My question is why did the previous tracking branches lost its tracking information when I switched to a new tracking branch? Is this a default and sound behavior? Would I have to add upstream by git branch -u every time I switch to a tracking branch?


text:
Q: Android- Firebase data not showing in ArrayList I am trying to retrieve data from Firebase database. The top level node is messages and child nodes are author and message. After logging in, the chat messages are pulled from the database. ChatActivity calls the ChatListAdapter
with the following code:-
    mAdapter = new ChatListAdapter(this, mDatabaseReference);
    mChatListView.setAdapter(mAdapter);

Here mChatListView is a RecyclerView. The adapter code is as following:-
    public class ChatListAdapter extends RecyclerView.Adapter<ChatListAdapter.ViewHolder> {
    private Activity mActivity;
    private DatabaseReference mDatabaseReference;
    private ArrayList<DataSnapshot> mSnapshotList;

    private ChildEventListener mListener = new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            mSnapshotList.add(dataSnapshot);
            notifyDataSetChanged();
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    };

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView authorName, body;

        public ViewHolder(View view) {
            super(view);
            authorName = (TextView) itemView.findViewById(R.id.author);
            body = (TextView) itemView.findViewById(R.id.message);

        }
    }

    public ChatListAdapter(Activity activity, DatabaseReference ref) {
        this.mActivity = activity;
        this.mDatabaseReference = ref.child("messages");
        mDatabaseReference.addChildEventListener(mListener);
        mSnapshotList = new ArrayList<>();
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.chat_row, parent, false);

        return new ViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {

        InstantMessage message = getItem(position);
        String author = message.getAuthor();
        holder.authorName.setText(author);
        String msg = message.getMessage();
        holder.body.setText(msg);
    }

    public InstantMessage getItem(int i) {
        DataSnapshot snapshot = mSnapshotList.get(i);
        return snapshot.getValue(InstantMessage.class);
    }

    @Override
    public int getItemCount() {
        return mSnapshotList.size();
    }
}

The ChatActivity is as follows:-
    public class ChatActivity extends AppCompatActivity {

    private RecyclerView mChatListView;
    private DatabaseReference mDatabaseReference;
    private ChatListAdapter mAdapter;

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

        mDatabaseReference = FirebaseDatabase.getInstance().getReference();
        mChatListView = (RecyclerView) findViewById(R.id.chat_list_view);
    }

    @Override
    public void onStart(){
        super.onStart();
        mAdapter = new ChatListAdapter(this, mDatabaseReference);
        mChatListView.setAdapter(mAdapter);
    }

    @Override
    public void onStop() {
        super.onStop();
        mAdapter.cleanUp();
    }
}

A: Add Data in array list through Map, Example shoving the detail
Following method to fetch Data from Firebase :
public void getUsers(){
    final ArrayList arrayList=new ArrayList();
    DatabaseReference q1=FirebaseDatabase.getInstance().getReference();
    q1.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            collectiouser((Map<String,Object>)dataSnapshot.getValue());
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
    toolbar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent i=new Intent(ChatPage.this,FriendsProfile.class);
            i.putExtra("receiver",receiver);
            startActivity(i);
            finish();
        }
    });

}

Add Data into List :
private void collectiouser(Map<String, Object> value) {
    ArrayList<String> user=new ArrayList<>();
    for(Map.Entry<String,Object> entry : value.entrySet()){
        Map singleuser=(Map)entry.getValue();
        String u=entry.getKey();
        String s=singleuser.toString();
        user.add(u); // Add Data into List
    }
}

A: There are two ways in which you can solve thos problem. This is a recommended way in which you can retrieve data from a Firebase Realtime database and display it in a RecyclerView using FirebaseRecyclerAdapter and this is how you can use an ArrayAdapter.
But note, in order to use those answers you need to add Firebase-UI dependency. See here the latest versions.

A: List<Insight> insightList = new ArrayList<>();
FirebaseData mFirebaseDatabase = FirebaseDatabase.getInstance().getReference(your reference key);
mFirebaseDatabase.addValueEventListener(new ValueEventListener() {
     @Override
     public void onDataChange(DataSnapshot dataSnapshot) {
         insightList.clear();
         for (DataSnapshot noteSnapshot:dataSnapshot.getChildren(){
               Insight note = noteSnapshot.getValue(Insight.class);
               insightList.add(note);
         }
         // pass list in recyclerview
       }
           @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.d(TAG, databaseError.getMessage());
            }
        });


text:
Q: Composer package installation order Say I have package-a and package-b. I want to install these in a particular order, package-a to install first, then package-b. Is that possible?

A: The scenario you are describing is effectively a dependency. Package B depends on Package A to be installed. So make sure that package B depends on package A.
Other than that, no guarantees are given for order.


text:
Q: Return to sheet where button was pushed I have the following macro that selects cell A3 in every sheet:
Sub test ()
Sheet1.Select
Range("A3").Select
Sheet2.Select
Range("A3").Select
Sheet3.Select
Range("A3").Select
End Sub

In each of the sheets I have a button that is linked to this macro.
If you are in sheet2 and you click on the button in every sheet
the cell A3 will be selected and in the end you will be in sheet3 although
you pushed the button in sheet2 since the macro ends with sheet3.
However, I want that once the macro did run you are in the sheet in which you pushed the button. Do you have any idea how to solve this?

A: Check this
Sub test()
Dim sht_name As String
sht_name = ActiveSheet.Name
Sheet1.Select
Range("A3").Select
Sheet2.Select
Range("A3").Select
Sheet3.Select
Range("A3").Select
Sheets(sht_name).Activate
End Sub

A: Sub test()
strME = Application.ActiveSheet.Name

Sheet1.Select
Range("A3").Select
Sheet2.Select
Range("A3").Select
Sheet3.Select
Range("A3").Select

Application.Sheets(strME).Select

End Sub


text:
Q: Function that acts like a decorator, but uses mutation instead of wrapping? A decorator adds additional functionality to an object by "wrapping" around the original value.
Is there a name for an object or function that ingests a pre-constructed object and adds additional functionality to it via mutation?.
Example:
function mutatesObjects(target) {
  target.additionalFunctionality = "I've been mutated!";
}

This is similar to a contrcutor or factory except that it is adding functionality to an object that was already created.
Is there a name for this pattern?

A: Depending on the purpose for this change, Monkey Patching might apply.
"A monkey patch is a way for a program to extend or modify supporting system software locally (affecting only the running instance of the program)."

A: I would suggest Plugin name as a reference to jquery plugins.
But I also think this is actually an anti-pattern in most cases. This not only breaks the encapsulation (one of the main concepts in OOP), it goes even beyond it and changes object functionality.
Imagine a simple case where you do something like:
doSomething(object)

In the best case you can hope the object state was not changed. In the worse case you can suspect that it was mutated and it's state changed.
It's really unexpected if you get something completely different with new methods or properties.
But of course, there can be good usages (like jquery plugins).


text:
Q: Gstreamer how to get element information from STATE_CHANGED message from the bus I am working with Gstreamer and its Python bindings. Consider the following bus_call function:
import sys
from gi.repository import Gst

def bus_call(bus, message, loop):
    t = message.type
    if t == Gst.MessageType.EOS:
        print("Bus call: End-of-stream\n")
        # loop.quit()
    elif t == Gst.MessageType.WARNING:
        err, debug = message.parse_warning()
        sys.stderr.write("Bus call: Warning: %s: %s\n" % (err, debug))
    elif t == Gst.MessageType.ERROR:
        err, debug = message.parse_error()
        sys.stderr.write("Bus call: Error: %s: %s\n" % (err, debug))
        # loop.quit()
    elif t == Gst.MessageType.BUFFERING:
        print("Bus call: Buffering\n")
    elif t == Gst.MessageType.STATE_CHANGED:
        old_state, new_state, pending_state = message.parse_state_changed()
        print((
            f"Bus call: Pipeline state changed from {old_state.value_nick} to {new_state.value_nick} "
            f"(pending {pending_state.value_nick})"
        ))
    else:
        print(f"Bus call: {message}\n")
    return True

When the message type is Gst.MessageType.STATE_CHANGED, how can I retrieve the element that has changed the state?

A: Not sure I correctly understand, but you may try something like:
old_state, new_state, pending_state = message.parse_state_changed()
print('%s : State changed from %s to %s' % (message.src.get_name(), old_state, new_state))


text:
Q: How do I convert spatial points to neighbours list in R? I am trying to convert some spatial points to a neighbour list in R. I have a list of individual animal species occurrences worldwide, each one with a single value of latitude and longitude. As I am trying to conduct a statistical analysis of a possible spatial autocorrelation, I would need to create an object class nb (neighbour list), but I do not know how to do this conversion in R.
My data looks like:
SPECIES   LATITUDE    LONGITUDE
species A     -85           134
species B      34             2
species B      42             3
species B      45             5
species C      -2            80
species C      -5            79
(...)

The dataset also contains other columns with the values of certain variables, but I think this is not important for my purpose.
Any help will be appreciated.

A: Package spdep have different methods to calculate neighbors list. It's better to first convert your data frame to a spatial object. That will ensure that the coordinates will be correctly interpreted.
dataSp <- read.table( text = '
  SPECIES   LATITUDE    LONGITUDE
  speciesA     -85           134
  speciesB      34             2
  speciesB      42             3
  speciesB      45             5
  speciesC      -2            80
  speciesC      -5            79',
  header = TRUE )

library(spdep)

coordinates(dataSp) <- ~ LONGITUDE + LATITUDE

Neighbors are usually computed from polygons, since shared boundaries is the main criteria. You can generate polygons using techniques like Voronoi and Thiessen, but it's not necessary. Instead of using boundaries, you can use k nearest as criteria:
knea <- knearneigh(coordinates(dataSp), longlat = TRUE)
neib <- knn2nb(knea)

Or use distance range:
neib <- dnearneigh(coordinates(dataSp), 0, 10, longlat = TRUE)


text:
Q: Find the sum of the series $\sum_{k=1}^\infty \frac{(-1)^{k-1}}{2^kk}$
Find the sum of the series $\sum_{k=1}^\infty \frac{(-1)^{k-1}}{2^kk}$

Whether I can find some $x$ such that $f(x)=\sum_{k=1}^\infty \frac{(-1)^{k-1}}{2^kk}$ ,then find the closed form of $f(x)$.
And substitute x into the closed of $f(x)$ to find out the sum?

A: You can manipulate a geometric series to look like that series.
$$\sum_n^\infty q^n=\frac{1}{1-q}$$
Substituting $-x=q$
$$\sum_n^\infty (-1)^n x^{n}=\frac{1}{1+x}$$
Dividing both sides by $x$.
$$\sum_n^\infty (-1)^n x^{n-1}=\frac{1}{x(1+x)}$$
You can now integrate and substitute $x=1/2$, can you finish this?

A: For any $x$ such that $|x|<1$ we have $\sum_{n\geq 1}\left(-\frac{x}{2}\right)^{n-1}=\frac{1}{1+\frac{x}{2}}$, and by applying $\frac{1}{2}\int_{0}^{1}\left(\ldots\right)\,dx$ to both sides we get:
$$ \sum_{n\geq 1}\frac{(-1)^{n-1}}{n 2^{n}} = \int_{0}^{1}\frac{dx}{2+x} = \log\left(\frac{3}{2}\right).$$

A: $$\sum_{k=1}^\infty\dfrac{(-1)^{k-1}}{k2^k}=-\sum_{k=1}^\infty\dfrac{(-1/2)^k}k$$
Now for $\displaystyle-1\le x<1,\ln(1-x)=-\sum_{k=1}^\infty\dfrac{x^k}k$


text:
Q: keypress event vs click event My eyes are destroyed so this question will be specific to keyboard events.
When I define a handler for a click event for a button, like this:
$("#button").on("click", function() {
    alert("clicked");
});

Since I can't use the mouse (and I think most web applications use the click event to execute an html element), I tested this event by going to the button and pressing enter on it. The event fired successfully. Since then I came to believe that pressing the enter key simulates a click event to an html element. I've been executing submit buttons lots of times so there is no reason to believe that is not the case.
Now, I am creating a textbox which needs to be populated with a value when accessed. So I did this:
$("#text").on("click", function() {
    alert("clicked");
});

However, pressing enter on it no longer works, no value appears. But when some other human clicks the element using a mouse, the event fires successfully.
Here is the code I am working on:
I am using jquery-ui's autocomplete. I'd like the textbox to be populated when the user goes inside the textbox. I press enter to go inside...
$( "#tags" ).autocomplete({
    source: names,
    minLength: 0,
    select: function( event, ui ) {
        var index = names.indexOf($(this).prop("value"));
        $(this).val("");
        $("#selected").append("
"+names[index]+
        "<input type='hidden' id='id' value='"+ids[index]+"'/>"+
        "remove
");
        ids.splice(index, 1);
        names.splice(index, 1);
        return false;
    }
}).on("click", function(event) {
    $(this).autocomplete("search", $(this).val());
});

Is there really a difference between pressing enter and a mouse click? What should I do?

A: Catching the keypress event and testing for 'enter' is the best way to deal with this. The reason why the buttons execute on enter without this is due to them being of type 'submit'.

A: Basically, it is not a good idea to fire onClick on edit boxes since you won't have keyboard alternatives this way without more efforts.
As you are blind like me (I supposed this from your question), you are probably using some screen reading software. In screen readers, Enter usually simulates mouse click but. But JAWS for Windows, for instance, adds even more flexibility allowing you to adjust what to do when Enter key is pressed: simulate a mouse click or send Enter to the system.
So, in your case I'd make a button that would fire your onClick event.


text:
Q: Ngrx: How to monitor a single object in array for change This is how I am monitoring a selectedUser in array. However, if any other element of the array is updated the watchSelectedUser observable is triggered where as it should only be triggered on the update to selectedUser object.
--- Current code ---
Reducer Code:
export const userAdapter = createEntityAdapter<UserModel>({
  selectId: x => x.UserId
});
export interface UserlistState extends EntityState<UserModel>{
  selectedUserId: number
};

export const initialState: UserlistState = userAdapter.getInitialState({
  selectedUserId: undefined,
});

const getSelectedUserIdState = (state) => {
  return state.userlist.selectedUserId
};
export const getSelectedUserId = createSelector(getSelectedUserIdState,userId => userId);

Subscribing to a selectedUser model change
watchSelectedUser = (): Observable<UserModel>=>{
        return this.userlistStore.select(userlistReducers.selectAll).pipe(map(users => {
            return users.find(x=> x.UserId == this.getSelectedUserId());
        }));
    }

A: I would recommend converting your data structure from an array into a collection / key-value pair for each user.
This will allow you to select(userlistReducers[_id]) and means that you will not have other UserModel objects altering an array that they are contained within.
state: ApplicationState = {
   users: {
      'd27f23d67f23i7d23': {name: 'Nate, '_id': 'd27f23d67f23i7d23'},
      '87387387g3487gd83': {name: 'Shyamal, '_id': '87387387g3487gd83'}
   }
}

watchSelectedUser = (): Observable <UserModel> => {
    return this.userlistStore.select(userReducers['87387387g3487gd83']);
}

This is a bit crude and I'm not sure if the select() logic is perfect, but you can now access just one user at a time. It will require a bit of refactor and a new entity adapter, but it is IMO a better structure.