Q: Displaying data from a SQLiteDatabase with adapter Code for the DBHelper class:
class DBHelper extends SQLiteOpenHelper {

    private static final String DATABASE_PATH = Environment.getDataDirectory()
            + "/data/test.data/databases/";
    private static final String DATABASE_NAME = "test.sqlite3";
    private static final int SCHEMA_VERSION = 1;
    public static final String TABLE_NAME = "terran_builds";
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_NAME = "name";
    public static final String COLUMN_OVERVIEW = "overview";

    public SQLiteDatabase dbSqlite;

    private final Context myContext;

    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, SCHEMA_VERSION);
        this.myContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public void createDatabase() {
        createDB();
    }

    private void createDB() {

        boolean dbExist = DBExists();
        if (!dbExist) {

            this.getReadableDatabase();

            copyDBFromResource();

        }

    }

    private boolean DBExists() {
        SQLiteDatabase db = null;

        try {
            String databasePath = DATABASE_PATH + DATABASE_NAME;
            db = SQLiteDatabase.openDatabase(databasePath, null,
                    SQLiteDatabase.OPEN_READWRITE);
            db.setLocale(Locale.getDefault());
            db.setLockingEnabled(true);
            db.setVersion(1);
        } catch (SQLiteException e) {
            Log.e("SqlHelper", "database not found");
        }

        if (db != null) {

            db.close();
        }

        return db != null ? true : false;
    }

    private void copyDBFromResource() {

        InputStream inputStream = null;
        OutputStream outStream = null;
        String dbFilePath = DATABASE_PATH + DATABASE_NAME;

        try {

            inputStream = myContext.getAssets().open(DATABASE_NAME);

            outStream = new FileOutputStream(dbFilePath);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                outStream.write(buffer, 0, length);
            }
            outStream.flush();
            outStream.close();
            inputStream.close();
        } catch (IOException e) {

            throw new Error("Problem copying database from resource file.");
        }

    }

    public void openDataBase() throws SQLException {

        String myPath = DATABASE_PATH + DATABASE_NAME;
        dbSqlite = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READWRITE);
    }

    @Override
    public synchronized void close() {
        // TODO Auto-generated method stub

        if (dbSqlite != null) {
            dbSqlite.close();
        }
        super.close();
    }

    public Cursor getTerran() {

        SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

        queryBuilder.setTables(TABLE_NAME);

        String[] asColumnsToReturn = new String[] { COLUMN_ID, COLUMN_NAME,
                COLUMN_OVERVIEW };

        Cursor mCursor = queryBuilder.query(dbSqlite, asColumnsToReturn, null,
                null, null, null, "name");

        return mCursor;
    }

    public String getName(Cursor c) {
        return (c.getString(1));
    }
}

Code for the Terran activity:
public class Terran extends Activity {

    private DBHelper dbHelp = null;
    private Cursor ourCursor = null;
    private DBAdapter adapter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        try {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.terran_layout);

            // this is our listview element, obtained by id from our xml layout
            ListView myListView = (ListView) findViewById(R.id.tvterran);

            // create our database helper
            dbHelp = new DBHelper(this);
            // we call the create right afther initializing helper
            dbHelp.createDatabase();
            // open the database
            dbHelp.openDataBase();
            // get our cursor
            ourCursor = dbHelp.getTerran();

            // tell android to start managing cursor
            startManagingCursor(ourCursor);
            // create our adapter
            adapter = new DBAdapter(ourCursor);
            // set the adapter
            myListView.setAdapter(adapter);

        } catch (Exception e) {

            // send real error message
            Log.e("ERROR", "ERROR IN CODE: " + e.toString());

            e.printStackTrace();
        }
    }

    class DBAdapter extends CursorAdapter {
        DBAdapter(Cursor c) {
            super(Terran.this, c);
        }

        @Override
        public void bindView(View row, Context ctxt, Cursor c) {
            // TODO Auto-generated method stub
            terranHolder holder = (terranHolder) row.getTag();
            holder.populateFrom(c, dbHelp);

        }

        @Override
        public View newView(Context ctxt, Cursor c, ViewGroup parent) {
            // TODO Auto-generated method stub
            LayoutInflater inflater = getLayoutInflater();
            View row = inflater.inflate(R.layout.terran_layout, parent, false);
            terranHolder holder = new terranHolder(row);
            row.setTag(holder);
            return (row);
        }
    }

    static class terranHolder {
        private TextView name = null;

        terranHolder(View row) {
            name = (TextView) row.findViewById(R.id.tvterran);
        }

        void populateFrom(Cursor c, DBHelper r) {
            name.setText(r.getName(c));
        }
    }

}

Logcat exception:
01-30 20:07:13.765: E/ERROR(7153): ERROR IN CODE: java.lang.NullPointerException
01-30 20:07:13.775: W/System.err(7153): java.lang.NullPointerException
01-30 20:07:13.775: W/System.err(7153):     at com.subdeveloper.starcraftbuilds.Terran.onCreate(Terran.java:46)
01-30 20:07:13.775: W/System.err(7153):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-30 20:07:13.775: W/System.err(7153):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1623)
01-30 20:07:13.775: W/System.err(7153):     at android.app.ActivityThread.startActivityNow(ActivityThread.java:1499)
01-30 20:07:13.775: W/System.err(7153):     at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:127)
01-30 20:07:13.775: W/System.err(7153):     at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:339)
01-30 20:07:13.775: W/System.err(7153):     at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:731)
01-30 20:07:13.775: W/System.err(7153):     at android.widget.TabHost.setCurrentTab(TabHost.java:403)
01-30 20:07:13.775: W/System.err(7153):     at android.widget.TabHost.addTab(TabHost.java:242)

I can't get the ListView to generate from the query results. From my debugging I understand that the error is in the Terran class on line 46. I can't figure out what is wrong. Tested with other database, database connection works.

A: com.subdeveloper.starcraftbuilds.Terran.onCreate(Terran.java:46)
put a break point in and run the debugger. Something is null, and I'm guessing it's the list. It's on like 46.
Btw, I'm gold random player. Used to be high diamond Toss. Good luck with the project.

A: Your ListView is null that means that either don't have a ListView with that id in your layout or android didn't generate the proper id for the list and you have an old one that is incorrect.
Try to refresh the project, delete the R class from the folder gen so that the ID are generated again, restart the IDE.


Q: Prolog different variable, same value If you query e.g.
?- X = 10, Y = 10, Z = 10.

The output is
X = Y, Y = Z, Z = 10.

But my X is totally different from Y, they just happen to accidentally both be 10, so it doesn't seem clear/logical to display it that way.
Can i make it look like this instead?:
X = 10, Y = 10, Z = 10.

A: I share your preference. Note that different Prolog systems have different top levels...
SWI-Prolog gives me this:

$ swipl
?- X = 10, Y = 10, Z = 10.
X = Y, Y = Z, Z = 10.

Traella Prolog says something quite similar:

$ tpl
?- X = 10, Y = 10, Z = 10.
   X = 10, Y = X, Z = X.

GNU-Prolog and Scryer Prolog, however, give me answers that I like better:

$ gprolog
| ?- X = 10, Y = 10, Z = 10.

X = 10
Y = 10
Z = 10

yes

$ scryer-prolog
?- X = 10, Y = 10, Z = 10.
   X = 10, Y = 10, Z = 10.

