text:
Q: Docker swarm service on different nodes can't communicate I'm running docker in swarm mode where I have some services running on the same overlay network but different nodes.
I'm trying to get the nodes of these services to be able to talk to each other; which works fine until I try to talk cross node.
Here is the definition of my network, as gotten from one node:
{
    "Name": "my-nw",
    "Id": "0jk0h0sor0839i2j91rz8b7c9",
    "Scope": "swarm",
    "Driver": "overlay",
    "EnableIPv6": false,
    "IPAM": {
        "Driver": "default",
        "Options": null,
        "Config": [
            {
                "Subnet": "10.0.0.0/24",
                "Gateway": "10.0.0.1"
            }
        ]
    },
    "Internal": false,
    "Containers": {
        "0467076e0f3b3618115a4d023e78a74921eb6ef7c7ba1e5baeffe1ea4500ee1e": {
            "Name": "sleepy_fermi.2.59adig1cqoe6s5frqvwco3fyk",
            "EndpointID": "7276764bd319c57f3343ff871db136e0a224eedb52e93dc8bb1e0d488bf6de83",
            "MacAddress": "02:42:0a:00:00:04",
            "IPv4Address": "10.0.0.4/24",
            "IPv6Address": ""
        },
        "4554f04efa9c2d66e584fefa3d610314761f8dc6599f3723e878e6e5326cd21e": {
            "Name": "sleepy_fermi.3.4jdpxy1zbu33tf55cbp24llbk",
            "EndpointID": "b498650bac96aa780a88f0c7a0c70dc716e00b3a4852dcaaf22450d71712ef5f",
            "MacAddress": "02:42:0a:00:00:05",
            "IPv4Address": "10.0.0.5/24",
            "IPv6Address": ""
        }
    },
    "Options": {
        "com.docker.network.driver.overlay.vxlanid_list": "257",
        "encrypted": ""
    },
    "Labels": {}
}

And here it is from another node:
{
    "Name": "my-nw",
    "Id": "0jk0h0sor0839i2j91rz8b7c9",
    "Scope": "swarm",
    "Driver": "overlay",
    "EnableIPv6": false,
    "IPAM": {
        "Driver": "default",
        "Options": null,
        "Config": [
            {
                "Subnet": "10.0.0.0/24",
                "Gateway": "10.0.0.1"
            }
        ]
    },
    "Internal": false,
    "Containers": {
        "68ae6de87b418168fdc708ea015d3b4130911124eab9821902d03de59eb91264": {
            "Name": "sleepy_fermi.1.azu3d6fdjq1jovspok3xn0rrk",
            "EndpointID": "dc485439790fa586c8c592f2e53f8bdb7e50142c560538349a70e2cda6e065a4",
            "MacAddress": "02:42:0a:00:00:03",
            "IPv4Address": "10.0.0.3/24",
            "IPv6Address": ""
        },
        "f4fdacd84bf8b40dace568d3ced1635bec0f982f03566e043e59c29eccc2bf19": {
            "Name": "tiny_montalcini.1.a3ovorl23ak351gozxr9o7nvt",
            "EndpointID": "f3951430836fbb056e559e43de921b8c437f72d1ee0c59b4179220c6c0ea0eee",
            "MacAddress": "02:42:0a:00:00:07",
            "IPv4Address": "10.0.0.7/24",
            "IPv6Address": ""
        }
    },
    "Options": {
        "com.docker.network.driver.overlay.vxlanid_list": "257",
        "encrypted": ""
    },
    "Labels": {}
}

So, for example, I can curl sleepy_fermi.4. from sleepy_fermi.5. but not from sleepy_fermi.3 (the ip-address doesn't work either so it's not just a name lookup issue).


text:
Q: How to remove excess border in :active state? tailwindcss I currently have a weird problem using tailwindcss. The button below looks fine.

But when I click it does shape pill/rounded, instead its a rectangle below.

Someone knows how to make the active state shape same as the current one?

Here is my button code:
<button class="flex items-center justify-center focus:outline-none rounded-3xl
bg-green-200 text-gray-800 text-13 h-8 px-3">
  Goto Button
</button>

I tried to add below code. But doesn't work
active:rounded-3xl

Device tested: iPhone X (using chrome browser (CTRL+SHFT+M))

A: Two possible solutions
1) This could be fix by disabling the preflight of tailwind but unfortunately it can cause major design problems for possible affected pages.
corePlugins: {
    preflight: false,
}

2) Alternatively this could be solve by changing the cursor style. Add this class to the button cursor-auto.
<button class="cursor-auto flex items-center justify-center focus:outline-none rounded-3xl
bg-green-200 text-gray-800 text-13 h-8 px-3">
  Goto Button
</button>

A: By default, active variant is not enabled for most of the plugins.
You need to add a small config change in tailwind.config.js
Extend the borderRadius plugin
//Add this change in tailwind.config.js
module.exports = {
  variants: {
    extend: {
      borderRadius: ['active'],
    }
  }
}

Note:
By default, only some variants like focus, hover etc are enabled for the plugins(core-plugins only)
For more info, refer to
https://tailwindcss.com/docs/hover-focus-and-other-states
For borderRadius,
https://tailwindcss.com/docs/border-radius

redpajama_set_name: RedPajamaStackExchange


text:
Q: How does this work: http://welbog.homeip.net/ How does this work?: http://welbog.homeip.net/
Just scroll down. It looks cool, it looks damn cool, and it works without javascript. What's that?

A: That's made by the divs having a fixed background that doesn't scroll with it and is very tall.
You can see here in the CSS:
background-attachment: fixed;
background-repeat: no-repeat;
background-position: right top;

This will keep it attached to the top-right, never repeat it and make it appear "fixed" to the site.
Each div has a different background to give this effect.

A: It is fixed background, and every element(paragraph) has it

A: background-attachment: fixed

plus some css expression magic for older versions of ie


text:
Q: What's the simplest way to render a polygon in Deck.GL? I'm trying to understand conceptually how Deck.GL renders things so I'm working through the example layers from Lines to Polygons to GeoJson. Lines work fine but something is preventing me from rendering even the simplest polygons DeckGL has in their examples.
Here's some example line code that works
import React from "react";
import DeckGL, { LineLayer } from "deck.gl";
import { StaticMap } from "react-map-gl";

const MAPBOX_ACCESS_TOKEN = process.env.REACT_APP_MAPBOX_KEY;

// Viewport settings
const viewState = {
  longitude: -122.41669,
  latitude: 37.7853,
  zoom: 13,
  pitch: 0,
  bearing: 0
};

// Data to be used by the LineLayer
const data = [
  {
    sourcePosition: [-91.72307036099997, 31.814196736000035],
    targetPosition: [-122.41669, 37.781]
  },
  {
    sourcePosition: [-122.41669, 37.781],
    targetPosition: [-95.52274057225983, 30.131426214982195]
  }
];

// DeckGL react component
export default class ExampleMap extends React.Component {
  render() {
    const layers = [new LineLayer({ id: "line-layer", data })];

    return (
      <DeckGL initialViewState={viewState} controller={true} layers={[layers]}>
        <StaticMap mapboxApiAccessToken={MAPBOX_ACCESS_TOKEN} />
      </DeckGL>
    );
  }
}

When I replace the LineLayer with this Polygon layer below - it completely fails to show anything
//examplepoly.js

import { PolygonLayer } from "deck.gl";

// Data to be used by the POLYLayer

const polygonData = [
  -91.72307036099997,
  31.814196736000035,
  0,
  -122.41669,
  37.781,
  0,
  -95.52274057225983,
  30.131426214982195,
  0,
  -91.72307036099997,
  31.814196736000035,
  0
];

const LAYER_POLY = [
  new PolygonLayer({
    id: "poly-layer",
    data: polygonData
  })
];

export default LAYER_POLY;

Can anyone show me a simple Polygon layer that I can use? The one from the documentation doesn't seem to work and GeoJson one is a bit too complicated for now

A: Figured it out.
The PolygonLayer's getPolygon function didn't recognize my array's data so I needed to restructure it as below:
// examplePolygonLayer.js
import { PolygonLayer } from "deck.gl";

// Data to be used by the POLYLayer
const polygonData = [
  {
    contours: [
      [-91.72307036099997, 31.814196736000035],
      [-122.41669, 37.781],
      [-95.52274057225983, 30.131426214982195],
      [-91.72307036099997, 31.814196736000035]
    ],
    name: "firstPolygon"
  }
];

const LAYER_POLY = new PolygonLayer({
  id: "poly-layers",
  data: polygonData,
  stroked: true,
  filled: true,
  extruded: false,
  wireframe: true,
  lineWidthMinPixels: 1,
  getPolygon: d => d.contours,
  getLineColor: [80, 80, 80],
  getFillColor: [80, 80, 80],
  getLineWidth: 250
});
export default LAYER_POLY;

Shows this:


text:
Q: Sending information to ubidots only if the condition are met The Image shows the dashboard of the application
package com.example.leeyueloong.proximityapplication;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.estimote.mustard.rx_goodness.rx_requirements_wizard.Requirement;
import com.estimote.mustard.rx_goodness.rx_requirements_wizard.RequirementsWizardFactory;
import com.estimote.proximity_sdk.proximity.EstimoteCloudCredentials;
import com.estimote.proximity_sdk.proximity.ProximityContext;
import com.estimote.proximity_sdk.proximity.ProximityObserver;
import com.estimote.proximity_sdk.proximity.ProximityObserverBuilder;
import com.estimote.proximity_sdk.proximity.ProximityZone;
import com.ubidots.ApiClient;
import com.ubidots.Variable;

import java.util.ArrayList;
import java.util.List;

import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import kotlin.jvm.functions.Function1;

public class MainActivity extends AppCompatActivity {

private ProximityObserver proximityObserver;
private int send;

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

    EstimoteCloudCredentials cloudCredentials =
            new EstimoteCloudCredentials("tan-kok-hui-s-proximity-fo-07q", "d18623351c273ce3e09ffcc1f6201861");
    // 2. Create the Proximity Observer
    this.proximityObserver =
            new ProximityObserverBuilder(getApplicationContext(), cloudCredentials)
                    .withOnErrorAction(new Function1<Throwable, Unit>() {
                        @Override
                        public Unit invoke(Throwable throwable) {
                            Log.e("app", "proximity observer error: " + throwable);
                            return null;
                        }
                    })

                    .withLowLatencyPowerMode()
                    .build();

    // add this below:

    ProximityZone zone = this.proximityObserver.zoneBuilder()