A: change([H,Q,D,N,P]) :-member(H,[0,1,2]), /* Half-dollars /member(Q,[0,1,2,3,4]), / quarters /member(D,[0,1,2,3,4,5,6,7,8,9,10]) , / dimes /member(N,[0,1,2,3,4,5,6,7,8,9,10, / nickels /11,12,13,14,15,16,17,18,19,20]),S is 50H + 25Q +10D + 5*N,S =< 100,P is 100-S.


Q: Compiling ocaml can't find module in opam library, Js.ml in js_from_ocaml Trying to compile ocaml into javascript.
Some OCaml code I have put in https://gist.github.com/larsr/6b3cd6f62d54d56e3f9a uses the menhir parser, and the js_of_ocaml library together.   I've installed them with opam.
The code comes from http://toss.sourceforge.net/ocaml.html.
It is a lexer and a parser and a main program that calls them.
The goal is to generate a javascript program from the ocaml code and run it from within a web page.
I am able to compile the first Main program using only menhir with make from the Makefile in the repo, which does
ocamlbuild -use-menhir -menhir "menhir --external-tokens Lexer" Main.native

and I can compile a program that only uses js_of_ocaml, with make Formula.js, which does
ocamlfind ocamlc -package js_of_ocaml -package js_of_ocaml.syntax \
      -syntax camlp4o -linkpkg -o Formula.byte Formula.ml
js_of_ocaml Formula.byte

My problem is that now I'm unable to get ocamlfind to build JsClient.js, with
make JsClient.js

so I can't produce javascript code for 'JsClient.ml'.  The error I get is that the compiler can't find the module Js which is used by JsClient.  The code seems to be in the opam library in my home-dir, but I can't get the right arguments to ocamlfind to use it.
How do I compile the JsClient.ml into JsClient.js?

A: The rule that you use to compile the JsClient.ml file is not good.
JsClient.byte:
    ocamlbuild -use-menhir -menhir "menhir --external-tokens Lexer"

As you said, this file use the module Js so you need to compile with the same way than the file Formula.ml :
ocamlfind ocamlc -package js_of_ocaml -package js_of_ocaml.syntax \
      -syntax camlp4o -linkpkg -o JsClient.byte JsClient.ml
js_of_ocaml JSClient.byte


Q: Why are my classes not found even though my imports are correct? The Classes ADSTool and the Class PPM are not found by my compiler. I'm using Eclipse Helios. The docs say that I have to import java.lang.Object for both, and I imported java.lang*; I can't see why this isn't working.

A:
The docs say that I have to import java.lang.Object for both, and I imported java.lang*

Any documentation that tells you that you have to import classes in java.lang is blatantly wrong.  The classes in java.lang are implicitly imported.

In fact, I suspect that your problem is that you need to add the JAR files containing those two classes (ADSTool and PPM) to the build path of your Eclipse project.  If the classes are not available on the build path, the Eclipse compiler won't find them.

A: check Project->Properties->Java Build Path
did you include JRE System Library in Libraries Tab?

A: Import java.lang.*, not java.lang*. The second dot matters; without it, the compiler can get confused about what you're actually trying to import.


Q: How to access azure web app console or kudu console locally using putty or mac terminal? I have hosted a web app in azure and I am able to use console through kudu console or azure dashboard but for better development workflow, accessing it through mac terminal is essential.
I don't know how to access azure's web console (not azure server management console) through mac terminal.
Its not linux vm. Its default web app using windows.

A: No, it is not possible.
On Mac, if you want to access Kudu Console, you could use a browser open http://<yoursite>.scm.azurewebsites.net. But you could not do it on mac terminal.
On Mac terminal, you could call Kudu API to manage your web app, see this link.
On Mac terminal, you also could use Azure CLI 2.0 to manage your web app.

A: You're trying to do something web apps are not designed to do. You cannot rdp/ssh into a web app. That's what the kudu web console / powershell is for, if you need a command-line for something.
If you need to move specific app or data content to a web app, it's done through the version control provider you wire up to it (e.g. git), or ftp.


Q: Why doesn't OpenSSH work but paramiko does when using ansible playbook? I am running ansible-playbook with
ansible-playbook -u vagrant -i .vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory playbook.yml -c ssh

This throws error fatal: [default]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: ", "unreachable": true}
However, it works fine after adding connection flag -c paramiko.
ansible-playbook -u vagrant -i .vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory playbook.yml -c paramiko

Question: what could be the reasons the default connection (OpenSSH) does not work but paramiko does? How can I debug it and make OpenSSH works too?
I would like to understand the reasons. Please let me know if you need more information other than

*

*local: ubuntu 20.04

*remote: CentOS 7

*ansible [core 2.13.6]

When running with verbose mode
ansible-playbook -u vagrant -i .vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory playbook.yml -c ssh -vvv

The output is
/usr/lib/python3/dist-packages/paramiko/transport.py:236: CryptographyDeprecationWarning: Blowfish has been deprecated
  "class": algorithms.Blowfish,
ansible-playbook [core 2.13.6]
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/home/john/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /home/john/.local/lib/python3.10/site-packages/ansible
  ansible collection location = /home/john/.ansible/collections:/usr/share/ansible/collections
  executable location = /usr/bin/ansible-playbook
  python version = 3.10.6 (main, Nov  2 2022, 18:53:38) [GCC 11.3.0]
  jinja version = 3.1.2
  libyaml = True
Using /etc/ansible/ansible.cfg as config file
host_list declined parsing /home/john/test/.vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory as it did not pass its verify_file() method
script declined parsing /home/john/test/.vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory as it did not pass its verify_file() method
auto declined parsing /home/john/test/.vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory as it did not pass its verify_file() method
Parsed /home/john/test/.vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory inventory source with ini plugin
Skipping callback 'default', as we already have a stdout callback.
Skipping callback 'minimal', as we already have a stdout callback.
Skipping callback 'oneline', as we already have a stdout callback.

PLAYBOOK: playbook.yml *************************************************************************************************
1 plays in playbook.yml

PLAY [all] *************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************
task path: /home/john/test/playbook.yml:2
<127.0.0.1> ESTABLISH SSH CONNECTION FOR USER: vagrant
<127.0.0.1> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o Port=2222 -o 'IdentityFile="/home/john/test/.vagrant/machines/default/virtualbox/private_key"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o 'User="vagrant"' -o ConnectTimeout=10 -o 'ControlPath="/home/john/.ansible/cp/055b8f4af0"' 127.0.0.1 '/bin/sh -c '"'"'echo ~vagrant && sleep 0'"'"''
<127.0.0.1> (255, b'/home/vagrant\n', b'')
fatal: [default]: UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: ",
    "unreachable": true
}

PLAY RECAP *************************************************************************************************************
default                    : ok=0    changed=0    unreachable=1    failed=0    skipped=0    rescued=0    ignored=0

A: The command that Ansible is running is returning 255 as the return code, for some reason:
<127.0.0.1> (255, b'/home/vagrant\n', b'')

OpenSSH uses this return code for connection errors but does not prevent remote processes from returning it, and Ansible can't tell the difference between a 255 that is a genuine connection error and whatever happened here.
Paramiko is a Python library and raises errors using native Python error handling, so it doesn't have the same issue.
The only way to get Ansible's OpenSSH plugin working is to figure out why '/bin/sh -c '"'"'echo ~vagrant && sleep 0'"'"' is returning 255 on your target host, and fix that issue.


Q: Return content of read-only  Here is the HTML:

<input type="text" maxlength="30" size="30"
class="ax-terminal-inputField ax_x20i" readonly="readonly" style="width: 240px;">

Here is some of my casper code:
var x = require('casper').selectXPath;
....//truncated for shortness//....
    casper.echo(x('//*[@id="ifldf14"]/input').value);

The result in undefined. I tried .value, .text, .innerHTML, but they all come up undefined when run. How do I get the content of the input field?

A: DOM context
CasperJS a sandboxed DOM context (page context). It is only there where you can access DOM elements directly. The page context is inside of the casper.evaluate() callback. Everything else about a DOM element is only a representation of it, because DOM nodes cannot be passed to the outside context.
Accessing input value
There are a lot of ways to get information out of the DOM, but DOM nodes cannot be printed to the console as-is. Here are two ways to get the input value.

*

*You can use casper.evaluate(). Since you want to use an XPath expression, you can use __utils__.getElementByXPath() helper function that is injected by CasperJS into the page:
var value = casper.evaluate(function(xpathexpr){
    return __utils__.getElementByXPath(xpathexpr).value;
}, '//*[@id="ifldf14"]/input');
casper.echo("value: " + value);

*If the input field is inside of a form and if the element has a name attribute, then you can use casper.getFormValues() and get the value using the name of the field.
casper.echo(casper.getFormValues('form').nameHere);

XPath helper utility
var x = require('casper').selectXPath;

Is only a little helper that transforms a string to an object with the properties type and path. It's only used in CasperJS internally to represent XPaths. The distinction is necessary, because CasperJS supports both CSS selectors and XPath expressions. Both of them are simple strings initially, but are executed differently.

A: The problem was I was not using jQuery to get my value out. Thanks for everyone's input!


Q: Tomcat: not appending trailing "/" when finding a directory I deployed a .war archive in Tomcat 7.0.22 (Java 1.6, MacOS Lion). The war is called "myapp.war" and so Tomcat is serving http://localhost/myapp (having expanded the war in /webapps/myapp). This is the usual behavious
When accessing a url that corresponds to a directory, it should append "/" . For having static files (.css, .js..) working correctly, this is needed, but while with the sample sites that ship with Tomcat this works (for example visiting http://127.0.0.1:8080/examples suddenly remaps to http://127.0.0.1:8080/examples/), on my site tomcat doesn't add any "/" making the search for static files broken. When manually calling localhost:8080/myapp/ (<-- I add the slash) everything works fine.
What should be going on? Mind that I haven't touched any Tomcat setting, I'm just experimenting with what comes out directly from Apache's zip file!
Thanks

A: Firstly you should explain more about your situation. As @mico has told here is a solution:
<filter>
    <filter-name>Jersey Filter</filter-name>
     <filter-class>com.sun.jersey.spi.container.servlet.ServletContainer</filter-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>your package name(s)</param-value>
        </init-param>
    <init-param>
            <param-name>com.sun.jersey.config.property.WebPageContentRegex</param-name>
            <param-value>.*\.jsp|.*\.css|.*\.png|.*\.js|.*\.gif|.*\.jpg</param-value>
        </init-param>
</filter>

<filter-mapping>
    <filter-name>Jersey Filter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
</filter-mapping>

 <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

The idea on solution based on:

defining Jersey ServletContainer as a filter instead of a servlet

Here you can read more: http://jersey.576304.n2.nabble.com/Tomcat-trailing-slashes-and-welcome-files-td4684494.html
Here says that: If you have a '/*' mapping, then Tomcat won't redirect
One more: you should see how tomcat logs your request and decide the main problem.


Q: How to use npm installed package in laravel application? I want to use select2 package in my laravel 5 application.
I installed it using npm install select2 and also ran npm run dev. It appears in my node_modules folder.
But how do I actually refer to the files - js and scss of select2 package in my app.blade.php ?

A: I suggest an answer to this thread because it isn't marked as resolved and despite the answer given it didn't allow me to resolve the issue as of the time of reading this.

Resources

*

*select2.org

*npm

I have since found a functional solution of which here are the details in relation to the question of the OP. Verified and working with Laravel 8

*

*Install package via npm
npm install select2

*Edit /resources/js/app.js to import javascript from package
require('./bootstrap');

/* ... */
require('select2');  // Add this
/* ... */

Alpine.start();

*Edit /resources/css/app.css to import styles from package
/* ... */
@import 'select2'; // Add this

*Edit /resources/js/bootstrap.js to enable the use of .select2();
window._ = require('lodash');
/* ... */
window.select2 = require('select2'); // Add this

*Run NPM
npm run dev
npm run watch

*NPM result in my case

Laravel Mix v6.0.39
✔ Compiled Successfully in 2982ms
√ Mix: Compiled successfully in 3.05s
webpack compiled successfully

Testing
According to configuration documentation
HTML
<input type="text" class="form-control js-example-basic-single">

JS
<script type="text/javascript">
  $(document).ready(function () {

    $('.js-example-basic-single').select2({
      placeholder: 'Select2 testing purpose'
    });

  });
</script>

Render

A: Run npm run watch , because keeps track of all changes in .js.
In app.js add
require('select2/dist/js/select2');

In app.blade.php example:
<div>
   <select class="js-select2 css-select2-50">
                    <option>1</option>
   </select>
</div>


Q: How to fix error with resource routes definition Here https://laravel.com/docs/5.7/controllers#resource-controllers I read that defining a resource
I had post/put methods :
POST    /photos store   photos.store
...
PUT/PATCH   /photos/{photo} update  photos.update

but defining in routes/web.php next resource routes:
Route::resource('site-subscriptions', 'Admin\SiteSubscriptionsController', [ 'except' => [] ] )->middleware('WorkTextString');

with form definition :
   <form method="POST" action="http://local-votes.com/admin/site-subscriptions/store" accept-charset="UTF-8" id="form_site_subscription_edit" enctype="multipart/form-data">
            <input type="hidden" name="_token" value="X7rzFjRq4o4TeA67FmkQTMI9ApjygM3ovE1C14i2">

I got error for POST :
  "message": "",
    "exception": "Symfony\\Component\\HttpKernel\\Exception\\MethodNotAllowedHttpException",
    "file": "/mnt/_work_sdb8/wwwroot/lar/votes/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php",
    "line": 255,

Have I error in my web.php definition error ?
Thanks!

A: if you are working with blade, getting a working link this way is bad, you should use laravel helpers like the following:
<form method="POST" action="{{route('site-subscriptions.store')}}" accept-charset="UTF-8" id="form_site_subscription_edit" enctype="multipart/form-data">

this way you are making sure that the links are correct even if you change your APP_URL in the deployment.
what actually done, is calling route helper function to get the URL for you by the route's name.
from the docs:

route():
The route function generates a URL for the given named route:
$url = route('routeName');
If the route accepts parameters, you may pass them as the second argument to the method:
$url = route('routeName', ['id' => 1]);
By default, the route function generates an absolute URL. If you wish to generate a relative URL, you may pass false as the third argument:
$url = route('routeName', ['id' => 1], false);