            .forTag("desks")
            .inNearRange()
            .withOnEnterAction(new Function1<ProximityContext, Unit>() {
                @Override
                public Unit invoke(ProximityContext context) {
                    String deskOwner = context.getAttachments().get("desk-owner");
                    Log.d("app", "Welcome to " + deskOwner + "'s desk");
                    return null;
                }
            })
            .withOnExitAction(new Function1<ProximityContext, Unit>() {
                @Override
                public Unit invoke(ProximityContext context) {
                    return null;
                }

            })

            .withOnChangeAction(new Function1<List<? extends ProximityContext>, Unit>() {

                @Override
                public Unit invoke(List<? extends ProximityContext> contexts) {

                    List<String> deskOwners = new ArrayList<>();
                    for (ProximityContext context : contexts) {

                        deskOwners.add(context.getAttachments().get("desk-owner"));
                    }
                    for (int i = 0; i < deskOwners.size(); i++) {

                        if (deskOwners.get(i).contains("Peter")) {
                            send = 1;
                            Toast.makeText(MainActivity.this, "Alert:Unauthorized Zone", Toast.LENGTH_SHORT).show();
                            Toast.makeText(MainActivity.this, "Sending information to ubidots..........", Toast.LENGTH_LONG).show();
                        } else if (deskOwners.get(i).contains("Alex")) {
                            send = 0;
                            Toast.makeText(MainActivity.this, "Device has entered this range", Toast.LENGTH_SHORT).show();

                        }
                        else if (deskOwners.get(i).contains("Paul"))
                        {

                        }
                    }

                    Log.d("app", "In range of desks: " + deskOwners);
                    return null;
                }

            })
            .create();

    this.proximityObserver.addProximityZone(zone);
    ProximityZone innerZone = this.proximityObserver.zoneBuilder()
            .forTag("treasure")
            .inCustomRange(3.0)
            .create();

    ProximityZone outerZone = this.proximityObserver.zoneBuilder()
            .forTag("treasure")
            .inCustomRange(9.0)
            .create();

    RequirementsWizardFactory
            .createEstimoteRequirementsWizard()
            .fulfillRequirements(MainActivity.this,
                    // onRequirementsFulfilled
                    new Function0<Unit>() {
                        @Override
                        public Unit invoke() {
                            Log.d("app", "requirements fulfilled");
                            proximityObserver.start();
                            return null;
                        }
                    },
                    // onRequirementsMissing
                    new Function1<List<? extends Requirement>, Unit>() {
                        @Override
                        public Unit invoke(List<? extends Requirement> requirements) {
                            Log.e("app", "requirements missing: " + requirements);
                            return null;
                        }
                    },
                    // onError
                    new Function1<Throwable, Unit>() {
                        @Override
                        public Unit invoke(Throwable throwable) {
                            Log.e("app", "requirements error: " + throwable);
                            return null;
                        }
                    });
}
private BroadcastReceiver mBatteryReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (send == 1 || send == 0) {
            new ApiUbidots().execute(send);
        }

    }
};
    @Override
    protected void onStart() {
        super.onStart();
            registerReceiver(mBatteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        }

// Stop the BroadcastReceiver
    @Override
    protected void onStop() {
        unregisterReceiver(mBatteryReceiver);
        super.onStop();
    }

// In Charge of sending variable to ubidots
    public class ApiUbidots extends AsyncTask<Integer, Void, Void> {
        private final String API_KEY = "A1E-0109ebb46b4990a4ed82f74d2912a9e6b481";
        private final String VARIABLE_ID = "5b62ab7ac03f97418ba1c28e";

        @Override
        protected Void doInBackground(Integer... params) {
            ApiClient apiClient = new ApiClient(API_KEY);
            Variable batteryLevel = apiClient.getVariable(VARIABLE_ID);

            batteryLevel.saveValue(params[0]);
            return null;
        }
    }

}

The problem is i am able to sending the data to the ubidots however i want to make it so that only if the condition has met, it will then send to the cloud. Other than that, it would not have send any data to the cloud.


text:
Q: Cannot get ARB debug output from LWJGL I am trying to use the ARB_debug_output extension but I cannot get any output from it (intentionally incorrect shaders will not cause debug output). I'm guessing I have made a mistake using the extension.
I have set up my context with debug enabled using;
        ContextAttribs contextAtrributes = new ContextAttribs(3, 2) // Core OpenGL version 3.2
        .withForwardCompatible(true)
        .withProfileCore(true)
        .withDebug(true);

I check for the debug output extension using;
            ContextCapabilities caps = GLContext.getCapabilities();
        if ( caps.OpenGL32 )
            System.out.println("OpenGL version 3.2 supported");
        if ( caps.GL_ARB_debug_output )
            System.out.println("ARB_debug_output extension supported");

Which gives the following output;
OpenGL version 3.2 supported
ARB_debug_output extension supported

I setup a callback function to print the debug output using;
new ARBDebugOutputCallback();

After this I run my program using incorrect/wrong shaders etc that produce compiler/linker errors using glGetShaderInfoLog and glGetError but I do not receive debug information from the callback function.

A: You need to pass the ARBDebugOutputCallback instance to the glDebugMessageCallbackARB method, like so:
glDebugMessageCallbackARB(new ARBDebugOutputCallback());

This is equivalent to passing a function pointer in the C API.
Note that there is no userParam argument; it is used internally by LWJGL to implement ARB_debug_output properly when there are multiple OpenGL contexts present. It's not necessary in Java anyway, you can pass per-instance data using the ARBDebugOutputCallback(Handler) constructor.

A: I am unfamiliar with LWJGL, but I am very familiar with this extension... setting the callback is insufficient to have it produce any output. You also need to specify which types of events you are interested in, the severities, and sources.
From the C bindings for OpenGL, a call like this would be necessary to enable generation of output messages:
glDebugMessageControlARB (GL_DONT_CARE,GL_DONT_CARE,GL_DONT_CARE,0,NULL,GL_TRUE);

In short, this enables messages for all sources, severities and types. This will make your debug output as verbose as your implementation can possibly give you.
Another thing you might consider is:
glEnable (GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);

This may increase overhead, but will output debug information immediately instead of buffering it and flushing periodically. This is very useful for diagnosing application terminating events.

I have an example of all of these things in action in an answer I wrote a while back, you may find some of the code (even though it is for C) useful.


text:
Q: Allow users to decline running the FrameBusting script when prompted Shortly after the IT Security SE site went into public beta, I posted a link to it, on several security-focused groups on LinkedIn.
In one of them, I received a negative response (though I'm not sure you'll be able to view it if you're not in the group) that really got me thinking...
When SE site first loads, it checks if its loading inside a frame on another site, and if so, it reloads itself as the top level page. When posting links in LinkedIn, it in fact opens it in a frame, with a top header-frame showing that you're still in LI...
The problem here was that SE, in trying to be a good citizen and not surprise its users, displayed a popup, alerting the user that the site will be re-displayed without frames for security reasons. While it's completely understood why framebusting is necessary, and of course I think the popup is probably a good idea, here's the problem...
There was no way to cancel the reloading.
The fellow who responded apparently freaked out a bit, from this dodgy javascript alert that wants to do stuff to him for security reasons (heh, sounds like AIT...), and since he's security conscious (if not an expert in javascript security - obviously his approval was not needed to do the bad stuff...), REFUSED to click OK, even though that was his only option.
So, he wound up doing a hard restart (and providing some bad publicity to the site).
Problem 1: Scary popup with no option to cancel.
Problem 2: Is this scary popup really necessary?
I also asked this question in a different direction, to try to garner some more discussion...

For the record, here is the main part of my response to him there:

There are two things you should consider, however:
  1. Removing frames IS recommended for any site that wants to be even remotely secure and isolated from other sites, there are many attacks based on framing the targeted website. In fact, your outrage should be directed at LinkedIn, for constantly framing everything! But then, links here are typically static, and NOT to such secure sites.
  2. If the website wanted to run some "malicious" javascript, they really would not have to ask you for permission first. Accepting the popup, as annoying as it was, would not have ALLOWED them to run the script, it could have happened anyway.
Either way, I think you are correct that this popup is not as it should be. I think their thinking was that they shouldnt "surprise" the user by changing his expected experience, or by redirecting without the user's acknowledgment. At the very least, I agree that there should have been an option to cancel the scary popup... I will try to submit this to the devs to fix the UI issue.
  For the record, StackExchange is a very wellknown and TRUSTED brand, and hundreds of thousands developers worldwide use StackOverflow.com often. Also the content is NOT generated by the developers themselves of course, but by us, the community. That is it's strength.

A: We can't allow declining this alert, ironically, because that would lead to a possible security issue. (also, why didn't this person simply terminate the browser process? rebooting seems extreme..)
That is, another script could override ours and allow framing, overwriting our UI in a frame ala this Twitter exploit:
http://shiflett.org/blog/2009/feb/twitter-dont-click-exploit
Basically, see here:
Frame Buster Buster ... buster code needed
it looks like X-Frame-Options: deny will now work, but only for very modern browsers http://blogs.msdn.com/ie/archive/2009/01/27/ie8-security-part-vii-clickjacking-defenses.aspx


text:
Q: Getting data from database based on user id Hi I am trying to get data from the database where the user can click on a person name and be redirected to some other page to see the person detail example like "user id = 1". Any idea on how to do it? If possible could you show me some example on how to do it thanks
Below is a screenshot on what I have done so far, the name below are in href so that it can redirect the user to another page and see the person details

A: you can use Laravel Eloquent for this one.
User::find($userid);

or using Laravel Query Builder
$users = DB::table('users')where('id','=', $userid)->get();

A: You can write a function for redirect in javascript with parameter is User ID. After that use your routes to get parameter (user id) on your link and write a query mysql in your controller to get data of this user id. Finally , you bring all of data from this user to your view.
function Redirect(userid) {
    window.location = 'http://yourdomain.com/profile/'+userid;
}

in your view add event onclick to username.
bob

in routes/web.php add new route:
Route::get('/{userid}','Controller@index');

in your controller:
$UserID=$request->input('userid');

now your parameter on your link will stored in $UserID. You can use this value to query data and show it on you view.

A: Here's a sample code of how to get the desired user from the data base.
$dbUser="root";
$dbPassword="root";
$dbServer="localhost:8889";
$dbName="test_database";

$connection = new mysqli($dbServer, $dbUser, $dbPassword, $dbName);

if($connection->connect_errno)
{
    exit("Database Connection Failed. Reason: ".$connection->connect_error);
}else{
    echo "Connection successful..;
}

$query = "SELECT id,first_name,last_name FROM Author where user_id= XXXX ";
$resultObj = $connection->query($query);

if ($resultObj->num_rows > 0)
{
    while ($singleRowFromQuery = $resultObj->fetch_array())
    {
        print_r($singleRowFromQuery);
        echo "Author: ".$singleRowFromQuery['first_name'].PHP_EOL."
";
    }
}

$resultObj->close();
$connection->close();

Make sure you replace the user_id appropriately and provide appropriate declaration.
you also pass data through the call url in the anchor tag using .. url ..?user_id=XXX


text:
Q: What's the difference between getElementById and getElementsByClassName I know maybe is not the right way of using the getElementsByClassName. For example the code below doesn't work as it is ¿why?, but when change getElementsByClassName("demo") for getElementById("demo2") does work
<!DOCTYPE html>

Click the button.

<button onclick="myFunction()">Try it</button>

anything

A: getElementsByClassName returns a collection (an HTMLCollection, which is "an array-like object"), because there may be multiple elements with that class name. A collection has no innerHTML property. You would have to iterate over each element in the collection using a loop:
var elements = document.getElementsByClassName("demo");
for (var i = 0; i < elements.length; i++) {
   elements[i].innerHTML = res;
}

By contrast, getElementById returns a single element, and it can do so because an IDs are unique.
(I'm assuming that getElementsByNameClass in your example is a typo.)

A: getElementById() is used to access the DOM elements using their id and getElementsByClassName() is used to access element(s) using their class.
Your code does not work because getElementsByClassName() returns an array-like object of all elements with given class. You need to access the first element of the array for your scenario

Click the button.

    <button onclick="myFunction()">Try it</button>

anything


text:
Q: How to post JSON using Oracle Rest Data Services I am using Oracle regular database(not like NoSQL or something) with oracle rest data services. I need to know how to fetch the HTTP message body using pl/sql. For an example,
send json object to the oracle application express through oracle rest data service, inside the application express expose the message body and get the content structured with json and fetch the fields one by one.

A: I deleted my earlier post. You can get the body as BLOB and convert to a character to work with but at least in the 4.2 version of the Application Express hosted instance at apex.oracle.com I got this to work with automatic JSON value binding.

Begin
  htp.p('JSON ename = ' || :ename);
  htp.p('JSON dept = ' || :dept);

  insert into emp(ename, deptno)
    values (:ename, :dept);
  htp.p('Rows Inserted = ' || sql%rowcount);

end;

You can test it by posting something like this:
{ "ename": "Seema", "dept": 10}
to the demo at : https://apex.oracle.com/pls/apex/gjarmiolowski/hr/employees/
make sure the Content-Type header is set to application/json
UPDATE: here's a windows curl command that works
curl --header "Content-type: application/json" --request POST --data-ascii "{\"ename\":\"hello\",\"dept\":\"10\"}" https://apex.oracle.com/pls/apex/gjarmiolowski/hr/employees/

A: If you install the latest APEX 5.0 which was released on April 15. You get access to a great API to work with JSON
I'm using it on 11.2 and have been able to crunch every single json, from simple to very complex objects with multiple arrays and 4/5 levels.  APEX_JSON
If you do not want to use APEX.  Simply install the runtime environment to get access to the API.
Example of a (real) POST method that accepts a very complex JSON object. Array with multiple objects and sub-arrays 3-5 levels deep.

I take the whole body and send it to a package for crunching. (the :body).  the :apikey comes with the header (not applicable here).
:body is blob so you package needs to convert it to clob and do any character set conversion if your database isn't UTF8.
After that you take the clob and parse it as json.
apex_json.parse (p_source => l_clob);

In my case the initial object is an array so I loop through all the items with
for i in 1 .. nvl (apex_json.get_count (p_path => '.'), 0) loop

Example of finding a varchar2 value
l_app.medication_description := apex_json.get_varchar2 ('[%d].regularMedicationDetails', i);

Where the "i" is referencing the nth object in the array,.
As a veteran PL/SQL programmer,  this setup as blasted me into the modern web driven world.


text:
Q: How to colourise user input in Python? I'm creating a command-line calculator tool, and I'd like to get it to format the user's input as they type, similar to what Fish and Powershell do (screenshots).
Currently, the only easy method for doing this that I can think of is getting characters one at a time, and then reprinting the formatted line to the screen.
# This code is probably very dodgy,
# it's just to give you an idea what I'm thinking
# Use external getch module to get input without echoing to screen
from getch import getch
inp = ""
while True:
    char = getch()
    if char == '\n': break
    if char == '\b': inp = inp[:-1]
    else: inp += char
    # Print with carriage return so that next input overwrites it
    print(colourFormatInput(inp) + '\r')
# Outside loop: process input and devliver results

Whilst this would techincally work, I feel like it is a ton of manual effort, and would only become more complex if I wanted to add functionality such as using arrow keys to move the cursor's position.
Is there a simple way to get this kind of functionality without having to code all of it up myself?

A: I use the library colorama.
import colorama
import sys

def hook(tp, *args):
    if tp is KeyboardInterrupt:
        print(colorama.Fore.RESET)
        exit()

def colored_input(text: str, color):
    sys.excepthook = hook
    inp = input(text + color)
    print(colorama.Fore.RESET, end="", flush=True)
    sys.excepthook = sys.__excepthook__
    return inp

name = colored_input("What's your name? ", colorama.Fore.RED)
age = colored_input("What's your age? ", colorama.Fore.YELLOW)

print(f"Nice to meet you {name}({age})")

I use sys.excepthook to catch the KeyboardInterrupt so I can reset the color back when the user types CTRL+C, and then I set the original excepthook back (sys.__excepthook__)

A: You can do this with prompt_toolkit
here is the documentation if you need:

*

*Getting Started

*Asking for input/prompts
You can add Syntax Highlighting to input by the following as given in examples:

Adding syntax highlighting is as simple as adding a lexer. All of the Pygments lexers can be used after wrapping them in a PygmentsLexer. It is also possible to create a custom lexer by implementing the Lexer abstract base class.
from pygments.lexers.html import HtmlLexer
from prompt_toolkit.shortcuts import prompt
from prompt_toolkit.lexers import PygmentsLexer

text = prompt('Enter HTML: ', lexer=PygmentsLexer(HtmlLexer))
print('You said: %s' % text)

In the same way as above you can create custom prompt_toolkit.lexers.Lexer for calculator highlighting just like the following example. Here I create a custom helper class:
from typing import Callable
from prompt_toolkit.document import Document
from prompt_toolkit.formatted_text.base import StyleAndTextTuples
from prompt_toolkit.formatted_text import FormattedText
from prompt_toolkit.shortcuts import prompt
import prompt_toolkit.lexers
import re

class CustomRegexLexer(prompt_toolkit.lexers.Lexer):
    def __init__(self, regex_mapping):
        super().__init__()
        self.regex_mapping = regex_mapping

    def lex_document(self, document: Document) -> Callable[[int], StyleAndTextTuples]:
        def lex(_: int):
            line = document.text
            tokens = []
            while len(line) != 0:
                for pattern, style_string in self.regex_mapping.items():
                    match: re.Match = pattern.search(line)

                    if not match:
                        continue
                    else:
                        # print(f"found_match: {match}")
                        pass
                    match_string = line[:match.span()[1]]
                    line = line[match.span()[1]:]
                    tokens.append((style_string, match_string))
                    break
            return tokens
        return lex

Now with the above helper class implemented we can create our regex patterns and their respective styles, to learn more about what you can have in styling string go to this page
# Making regex for different operators. Make sure you add `^` anchor
# to the start of all the patterns
operators_allowed = ["+", "-", "/", "*", "(", ")", "=", "^"]
operators = re.compile("^["+''.join([f"\\{x}" for x in operators_allowed])+"]")
numbers = re.compile(r"^\d+(\.\d+)?")
text = re.compile(r"^.")

regex_mapping = {
    operators: "#ff70e5",  # Change colors according to your requirement
    numbers: "#ffa500",
    text: "#2ef5ff",
}

MyCalculatorLexer = CustomRegexLexer(regex_mapping)

With the lexers created you can now use the lexer in the function prompt:
text = prompt("Enter Equation: ", lexer=MyCalculatorLexer)

# Or

def input_maths(message):
    return prompt(message, lexer=MyCalculatorLexer)

text = input_maths("Enter Equation: ")

Here is some example output:

And now everything works. Also do check out prompt_toolkit, you can
create tons of custom things as shown in there gallery

A: Another example:

CGREEN = '\33[32m'
CYELLOW = '\33[33m'
CBLUE = '\33[34m'
CVIOLET = '\33[35m'
CBEIGE = '\33[36m'
CWHITE = '\33[37m'
CGREY = '\33[90m'
CRED = '\033[91m'
CYELLOW = '\33[33m'
CYELLOW2 = '\33[93m'
CEND = '\033[0m'

print(CGREEN + "This is green text" + CEND)
print(CYELLOW + "This is yellow text" + CEND)

# Another interesting example (courtesy: https://www.lihaoyi.com/post/BuildyourownCommandLinewithANSIescapecodes.html)

for i in range(0, 16):
    for j in range(0, 16):
        code = str(i * 16 + j)
        colorCode = u"\u001b[48;5;" + code + "m"
        print(colorCode + " Color {} ".format(code) + CEND)


text:
Q: Graphql without a server I'd like to include an embedded graphql processor in my .net app.
I want to execute GraphQL functions via a method and I don't need the server or an endpoint.
Basically an internal GraphQL processor. I'll define the resolvers and the schema and then run queries via a method call. Is this possible?

A: You may take a look NReco.GraphQL (which is based on GraphQL.Net but has an additional features, like aggregation, filter, ect.). You can compose in code schema, query (or query object) and call it just in-code.


text:
Q: I am receiving a Component returned failure code: 0x80040111 even though the js function is defined internally I am in need to open a pop-up message when my client clicks the link to open an internal application. The message is provided in the alert function. When the user closes the alert, I want him/ her taken to the internal application, for which the link is provided in window.location func.
But as told, I am receiving the error - The function is not defined. Pls guide me through this.

AlertIt() defined internally in my html file


text:
Q: Delete text in between HTML tags in vim? I know
di<

will delete in an HTML tag itself.
Is there an easy way to delete text in between two tags?
How can I delete this text?

Thanks!

A: try dt< while the cursor is on the first character to delete. In your example the 'H'.

A: dit - delete inner tag, remains in command mode
cit - change inner tag, changes to edit mode
di" - delete inside ""
di' - delete inside ''
di( - delete inside ()
di) - delete inside ()
di[ - delete inside []
di] - delete inside []
di{  -delete inside {}
di} - delete inside {}
di< - delete inside <>
di> - etc
swap first letter d for c, if you want to be in edit mode after typing the command

A: dit will delete the text between matching XML tags.  (it is for "inner tag block".)
See :h it and :h tag-blocks.

A: cit
ci"

Two of the best productivity enabler commands of vim.
I save a lot of time and effort with just those two.

A: (cursor on first character to delete)
v/<[enter]d
This solution starts on the first character, then enters visual mode ("v"). It then searches for the next start bracket ("/<"), and then press enter to exit the search.
At this point, your visual selection will cover the text to delete.  press d ("d") to delete it.
If I had to do this for a bunch of tags, I'd record the command and combine it with some other searches to make it repeatable.  The key sequence might look like this:
[cursor on start of file]
qa/>[enter]lv/<[enter]dnq
then press:
20@a
to do this for 20 tags

A: If you're aiming to do the inverse of deleting text between flags, I suggest installing Vim-Surround and running dst which deletes the surround tag

A: This applies to wherever your cursor is:
HTML
dit - for deleting tag content while still in command mode
cit - for deleting tag content, insert mode (Preferred Way)
STRING
dit - for deleting string content which still in command mode
ci"/ci' - for deleting string content, insert mode (Preferred Way)


text:
Q: How to compare 2 datasets in Java Spark? I am new to Spark and have been given a task to compare 2 csv files in spark java. I am creating the 2 datasets from those csv files. I have to compare using the key and display the output as to which value is different and for what field. Could someone please help. Thank you

A: You can use df.except(df1)
This function can compare 2 dataset, it will return a new dataset containing rows in df but not in df1.


text:
Q: "input" signal corresponding feedback network The pictures below are enhanced output impedance current mirror and a general negative feedback model.
The current mirror has a negative feedback loop. However, I can't determine where is the input that is corresponding to the "input" signal in the general feedback model.
What is the input signal of the feedback network here?
The output signal is Iout, and the input is not clear to me.
PS: I would like to talk more about my purpose of this post now.
I want to make it clear what feedback configuration the circuit is (voltage-voltage, current-voltage, voltage-current or current-current) and then I can apply the feedback theorem to calculate output impedance of this circuit.
Rout = gm1*ro1*ro2*(1+A) where A is the loop gain and the output impedance of the network without feedback is gm1*ro1*ro2.

A: The input signal is Vbias and the output signal is the voltage at the drain of Q2. The gain Aol is simply A since Q1 acts as a source follower when driven by the amplifier.
The goal is to stabilize the drain voltage of Q2 to increase the output resistance of the cascode. The technique is called "gain boosting", because the increased output resistance results in a higher gain when this circuit is used as part of an amplifier.
In order to determine the output resistance a two port model can be used as shown below, here the amplifier A is missing, but it could be taken into account by using gm A instead of simply gm. Also the current sensing path is assumed to be ideal which introduces a slight error. To fix this an additional resistor ro2
would be required in at the feedback input of the lower two-port.

Without modification the result is:
$$
R_{out} = \frac{v_x}{i_x} = ro(1 + g_m R_F)
$$


text:
Q: Free array of pointers in C I work on an eclipse environment with C. To explain things simply I have a simple struct to define some elements needed in my project :
typedef struct adc adc_def;

     struct adc {
        SPI_HandleTypeDef *spi_hal;
        //Adresse de l'esclave avec qui communiquer
        uint8_t numero_adc;
        registres_adc config;

    };

I also have a function instantiating a new struct (the one declared previously). I need 4 of them, that I store in a global array:
adc_def* adc_new(SPI_HandleTypeDef *param_spi_hal, uint8_t numero_adc) {

    adc_def *adc = NULL;

    registres_adc tmp_config;

    adc_status_t status_adc;

    if ((NULL != param_spi_hal) && numero_adc <= ADC_MAX) {
        if (NULL != (adc = malloc(sizeof(adc_def)))) {

            adc->spi_hal = param_spi_hal;
            adc->numero_adc = numero_adc;

            adc->config.configuration = DEFAULT_CONF;

            //Copie des tab en const pour les passer dans la fonction
            memcpy(adc->config.hpf, HPF, 2);
            memcpy(adc->config.fsc, FSC, 3);
            memcpy(adc->config.ofc, OFC, 3);

            if (HAL_OK != adc_stopCont(adc)) {
                free(adc);
                adc = NULL;
            }
            ///////////
            if (HAL_OK != adc_setConfig(adc, adc->config)) {
                free(adc);
                adc = NULL;

            }

        }
    }
    return adc;
}

Once I'm in my main program I store 4 of them in a global array :
SPI_HandleTypeDef hspi1;
adc_def *adc_present[4];

void re_init(){

    for (int z = 0; z < 4; z++) {
        free(adc_present[z]);
        adc_present[z] = NULL;
    }

    for (int a = 0; a < 4; a++) {
        adc_present[a] = adc_new(&hspi1, a+1);
    }

}

int main(void) {

    for (int a = 0; a < 4; a++) {
        adc_present[a] = adc_new(&hspi1, a+1);

    }

    re_init();

}

In my program I will need to free all the struct stored in adc_present to, again, recreate other adc_def struct elements. Therefore I do this code for that :
It seems like this code provoke memory leaks and bugs, I cannot reaffect in this tab even though I used free previously. Am I missing something? The tab is not being freed correctly here?
I have an array of pointers allocated dynamically that I free before reaffecting them, I don't understand

A: One problem is in this code:
        if (HAL_OK != adc_stopCont(adc)) {
            free(adc);
            adc = NULL;
        }
        ///////////
        if (HAL_OK != adc_setConfig(adc, adc->config)) {
            free(adc);
            adc = NULL;

        }

If the call to adc_stopCont() fails, you set adc to NULL with
            adc = NULL;

but then call adc_setConfig() anyway:
        if (HAL_OK != adc_setConfig(adc, adc->config)) {

If adc is NULL, that will fail because adc->config will try to dereference a NULL pointer.
This would be much better:
        if (HAL_OK != adc_stopCont(adc)) {
            free(adc);
            adc = NULL;
        }
        else if (HAL_OK != adc_setConfig(adc, adc->config)) {
            free(adc);
            adc = NULL;
        }

or
        if (HAL_OK != adc_stopCont(adc)) {
            free(adc);
            return(NULL);
        }
        if (HAL_OK != adc_setConfig(adc, adc->config)) {
            free(adc);
            return(NULL);
        }


text:
Q: Comparison of the functions print between Python and R Python is usually much faster than R but the following code takes more time in Python than in R.
# R
for (i in 1:10000){print(i)}
# It takes less than a second

###############################################

# Python
for i in xrange(10000):
    print i
# It takes 5 minutes!

What explain this difference?
Note: The point of my question is not to know how to increase the performance of my code but "why is Python much slower than R at running this code".

A: The Verdict:
The cause for this is the printing, In python writing to stdout is quite slow when comparing with R so trying to write to the stdout 10000 TIMES! in python might seem a bit slow (ignoring the range overhead) however printing it in one go reduces this gap significantly.
This code is much quicker because it writes to stdout only once:
lst = []

for i in range(10000):
    lst.append(i)

print lst

However this isn't because this writes to the stdout stream 10000 times:
for i in range(10000):
    print i

Also use the more memory efficient xrange() function and due to causes such as these only python 2's range() function has been replaced with the xrange() function in python 3...
It must be said that no matter what your original code only took about 5-6 seconds not 5 minutes...


text:
Q: no puede leer el id del xml esoty hacinedo un ,menu para que muestre las ventanas del pop up qu estoy diseñando pero a la hora de actualuizar esos cambios me mnada un error dice que no puede encontras un id estuve tratando de corregirlo pero me sigue mandando error
Adjunto codigo del menu:
```<odoo>
    <menuitem id="menu_3_mti_report_sale_terrestre"
              name="Informes(Terrestre)"
              parent="sale.sale_menu_root"
              sequence="1"/>

    <menuitem id="menu_mti_sale_report"
              parent="menu_3_mti_report_sale_terrestre"
              name="Numeros de referencia"
              action="mti_sale_report"
              sequence="2"
              />
   </odoo>```

asi es como estoy estructurando el menu en la carpeta views
archivo xml de la carpeta wizard
```<?xml version="1.0" encoding="utf-8"?>

    <odoo>
<record id="mti_sale_report_wizard" model="ir.ui.view">
    <field name="name">referencias_sales_terrestre</field>
    <field name="model">mti_referencia</field>
    <field name="arch" type="xml">
        <form>
            <group>
              <group>
                <field name="date_order"/>
              </group>
              <group>
                <field name="seller_id"/>
              </group>
            </group>
            <footer>
                <button name="get_referencia_report" string="PDF Report" type="object" class="btn-primary"/>
            </footer>
        </form>
    </field>
</record>

<record id="mti_sale_report" model="ir.actions.act_window">
<field name="name">Informe de numeros de referencia</field>
<field name="type">ir.actions.act_window</field>
<field name="res_model">mti_referencia</field>
<field name="view_mode">form</field>
<field name="target">new</field>
 </record>
       </odoo>```

y asi es como tengo el xml del wizard estuve haciendo cambios tratando de corregir el error pero nada me a funcionado que puedo hacer aqui para corregir el error


text:
Q: What do I do when my iPhone is stuck at a screen with an USB cable and iTunes logo? I just tried updating the iPhone's firmware, and things went haywire.
iTunes informed the update had failed and linked me to iOS: Resolving update and restore alert messages.
The iPhone is stuck on the image from the top of that page.
I held down the sleep and home buttons until it turned off and turned it back on, and then went through the iPhone's 'restore' mode.
It then error'd again and I'm stuck back with the logos on the iPhone.
How do I to fix this?

A: I would definitly follow all directions on that page, they should help, If not I recommend taking it to the apple store, A bunch of people I know have been having weird problems with their iPhones. One took his into the apple store and got a completely new phone because of it.

A: I saw that screen the other day .. I was using my laptop unplugged and told it to go ahead with the latest iPhone software upgrade.  It took a while, I wasn't paying attention, and BANG .. the laptop goes to sleep because it is out of juice.  When I plugged it in it sat for a few minutes then asked if I wanted to restore.  I did, and it worked.
I presume that you have followed the suggestions in the linked page, and that they haven't worked.  The only other things I would try (before visiting the Genius Bar) are:

*

*Hard reset the iPhone (hold both buttons until the apple appears).  This likely will not fix the problem, but will clear out any detritus.

*With iTunes running, connect the iPhone and let it sit a while.

*If iTunes recognizes the iPhone, try the restore option.

Good luck.


text:
Q: Create a heap at a specific memory address for dynamic memory allocation Is there a way to create a heap at a specific memory location (separate from the system heap) that can be used for dynamic memory allocation, but makes use of the dynamic memory allocator built into the C library.
I'm looking for something functionally equivalent to this:
UserHeap heap(startAddress, size);

void* allocatedMemory1 = heap.Allocate(100);  //Allocate 100 bytes.
void* allocatedMemory2 = heap.Allocate(200);  //Allocate 200 bytes.

/* ... Do seomthing useful with the memory ... */

heap.Free(allocatedMemory1);
heap.Free(allocatedMemory2);

This uheap.h seems to have what I'm looking for, but this doesn't seem to exist in newlib.  I'm wondering if GCC or newlib might have something.  If not I think I may end up porting ptmalloc.  However, its my understanding that this code is already in the C library and I'd hate to waste the memory reproducing it.
I'm using Sourcery Codebench Lite (GCC) with newlib (C library).

A: Rolling out your own allocator isn't all that hard and in many ways can be quite instructive.
First you need to figure out what sort of allocation/deallocation pattern you want to support in that heap. For general use, allocators similar to dlmalloc (Doug Lea's) are quite good.
There are many more kinds for specific usages: stack based (where a free is always the address of the last allocated unfreed memory block), fixed sized based (where the memory is divided in fixed sizes which are returned), queue based, small block, etc.
Most of these can have an internal allocator as well, for example suppose you have a fixed sized allocator, you could tell it to allocates in blocks of X bytes (from a second allocator or from the system) which then get divided in blocks of Y bytes. Pointers to chunks of size Y bytes are returned but when there is no free block, you allocate a new block of size X and divide it up.
For convenience, you can also implement the new/delete operators globally or on certain classes to redirect their allocations to your custom allocator.
Placement new on your heap is also handy, see below.
I personally prefer using macros since it allows extra debug information to be added (function/line/etc) quite easily. ie:
#define CUSTOM_NEW(Heap) new(Heap, __FUNCTION__, __LINE__)
int* ptr = CUSTOM_NEW(someHeap) int[32];

A: I finally came across a blog by Eli Bendersky that illustrates exactly what I was looking for.  memmgr – a fixed-pool memory allocator


text:
Q: Multiplication Question I have this question for my math class. I've been working on it for about an hour. Here it is:
Each of the letters, F,I,V,E, in this multiplication stands for a different digit. What are the values of the letters?
    FIVE
  X FIVE
  -------
   ****F
  ****I
 ****V
****E
--------
********

From this I've figured out that this essentially means:
E*E % 10 = F, V*E % 10 = I, I*E % 10 = V, F*E % 10 =E

with the % meaning modulo.
I wrote a quick python script to try and brute force it with the code shown below:
tries = 9
for F in range(tries):
    for I in range(tries):
        for V in range(tries):
            for E in range(tries):
                if E * E % 10 == F and V*E % 10 == I and I*E%10 == V and F*V%10 == E:
                    print(F,I,V,E)

and it output:
0 0 0 0
1 1 1 1
5 5 5 5
6 6 4 4
6 6 6 6

Which all fit the criteria but aren't the right answer since there are repeating numbers.
I have no idea how else to approach this. Any help is appreciated.

A: You have a typo in the second to last line of your Python script. Re-run with:

if E * E % 10 == F and V*E % 10 == I and I*E%10 == V and F*E%10 == E:

and the solution (6, 8, 2, 4) shows up.

A: $F$ is the last digit of a perfect square.
and $F\ne E$
It appears that every based on the asterix that $F>1$ i.e. each line appears to be a 5 digit number and that is not going to happen if the leading digits are $1$'s.
$F\in \{4,6,9\}$
which puts $E\in\{2,3,4,7,8\}$
$VE = I\pmod {10}$ and $IE = V\pmod {10}$
$IE^2 = IF = I\pmod {10}$
$(F = 1)$ or ($F = 6$ and $I,V$ are even).
But we have decided that $F\ne 1$
$F = 6, E = 4$ and $V,I$ are even
$6824$ and $6284$ should both work.


text:
Q: Fonts family are not rendering correctly in HTML page , AngularJS application In our AngularJS application, we are binding following HTML 'Description'(which is stored in Database) to DIV. This HTML code generates from TinyMCE editor.

Friday
fever!

In html page, we have written this code,

But it is not showing applied fonts. Expected result is it needs to be displayed in proper font.


text:
Q: LinkedIn access token api returns bad request error in c# I am using linked oauth 2 api to fetch the access token.But I am getting a 400 (BadRequest) response from that api.I am sharing the code below
NameValueCollection parameters = new NameValueCollection();
parameters.Add("grant_type", "authorization_code");
parameters.Add("code", Code);
parameters.Add("redirect_uri", RedirectURL);
parameters.Add("client_id", ClientId);
parameters.Add("client_secret", ClientSecret);

WebClient client = new WebClient();
client.Headers[HttpRequestHeader.ContentType]="application/x-www-form-urlencoded";
var result = client.UploadValues("https://www.linkedin.com/oauth/v2/accessToken", parameters);

Could anyone help me to find what went wrong here. I am passing the correct values for all parameters, got client_id, client_secret from my application and the code I am getting from my initial authorization request.
I am not able to test this scenario in postman since the auth-token request depends on the code generated from the authorization step.

A: AuthorizationUrl must look like this

https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=78y4rii84jcf43&state=E30980C1T666444z&redirect_uri=https://www.testWeb.com

Access Token Url will look like this,

https://www.linkedin.com/uas/oauth2/accessToken?grant_type=authorization_code&code=AQTTP5DZ68JHRVO2_i9vpie8KBZ3gfgffhjfhjfhjfp88hf3szNauFkUpuvqfyKhjsmO7Bcps4JXUo1EWQay1q1q1MXKsajRWoZ4q-ofmTjJfknaYTk5SO5oHUgfhgfdsgfdgdfdgfsgdgdhgdhgddipkfTIzdkGUSWZkPYS1&client_id=78y4rii465rv084&redirect_uri=https://www.testweb.com&client_secret=1t56E7bLDl2fnVWh

And your Params are missing with
QUESTION_MARK (?) after https://www.linkedin.com/oauth/v2/accessToken
your Grant type param must include grant_type=authorization_code
than & param
than client_id=YourApiKey
than & param
than redirect_uri=YourRedirectUri
than &
than client_secret=YourSecretKey


text:
Q: Terraform for loop get index I was wondering how can I get the index in a for loop?
I am working on NACL of my vpc:
[
    for myIpList in data.terraform_remote_state.globals.outputs.myIpRanges:
    {
      # allow inbound traffic for IPv6
      "ipv6_cidr_block": myIpList,
      "from_port": 0,
      "protocol": -1,
      "rule_action": "allow",
      "rule_number": (here  I would like to insert the index of the for loop),
      "to_port": 0
    }
  ]

And I was trying to place for the "rule_number" the index of the for loop.
*sorry for my bad english

A: You can get index by adding it in the for loop (index):
[
    for index, myIpList in data.terraform_remote_state.globals.outputs.myIpRanges:
    {
      # allow inbound traffic for IPv6
      "ipv6_cidr_block": myIpList,
      "from_port": 0,
      "protocol": -1,
      "rule_action": "allow",
      "rule_number": index,
      "to_port": 0
    }
  ]

I assume that everything else is correct in your code.


text:
Q: Delete Rows in apache spark using java Need to delete second row in that dataset i am new to apache spark can anyone help me to resolve.
below is the code:
  public class DeleteRow {
         public static void main(String[] args) {
          System.setProperty("hadoop.home.dir", "C:\\winutils");
          JavaSparkContext sc = new JavaSparkContext(new SparkConf().setAppName("JoinFunctions").setMaster("local[*]"));
          SQLContext sqlContext = new SQLContext(sc);
          SparkSession spark = SparkSession.builder().appName("JavaTokenizerExample").getOrCreate();

          List<Row> data = Arrays.asList(
            RowFactory.create(1,"Hi I heard about Spark"),
            RowFactory.create(2,"I wish Java could use case classes"),
            RowFactory.create(3,"Logistic,regression,models,are,neat"));

          StructType schema = new StructType(new StructField[] {
            new StructField("label", DataTypes.IntegerType, false,
              Metadata.empty()),
          new StructField("sentence", DataTypes.StringType, false,
            Metadata.empty()) });

            String ins  = data.get(1).toString();
            System.out.println(ins);

          Dataset<Row> sentenceDataFrame = spark.createDataFrame(data, schema);
        sentenceDataFrame.drop(data.get(1).toString());

Any help appreciated.

A: Use a FilterFunction.
I wrote a JUnit Test to help you out.
@Test
public void sampleDeleteRowTest() throws Exception {
    List<Row> data = Arrays.asList(
            RowFactory.create(1, "Hi I heard about Spark"),
            RowFactory.create(2, "I wish Java could use case classes"),
            RowFactory.create(3, "Logistic,regression,models,are,neat"));

    StructType schema = new StructType(new StructField[]{
            new StructField("label", DataTypes.IntegerType, false,
                    Metadata.empty()),
            new StructField("sentence", DataTypes.StringType, false,
                    Metadata.empty())});

    String ins = data.get(1).toString();
    System.out.println(ins);

    Dataset<Row> sentenceDataFrame = spark.createDataFrame(data, schema);
    long size = sentenceDataFrame.count();

    assertTrue("SentenceDataFrame Size = " + sentenceDataFrame.count(), size == 3);

    sentenceDataFrame = sentenceDataFrame.filter(new FilterFunction<Row>() {
        @Override
        public boolean call(Row row) throws Exception {
            Integer label = row.getInt(0);
            return label != 2;
        }
    });

    size = sentenceDataFrame.count();

    assertTrue("SentenceDataFrame Size = " + sentenceDataFrame.count(), size == 2);
}

https://spark.apache.org/docs/2.1.0/api/java/org/apache/spark/sql/Dataset.html#filter(org.apache.spark.api.java.function.FilterFunction)
https://spark.apache.org/docs/2.1.0/api/java/org/apache/spark/api/java/function/FilterFunction.html
Alternatively, you can use a Lambda function to achieve the same desired result:
sentenceDataFrame = sentenceDataFrame.filter((FilterFunction<Row>) r -> (r).getInt(0) != 2);


text:
Q: Regex or another way to extract full URLs + relative URLs from HTML So I have a SharePoint site and I have users who submit new items into a SharePoint List. Some fields in the list item contain URLs that reference files or images, e.g. "http://host/abc.jpg" or "/abc.jpg".
In another field, users edit HTML code which may contain any tags such as ,  and so on.
My goal is to find fields that contain links/URLs, and extract those URLs that point to something that has a filename plus extension. I have no problem extracting this from the SharePoint fields which may contain either some irrelevant information or the URL (and the URL only) using these two regexes:
//this will match full url e.g. http://localhost/path/a.jpg
var fullUrlRegex =
            new Regex(@"^https?:\/\/(?:.*)[\.]+(?:[a-z0-9]{1,4})$");
//this will match an absolute path like //test/files to upload/222.jpg
var absolutePathRegex =
            new Regex(@"^\/.*[\.]+(?:[a-z0-9]{1,4})$");

var fullUrlRegexMatch = fullUrlRegex.Match(value);
var absolutePathRegexMatch = absolutePathRegex.Match(value);

//now check which one matched and save the value

However, I am not sure how to approach extracting URLs (both relative and full URLs) from HTML code that users enter in the other field.
Suppose this is the user's input, and I need to extract both links to files from that HTML code.

This is a picture!
And this is a pic too:

The tags can really be anything, not just limited to  and . One way I thought I could approach this is to use HTML Agility Pack, but this seems like an overkill. Would it be sufficient to regex-search for src="(match this)" and href="(match this)"? Anything I might miss?

A: Try this regex
(?<=(href="|src="))[/]*(?:[A-Za-z0-9-._~!$&'()*+,;=:@]|%[0-9a-fA-F]{2})*(?:/(?:[A-Za-z0-9-._~!$&'()*+,;=:@]|%[0-9a-fA-F]{2})*)*

Just add any other valid tags to the list in (href="|src=")

A: Your regexes should not contain ^ at the start and $ at the end. It is an achor. See: https://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx.
Also use Matches method to get all matches.


text:
Q: PrimeNG TimeOnly Calendar: Cannot Select default time intuitively I am using this PrimeNG timeonly calendar:
    <p-calendar  id="startHour" name="startHour" [defaultDate]="startHourDefault"  [(ngModel)]="startHourValue" [timeOnly]="true" hourFormat="12" [inline]="false"
placeholder="Select start hour"  [disabled]="IsDisabled"></p-calendar>

I am setting start default hour to 9:00 AM
var today = new Date();
    this.startHourDefault= new Date(today.getFullYear(), today.getMonth(), today.getDate(), 9, 0, 0);

Now when I open widget I cannot select 9:00 AM. Either I have to select carrots to select 9:01 and then move back to 09:00 AM again. This does not look very intuitive.

Is there a way to click on below box(highlighted in red box) to select time

Currently using PrimeNG 8 with Angular 8.
Thanks in advance.

A: After so many days looking into it. I can not see any solution provided by PrimeNG community. Best workaround for this kind of scenario is to set default date when user clicks on the textbox. For this purpose PrimeNG provide onFocus event.In template set like this:
  <p-calendar  id="startHour" name="startHour" [defaultDate]="startHourDefault"  [(ngModel)]="startHourValue" [timeOnly]="true" hourFormat="12" (onFocus)="selectDefaultDate()" [inline]="false"
placeholder="Select start hour"  [disabled]="IsDisabled" ></p-calendar>

In component set the default time.
selectDefaultDate(){
if(!this.startHourValue)
this.startHourValue=this.defaultDate;
}


text:
Q: Accessing members of elements of a 2d array c++ I'm having trouble getting access to the data members of the elements in an array.  I have an array of type gamePiece which is a class I defined in a separate header.  The gamePiece has a string data member "name"  which I need to set from a function in my gameBoard file, a gameBoard being a 2d array of gamePieces.  Whenever I try to run the main program, which calls "readBoard" it stalls when it tries to assign a "name" to one of the gamePieces.  What am I doing wrong?
//gamePiece.h file
#ifndef GAMEPIECE_H_INCLUDED
#define GAMEPIECE_H_INCLUDED
#include <string>

using namespace std;

class gamePiece //not a struct b/c there are other functions not included here
{
    public:
        string name;
        int row;
}

//gameBoard.h
class gameBoard
{
    public:

    gamePiece board[][6];
    int foxCount, sheepCount;
    void readBoard(istream& boardFile);
    //void printBoard();
};

//gameBoard.cpp
void gameBoard::readBoard(istream& boardFile)
{
    int tFoxCount = 0;
    int tSheepCount = 0;
    gamePiece tBoard[6][6];
    gamePiece tPiece;

    tboard[0][0].name = "Sherry";

    cout << tboard[0][0].name;
}


text:
Q: Am I missing something by not installing ri and rdoc for gems? I've never seen the point of installing the ri and rdoc for gems and my .gemrc file has --no-ri and --no-rdoc set. Since every gem includes ri and rdoc info, I just wondered if I'm missing something? Is there any advantage to installing the ri and rdoc for a gem?
Thanks
Chris
Summary
If you don't install the ri and rdoc, you don't lose anything of great value. I thought perhaps it got used in some of the IDEs (I'm an Emacs user) but that doesn't seem to be the case.

A: Personally, I'm installing my gems without rdoc and ri, too, because normally you can find all the documentation you need on the internet as well (i.e. www.rdoc.info), so there's no need for investing hard disk space and time the generation takes

A: Install it if you want locally available documentation for the gem.

A: The point of installing ri documentation is simply that you can use the "ri" command to access method-by-method documentation. For an example, try: "ri String#reverse". Exit by pressing "q".
To try out RDoc documentation, run "gem server" and then connect to localhost:8808 in your browser. I find it useful - you can even click on a method name to see the source code. Of course, you can just go into your gems folder and open the HTML files in the doc folder.
An alternate way to access RDoc is the gemdoc command. See http://www.stephencelis.com/2008/06/12/bashfully-yours-gem-shortcuts.html. That's quite handy, IMHO.
Anyway, you can be lazy and wait until you need the RDoc documentation, and then generate it with "gem rdoc ".

A: This article gives a great why and how of using ri:
http://jstorimer.com/ri.html
Best point on that list is #1: ri understands Ruby.  For instance:

$ ri ActiveRecord::Base#save
(from gem activerecord-3.2.8)
Implementation from ActiveRecord::Persistence

[...]

(from gem activerecord-3.2.8)
Implementation from ActiveRecord::Validations

[...]

Notice the method is found even if not directly on ActiveRecord::Base itself.


text:
Q: jQuery.post() can't send too long queries/serialized data? I have a $.post() that is trying to send a serialized form as the data, but also some additional variables from the page. One of them is the HTML code of the #designer-window div. This HTML can be thousands of characters long, in my example its 3411 characters.
The post request looks like this:
var html = $('#designer-window').html();
var cardid = $('input[name="cardid"]').val();
var id_card = $('input[name="id_card"]').val();

$.post('sv/ajaxadmin/', $('form[name="savecard"]').serialize()+"&html="+html+"&image="+renderedImage+"&cardid="+cardid+"&id_card="+id_card, function(data){
    location.html(original);
    $('form[name="savecard"] button').attr("disabled", false);
    $('form[name="savecard"]').prepend(data);
    console.log(data);
}, "text");

Now, if I use console.log(html); to print the data before it is send. I get the complete HTML string. However in my /sv/ajaxadmin/, if i echo $_POST['html']; then the string is cut off halfway through. The end of the string is missing.
So what I'm guessing is that there is some kind of limit with the amount of characters or bytes you can send using the function above, so the whole string isnt send. Only parts of it.
So a few things:

*

*Maybe there is another way to set the post data to be send in the jQuery.post() function? Obviously I can use {data: var, data2: var2...}, the problem with this is combining it with $('form').serialize(). Is it possible?

*Anyone know if there actually is a limit? I have not found any information regarding a byte/character-limit in jquery post requests. But the only way I can see it, is that there is a limit that is the cause of this issue. Do you have any other ideas?
EDIT:
After additional testing I noticed that it seems to have to do with the & character. So in the HTML, if a string contained & that meant that the $.post() data-query-string would get cut off. I tried escaping/replacing & with & but it still mess up the query. So... How the question is then, how do I escape &'s to be able to send them in my query.
SOLVED: I wrapped my html variable with encodeURIComponent(); to escape it. Worked!

A: The problem may not be the limit of the character count but the limit on how many inputs variables you can send (defaults to 1000).
Adding/Changing this in your php.ini should fix it
max_input_vars 2000

max_input_vars  integer
How many input variables may be accepted (limit
  is applied to $_GET, $_POST and $_COOKIE superglobal separately). Use
  of this directive mitigates the possibility of denial of service
  attacks which use hash collisions. If there are more input variables
  than specified by this directive, an E_WARNING is issued, and further
  input variables are truncated from the request.

http://php.net/manual/en/info.configuration.php#ini.max-input-vars

A: The reason it didnt work was because I didnt escape my var html. The variable was containing hundreds of characters of HTML and if there was an ampersand (&) in there, it meant that my POST string was cut off.
I solved this by using encodeURIComponent() which escapes all the special characters, such as &.


text:
Q: Calc question regarding the volume of my cheese So I've just got my cheese from the cheesemonger and he's cut it along the axis $x$,$y$, and $z$ so I can do my math homework with it.  The lengths of my cheese are:
$x$=6
$y$=4
$z$=2
I'm asked to find the volume using calculus, because using geometry would be cheating, evidently.
The three ways I am asked to "cut up" the cheese are perpendicular to the $y$-axis (triangles), the $x$-axis (rectangles), and $z$-axis (also rectangles).
This is easy, and it turns out the volume is 24 units cubed (all three times).  E.g:
4$\int_0^6 \frac{x}{3} \mathrm{d}x = 24$
Now, I ask myself what if I want to take the other rectangle, and use that as my slice.  I know that width is 4 ($y$-axis), and the length is z$\sqrt{10}$ (pythagoras with $\sqrt{z^2 + (3z)^2}$).  But how do I find my limits of integration?
$4\sqrt{10}\int_a^b z \mathrm{d}z.$
I would need to know the distance from the $y$-axis to the top (in this photo) of the wedge.  However, I've exhausted my math knowledge here.
I asked my calc teacher, and he told me that I find this number by "taking more calculus classes" (a good joke actually).  Since I don't have time to go bug him in his office hours, can someone explain some of the different ways to find this distance?

A: If we were to look at the cheese with the $Y$ axis going into the board, we will be seeing a right triangle in the $X-Z$ plane right angled at the origin.
The sides of the right triangle are given by $x=0$, $z=0$ and $\frac{x}{6} + \frac{z}{2} = 1$.
A cut parallel to the "top" side of the cheese will then be the equation of the form $\frac{x}{6} + \frac{z}{2} = c$ in the $X-Z$ plane, where $c \in (0,1)$ which is parallel to the line $\frac{x}{6} + \frac{z}{2} = 1$.

Staying in the $X-Z$ plane, the perpendicular distance, say $l$, of the line $\frac{x}{6} + \frac{z}{2} = c$ from the origin can be found as follows. We want a line passing through the origin and perpendicular to $\frac{x}{6} + \frac{z}{2} = c$. So we just need to take the negative inverse of the slope of the above line and we get $z = 3x$. The intersection of these two lines is the point where the perpendicular from the origin meets the line. The point of intersection is $(\frac{3c}{5},\frac{9c}{5})$. So $l = \sqrt{(\frac{3c}{5})^2 + (\frac{9c}{5})^2} = \frac{3c \sqrt{10}}{5}$. There are also other ways to find $l$ like equating the area of the triangle calculated by two different ways. i.e. $(6c) \times (2c) = l \times (2 \sqrt{10} c) \Rightarrow l = \frac{3c \sqrt{10}}{5}$.
Now the volume element becomes $dV = 4 \times \text{Length of the line segment} \{\frac{x}{6} + \frac{z}{2} = c\} \text{bounded by the axes} \times dl$.
Note that $4$ comes from the span along the $y$ direction which is constant for all slices.
$dV = 4 \times 2 \sqrt{10} c \times \text{ }dl$ and $dl = \frac{3 \sqrt{10}}{5} dc$.
$dV = 8 \sqrt{10} \frac{3 \sqrt{10}}{5} c dc = 48 c dc$.
Hence, the volume is given by $V = \displaystyle \int_{0}^{1} 48 c dc = 24$.


text:
Q: Running Cython in Windows x64 - fatal error C1083: Cannot open include file: 'basetsd.h': No such file or directory I have been trying to install Cython for Python 2.7 on my Window 7 system. In particular, I prefer everything in 64 bits. (In case you wonder, I need Cython because Cython is one of the components I need for another package for some specialized numerical analysis. And x64 is potentially an advantage for storage of large data sets.)
So I downloaded the x64 Python 2.7 from the official website. Got Cython from Christoph Gohlke. The amd64 version for Python 2.7 of course. Before I installed, I added Python 2.7 into the registry with the .reg file found in Joe DF's answer here. Afterwards, I installed the Visual C++ compiler from here (I don't think it works) and here (but this one should). At this point, I have in my C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin directory all of vcvars32.bat, vcvars64.bat, vcvars86_amd64.bat, vcvarsx86_ia64.bat. I ran vcvars64.bat and there was no error message.
Subsequently, I followed this page to create a "hello world" test file.
Then, I got this error.
...\Tests>python setup.py build_ext --inplace
running build_ext
building 'hello' extension
error: Unable to find vcvarsall.bat

So I thought to myself: Well, Cython can't find that file because it does not exist. (I searched my whole harddrive for it.) So I copied vcvars64.bat from ...\VC\bin to \VC and changed the name to vcvarsall.bat. Now vcvarsall error is gone. And ... naturally, a new error emerges.
...\Tests>python setup.py build_ext --inplace
running build_ext
building 'hello' extension
C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN\amd64\cl.exe /c /nolog
o /Ox /MD /W3 /GS- /DNDEBUG -IC:\Python27\include -IC:\Python27\PC /Tchello.c /F
obuild\temp.win-amd64-2.7\Release\hello.obj
hello.c
C:\Python27\include\pyconfig.h(227) : fatal error C1083: Cannot open include fil
e: 'basetsd.h': No such file or directory
error: command '"C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN\amd64
\cl.exe"' failed with exit status 2

Now I have no idea how to proceed. What should I do? Your help is much appreciated.
(For clarity, I did try setting the compiler to Mingw32. But there are other errors. I am focusing on getting VC to work for now.)

EDIT: I tried using the SDK build environment CMD following the instructions on this page. I received the same error.

A: In case anyone is currently (2017) facing same error with visual C++ 2015 tools, launch setup again and also select windows 8.1 / 10 SDK depending upon your OS. This will fix basestd.h error.
If it is still not working, try launching build tools from: C:\Program Files (x86)\Microsoft Visual C++ Build Tools.
Another alternative would be, just install anaconda 2 or 3 (64 bit if also you don't want memory errors). It contains all the important packages prebuilt: sklearn, matplotlib, scipy, numpy, pandas and even web development frameworks such as flask.

A: I encountered this problem while trying to install pandas in 'develop' mode. I'm up & running now. My environment:

*

*Windows XP Pro x64 SP2

*WinPython 64bit 2.7.5.3 (Python 2.7.5.amd64) <-- "registered" as system's python distro using WinPython Control Panel application

Problems encountered when running python setup.py develop:

*

*Unable to find vcvarsall.bat

*fatal error C1083: Cannot open include file: 'basetsd.h': No such file or directory ... exit code 2

Solution:

*

*Download and install Microsoft Visual C++ 2008 Express.

*Download and install Microsoft Windows SDK for Windows 7 and .NET Framework 3.5 SP1. You will need only:

*

*Developer Tools > Windows Headers and Libraries <-- this gives you basetsd.h

*Developer Tools > Visual C++ Compilers <-- this gives you the 64-bit compilers

*Copy C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin\vcvars64.bat
to C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin\amd64\vcvarsamd64.bat. Observe the change in file name.

*Add C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin to PATH. This may not be required (I did so before re-installing the SDK w/ Headers & Libs; therefore, the necessity is unknown).

At this point, running python setup.py develop completed successfully and python -c "import pandas; print pandas.__version__" resulted in the git tag I expected.
[EDIT] Further reading:

*

*error: Unable to find vcvarsall.bat

*

*answer if you just want binaries to install

*answer if you want to compile on x64 machine

*answer about the file location/name change

*distutils issue 7511

A: For those with Windows 10, download the SDK from here to fix the header file basestd.h.
I downloaded the .exe, installed and worked great. SDK was ~2.3GB.
Note: For those like me with 64-bit systems who got an additional error:
`LINK : fatal error LNK1158: cannot run 'rc.exe'
    error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\link.exe' failed with exit status 1158

There is a great answer here which solves the problem by placing the rc.exe file in the correct folder for your system.

A: Add these to the visual studio installation directories to your Environment variables

C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin
C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools
hope it solves the issue.

A: For suggestion, you can try it for build cython 64 bit with setup.py
I'm using Anaconda for python distribution, Microsoft's Windopws SDK 7, and MSVC 12.0.
Firstly, I make library for my cuda function,
Second, I run python setup.py build_ext -i for make temp folder (you wil get error),
then compile Makefile below,
Mostly, I get this from setup.py when it is compile 32 bit app, then change it for compile 64 bit.
Makefile
CL_EXE      = "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\amd64\cl.exe"
LINK_EXE    = "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\amd64\link.exe"

CL_FLAGS    = /c /nologo /Ox /MD /W3 /GS- /DNDEBUG /O2 /fp:fast
CL_INC      = -I. -I"C:\Program Files\Microsoft SDKs\Windows\v7.1\Include" \
            -I"C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include" -IC:\Users\name\Anaconda2\envs\py27\Lib\site-packages\numpy\core\include -IC:\Users\name\Anaconda2\envs\py27\include -IC:\Users\name\Anaconda2\envs\py27\PC

LINK_FLAGS      = /DLL /nologo /INCREMENTAL:NO /MACHINE:X64
LINK_LIBPATH    = "/LIBPATH:C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v7.5\lib\x64" \
                    /LIBPATH:C:\Users\name\Anaconda2\envs\py27\libs \
                    /LIBPATH:C:\Users\name\Anaconda2\envs\py27\PCbuild\amd64 \
                    /LIBPATH:C:\Users\name\Anaconda2\envs\py27\PC\VS9.0\amd64 \
                    "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\lib\amd64" \
                    "/LIBPATH:C:\Program Files\Microsoft SDKs\Windows\v7.1\Lib\x64"
LINK_LIB        = cuda_multiply4D.lib cudart.lib MSVCRT.lib kernel32.lib
LINK_EXPORT     = /EXPORT:initmy_cuda
LINK_OBJ        = build\temp.win-amd64-2.7\Release\my_cuda.obj
LINK_OUT        = "/OUT:E:\my_cuda.pyd"
LINK_OTHER_CONF = /IMPLIB:build\temp.win-amd64-2.7\Release\my_cuda.lib /MANIFESTFILE:build\temp.win-amd64-2.7\Release\my_cuda.pyd.manifest

all:
    $(CL_EXE) $(CL_FLAGS) $(CL_INC) /Tcmy_cuda.c /Fobuild\temp.win-amd64-2.7\Release\my_cuda.obj
    $(LINK_EXE) $(LINK_FLAGS) $(LINK_LIBPATH) $(LINK_LIB) $(LINK_EXPORT) $(LINK_OBJ) $(LINK_OUT) $(LINK_OTHER_CONF)

Note:

*

*MSVCRT.lib kernel32.lib are optional,

*/EXPORT:initmy_cuda is mandatory. Its format init%yourfilename_WO_Ext%

*"/OUT:E:\my_cuda.pyd" for determine your output location, its filename, and its extension.

A: I could solve this problem by downloading and installing the latest Windows 10 SDK from this link:
https://software-download.microsoft.com/download/pr/19041.685.201201-2105.vb_release_svc_prod1_WindowsSDK.iso
but then another problem appeared with (cpython):
error C2039: 'exc_type': is not a member of '_ts'

which I could resolve by declaring additional pointers in
(...\python38\include\cpython\pystate.h)

I found these at line 77:
/* The exception currently being raised */
PyObject *curexc_type;
PyObject *curexc_value;
PyObject *curexc_traceback;

and I add the following just after them (without the first three letters "cur"):
/* The exception currently being raised */
PyObject *exc_type;
PyObject *exc_value;
PyObject *exc_traceback;


text:
Q: Ember.js inflectors - where do they go? I am trying to create an inflector rule that specifies that that the singular of criteria is criterion. In the javascript console, I can get it work like so:
inflector = new Ember.Inflector(Ember.Inflector.defaultRules);
inflector.singularize('criteria') // => "criterium"
inflector.irregular('criterion', 'criteria')
inflector.singularize('criteria') // => 'criterion'

Here's the line I used to attempt to create an inflector rule:
Ember.Inflector.inflector.irregular('criterion', 'criteria')

// using a regex
Ember.Inflector.inflector.irregular(/ion$/, 'ia')

Unfortunately, I keep getting errors in the js console:
Error: No model was found for 'reviewCriterium'

When using the inflector rule with a regex expression, I get the error Uncaught TypeError: undefined is not a function.
In addition, after googling where to place Ember inflectors, I couldn't find an answer, not even from the EmberJS guides. I tried placing them before and after the ApplicationAdapter to no avail.
What am I doing wrong? Where should I place them? Thanks for any help guys!

A: So immediately after I asked this question, I found out the answer to my problem:
Ember.Inflector.inflector.singular(/ia$/, 'ion')

This solves the problem. I placed this right after the Ember.Application.create statement. I don't know if that's the best place to put it, but it works.


text:
Q: Login to AWS from AWS Tools for Powershell I'm trying to use AWS Tools from Powershell, but I don't know how to log in. So when I run a command I naturally get this error:

No credentials specified or obtained from persisted/shell defaults.

How do I login? I read the article at https://docs.aws.amazon.com/powershell/latest/userguide/specifying-your-aws-credentials.html, but it talks about public and private keys. I don't have those, I login to AWS from the web interface with my username and password (and also a token sent to my phone because I have MFA enabled).
Also, my user isn't allowed to create IAM users (it's a company policy and I can't override it).

A: If your IAM user account doesn't already have Access and Secret Keys you'll need to create them here.
http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html#Using_CreateAccessKey
Then create a profile
Writes a new (or updates existing) profile with name "myProfileName" in the encrypted SDK store file
Set-AWSCredential -AccessKey akey -SecretKey skey -StoreAs myProfileName

Checks the encrypted SDK credential store for the profile and then
falls back to the shared credentials file in the default location
Set-AWSCredential -ProfileName myProfileName


text:
Q: get available payment method in magento store how can i get list of payment methods with detaile like code,title,method and?
is it possible get available payment method in store with API ?

A: Magento has its own api function which provides list of payment depending on the quote. Here you need to just send quote id to get the payment method list.
For example, to get the available payment methods you can use Magento SOAP API v1:
$client = new SoapClient('http://magentohost/api/soap/?wsdl');

// If somestuff requires api authentification,
// then get a session token
$session = $client->login('apiUser', 'apiKey');

$result = $client->call($session, 'cart_payment.list', 'quoteId');
var_dump($result);

See more at http://www.magentocommerce.com/api/soap/checkout/cartPayment/cart_payment.list.html


text:
Q: List of thermodynamic processes Can anyone give me a list of all the possible types of thermodynamic processes ?
Like we can have : reverse adiabatic expansion, irreversible isobar contraction etc etc. The combinations are limitless and I don't understand the basis of classification.
Thanks

A: (1) We can start by writing the fundamental relation for the system of interest and considering keeping any variable constant. For example, for a system that we can heat, do work on (compression, electrical, and surface work, say), and add mass to, then the fundamental relation is
$$dU=T\,dS-P\,dV+E\,dD+\sigma\,dA+\mu\,dN,$$
where $U$ is energy, $T$ is temperature, $S$ is entropy, $P$ is pressure, $V$ is volume, $E$ is electric field, $D$ is polarization, $\sigma$ is surface tension, $A$ is surface area, $\mu$ is the chemical potential, and $N$ is the amount of material.
Note that each pair is a thermodynamic conjugate pair. The sole negative sign arises because pressure is a negative equitriaxial stress that tends to reduce the volume.
Now it's just a matter of remembering the terms: isenergic (constant energy $U$), isothermal (constant temperature $T$), isentropic (constant entropy $S$), closed (constant mass $N$), equilibrium with another phase (equal chemical potentials $\mu$) and so on. So we have 11 simple conditions we might apply during a process on this particular idealized system of interest.
(2) It can also be useful to classify a process as irreversible (entropy producing) or reversible (entropy conserving). All real processes are irreversible, but we can often come arbitrarily close to reversibility, an idealization, by reducing friction, gradients, turbulence, etc.
(3) There are a limitless number of other conditions we might maintain. For example, we might manually process a thin film under the condition of constant color, which might depend on the thickness, stress, impurity concentration and temperature.
(4) Finally, there's the name of the process, which usually emphasizes the aspect that's important to us: an expansion, for example, which increases the volume $V$ and generally provides us with useful work. Or heating, or mixing, or pressurization.
Putting these together, we might speak of, for example, reversible polarization at constant volume and constant electric field (i.e., $D$ is increasing while $S$, $V$, and $E$ remain constant).

A: Most of the familiar reversible thermodynamic processes involving ideal gases are special cases of the general reversible polytropic process, which is generally written as
$$pV^{n}=C$$
where $n$ is called the polytropic index (not to be confused with $n$ being the number of moles of a gas) and $C$ is a constant. The equation can be used to describe various different expansion and compression processes depending on the value of the polytropic index. Examples are
$n=0$ for an isobaric (constant pressure) process
$n=$ + infinity for an isochoric (constant volume) process
$n=1$ for an ideal gas isothermal (constant temperature) process
$n=\gamma = \frac{C_P}{C_V}$ for an ideal gas isentropic (reversible adiabatic) process
Theoretically, since there are an infinite number of possible values of n, there are an infinite number of possible processes capable of connecting two equilibrium states, not just the ones listed above, as long as the laws of thermodynamics are not violated.
Finally, for an ideal gas, closed system (no change in mass), the ideal gas equation
$$pV=nRT$$
Where $n$ is the number of moles of gas, and $R$ the universal gas constant, can be applied at each stage of a reversible process.
.
Hope this helps.


text:
Q: Nginx scaling and bottleneck identification on an EC2 cluster I am developing a big application and i have to load test it. It is a EC2 based cluster with one HighCPU Ex.Large instance for application which runs PHP / NGinx.
This applicaton is responsible for reading data from a redis server which holds some 5k - 10k key values, it then makes the response and logs the data into a mongoDB server and replies back to client.
Whenever i send a request to the app server, it does all its computations in about 20 - 25 ms which is awesome.
I am now trying to do some load testing and i run a php based app on my laptop to send requests to server. Many thousands of them quickly over 20 - 30 seconds. During this load period, whenever i open the app URL in the browser, it replies back with the execution time of around 25 - 35 ms which is again cool. So i am sure that redis and mongo are not causing bottlenecks. But it is taking about 25 seconds to get the response back during load.
The high CPU ex. large instance has 8 GB RAM and 8 cores.
Also, during the load test, the top command shows about 4 - 6 php_cgi processes consuming some 15 - 20% of CPU.
I have 50 worker processes on nginx and 1024 worker connections.
What could be the issue causing the bottleneck ?
IF this doesnt work out, i am seriously considering moving out to a whole java application with an embedded webserver and an embedded cache.
UPDATE - increased PHP_FCGI_CHILDREN to 8 and it halfed the response time during load

A: 50 worker processes is too many, you need only one worker process per CPU core. Using more worker processes will invoke inter-process switching, that will consume many time.
What you can do now:
  1. Set worker process to minimum (one worker per CPU, e.g. 4 worker process if you have 4 cpu units), but worker connections - to maximum (10240 for example)

*

*Tune up TCP stack via sysctl. You can reach stack limits if you have many connections

*Get statistics from nginx stub_status module (you can use munin + nginx, its easy to setup and gave you enough information about system status).

*Check nginx error.log and system messages log for errors.

*Tune up nginx (decrease connection timings and max query size).
I hope that helps you.


text:
Q: Is there a way to create a script and make it executable in less code than this? My code to create an executable script
touch script.sh && echo "echo 'Hello World'" > script.sh && sudo chmod +x script.sh

A: I prefer to use cat for tasks like this:
cat > script.sh && chmod +x script.sh
#!/bin/sh
echo 'Hello World'Enter
Ctrl+D

A: The install command (part of GNU coreutils along with cp, mv, rm, etc.) can copy a file while also setting its ownership and permissions and creating parent directories as necessary. By default it will make the new file executable. It doesn't understand '-' but /dev/stdin can be used instead:
install /dev/stdin script.sh <<< "echo Hello World"

The above uses a 'here string' to provide the text on stdin, which is slightly shorter than piping it in. The arguments to echo don't need quoting unless they contain characters with special meaning.

A: You can leave out the whole touch command and there's no need to use sudo. To shorten the command line further you can use bash History Expansion to save the filename the second time, and omit unnecessary spaces:
echo "echo 'Hello World'" >script.sh&&chmod +x !#:3

History Expansion replaces !#:3 with the fourth word from the current command line, which in your case is the filename script.sh. Of course this needs to be adapted in case you modify the first command, e.g.:
>script.sh echo "echo 'Hello World'"&&chmod +x !#:1

Note that a valid script needs a shebang:
>script.sh echo -e "#!/bin/bash\necho 'Hello World'"&&chmod +x !#:1

If you need this chain of commands more often I recommend defining a function, this way you'd just need to type the function name. A similarly adaptable – though longer – way is the use of a variable holding the filename:
f=script.sh;>$f echo "echo 'Hello World'"&&chmod +x $f

If your filename contains special characters don't forget to quote them properly.

A: You could also leave out the whole chmod and use umask instead before the echo. Should save you a few bytes. Shebang is optional as long as you use commands that are understood by every shell (bourne and C mainly).


text:
Q: The onregistered event does not occur after upgrading to Android Pie We created a hybrid app using phonegap.
So far, I've used GCM plugin well.
However, if you upgrade your phone with Android pie (9.0), the onRegistered event will not occur.
I do not go out on the issue when I google it.
I seek advice from your advisers.
public void onRegistered(Context context, String regId) {
    Log.v(TAG, "onRegistered: "+ regId);
    JSONObject json;
    try
    {
        json = new JSONObject().put("event", "registered");
        json.put("regid", regId);

        Log.v(TAG, "onRegistered: " + json.toString());

        // Send this JSON data to the JavaScript application above EVENT should be set to the msg type
        // In this case this is the registration ID
        PushPlugin.sendJavascript( json );
    }
    catch( JSONException e)
    {
        // No message to the user is sent, JSON failed
        Log.e(TAG, "onRegistered: JSON exception");
    }
}


text:
Q: Jparepository not deleting Html
            <form th:action="@{/deleteCartItem(id=${produkt.product.id})}" th:object="${produkty}" method="post">
                <div class="text-right">
                    <input type="submit" value="Delete" class="btn-sm btn-danger" />
                </div>
            </form>

Cart controller
@GetMapping("/kosik")
public String kosik(Principal principal,Model model){
    User user = userServices.findByEmail(principal.getName());
    Cart cart = cartServices.findCartByUser(user);
    model.addAttribute("produkty",cartItemServices.findAllCartItems(cart));
    model.addAttribute("cart",cartServices.findCartByUser(user));
    model.addAttribute("user",user);
    return "cart";
}

Delete method
@PostMapping("/deleteCartItem")
public String deleteCartItem(@ModelAttribute CartItem cartItem){
    cartItemServices.deleteCartItem(cartItem.getCartItemId());
    return "redirect:/kosik";
}

Service
public void deleteCartItem(Integer id){
        cartItemRepository.deleteById(id);
    }

CartItem Entity
@Entity
public class CartItem {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer cartItemId;
    @NotNull
    @Max(11)
    private int quantity;
    private double price;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "product_id")
    private Product product;

    @ManyToOne
    @JoinColumn(name = "cart_id")
    private Cart cart;

Getting cartitem id works, but i cant delete cartItem.. I also tryied delete it not by id, but delete cartItem instantly..

A: Since your entity don't have id field as primary key. It's not working.
Define the below method in CartItemRepository and use it to delete the Object.
Long deleteByCartItemId(Long id);

Or rename the cartItemId field as id.