Q: How To Obtain Monthly Data from Quarterly Data Problem:
I have quarterly level data. I need to perform a month over month analysis. Is there a function, or a ggplot feature that will interpolate the quarterly data and fill in monthly data?
Reference Data:
dput(HPF[1:25, ])
structure(list(region = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), path = c(1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
), date = structure(c(16116, 16205, 16297, 16389, 16481, 16570,
16662, 16754, 16846, 16936, 17028, 17120, 17212, 17301, 17393,
17485, 17577, 17666, 17758, 17850, 17942, 18031, 18123, 18215,
18307), class = "Date"), index_value = c(1, 1.033852765, 1.041697122,
1.038876363, 1.041043093, 1.060900982, 1.073728928, 1.075879441,
1.080898915, 1.10368893, 1.119240863, 1.122827602, 1.128639801,
1.15275796, 1.169021733, 1.172707492, 1.178666441, 1.203634882,
1.220348482, 1.223890323, 1.229770019, 1.255791539, 1.273560554,
1.278236959, 1.285508086), index = c(0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24), counter = 1:25, BaseQoQ = c(0, 0.033852765, 0.00758749917354051,
-0.00270784947028013, 0.00208564760655761, 0.0190749923163842,
0.0120915582298895, 0.00200284535874973, 0.00466546139717505,
0.0210843166587877, 0.0140908661646175, 0.00320461762840418,
0.00517639483536669, 0.0213692260175751, 0.0141085757499344,
0.00315285755256367, 0.00508136004984272, 0.0211836361259394,
0.0138859385432799, 0.00290231933930496, 0.00480410367620832,
0.021159663675294, 0.0141496533844698, 0.00367191413499146, 0.00568840303732765
), fdate = structure(c(16116, 16205, 16297, 16389, 16481, 16570,
16662, 16754, 16846, 16936, 17028, 17120, 17212, 17301, 17393,
17485, 17577, 17666, 17758, 17850, 17942, 18031, 18123, 18215,
18307), class = "Date"), StressC = c(0.99749, 1.031342765, 1.039187122,
1.036366363, 1.038533093, 1.058390982, 1.071218928, 1.073369441,
1.078388915, 1.10117893, 1.116730863, 1.120317602, 1.126129801,
1.15024796, 1.166511733, 1.170197492, 1.176156441, 1.201124882,
1.217838482, 1.221380323, 1.229770019, 1.255791539, 1.273560554,
1.278236959, 1.285508086), StressQoQ = c(0, 0.0339379492526242,
0.00760596502560418, -0.0027143898728953, 0.00209069888540969,
0.0191210941026796, 0.0121202336548254, 0.00200753827606026,
0.00467637125510434, 0.0211333913794913, 0.0141229845362187,
0.00321182042946733, 0.00518799221722843, 0.021416855302633,
0.0141393626118667, 0.00315964160130755, 0.00509225924746737,
0.021228843485116, 0.0139149560969629, 0.00290830110260876, 0.0068690282969297,
0.021159663675294, 0.0141496533844698, 0.00367191413499146, 0.00568840303732765
)), .Names = c("region", "path", "date", "index_value", "index",
"counter", "BaseQoQ", "fdate", "StressC", "StressQoQ"), row.names = c(NA,
-25L), class = c("grouped_df", "tbl_df", "tbl", "data.frame"), vars = "region", drop = TRUE, indices = list(
    0:24), group_sizes = 25L, biggest_group_size = 25L, labels = structure(list(
    region = 1), row.names = c(NA, -1L), class = "data.frame", vars = "region", drop = TRUE, .Names = "region"))

Any insight would be much appreciated! I hope the data I have provided is enough to offer suggestions.
Goal:
I only need to plot/graph the monthly information, I do not need it reference in a data.frame.

A: So this is what you can do:
1) create a vector of dates to interpolate
months <- lapply(X = data$date, FUN = seq.Date, by = "month", length.out = 3)
months <- data.frame(date = do.call(what = c, months))

2) left join you date.frame to the months data.frame to create NAs for extrapolation
library(dplyr)
monthly_data <- left_join(x = months, y = data, by = "date")

3) use one of na.locf() na.appox() na.spline() to interpolate f.ex StressC
library(zoo)
monthly_data$StressC <- na.spline(object = monthly_data$StressC)

Note: the extrapolations above are

*

*na.locf() - most recent point

*na.appox() - linear

*na.spline() - spline (often used in graphics)

Run the following (before interpolation) to see the difference:
plot(x = monthly_data$StressC, ylab = "StressC", xlab="", xaxt = "n")
lines(x = na.locf(monthly_data$StressC), col = "red")
lines(x = na.approx(monthly_data$StressC), col = "green")
lines(x = na.spline(monthly_data$StressC), col = "blue")

Can also do something like this to get gglot:
ggplot(monthly_data, aes(x=date)) +
  geom_point(aes(y = StressC), colour="black") +
  geom_line(aes(y = na.locf(StressC)), col="red") +
  geom_line(aes(y = na.spline(StressC)), col="red")


Q: Json file to Room Db I am a newbie on Android Development.I have a json file formatted like this:
"users": [{
    "id": "1",
    "name": "Vanessa",
    "profilepic": "https://.."
  },...
]

I am creating room database but how can I record this user json file into it. I heard about gson but I could not find any solution for my problem

A: For this you need to first create a model that can parse this kind of json for you. you can use a pretty neat plugin that I have been sing called json to kotlin class.
Steps to install:

*

*Go to file->settings->plugins

*search for json to kotlin and install

*now just like you make a new file there will be a new option paste your json and give it a name and now it automatically generates a model for you.

*Also I will recommend you to watch some tutorials on youtube, my favorite content creator is Philip Lackener he has a very good tutorial on roomdb

I am also new to android development so i get it.
I recommend you to go through a beginner playlist it will really help you get the basics. you also need to see basics of roomdb because what you are asking is really basics of roomdb.


Q: NiFi ListenHTTP processor: Uses an unsupported protocol I have configured a ListenHTTP 1.7.0 processor in NiFi 1.7.0-RC1. It is listening on a custom port behind a reverse proxy. I have configured a StandardRestrictedSSLContextService with a JKS keystore and have added the keystore password. We have not configured the truststore as we don't expect to need mutual TLS. The certificate is signed by an internal enterprise CA and is (or should be!) trusted by the client.
When I test this with Chrome I receive the following:

This site can’t provide a secure connection
my.server uses an unsupported protocol.
ERR_SSL_VERSION_OR_CIPHER_MISMATCH
Unsupported protocol
The client and server don't support a common SSL protocol version or cipher suite.

Troubleshooting:

*

*We have tried both TLS and TLSv1.2 in the ListenHTTP processor.

*We have treid using curl (Linux) and Invoke-WebRequest (Windows) but have received variations on the bad cipher/SSL version message above.

*I don't see anything in the release notes suggesting that the ListenHTTP processor changed much since 1.7.0, so I'm assuming that I don't need to upgrade NiFi.

Can anyone suggest what to try next or explain why we see this error?

I have read the following:

*

*https://www.simonellistonball.com/technology/nifi-ssl-listenhttp/

*https://cwiki.apache.org/confluence/display/NIFI/Release+Notes

*Nifi: how to make ListenHTTP work with SSL

A: What version of Java are you running on? Java 11 provides TLSv1.3, which is the default offering if you have generic TLS selected, but NiFi 1.7.0 doesn't support TLSv1.3 (and doesn't run on Java 11). So assuming you are running on Java 8, recent updates have introduced TLSv1.3 but should still provide for TLSv1.2. This can also indicate that the certificate you have provided is invalid or incompatible with the cipher suite list provided by the client. You can use $ openssl s_client -connect <host:port> -debug -state -CAfile <path_to_your_CA_cert.pem> to try diagnosing the available cipher suites & protocol versions. Adding -tls1_2 or -tls1_3, etc. will restrict the connection attempt to the specified protocol version as well.
You should definitely upgrade from NiFi 1.7.0 -- it was released over 2 years ago, has known issues, and there have been close to 2000 bug fixes and features added since, including numerous security issues. NiFi 1.12.1 is the latest released version.


Q: how to clear facebook stream cache I am using facebook publish_stream method to post feed on facebook user timeline. The post is containing the image URL and title with some description. However the posted image could be change later but that change couldn't reflect on facebook side as they had cached the image.
So I wanted to be know how could clear the facebook cache on publish stream so they can show the latest image on user timeline.

A: Once a image has been published on Facebook, FB will always show the cached version. if, however, you want to update the image for a new post, try running the URL to the Debug Tool to update Facebook's cache. Any existing posts that use this image won't be updated.
It's to prevent people from changing content once it's already shared - otherwise it won't represent what the user originally shared. This would be something spammers could easily abuse.


Q: custom dialog border is always white <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/yellow"
    android:orientation="vertical" >
     <LinearLayout
        android:id="@+id/progresscontent"
        android:layout_width="266dp"
        android:layout_height="52dp"
        android:layout_margin="8dp"
        android:background="@color/red"
        android:orientation="horizontal" >

        <ProgressBar
            android:id="@+id/progress"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="12dip"
            android:visibility="visible"
            android:padding="5dp"
            style="@android:style/Widget.ProgressBar.Inverse"/>

        <TextView
            android:id="@+id/progressmessage"
            style="@style/DialogText.Title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="10dip"
            android:paddingLeft="40dip"
            android:paddingTop="10dip"
            android:textColor="@color/codeFont"
            android:textSize="15dip" />

    </LinearLayout>

</LinearLayout>

I am trying create my own custom dialog but there is one problem here. Custom dialog border is always showing white color, what's the problem here. Any help please.

A: If you want the Dialog Border to appear in any colour you wish you have to use layout style and a theme. There is an excellent article about it here: http://blog.androgames.net/10/custom-android-dialog/


Q: C++ : Reading file and store data in multi-vector I am trying to read data file with the this format
T1: I1,I2,I5
T2: I2,I4
T3: I2,I3
T4: I1,I2,I4
T5: I1,I3
T6: I2,I3
T7: I1,I3
T8: I1,I2,I3,I5
T9: I1,I2,I3

I don't want to read the first column T1,T2,T3 ...... , but each line will be a dataset I want to start read after (space '  ' ) and end with each line and how can I separate the data according to (comma ',')
I wrote this code but it didn't work correctly and it reads the first column anyway
string CItem;

// set of elements
set< CItem > CItemSet;

//Transactions
 CItemSet CTransaction;

// set of transactions
vector< CTransaction > CTransactionSet;

ifstream inFile(inFileName);
    if (!inFile)
    {
        cout << "Failed to open input file filename:." << inFileName;
    }

CTransactionSet transSet;
    CTransaction tran;
    string txtLine;
    // read every line from the stream
    while (getline(inFile, txtLine))
    {

        istringstream txtStream(txtLine);
        string txtElement;
        // read every element from the line that is seperated by commas
        // and put it into the vector or strings

        while (getline(txtStream, txtElement, ','))
        {
            if (txtElement == ": ") break;
            else tran.insert(txtElement);
        }
        transSet.push_back(tran);
    }

A: Since you have
CTransaction tran;

outside the first while loop, items keep getting added to it. Move it inside the while loop.
CTransactionSet transSet;
string txtLine;
// read every line from the stream
while (getline(inFile, txtLine))
{
    CTransaction tran;

A: I solve the problem by doing what you said R Sahu but the most important solution is by using .ignore so we don't read the part before the ' '
CTransactionSet transSet;
    string txtLine;
    // read every line from the stream
    while (getline(inFile, txtLine))
    {
        istringstream txtStream(txtLine);
        txtStream.ignore(txtLine.length(), ' ');
        // read every element from the line that is seperated by commas
        // and put it into the vector or strings
        string txtElement;
        CTransaction tran;
        while (getline(txtStream, txtElement, ','))
        {
            tran.insert(txtElement);
        }
        transSet.push_back(tran);
    }


Q: System has not been booted with systemd ERROR when updating Postgresql in Ubuntu I've been following this link to update Postgresql on my Ubuntu-18.04 (VM running on Windows 10)
https://computingforgeeks.com/install-postgresql-12-on-ubuntu/
However, Im getting the below error, so I cannot proceed.
.../desktop/my_app$ systemctl status postgresql.service
System has not been booted with systemd as init system (PID 1). Can't operate.

What can I do?

A: service postgresql status
or
systemctl status postgresql
Must work.


Q: broken pipe when installing NodeJS 16 on Ubuntu 22.04 Trying to install NodeJS 16 on ubuntu 22.04.
Ran the official installation instructions:
sudo apt-get install -y nodejs
Got the following error:
The following NEW packages will be installed:
  nodejs
0 upgraded, 1 newly installed, 0 to remove and 4 not upgraded.
Need to get 0 B/27.1 MB of archives.
After this operation, 128 MB of additional disk space will be used.
Selecting previously unselected package nodejs.
(Reading database ... 218989 files and directories currently installed.)
Preparing to unpack .../nodejs_16.17.0-deb-1nodesource1_amd64.deb ...
Unpacking nodejs (16.17.0-deb-1nodesource1) ...
dpkg: error processing archive /var/cache/apt/archives/nodejs_16.17.0-deb-1nodesource1_amd64.deb (--unpack):
 trying to overwrite '/usr/include/node/common.gypi', which is also in package libnode-dev 12.22.9~dfsg-1ubuntu3
dpkg-deb: error: paste subprocess was killed by signal (Broken pipe)
Errors were encountered while processing:
 /var/cache/apt/archives/nodejs_16.17.0-deb-1nodesource1_amd64.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)

A: Various versions of Node.js are using a same file (one from apt install, one from manually download), which caused the conflict, resulting the error.
Remove your Node.js 12.22.9 first.


Q: Java modulus operator and PreIncrement - SCJA Im revising for my SCJA exam at the minute and im confused by this question and answer. The question is what is the result of running and compiling the code.
    public class Test{
       public static void main(String args[]){
         int counter = 0;
         for(int i=0; i< 4; ++i){
            for(int k=0; k< 4; ++k){
               system.out.println("Hello - "+ ++counter);
               if((k % 4) == 0)
               break;
            }
         }
       }
    }

So the answer they give is "Hello-1" because 0 % 4 = 0
But my question is should k not be 1 because its been pre-incremented?
Thanks in advance!

A: A for loop has the following structure:
for (initialization; condition; update)

The update is executed after every execution of the loop.
Therefore the following two loops are identical:
for (int i = 0; i < 10; i++) {

and
for (int i = 0; i < 10; ++i) {

A:
my question is should k not be 1 because its been pre-incremented?

The ++k happens at the end of the loop iteration, i.e. after the if statement.
It makes no difference whether it's ++k or k++; in either case the first value of k is zero.

So the answer they give is "Hello-1"

This is clearly incorrect, since counter is never incremented and stays at zero throughout the program.

A: k cannot be 1.
This is because when a for loop runs, it only updates after it has executed all the code within    the loop. Since the loop breaks even before the first iteration is completed, k remains 0.


Q: Java scanner hasNextLine returns null after an object is constructed only once(?) first post.
I have a list file with user information I'm trying to create objects out of, to then put into an array list. When it has read the first 4 lines it constructs the object once, and when it loops to continue reading the file it stops because hasNextResult = null. (proof)
List file:
Lilly
Lilly Anderson
193.164.85.111
avatar.img
Johnny
Jonathan Anderson
224.12.8.94
avatar.img

Constructor:
public Friend(String nickname, String fullname, String lastip, String image){
    this.nickname = nickname;
    this.fullname =fullname;
    this.lastip =lastip;
    this.image =image;
}

@Override
public String toString(){
    return nickname + ", " + fullname + ", " + lastip + ", " + image;
}

Scanner:
public static Friend build(InputStream in){
    Friend friend;

    Scanner reader = new Scanner(in, StandardCharsets.UTF_8);

    if(reader.hasNextLine()){
        friend = new Friend(reader.nextLine(), null, null, null);
    }else{
        return null;
    }
    if(reader.hasNextLine()){
        friend.setFullname(reader.nextLine());
    }
    if(reader.hasNextLine()){
        friend.setIp(reader.nextLine());
    }
    if(reader.hasNextLine()){
        friend.setImg(reader.nextLine());
    }
    return friend;
}

Main:
public static void main(String[] args) throws FileNotFoundException {
    List<Friend> al = new ArrayList<>();

    FileInputStream reader = new FileInputStream("Friends.list");
    Friend f;

    while((f = Friend.build(reader))!= null){
        al.add(f);
    }
    Collections.sort(al);
    printCollection(al.iterator());
}

Output:
run:
Lilly, Lilly Anderson, 193.164.85.111, avatar.img
BUILD SUCCESSFUL (total time: 0 seconds)

Thanks for reading.

A: It tries to read the next line after the last line, Try this: Change the code for the scanner to this:
Scanner:
public static Friend build(InputStream in, int counter){
    Friend friend;

    Scanner reader = new Scanner(in, StandardCharsets.UTF_8);

    if(reader.hasNextLine()){
        friend = new Friend(reader.nextLine(), null, null, null);
    }else if(counter < 0){
    if(true){
        friend.setFullname(reader.readLine());
    }
    if(reader.hasNextLine()){
        friend.setIp(reader.nextLine());
    }
    if(reader.hasNextLine()){
        friend.setImg(reader.nextLine());
    }
        return friend;
    } else {
    return null;
    }
    if(reader.hasNextLine()){
        friend.setFullname(reader.nextLine());
    }
    if(reader.hasNextLine()){
        friend.setIp(reader.nextLine());
    }
    if(reader.hasNextLine()){
        friend.setImg(reader.nextLine());
    }
    return friend;
  }

Main:
 public static void main(String[] args) throws FileNotFoundException {
    List<Friend> al = new ArrayList<>();

    FileInputStream reader = new FileInputStream("Friends.list");
    Friend f;
    int counter = 0;
    while((f = Friend.build(reader, counter))!= null){
        al.add(f);
        counter++;
    }
    Collections.sort(al);
    printCollection(al.iterator());
 }

A: Do not create a new Scanner for each friend, try this:
    public static Friend build(Scanner reader){
        Friend friend;

        if(reader.hasNextLine()){
            friend = new Friend(reader.nextLine(), null, null, null);
        }else{
            return null;
        }
        if(reader.hasNextLine()){
            friend.setFullname(reader.nextLine());
        }
        if(reader.hasNextLine()){
            friend.setIp(reader.nextLine());
        }
        if(reader.hasNextLine()){
            friend.setImg(reader.nextLine());
        }
        return friend;
    }

and call it like in:
...
FileInputStream in = new FileInputStream("Friends.list");
Scanner reader = new Scanner(in, StandardCharsets.UTF_8.name());
Friend f;

while((f = Friend.build(reader))!= null){
     al.add(f);
}
...

Reason: Scanner kind of does read ahead the next token(s), so it is/they are already consumed when the next Scanner is created. From its source code:

 // Internal buffer used to hold input
 private CharBuffer buf;

 // Size of internal character buffer
 private static final int BUFFER_SIZE = 1024; // change to 1024;

I would use a BufferedReader instead of Scanner (for reading just lines)


Q: Excel VBA - CountIfs - Moving from one spreadsheet to another I'm working on a CountIfs formula for a project and am having a little trouble. I'm pulling data from worksheet HR Data Detail and pasting it onto worksheet HR Data Summary. At the end of my CountIfs formula I have the range Z2:Z, which contains the years 2017, 2018, 2019, from worksheet HR Data Summary. I want Cell C2 on HR Data Summary to be a box that I can auto-fill in any year. For example, if I put 2018 into C2 then I want the CountIfs formula to pull the data for that specific year.
Sub Linking ()

'Defining finRow
Sheets("HR Data Detail". Activate)
Dim finRow As String
finRow = Sheets("HR Data Detail").Range("A50000").End(xlUp).Row

With Sheets ("HR Data Detail")

'Division 21 Employees
    Sheets("HR Data Summary").Range("L4") = _
        Application.WorksheetFunction.CountIfs(.Range("V2:V" & finRow), ">0", _
            .Range("S2:S" & finRow), "=21", .Range("L2:L" & finRow), "=January", _
            .Range("H2:H" & finRow), "=Employee", _
            Sheets("HR Data Detail").Range("Z2:Z" & finRow), "'HR Data Summary'!C2")

A: Assuming I'm understanding the purpose of this complex COUNTIFS formula -
It seems the problem is with the last range/criteria combo. Try changing
Sheets("HR Data Detail").Range("Z2:Z" & finRow), "'HR Data Summary'!C2")

to the following:
.Range("Z2:Z" & finRow), "=" & Sheets("HR Data Summary").Range("$C$2").Value


Q: How to implement monkey patch in C++? Is it possible to implement monkey patching in C++?
Or any other similar approach to that?
Thanks.

A: To add to other answers, consider that any function exposed through a shared object or DLL (depending on platform) can be overridden at run-time.  Linux provides the LD_PRELOAD environment variable, which can specify a shared object to load after all others, which can be used to override arbitrary function definitions.  It's actually about the best way to provide a "mock object" for unit-testing purposes, since it is not really invasive.  However, unlike other forms of monkey-patching, be aware that a change like this is global.  You can't specify one particular call to be different, without impacting other calls.

A: Considering the "guerilla third-party library use" aspect of monkey-patching, C++ offers a number of facilities:

*

*const_cast lets you work around zealous const declarations.

*#define private public prior to header inclusion lets you access private members.

*subclassing and use Parent::protected_field lets you access protected members.

*you can redefine a number of things at link time.

If the third party content you're working around is provided already compiled, though, most of the things feasible in dynamic languages isn't as easy, and often isn't possible at all.

A: I suppose it depends what you want to do. If you've already linked your program, you're gonna have a hard time replacing anything (short of actually changing the instructions in memory, which might be a stretch as well). However, before this happens, there are options. If you have a dynamically linked program, you can alter the way the linker operates (e.g. LD_LIBRARY_PATH environment variable) and have it link something else than the intended library.
Have a look at valgrind for example, which replaces (among alot of other magic stuff it's dealing with) the standard memory allocation mechanisms.

A: Not portably so, and due to the dangers for larger projects you better have good reason.
The Preprocessor is probably the best candidate, due to it's ignorance of the language itself. It can be used to rename attributes, methods and other symbol names - but the replacement is global at least for a single #include or sequence of code.
I've used that before to beat "library diamonds" into submission - Library A and B both importing an OS library S, but in different ways so that some symbols of S would be identically named but different. (namespaces were out of the question, for they'd have much more far-reaching consequences).
Similary, you can replace symbol names with compatible-but-superior classes.
e.g. in VC, #import generates an import library that uses _bstr_t as type adapter. In one project I've successfully replaced these _bstr_t uses with a compatible-enough class that interoperated better with other code, just be #define'ing _bstr_t as my replacement class for the #import.
Patching the Virtual Method Table - either replacing the entire VMT or individual methods - is somethign else I've come across. It requires good understanding of how your compiler implements VMTs. I wouldn't do that in a real life project, because it depends on  compiler internals, and you don't get any warning when thigns have changed. It's a fun exercise to learn about the implementation details of C++, though.  One application would be switching at runtime from an initializer/loader stub to a full - or even data-dependent - implementation.
Generating code on the fly is common in certain scenarios, such as forwarding/filtering COM Interface calls or mapping OS Window Handles to library objects. I'm not sure if this is still "monkey-patching", as it isn't really toying with the language itself.

A: As monkey patching refers to dynamically changing code, I can't imagine how this could be implemented in C++...


Q: How to calculate the rank of a list without pandas and numpy? i've written the following code:
  s = [2,1,-99,100,45,-2]
    li=[]

    for i in range(len(s)):
       li.append([s[i],i])
       li.sort()
       sort_index = []

    for x in li:
       sort_index.append(x[1])

    print(sort_index)

   this gives the output as :[2, 5, 1, 0, 4, 3]

required output : [4,3,1,6,5,2]
I need the rank such that the output is the rank of the first element of s
what are the suggested changes in my code to find the rank. And we shouldn't use numpy and pandas

A: Ranking in this context appears to be in terms of sorted order.  For that purpose one can compare the position of the elements in the original list against a sorted list to get the correct answer.
Example:
s = [2,1,-99,100,45,-2]
sorted_s = sorted(s)
ranked_s = [
    sorted_s.index(value) + 1
    for value in s
]
print(rank)

Output:
[4, 3, 1, 6, 5, 2]


Q: something wrong with this jquery? There is a debugging syntax error, but I can’t see it! im a bit of a newbie, so excuse my code!!
$(document).ready(function(){
     /* fetch elements and stop form event */
     $("form.follow-form").submit(function (e) {
        /* stop event */
        e.preventDefault();
        /* "on request" */
        $(this).find('i').addClass('active');
        /* send ajax request */
            $.ajax({
                type: "POST",
                url: "ajax_more.php",
                data: $(this).serialize(),
                cache: false,
                success: function(html){
                    $("ul.statuses").append(html);
                    $("form.follow-form").remove();
                }
            });
            else {
                $(".morebox").html('The End');
            }
            return false;
     });
});

A: Try this
$(document).ready(function() {
    /* fetch elements and stop form event */
    $("form.follow-form").submit(function(e) { /* stop event */
        e.preventDefault(); /* "on request" */
        $(this).find('i').addClass('active'); /* send ajax request */
        $.ajax({
            type: "POST",
            url: "ajax_more.php",
            data: $(this).serialize(),
            cache: false,
            success: function(html) {
                $("ul.statuses").append(html);
                $("form.follow-form").remove();
            }
        });
        $(".morebox").html('The End');
        return false;
    });
});

A: You’ve got an else, but no if.
Here’s the code with some proper indentation — indentation makes the code much easier to understand, so you spot errors more quickly.
$(document).ready(function(){

    /* fetch elements and stop form event */
    $("form.follow-form").submit(function (e) {

        /* stop event */
        e.preventDefault();

        /* "on request" */
        $(this).find('i').addClass('active');

        /* send ajax request */
        $.ajax({
            type: "POST",
            url: "ajax_more.php",
            data: $(this).serialize(),
            cache: false,
            success: function(html){
                $("ul.statuses").append(html);
                $("form.follow-form").remove();
            }
        });

======> /* HERE’S THE ELSE WITHOUT AN IF */

        else {
            $(".morebox").html('The End');
        }

        return false;
    });

});


Q: Perl - How to change every $variable occurrence of ";" in a string Very new here so be gentle. :)
Here is the jist of what I want to do:
I want to take a string that is made up of numbers separated by semi-colons (ex. 6;7;8;9;1;17;4;5;90) and replace every "X" number of semicolons with a "\n" instead. The "X" number will be defined by the user.
So if:
$string = "6;7;8;9;1;17;4;5;90";
$Nth_number_of_semicolons_to_replace = 3;

The output should be:
6;7;8\n9;1;17\n4;5;90

I've found lots on changing the Nth occurrence of something but I haven't been able to find anything on changing every Nth occurrence of something like I am trying to describe above.
Thanks for all your help!

A: use List::MoreUtils qw(natatime);
my $input_string = "6;7;8;9;1;17;4;5;90";
my $it = natatime 3, split(";", $input_string);
my $output_string;

while (my @vals = $it->()) {
    $output_string .= join(";", @vals)."\n";
}

A: Here is a quick and dirty answer.
my $input_string = "6;7;8;9;1;17;4;5;90";
my $count = 0;
$input_string =~ s/;/++$count % 3 ? ";" : "\n"/eg;

A: Don't have time for a full answer now, but this should get you started.
$string = "6;7;8;9;1;17;4;5;90";
$Nth_number_of_semicolons_to_replace = 3;
my $regexp = '(' . ('\d+;' x ($Nth_number_of_semicolons_to_replace - 1)) . '\d+);';
$string =~ s{ $regexp ) ; }{$1\n}xsmg

A: sub split_x{
  my($str,$num,$sep) = @_;
  return unless defined $str;

  $num ||= 1;
  $sep = ';' unless defined $sep;

  my @return;
  my @tmp = split $sep, $str;
  while( @tmp >= $num ){
    push @return, join $sep, splice @tmp, 0, $num;
  }
  push @return, join $sep, @tmp if @tmp;

  return @return;
}

print "$_\n" for split_x '6;7;8;9;1;17;4;5;90', 3

print join( ',', split_x( '6;7;8;9;1;17;4;5;90', 3 ) ), "\n";

A: my $string = "6;7;8;9;1;17;4;5;90";
my $Nth_number_of_semicolons_to_replace = 3;

my $num = $Nth_number_of_semicolons_to_replace - 1;
$string =~ s{ ( (?:[^;]+;){$num} [^;]+ ) ; }{$1\n}gx;

print $string;

prints:

6;7;8
9;1;17
4;5;90

The regex explained:
s{
  (                   # start of capture group 1
     (?:[^;]+;){$num} # any number of non ';' characters followed by a ';'
                      # repeated $num times
     [^;]+            # any non ';' characters
  )                   # end of capture group
  ;                   # the ';' to replace
}{$1\n}gx;            # replace with capture group 1 followed by a new line

A: If you've got 5.10 or higher, this could do the trick:
#!/usr/bin/perl

use strict;
use warnings;

my $string = '1;2;3;4;5;6;7;8;9;0';
my $n = 3;

my $search = ';.*?' x ($n -1);

print "string before: [$string]\n";

$string =~ s/$search\K;/\n/g;

print "print string after: [$string]\n";

HTH,
Paul


Q: Set button and textView weight programmatically I'm creating a basic to-do app, when the event addRow is called, I want to programmatically add the XML layout below (a new row containing a text and button)
How can I create the following layout programmatically?
    <TableLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/main_table"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintHorizontal_bias="0.466"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toTopOf="@+id/ll_component_container">

        <TableRow
                android:layout_width="match_parent"
                android:layout_marginTop="30dp"
                android:id="@+id/tab1"
                android:weightSum="5"
                android:layout_height="84dp">
            <TextView
                    android:id="@+id/textView1"
                    android:layout_width="fill_parent"
                    android:layout_weight="4"
                    android:paddingLeft="20dp"
                    android:textColor="#FFFFFF"
                    android:layout_height="wrap_content"
                    android:text="Value1"
                    android:textAppearance="?android:attr/textAppearanceSmall"/>
            <Button
                    android:text="Remove"
                    android:background="#fc032c"
                    android:layout_marginRight="20dp"
                    android:layout_weight="1"
                    android:layout_height="40dp" android:id="@+id/button1"/>
        </TableRow>
    </TableLayout>

I've tried this, but I can't find how to change neither the weight nor the button marginRight.
   private fun addRow(content: Editable) {
        val tl = findViewById<TableLayout>(R.id.main_table)
        val _id = View.generateViewId()
        val tr_head = TableRow(this)
        tr_head.id = _id
        tr_head.layoutParams = TableRow.LayoutParams(
            TableRow.LayoutParams.MATCH_PARENT,
            84,
            5f
        )

        val label = TextView(this)
        label.id = View.generateViewId()
        label.text = content
        label.setTextColor(Color.WHITE)
        label.setPadding(20, 0,0,0)
        tr_head.addView(label)

        val btn = Button(this)
        btn.id = _id + 1
        btn.setBackgroundColor(Color.RED)
        btn.setText("Remove")

        tr_head.addView(label)
        tr_head.addView(btn)

        tl.addView(
            tr_head, TableLayout.LayoutParams(
                TableRow.LayoutParams.MATCH_PARENT,
                TableRow.LayoutParams.WRAP_CONTENT
            )
        )
    }

A: I found another way around to accomplish what I wanted, so instead of using weight I used the screen width in order to get a relative width. and to add margin, I just added an empty row before the row that contains the button and text. Here is the full code for the interested.
private fun addRow(content: Editable) {
    val tl = findViewById<TableLayout>(R.id.main_table)
    val margin = TableRow(this)
    val tr_head = TableRow(this)
    margin.id = View.generateViewId()

    tr_head.id = View.generateViewId()
    val tabParams = TableRow.LayoutParams(
        TableRow.LayoutParams.MATCH_PARENT,
        84
    )
    tr_head.setLayoutParams(tabParams)

    val label = TextView(this)
    label.id = View.generateViewId()
    label.text = content
    label.setTextColor(Color.WHITE)
    val displayMetrics = DisplayMetrics()
    windowManager.defaultDisplay.getMetrics(displayMetrics)
    label.width = (displayMetrics.widthPixels / 3)*2
    label.setPadding(50, 0,0,0)
    tr_head.addView(label)

    val btn = Button(this)
    btn.id = View.generateViewId()
    btn.width = (displayMetrics.widthPixels / 3) - 50

    btn.setBackgroundColor(Color.RED)
    btn.setText("Remove")
    btn.setOnClickListener {
        tl.removeView(tr_head)
        tl.removeView(margin)
    }
    label.id = View.generateViewId()

    val filler = TextView(this)
    filler.id = View.generateViewId()

    margin.addView(filler)
    tr_head.addView(btn)
    tl.addView(
        margin,  TableLayout.LayoutParams(
            TableRow.LayoutParams.MATCH_PARENT,
            20
        )
    )
    tl.addView(
        tr_head, tabParams
    )
}


Q: Which Thread will a Service run in? I have an Activity A that starts a service S via startService method.
 Now as per the documentation Service S will run on main thread or the UI thread
 Now my question is when activity A is destroyed will the UI thread still exist?  What will happen if I reopen the Activity A through its launcher icon will there be two UI threads spawned in total?
Thanks in Advance.

A: On Android platform: MainThread == UiThread == "ApplicationThread" (it doesn't really exists), so in your case the new Activity will NOT start a new Service but Service's OnStartCommand() method will be raised. The Service will continue to run in the "ApplicationThread".

A: According to the Android Developer Doc,

A service runs in the main thread of its hosting process; the service does not create its own thread and does not run in a separate process unless you specify otherwise.

A: When you start an app by clicking on app's icon on launcher or home screen, Android will create a process for the app with a single thread (aka main or UI thread) of execution. This thread will exist even though there is no component started, such as Activity, Service, BroadcastReceiver, ContentProvider.
Then, it will find and start the default or entry activity for the app (which defined in AndroidManifest.xml file).

I have an Activity A that starts a service S via startService method.
  Now as per the documentation Service S will run on main thread or the
  UI thread  Now my question is when activity A is destroyed will the UI
  thread still exist?

Yes, UI thread still exist.

What will happen if I reopen the Activity A through its launcher icon
  will there be two UI threads spawned in total?

When you finish Activity A, Android does not destroy the process for the application at that time. It will keep the application in the memory for faster loading if you start the app later.
So when you reopen the Activity A, if there is a process for that application exists already, then the Activity A is started within that process and uses the same thread of execution. Otherwise, Android will create a new process for the application.

Which Thread will a Service run in?

By default, all components (including Service) of the same application run in the same process and thread (called the main or UI thread).
You can find more details in this link:
https://developer.android.com/guide/components/processes-and-threads


Q: CMake subdirectory install/uninstall targets I've got a project with two subdirectory projects (added with add_subdirectory), each with their own libraries, binaries and install/uninstall targets.  So:
main_project
|
|--CMakeLists.txt
|--src/
   |--CMakeLists.txt (with binary target, install()
|
|--project_a
   |--CMakeLists.txt
   |--src/
      |--CMakeLists.txt (with library, install())
|
|--project_b
   |--CMakeLists.txt
   |--src/
      |--CMakeLists.txt (with library, install())

I'd like for the top-level project (main_project) to automatically install the libraries a and b (included in main_project from target_link_libraries()).  So, I'd like to be able to go:
cd main_project/build
cmake ..
make
sudo make install

and have the main_project binary and project_a/b libraries installed automatically.  I've tried this:
main_project/src/CMakeLists.txt
...
install(FILES main project_a project_b DESTINATION bin
        LIBRARY DESTINATION lib)

but a cmake .. results in
install TARGETS given target "project_a" which does not exist in this directory.

as expected.
I've also tried specifying a path:
main_project/src/CMakeLists.txt
...
install(FILES main ${CMAKE_SOURCE_DIR}/project_a/ ${CMAKE_SOURCE_DIR}/project_b DESTINATION bin
        LIBRARY DESTINATION lib)

which also complains that project_a/b are not in this directory (also expected, I guess?)
I've also tried installing the libraries "manually" with the FILES option in install(), and that works just fine, but that seems very kludgy considering there are perfectly good install()s in the subprojects.
One additional issue: since project_a and project_b also have uninstall() custom targets, I can't add an uninstall target to the main_project without CMake complaining about the custom target already existing.  When I try adding an uninstall directive to the top dir CMakeLists:
add_custom_target(uninstall
    COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake)

But, since my project_a has an uninstall directive, I get:
CMake Error at CMakeLists.txt:37 (add_custom_target):
  add_custom_target cannot create target "uninstall" because another
  target with the same name already exists.  The existing target is a
  custom target created in source directory "/main_project/project_a".
  See documentation for policy CMP0002 for more details.

So, how do I install and uninstall the necessary library files from my subproject alongside my main_project?

A: I found the problem. I am adding the subdirectory I want to install with EXCLUDE_FROM_ALL such that it doesn't build everything in the subdirectory, only the library I need. That flag seems to prevent the subdirectory install() from happening. Perhaps ExternalProject_Add is indeed the best way to go here...
Also, RE overriding custom targets, this worked for me: http://public.kitware.com/pipermail/cmake/2011-July/045269.html


Q: Getting distance from Google Direction API in Android http://maps.googleapis.com/maps/api/directions/json?origin=-20.291825,57.448668&destination=-20.179724,57.613463&sensor=false&mode=%22DRIVING%22
For example this link generate the following:
"routes" : [
      {
         "bounds" : {
            "northeast" : {
               "lat" : -20.1765204,
               "lng" : 57.6137001
            },
           "southwest" : {
               "lat" : -20.2921672,
               "lng" : 57.4472155
            }
         },
         "copyrights" : "Map data ©2014 Google",
         "legs" : [
            {
               "distance" : {
                  "text" : "24.6 km",
                  "value" : 24628
               },

i want to extract only the distance and display it in android

A: To get a distance from a Google Maps you can use Google Directions API and JSON parser to retrieve the distance value.
Sample Method
private double getDistanceInfo(double lat1, double lng1, String destinationAddress) {
            StringBuilder stringBuilder = new StringBuilder();
            Double dist = 0.0;
            try {

            destinationAddress = destinationAddress.replaceAll(" ","%20");
            String url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + latFrom + "," + lngFrom + "&destination=" + latTo + "," + lngTo + "&mode=driving&sensor=false";

            HttpPost httppost = new HttpPost(url);

            HttpClient client = new DefaultHttpClient();
            HttpResponse response;
            stringBuilder = new StringBuilder();

                response = client.execute(httppost);
                HttpEntity entity = response.getEntity();
                InputStream stream = entity.getContent();
                int b;
                while ((b = stream.read()) != -1) {
                    stringBuilder.append((char) b);
                }
            } catch (ClientProtocolException e) {
            } catch (IOException e) {
            }

            JSONObject jsonObject = new JSONObject();
            try {

                jsonObject = new JSONObject(stringBuilder.toString());

                JSONArray array = jsonObject.getJSONArray("routes");

                JSONObject routes = array.getJSONObject(0);

                JSONArray legs = routes.getJSONArray("legs");

                JSONObject steps = legs.getJSONObject(0);

                JSONObject distance = steps.getJSONObject("distance");

                Log.i("Distance", distance.toString());
                dist = Double.parseDouble(distance.getString("text").replaceAll("[^\\.0123456789]","") );

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return dist;
        }

For details on parameters and more details on what are the different options available, please refer this.
https://developers.google.com/maps/documentation/directions/

A: public class ApiDirectionsAsyncTask extends AsyncTask<URL, Integer, StringBuilder> {

    private static final String TAG = makeLogTag(ApiDirectionsAsyncTask.class);

    private static final String DIRECTIONS_API_BASE = "https://maps.googleapis.com/maps/api/directions";
    private static final String OUT_JSON = "/json";

    // API KEY of the project Google Map Api For work
    private static final String API_KEY = "YOUR_API_KEY";

    @Override
    protected StringBuilder doInBackground(URL... params) {
        Log.i(TAG, "doInBackground of ApiDirectionsAsyncTask");

        HttpURLConnection mUrlConnection = null;
        StringBuilder mJsonResults = new StringBuilder();
        try {
            StringBuilder sb = new StringBuilder(DIRECTIONS_API_BASE + OUT_JSON);
            sb.append("?origin=" + URLEncoder.encode("Your origin address", "utf8"));
            sb.append("&destination=" + URLEncoder.encode("Your destination address", "utf8"));
            sb.append("&key=" + API_KEY);

            URL url = new URL(sb.toString());
            mUrlConnection = (HttpURLConnection) url.openConnection();
            InputStreamReader in = new InputStreamReader(mUrlConnection.getInputStream());

            // Load the results into a StringBuilder
            int read;
            char[] buff = new char[1024];
            while ((read = in.read(buff)) != -1){
                mJsonResults.append(buff, 0, read);
            }

        } catch (MalformedURLException e) {
            Log.e(TAG, "Error processing Distance Matrix API URL");
            return null;

        } catch (IOException e) {
            System.out.println("Error connecting to Distance Matrix");
            return null;
        } finally {
            if (mUrlConnection != null) {
                mUrlConnection.disconnect();
            }
        }

        return mJsonResults;
    }
}

I hope that help you!

A: Just check below link. You will probably get idea of it and try it on your own.
http://about-android.blogspot.in/2010/03/sample-google-map-driving-direction.html
Also you can use Google Distance Matrix API
https://developers.google.com/maps/documentation/distancematrix/

A: String url = getDirectionsUrl(pickupLatLng, dropLatLng);
new GetDisDur().execute(url);

Create URL using latlng
private String getDirectionsUrl(LatLng origin, LatLng dest) {

        String str_origin = "origin=" + origin.latitude + "," + origin.longitude;

        String str_dest = "destination=" + dest.latitude + "," + dest.longitude;

        String sensor = "sensor=false";

        String mode = "mode=driving";

        String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + mode;

        String output = "json";

        return "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
    }

Class GetDisDur
private class GetDisDur extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... url) {

            String data = "";

            try {
                data = downloadUrl(url[0]);
            } catch (Exception e) {
                Log.d("Background Task", e.toString());
            }
            return data;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            try {
                JSONObject jsonObject = new JSONObject(result);

                JSONArray routes = jsonObject.getJSONArray("routes");

                JSONObject routes1 = routes.getJSONObject(0);

                JSONArray legs = routes1.getJSONArray("legs");

                JSONObject legs1 = legs.getJSONObject(0);

                JSONObject distance = legs1.getJSONObject("distance");

                JSONObject duration = legs1.getJSONObject("duration");

                distanceText = distance.getString("text");

                durationText = duration.getString("text");

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

        }
    }


Q: what is difference between TDF and PCEF? In the PCC architecture there is  is TDF and PCEF that they are same. What is difference between TDF and PCEF?
HowTDF and PCEF work with together?

A: Firstly it is worth also mentioning the PCRF, the Policy and Charging Rules Function, which is the entity that defines and manages the policies. It will often group sets of rules into profiles.
The TDF, Traffic Detection Function, is 'is a functional entity that performs application detection and reporting of detected application and its service data flow description to the PCRF'.
The PCEF 'encompasses service data flow detection, policy enforcement and flow based charging functionalities.'
From the above descriptions, all from the 3GPP spec the distinction seem quite clear - the PCRF is the brains, the TDF detects application flow and the PCEF enforces policy. However, the TDF definition goes on to say that a TDF:

For solicited application reporting, the PCRF can request the TDF to also perform enforcement actions and usage monitoring.
  For those cases where service data flow description is not possible to be provided by the TDF to the PCRF, the TDF performs:

*

*Gating;

*Redirection;

*Bandwidth limitation.
  for the detected applications.

and to also note that a PCEF can be extended to include TDF functionality:

NOTE: The PCEF can be enhanced with application detection and control feature as specified in clause 6.2.2.5

So, your question is a good one, there is clearly some potential for overlap, and it is quite common for vendors to actually offer a single combined TDF/PCEF product.

A: TDF was introduced as a functional entity from Release 11 and the related information are present in the specification. Let met touch upon few key points w.r.t TDF, PCEF and PCRF for setting the context for the differences between them.
TDF :

The TDF is a functional entity that performs application detection and
  reporting of detected application and its service data flow
  description to the PCRF. The TDF supports solicited application
  reporting and/or unsolicited application reporting.

PCEF :

The PCEF encompasses service data flow detection, policy enforcement
  and flow based charging functionalities. It also provides user plane traffic
  handling, triggering control plane
  session management (where the IP-CAN permits), QoS handling, and
  service data flow measurement as well as online and offline charging
  interactions.
  Policy Control is enforced by PCEF as indicated by the PCRF
  in two different ways: a.Gate enforcement and b.QoS enforcement.
  Charging control is enforced by PCEF in the following way:
  - For a service data flow (defined by an active PCC rule) that is subject to charging control, the PCEF shall allow the service data
  flow to pass through the PCEF if and only if there is a corresponding
  active PCC rule with and, for online charging the OCS has authorized credit for the charging key.

PCRF :

The PCRF that uses usage monitoring for making dynamic policy
  decisions shall set and send the applicable thresholds to the PCEF or
  TDF for monitoring.  The usage monitoring thresholds shall be based on
  volume. The PCEF or TDF shall notify the PCRF when a threshold is
  reached and report the accumulated usage since the last report for
  usage monitoring.

Other points to note :

*

*PCEF interacts with PCRF and OCS.  The TDF interacts only with PCRF and not with charging system (Online or Offline CS).

*PCEF resides with-in the PDN GW. The TDF resides as a separate entity outside PGW.

*Interfaces :  The Sd reference point enables a PCRF to have dynamic control over the ADC (Application Detection and Control) behaviour at a TDF. The Gx reference point enables a PCRF to have dynamic control over the PCC(Policy Charging and Control)/ADC (Application Detection and Control) behaviour at a PCEF.

ADC - This is present in TDF or in some scenario along with PCEF in which case, the PCEF is termed as PCEF enhanced with ADC.

In Application Detection and Control(ADC), two models may be applied,
  depending on operator requirements: solicited and unsolicited
  application reporting
Solicited application reporting: The PCRF shall instruct the TDF, or the PCEF enhanced with ADC, on which applications to detect and
  whether to report start or stop event to the PCRF by activating the
  appropriate ADC rules.
Unsolicited application reporting: The TDF is pre-configured on which applications to detect and report. The enforcement is done in
  the PCEF

The report to the PCRF shall include the same information for solicited and unsolicited application reporting that is whether the report is for start or stop, the detected Application Identifier and, if deducible, the service data flow descriptions for the application user plane traffic.

The PCRF shall accept input for PCC decision-making from the PCEF, the
  TDF if present and other entities.

High level Information obtained from the PCEF via the Gx reference point, e.g. IP-CAN bearer attributes, request type, subscriber related information, IP flow mobility routing rules (if IP flow mobility is supported) and detected application’s traffic information, if the PCEF supports Application Detection and Control feature (Detected Application Identifier, Allocated Application Instance Identifier, Detected service data flow descriptions.)
PCC procedures over Gx reference point

Request for PCC rules
  Provisioning of PCC rules
  Provisioning of Event Triggers
  Provisioning of charging related information for the IP-CAN session
  Provisioning and Policy Enforcement of Authorized QoS
  Requesting Usage Monitoring Control
  Reporting Accumulated Usage

ADC procedures over Gx reference point :

Request for ADC rules
  Provisioning of ADC rules
  Requesting Usage Monitoring Control for applications
  Reporting applications' Accumulated Usage
  Application Detection Information

High level Information obtained from the TDF via the Sd reference point, e.g. report on application’s traffic detection start/stop, Detected Application Identifier, Allocated Application Instance Identifier, Detected service data flow descriptions.
ADC procedures over Sd reference point for solicited application reporting :

Provisioning of ADC rules
  Request for ADC rules
  Provisioning of Event Triggers
  Requesting Usage Monitoring Control
  Reporting Accumulated Usage
  Application Detection Information

ADC procedures over Sd reference point for unsolicited application reporting :

Provisioning of ADC rules
  Application Detection Information
  TDF session to Gx session linking


Q: SonarQube giving unused private method issue for lambda usage I have the following logic;
..
if(list.stream()
       .filter(MyClass::isEnabled)
       .filter(this::isActive)
       .count() > 0) {
    //do smth
}
..
private boolean isActive(MyClass obj) {
    return bool;
}

As you see, isActive method is being used in the stream structure, but when I build this class on Jenkins, I get the unused private method issue from SonarQube, it says you should delete this redundant private method. Is this a bug? If not, why haven't they still included lambda logic in their analyze structure?
Only solution is, obviously, to do this;
.filter(obj -> isActive(obj)), but it destroys the uniformity, and even the readability (imo).

A: This is a known issue of SonarQube java analyzer : https://jira.sonarsource.com/browse/SONARJAVA-583
This is due to a lack of semantic analysis to resolve properly method reference (thus identify to which method this::isActive refers to).


Q: Material UI Typography & Media Queries in below in the typography component, i wanted to make the variant prop dynamic in accordance to the different screen widths , how it can be done??  appreciate your feedback
import { useTheme, useMediaQuery } from "@material-ui/core";

const Home = () => {
  const classes = useStyles();
  const theme = useTheme();
  const MQlg = useMediaQuery(theme.breakpoints.down("lg"));
  const MQmd = useMediaQuery(theme.breakpoints.down("md"));
  const MQsm = useMediaQuery(theme.breakpoints.down("sm"));

<Typography
          variant={`${MQsm && "h4"}   ${MQmd && "h3"}  $ {MQlg && "h2"} `}
          className={classes.text}
          gutterBottom
        >
          pioneering
</Typography>

A: Following the example on this MUI page for useMediaQuery, please see what I have created to assist you:
import * as React from "react";
import { createTheme, ThemeProvider, useTheme } from "@mui/material/styles";
import useMediaQuery from "@mui/material/useMediaQuery";
import { Typography } from "@material-ui/core";
function MyComponent() {
  const theme = useTheme();
  const large = useMediaQuery(theme.breakpoints.up("lg"));
  const medium = useMediaQuery(theme.breakpoints.up("md"));
  const small = useMediaQuery(theme.breakpoints.up("sm"));

  return (
    <>

{`large: ${large}`}

{`medium: ${medium}`}

{`small: ${small}`}

      <Typography
        variant={large ? "h1" : medium ? "h2" : small ? "h3" : "body1"}
      >
        Font Size Change
      </Typography>
    </>
  );
}

const theme = createTheme();

export default function ThemeHelper() {
  return (
    <ThemeProvider theme={theme}>
      <MyComponent />
    </ThemeProvider>
  );
}

Inspect the page, and change the sizes for the screen. Some will appear true, whilst other's false.


Q: AttributeError: 'module' object has no attribute 'point' When I try to run this code:
import arcpy, os
arcpy.env.overwriteOutput = True
def polylineArea(x, y): # this is your function definition
   count=len(xlist)
   area=0
   j=count-1
   for i in range (0, count):
       area+=((x[j]+x[i])*(y[j]-y[i]))
       j=i
   return area*.5

infile=open("C:/KateFiles/Courses/SIE510/ParcelStuff/parcel15.txt", "r")
outputname = "C:/KateFiles/Courses/SIE510/ParcelStuff/P_12/ParcelPolys2.shp"

sr=arcpy.SpatialReference(102683)
arcpy.CreateFeatureclass_management(os.path.dirname(outputname),os.path.basename(outputname),"POLYLINE", spatial_reference=sr)

arcpy.AddField_management(outputname, "ParcelID", "LONG", field_precision=8)
arcpy.AddField_management(outputname, "Map", "TEXT", field_length=4)
arcpy.AddField_management(outputname, "Lot", "TEXT", field_length=4)
arcpy.AddField_management(outputname, "point", "Float", field_precision=10, field_scale=2)
cursor1 = arcpy.da.InsertCursor(outputname,("ParcelID","SHAPE@", "Map","Lot", "point"))

header1 = infile.readline()
print header1 # print this out so you can see what this contains
header2 =header1.split()# split the header parts by white space
parcelID=header2[1]#assign parcel ID
Mapno=header2[2]# assign the Mapno
Lotno=header2[3]# assign the Lotno
xlist=[]
ylist=[]

#poly =[] # A list that will hold each of the Polygon objects
#point=arcpy.point
parray=arcpy.Array()
# Loop over lines and extract variables of interest
for line in infile:
   segments=line.split()
   x=float(segments[0]) # gets x
   y=float(segments[1]) # gets y
   print x, y
   pt=arcpy.point(x, y)
   parray.add(pt)

   xlist.append(x)
   ylist.append(y)

area=polylineArea(x, y) # this is your function call
print area
point=arcpy.polyline(parray)

row=(parcelID, poly, Mapno, Lotno, point) # these match the fields in your insert cursor specification
cursor1.insertRow(row)
infile.close()

I got this Error:
 Traceback (most recent call last):
  File "C:/Users/Ahmed A. Jasim/Desktop/Q3_Lb8.py", line 45, in <module>
    pt=arcpy.point(xlist, ylist)
AttributeError: 'module' object has no attribute 'point'

A: The ArcPy module is case sensitive, so you need to capitalize those objects, e.g.
pt=arcpy.Point(x, y)
point=arcpy.Polyline(parray)


Q: CBCharacteristic value in swift3 I am beginner in swift development. I was working on BLE based application.
Today I updated Xcode 8, iOS 10 and convert my code to swift3. Then some of my syntax are need to convert. After fixing this , I found one issue on CBCharacteristic.
Issue
Inside didUpdateValueforCharacteristic , I can get updated CBCharacteristic object.
If I print out whole object, it show correctly. -> value = <3a02>
When I retrieved value from CBCharacteristic , characteristic.value -> 2bytes (size of this value)
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic:     CBCharacteristic, error: Error?)
{
if (characteristic.uuid.description == LED_WAVELENGTH_CHARACTERISTIC_UUID)
{
            print("Characteristic - \(characteristic)")
            print("Data for characteristic  Wavelength - \  (characteristic.value)")
        }
 }

Log Result :

Characteristic - <CBCharacteristic: 0x1742a50a0, UUID = 2C14, properties = 0xE, value = <3a02>, notifying = NO>
Data for characteristic  Wavelength - Optional(2 bytes)

PS : This code is completely working fine on previous version.
Thanks for attention and hope someone can help me to fix this issue.

A: It seems that you have been relying on the description of NSData returning a string of the form <xxxx> in order to retrieve the value of your data. This is fragile, as you have found, since the description function is only meant for debugging and can change without warning.
The correct approach is to access the byte array that is wrapped in the Data object.  This has been made a little bit more tricky, since Swift 2 would let you copy UInt8 values into a single element UInt16 array.   Swift 3 won't let you do this, so you need to do the math yourself.
var wavelength: UInt16?
if let data = characteristic.value {
    var bytes = Array(repeating: 0 as UInt8, count:someData.count/MemoryLayout<UInt8>.size)

    data.copyBytes(to: &bytes, count:data.count)
    let data16 = bytes.map { UInt16($0) }
    wavelength = 256 * data16[1] + data16[0]
}

print(wavelength)

A: Now, you can use String(bytes: characteristic.value!, encoding: String.Encoding.utf8), to get the string value of the characteristic.


Q: Construct .htaccess file to cover set of cases This is what I need to do: I need to write an .htaccess file that:

*

*Redirect all http requests to https

*Redirect all https://example.com to https://www.example.com

*Block bad bots

*Prevent access to .htaccess

*Add compression to ALL file types on the site

This is all I need to do, yet no matter how many thousands of different ways I try, it doesn't work. Do I need the rewrite engine 'on' with every rule?
I have read 100's of sites telling me how, however everyone seems to have a different solution, yet whatever I try, it DOESN'T work. When I use the redirect tool in Godaddy it does redirect my site from http to https, but that is all. When I try to add more to the htaccess file, it stops working. Even the original redirect no long works.
Can anyone tell me how to put together all these codes so they work? I started a small business website, but no one told me there would be so  little technical help or examples of all the 'other' things you need to do to get your website ready for all the search engine requirements.
Please, please, can someone help me? The site name is billionairemailinglist.com, can anyone give me or help me create these codes to use in my htaccess file? I would be forever grateful and would be glad to offer you the products we sell for free for helping me.

A: The blocking of bad bots is a non discrete, nebulous task so I'll deal with that at the end of this answer.
After each itemized question I'll adjust the .htaccess to cover the solution along with all previous questions.  The final solution will address all questions.
1. Switches my site from http to https
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://www.example.com [R=301,L]

2. Switches my site from https://with no www to https://with www.
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule (.*) https://www.example.com [R=301,L]

4. Prevent viewing of .htaccess file
Taken from How to deny access to a file in .htaccess
<Files ~ "^.*\.([Hh][Tt][Aa])">
    order allow,deny
    deny from all
    satisfy all
</Files>

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule (.*) https://www.example.com [R=301,L]

5. Add compression to ALL file types on the site*
<Files ~ "^.*\.([Hh][Tt][Aa])">
    order allow,deny
    deny from all
    satisfy all
</Files>

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule (.*) https://www.example.com [R=301,L]

<ifmodule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript
</ifmodule>

*Note that not all file types should/could be compressed.  I've added the boilerplate that we used to use above which seemed to work well.  If you're interested in truly maximizing compression opportunities without the complexities of browser compatibility, look into ModPagespeed
3. block bad bots
I wish it was easy as BlockBadBots yes.  If you'd prefer to not analyze bandwidth usage and blocking of bots based on consumption etc., I would recommend that you put your site behind CloudFlare.  This service has a good reputation for dealing with high profile DDOS attacks, limiting harmful bots, and keeping sites alive even as demand increases.
Good luck!


Q: LEFT JOIN doesn't work with count I have a problem with my query:
SELECT table1.Name,
       COUNT(*)
FROM table1
LEFT JOIN table2 ON table2.Name_all = table1.Name
GROUP BY table1.Name

It shows and counts a names from table1. I want to join all names from table2 which do not exist in table1.
Maybe someone knows what I am doing wrong?
Thanks in advance

A: From your description you seem to mean this, which is a list of name_all that does not match table1 name.
SELECT table2.Name_all
FROM table2
LEFT JOIN table1 ON table2.Name_all = table1.Name
WHERE table1.Name Is Null

If you need a count as well, you can say:
SELECT table2.Name_all, Count(table2.Name_all) AS CountOf
FROM table2
LEFT JOIN table1 ON table2.Name_all= table1.Name
WHERE table1.Name Is Null
GROUP BY table2.Name_all;

A: Try this
This query will fetch common names from table 1 and table 2. It will also fetch names from table 2 which are not there in table 1.
SELECT table1.Name,
       table2.Name,
       COUNT(*)
FROM table2
LEFT JOIN table1
    ON table2.Name_all = table1.Name
GROUP BY table1.Name, table2.Name

Let me if this works.

A: I would do a simple in check then
SELECT table1.Name,
FROM table1
WHERE table1.Name In (SELECT table2.Name_all FROM table2)
GROUP BY table1.Name

There are other ways, but without more information this is a simple way t


Q: when i call str.replace() in javascript it goes to error ir is not defined See my code
for (var i = 0; i < allTextLines.length; i++) {
            var row_data = allTextLines[i];
            console.log(row_data);
            row_data = row_data.replace(/ /g,'');
            try {

                ir(row_data == "")
                {
                    continue;
                }
                if (document.getElementById("devicesList").value.length > 0) {
                    document.getElementById("devicesList").value += ",";
                }
                document.getElementById("devicesList").value += row_data;
            }
            catch (oErr) {
                not_read += 1;
                console.log(oErr.message);
                str_error_detail_rows += "
Error :" + oErr.message + " could not read line# " + i + " while reading from file.
";
            }

        }

when i run the code, in the console i got "ir is not defind" please someone help me. the code goes smooth when i remove str.replace. thanks.

A: ir(row_data == "")

should be
if(row_data == "")

A: The ir should be an if, I reckon - it's a typo.
To be perfectly frank, you really could have read through and practically immediately noticed the problem while paying attention.


Q: ASP.NET MVC3 Using Areas I'm having some troubles setting up two Areas in my project, I created both Areas by right clicking my project -> Add -> Area using VS 2010 Professional,
The code it generated in the *AreaRegistration.cs files is exactly as I'd expect it.
Both my areas have multiple controllers.
I've checked my global.asax.cs file and it contains what I'd expect, the following is at the bottom:

// Generated code
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);

When I change the default generated routing info I can get it to work for a Single controller:
context.MapRoute(
    "CommunityCourses_default",
    "CommunityCourses/{controller}/{action}/{id}",
    new {controller="NameOfController", action = "Index", id = UrlParameter.Optional }
);

The controller="NameOfController" is what I've tried adding to the generated code, but it only works for a single controller.
Edit: I renamed the namespace of my files to use PROJECTNAME.AREANAME within an area, is this causing issues? I thought it'd simplify my imports in a non-convention-breaking way.
What am I missing? I've noticed a lot of problems about areas on SO and tried to follow the answers without success. This issue has bothered eluded me for the majority of the day, any help would be greatly appreciated!

A: If you moved files from the Controllers folder or the VIews folder in the root of the project into Controllers or View folders contained in the {AreaName} folder, then all of those files moved need their namespaces changed from {ProjectName}.{*etCetera} to:
{ProjectName}.Areas.{AreaName}.{*etCetera}

A:
Turns out what was wrong was that the order or routing was incorrect, it was processing {controller}/{action}/{id} first which was breaking my areas. Moving the
AreaRegistration.RegisterAllAreas();

to the top of my application_start fixed my problem.
http://haacked.com/archive/2011/04/13/routedebugger-2.aspx Link to the tool I used to find the problem, unfortunately the current version of the tool doesn't work on the default 404 pages, so I also had to create a custom 404 page for it to work.


Q: Using sed (or other command line programs) to delete every other X lines I have a huge text file that has several iterations of the same thing at different times, with a basic structure of:
Header (5 lines)
Data (thousands of lines)
Header (5 lines)
Data (thousands of lines)
Header (5 lines)
Data (thousands of lines)

This repeats and goes on for a while.
I want to cull this file, by removing every other set of Header + Data. I was thinking I'd use sed, but I can't figure out how.
It might be of help that each "cycle" starts with the same line (for the purpose of this example, imagine it says Program X output) and that exact line only appears once, at the beginning of each "cycle".
Thanks

A: Sounds like all you need is:
awk '/Program X output/ && c++{exit} 1' file

e.g.
$ seq 50 | awk '/2/ && c++{exit} 1'
1
2
3
4
5
6
7
8
9
10
11

If that's not all you need then edit your question to clarify your requirements and show us concise, testable sample input and expected output.

A: Keep track of how often you see the keywords, and print only when this count is an odd number:
awk '/Program X output/ {n++} n%2 == 1' <<END
Program X output
a
b
c
Program X output
d
e
Program X output
f
g
h
i
j
Program X output
m
n
o
END

Program X output
a
b
c
Program X output
f
g
h
i
j

A: This might work for you (GNU sed):
sed -r '/Program X output/{x;s/^/x/;x};G;/\n(x{2})*$/!P;d' file

When encountering a header line, add 1 to a counter in the hold space (HS). Append the HS to every line and only print the first line in the pattern space (PS) if the counter is a multiple of the required amount.


Q: How do I merge the multiple If Else using decode in PL/SQL? The code goes like-
If X=x1
then
  select a,b
  from tab
  where zz=yy;

elsif X=x2 or X=x3
then
  select a,b
  from tab
  where zz=yy
  and yy= 123;

elsif X=x4
then
  select a,b
  from tab
  where zz=yy
  and yy= 456;

end if;

The code in select is being repeated. How should i merge it?

A: At first I thought that a CASE statement would be appropriate, but then I noticed that your logic always conditionally selects the same two columns a and b.  So I think that what you need here is a WHERE clause to handle all the cases.
SELECT a, b
FROM tab
WHERE (x = 'x1' OR
      ((x = 'x2' OR x = 'x3') AND yy = 123) OR
      (x = 'x4' AND yy = 456)) AND
      zz = yy

A: You can use dynamic SQL and compose your query from different parts.
For example:
-- common part of query
common_query := 'SELECT a, b FROM tab WHERE zz= yy';

-- set additional condition
IF X=x1 THEN add_where := '';
ELSIF X=x2 OR X=x3 THEN add_where := ' AND yy= 123';
ELSIF X=x4 THEN add_where := ' AND yy= 456';
END IF;

-- compose final query
final_query:=  common_query||add_where;

EXECUTE IMMEDIATE final_query;

Of couse when you use dynamic SQL you can use bind variables and you need to remember about return values.