text:
Q: Scala match and reference equality check Depending on the variable type Scala sometimes match value and sometimes don't.
The problem is illustrated by this simple program:
class NotEqualToAnything {
  override def equals(obj: Any): Boolean = false
}

val x = new NotEqualToAnything()
x match {
  case `x` =>
    println("WTF x equal to itself")
  case _ =>
    println("no-match") // This got printed
}

val y: AnyRef = new NotEqualToAnything()
y match {
  case `y` =>
    println("WTF y equal to itself") // This got printed
  case _ =>
    println("no-match")

When the variable is of type AnyRef the generated code contains a call to BoxesRunTime.equals which does indeed a y == y check before calling y.equals(y). When the type of the variable is NotEqualToAnything, we got a standard x == null check twice and then a call to x.equals(x).
I tested this on
Scala 2.13.0 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_201).

I wonder if this is a compiler bug and should be reported of if this is a "desired" behavior. In my opinion both cases should behave identically.
One hypothesis is that compiler expects classes to follow the contract when overriding equals, and so expects equals to be reflective (x.equals(x) == true). Can somebody confirm that this is indeed the case?

A: There is a contract for equals. x.equals(x) has to be true. If you break that contract, a lot of things that depend on it will not work anymore.
A compiler (and for example a collection library) has to assume the objects are "well-behaved". It is not a compiler bug if something breaks if they don't.
The upshot of this is that the compiler can optimize some things when it feels like it. In the present case, the BoxesRunTime.equals overhead can be skipped when the static type is known to not need that.


text:
Q: how find sum of an array, for a specific range of keys //input array
$array = {
          2 => 5,
          4 => 1,
          8 => 3,
          9 => 2,
}

want sum of key for a specific period like 1-5, 6-10
need output like array {1-5 => 6 ,6-10 => 5}

A: Try this code.. Not a rocket science..
function sumArray($array, $min, $max) {
   $sum = 0;
   foreach ($array as $k => $a) {
      if ($k >= $min && $k <= $max) {
         $sum += $a;
      }
   }
   return $sum;
}

echo sumArray($array, 1, 5);

# this is your answer
$sum = array_sum(array_slice($array, $from, $to));

A: Considering that you might want to see all groups/ranges represented in the result and that some data might not qualify for any group, I've extended the sample data to show these considerations.
Use a conditionally broken nested loop with minimum and maximum numbers which will add amounts to respective groups/ranges.
array_map() is used to establish a 0 value for all declared groups/ranges.
Code: (Demo)
$array = [
    2 => 5,
    4 => 1,
    8 => 3,
    0 => 17,
    9 => 2,
    11 => 67
];

$ranges = [
    '1-5' => ['min' => 1, 'max' => 5],
    '6-10' => ['min' => 6, 'max' => 10],
    '1000-5000' => ['min' => 1000, 'max' => 5000],
];

$result = array_map(fn() => 0, $ranges);
foreach ($array as $num => $amount) {
    foreach ($ranges as $rangeName => ['min' => $min, 'max' => $max]) {
        if ($num >= $min && $num <= $max) {
            $result[$rangeName] += $amount;
            break;
        }
    }
}
var_export($result);

Output:
array (
  '1-5' => 6,
  '6-10' => 5,
  '1000-5000' => 0,
)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ubuntu giving error in VM I'm trying to install Ubuntu 12.04 in many Virtual PC's But every time Getting same error's. Don't know why?
Here are some screenshots:

I'm using 20.GB for Ubuntu installation & 512 Ram But it says you don't have 4 GB free space.
And if it pass hard disk process Part it ll give error on other part.
Please let me know how can I fix this?

A: I had the same problem with a computer. I fixed it by selecting COMPATIBLE MODE in the BIOS. It will disable AICH or OICH or RAID and just leave everything as IDE or LEGACY as well as other options in their more compatible modes.


text:
Q: Failed to load plugin Tinymce Suddenly my TinyMCE classic editor shows this error:
Failed to load plugin url: https://www.example.com/wp-includes/js/tinymce/langs/pt.js
I've switched off plugins one by one, nothing
I've reinstalled WordPress core files, nothing
But when i switch from my theme to a default one, it works… But how a theme can affect this plugin?
The problem occurred after upgrading Wordpress to 4.8.
Is there any way to understand where it comes from?
Thanks!


text:
Q: Material design toolbar on devices pre-lollipop I'm flollowing next tutorial:

*

*https://chris.banes.me/2014/10/17/appcompat-v21/
I want do that similar design:

I know i need use Two toolbars.
values/themes.xml
<resources>
<style name="Theme.MiThema" parent="Theme.AppCompat.Light">
    <!-- Here we setting appcompat's actionBarStyle -->
    <!--<item name="actionBarStyle">@style/MyActionBarStyle</item>-->

    <!-- ...and here we setting appcompat's color theming attrs -->
    <item name="colorPrimary">@color/primary</item>
    <item name="colorPrimaryDark">@color/primary_dark</item>

    <!-- colorAccent is used as the default value for colorControlActivated
         which is used to tint widgets -->
    <item name="colorAccent">@color/accent</item>
</style>
    </resources>

class.java
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.Toolbar;

public class RegistrarInciTraActivity extends ActionBarActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.registrar_inci_traf_layout);

        //ocultamos ActionBar
        getSupportActionBar().hide();

       Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
       setSupportActionBar(toolbar);
    }
}

layout
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="horizontal">

    <!-- The toolbar -->
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:minHeight="?attr/actionBarSize"
        android:background="?attr/colorPrimary" />

    <android.support.v4.widget.DrawerLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/my_drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <!-- drawer view -->
        <LinearLayout
            android:layout_width="304dp"
            android:layout_height="match_parent"
            android:layout_gravity="left|start">

            <!-- drawer content -->

        </LinearLayout>

        <!-- normal content view -->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <!-- The rest of content view -->

        </LinearLayout>
    </android.support.v4.widget.DrawerLayout>

</LinearLayout>

Tha code report one error on "setSupportActionBar(toolbar);":

(first problem) ¿What is the problem about that? (SOLVED)
(Second problem)
On my layout appear

"?attr/actionBarSize" and "?attr/colorPrimary"

Where do I have to declare those attributes?
(Third problem)
When I do two toolbars only appear once of them and I want one inside the other to display content.

What I do have to display both toolbars?
Thanks

A: I can give you an answer for your first problem. It is very simple - you only have to read the message given by your IDE. You're using the wrong toolbar. The toolbar you're trying to pass to the setSupportActionBar-Method is from the package android.widget. But you've to use the toolbar from the package android.support.v7.widget. So your imports are wrong - correct them and your code should work.

A: As 1st Problem is solved, let me try Second one,
First of all, you do not have to define these values anywhere, they are pre-defined.

*

*"?attr/actionBarSize" : this is a default value provided by Android. You will get it at android.support.v7.appcompat/R,but it will give you an int reference. If you want to know the actual height of the Actionbar, you have to resolve the attribute actionBarSize at runtime. Follow this Link : Get ActionBar Size(answer given on other SO Q.).
Also Now with Material Design, Google shared some standards to be used while designing new Apps (or upgrading old one) in Material Design. You can follow those norms here : LayoutMetrics & keylines

*"?attr/colorPrimary" : This is also a pre-defined value. You can get it at android.support.v7.appcompat/R, but it will give you an int reference. But if you want a custom background color to your ToolBar then just add an appropriate color palette, android:background="@color/colorPrimary" and define colorPrimary value in color.xml. Use this site to get different color values : Material Palette (I prefer this site).


text:
Q: java null manual exception handling I have this static method of the class Plane which returns an object from some int id:
private static ArrayList<Plane>Planes = new ArrayList<Plane>();

public static Plane getPlane(int id)
{
Plane p = null;

int i=0;

while(i<=Planes.size())
{
    if(Planes.get(i).getid()==id)
    {
        p = Planes.get(i);

        break;

    }

    i++;
}`
return p;

}

And I have this code which I want to manually throw an exception when the Plane object is null and print Plane doesnt exist!:
try
{
    Plane planetofly = Plane.getPlane(pid);

    if(planetofly==null)
    {
        throw new Exception("Plane doesnt exist!");

    }

    this.planetofly = planetofly;

}
catch(Exception e)
{
    System.out.println(e.getMessage());

}

but instead of getting "Plane doesnt exist at the output" when the plane with that id doesnt exist i get output the message from the IndexOutofBounds Exception.What am I doing wrong?

A: Index out of bounds means that you are trying to access an index in your array which does not exist.
This line is the problem.
while(i<=Planes.size())

The index starts at zero and ends at Size - 1, so you have to check for less than, not less than or equal to.  Like this:
while(i < Planes.size())


text:
Q: Object to retain same size on screen regardless of its distance from the camera In Three.js I have an rectangle which is moving away from the camera, how can I compute a 3D x and y scale to apply to the rectangle such that the rectangle retains its same size on the screen in pixels, no matter how far away from the camera it is.
Here I made a codepen which shows the rectangle moving away from the camera. I would like it to retain its same width and height on the screen no matter how far away it is in the z index, that means the x and y scale of the rectangle needs to vary by some scale dependent on the distance in the z axis, this needs to occur dynamically dependent on the z index.
I don't know how to compute this, I suspect its some function taking as input some of the following, the z index offset, the height or width of the object, the field of view of the camera, the aspect ratio, the screen width and height. The end result would be that the object would not appear to be moving away from the camera, even though it is moving away.
https://codepen.io/philip368320/pen/bGwJPvE
var width = window.innerWidth;
var height = window.innerHeight;

var renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(width, height);
document.body.appendChild(renderer.domElement);

var scene = new THREE.Scene();

var cubeGeometry = new THREE.CubeGeometry(100, 100, 0.000001);
var cubeMaterial = new THREE.MeshLambertMaterial({ color: 0xffffff });
var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
//cube.rotation.y = Math.PI * 45 / 180;
scene.add(cube);

var camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 10000);
camera.position.y = 0;
camera.position.z = 400;
camera.lookAt(cube.position);

scene.add(camera);

var skyboxGeometry = new THREE.CubeGeometry(10000, 10000, 10000);
var skyboxMaterial = new THREE.MeshBasicMaterial({ color: 0x000000, side: THREE.BackSide });
var skybox = new THREE.Mesh(skyboxGeometry, skyboxMaterial);

scene.add(skybox);

var pointLight = new THREE.PointLight(0xffffff);
pointLight.position.set(0, 300, 200);

scene.add(pointLight);

var clock = new THREE.Clock();

var n = 0;

function render() {
  requestAnimationFrame(render);
  n = n + clock.getDelta() * 30;
  cube.position.z = -n;
  renderer.render(scene, camera);
}

render();

A: To keep the cube in place in your codepen example, just scale it according to the distance. If it's z away, the size of the cube on the screen is 1/z, so scale to the inverse of that.
The render function with the scaling (initial distance between the camera and the cube is 400):

    function render() {
      requestAnimationFrame(render);
      n = n + clock.getDelta() * 30;
      cube.position.z = -n;
      cube.scale.set((400+n)/400, (400+n)/400, 1);
      renderer.render(scene, camera);
    }

Or by calculating the distance between the camera and the cube:

    function render() {
      requestAnimationFrame(render);
      n = n + clock.getDelta() * 30;
      cube.position.z = -n;
      let distance = camera.position.distanceTo(cube.position);
      cube.scale.set(distance/400, distance/400, 1);
      renderer.render(scene, camera);
    }

Updated codepen here: https://codepen.io/mikael-l-nnroth/pen/LYRoaBB

A: Based upon the information as given by https://stackoverflow.com/users/4045502/prisoner849 in the comments above, which was this link Three JS Keep Label Size On Zoom which discusses an example which keeps the text labels at the same size no matter how far from the camera. The example codepen has been updated with two surfaces, one is moving away from the camera but retaining its current width and height in on screen pixels. Therefore it retains the same width and height in on screen pixels as it moved away from the camera. "Object to retain same size on screen regardless of its distance from the camera". That is cube1. The other cube2 is not moving.
https://codepen.io/philip368320/pen/bGwJPvE
var width = window.innerWidth;
var height = window.innerHeight;

var useScaleFactor = true;
var scaleVector = new THREE.Vector3();

var renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(width, height);
document.body.appendChild(renderer.domElement);

var scene = new THREE.Scene();

var cubeGeometry = new THREE.CubeGeometry(100, 100, 0.000001);
var cubeMaterial = new THREE.MeshLambertMaterial({ color: 0xffffff });
var cube1 = new THREE.Mesh(cubeGeometry, cubeMaterial);
var cube2 = new THREE.Mesh(cubeGeometry, cubeMaterial);
//cube.rotation.y = Math.PI * 45 / 180;
scene.add(cube1);
scene.add(cube2);

var camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 10000);
camera.position.y = 0;
camera.position.z = 400;
camera.lookAt(cube1.position);

scene.add(camera);

var skyboxGeometry = new THREE.CubeGeometry(10000, 10000, 10000);
var skyboxMaterial = new THREE.MeshBasicMaterial({ color: 0x000000, side: THREE.BackSide });
var skybox = new THREE.Mesh(skyboxGeometry, skyboxMaterial);

scene.add(skybox);

var pointLight = new THREE.PointLight(0xffffff);
pointLight.position.set(0, 300, 200);

scene.add(pointLight);

var clock = new THREE.Clock();

var n = 0;

function render() {
  requestAnimationFrame(render);
  n = n + clock.getDelta() * 30;
  cube1.position.z = -n;
  cube2.position.x = 200;

  if (useScaleFactor) {
        var scaleFactor = 400.0;
        var scale = scaleVector.subVectors(cube1.position, camera.position).length() / scaleFactor;
        cube1.scale.set(scale, scale, 1);
  }

  renderer.render(scene, camera);
}

render();


text:
Q: React Native: how to change status bar icon colors I can't seem to find a way to change the colors of the status bar icons to white - at the top of the screen, e.g time & battery.

I've tried adding the following in info.plist

*

*Status bar style: UIStatusBarStyleLightContent

*View controller-based status bar appearance: NO

But only seems to work in previous versions of IOS. Any help much appreciated.

A: You need to use StatusBarIOS inside your React Native component:
StatusBarIOS.setStyle('light-content')
Docs here: http://facebook.github.io/react-native/docs/statusbarios.html#content
Edit: As of RN 0.22, StatusBarIOS has been deprecated and the cross-platform StatusBar should be used. It has still be used imperatively as is mentioned above:
StatusBar.setBarStyle('light-content', true);
However, the recommended way to use this component is declaratively. For example:
 <View>
   <StatusBar
     backgroundColor="blue"
     barStyle="light-content"
   />
   <Navigator
     initialRoute={{statusBarHidden: true}}
     renderScene={(route, navigator) =>
       <View>
         <StatusBar hidden={route.statusBarHidden} />
         ...
       </View>
     }
   />
 </View>

See the new docs here: http://facebook.github.io/react-native/docs/statusbar.html

A: I faced the same problem. Following docs (https://reactnative.dev/docs/statusbar#barstyle) didn't help.
So, I just did a Opt+Click on StatusBar component to found what props you can change, and what methods it provides.
Snippet of props I found:
export declare type StatusBarStyle = 'auto' | 'inverted' | 'light' | 'dark';
export declare type StatusBarAnimation = 'none' | 'fade' | 'slide';
export declare type StatusBarProps = {
    /**
     * Sets the color of the status bar text. Default value is "auto" which
     * picks the appropriate value according to the active color scheme, eg:
     * if your app is dark mode, the style will be "light".
     */
    style?: StatusBarStyle;

I used this information and updated the StatusBar component like so:
<StatusBar style="light" />

And voilla, I changed the icons and text color to white!

A: I had to use react-native-safe-area-context and here's how I did it.
// ./screens/MyScreen.js
import { StatusBar } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';

const backgroundColor = 'red';

export default () => (
  <View>
    <SafeAreaView edges={['top']} style={{ backgroundColor }}>
      <StatusBar />
    </SafeAreaView>

    <View style={{ backgroundColor }}>
      <Text style={{ fontSize: 36 }}>Heading</Text>
    </View>
  </View>
);

A: use barStyle="dark-content" ..for example:
<StatusBar animated={true} backgroundColor="#F1F1F1" barStyle="dark-content" />


text:
Q: ocaml c interop passing struct I hit weird case when trying to call c from ocaml.
This is the c side of things:
typedef struct {
  TSNode node;
} AstNode;

CAMLprim value caml_ts_document_root_node(value document) {
  CAMLparam1(document);
  TSNode root_node = ts_document_root_node(document);
  AstNode elNode;
  elNode.node = root_node;
  CAMLreturn(&elNode);
}

CAMLprim value caml_ts_node_string(value node) {
  CAMLparam1(node)
  CAMLlocal1(mls);

  AstNode* n = (AstNode*) node;

  char *s = ts_node_string(n->node);
  mls = caml_copy_string(s);
  CAMLreturn(mls);
}

On the ocaml side
type ts_point
type ts_document

external ts_node_string : ts_node -> string = "caml_ts_node_string"
external ts_document_root_node : ts_document -> ts_node = "caml_ts_document_root_node"

If you see the code, I'm wrapping in caml_ts_document_root_node the TSNode root_node = ts_document_root_node(document); in an extra defined struct AstNode.
When I write the following implementation however:
CAMLprim value caml_ts_document_root_node(value document) {
  CAMLparam1(document);
  TSNode root_node = ts_document_root_node(document);

  CAMLreturn(&root_node);

}
My code segfaults when calling caml_ts_node_string on the returned node by caml_ts_document_root_node.
Does anyone have any hints on why the segfault appears when I don't wrap a TSNode in an extra struct when interoping from ocaml?

A: That's definitely not the right usage of the foreign interface! You can't just take a value and cast it to OCaml value. OCaml values are specially encoded, even integers, and have a different representation than C values.
If you want to encode a C value as an OCaml value, you shall use custom values.
First of all, you need to implement the interface of a custom value, fortunately, you can rely on defaults for that:
static struct custom_operations ast_ops = {
        "ast_node",
        custom_finalize_default
        custom_compare_default,
        custom_hash_default,
        custom_serialize_default,
        custom_deserialize_default,
        custom_compare_ext_default
};

Next, you need to learn how to allocate custom blocks. For example, the following call will allocate the new AstNode in the OCaml heap:
    res = caml_alloc_custom(&ast_ops, sizeof(AstNode), 0, 1);

To access the value itself, you need to use the Data_custom_val macro, e.g.,
   if (res) {
      AstNode *node = Data_custom_val(res);
      TsNode *tsnode = res->node;
   }

The complete example of a correct (I hope) implementation of your first function is below:
CAMLprim value caml_ts_document_root_node(value document) {
  CAMLparam1(document);
  CAMLlocal1(res);
  res = caml_alloc_custom(&ast_ops, sizeof(AstNodes), 0, 1);
  if (res) {
    AstNode *ast = (AstNode *)Data_custom_val(res);
    ast->node = ts_document_root_node(document);
  }
  CAMLreturn(res);
}

As you may see, this is not trivial and rather low-level. Though nothing really magical, especially after you've read the corresponding parts of the OCaml documentation. However, it is much easier to use the CTypes library, that hides most of those complexities and allows you to call C function directly from OCaml

A: This seems to be unrelated to the ocaml interop part; you are returning the address of a local variable in this function:
CAMLprim value caml_ts_document_root_node(value document) {
  // ...
  AstNode elNode;
  // ...
  CAMLreturn(&elNode);
}

When it returns, the (stack) memory it refers to is invalid (in the sense that it will be reused at the next function call).


text:
Q: Simple code that reads CSV values causes an error in System.IO.Directory I can't seem to figure out why I'm getting a compilation error with this code that tries to find the most recently updated file (all CSV files) in a directory, to then pull the last line of the CSV and update a device.
The exception I get is:

Line 3 Character 10 expected end of statement.

Don't worry about the hs.SetDevice, I know that part is correct.
Imports System.IO

Sub Main()
    Dim path = System.IO.DirectoryInfo.GetFiles("C:\Users\Ian\Documents\Wifi Sensor Software").OrderByDescending(Function(f) f.LastWriteTime).First()
    Dim line = System.IO.File.ReadLines(path).Last()
    Dim fields() = line.Split(",".ToCharArray())
    Dim fileTemp = fields(2)
    hs.SetDeviceValueByRef(124, fileTemp, True)
End Sub

EDIT:
Changed Directory to DirectoryInfo

A: *

*The original problem was that Directory.GetFiles() returns an array of strings, a string doesn't have a LastWriteTime Property.
This property belongs to the FileInfo base class, FileSystemInfo, the object type returned by DirectoryInfo.GetFiles().
Then, a FileInfo object cannot be passed to File.ReadLines(), this method expects a string, so you need to pass [FileInfo].FullName.

*Hard-coding a Path in that manner is not a good thing. Use Environment.GetFolderPath() to get the Path of special folders, as the MyDocuments folder, and Path.Combine() to build a valid path.

*Better use the TextFieldParser class to parse a CSV file. It's very simple to use and safe enough.
The worst problem is Option Strict set to Off.
Turn it On in the Project's Properties (Project->Properties->Compile), or in the general options of Visual Studio (Tools->Options->Projects and Solutions->VB Defaults), so it's already set for new Projects.
You can also add it on top of a file, as shown here.
With Option Strict On, you are immediately informed when a mishap of this kind is found in your code, so you can fix it immediately.
With Option Strict Off, some issues that come up at run-time can be very hard to identify and fix. Setting it On to try and fix the problem later is almost useless, since all the mishaps will come up all at once and you'll have a gazillion of error notifications that will hide the issue at hand.
Option Strict On

Imports System.IO
Imports Microsoft.VisualBasic.FileIO

Dim filesPath = Path.Combine(Environment.GetFolderPath(
    Environment.SpecialFolder.MyDocuments), "Wifi Sensor Software")
Dim mostRecentFile = New DirectoryInfo(filesPath).
    GetFiles("*.csv").OrderByDescending(Function(f) f.LastWriteTime).First()

Using tfp As New TextFieldParser(mostRecentFile.FullName)
    tfp.TextFieldType = FieldType.Delimited
    tfp.SetDelimiters({","})

    Dim fileTemp As String = String.Empty
    Try
        While Not tfp.EndOfData
            fileTemp = tfp.ReadFields()(2)
        End While
    Catch fnfEx As FileNotFoundException
        MessageBox.Show($"File not found: {fnfEx.Message}")
    Catch exIDX As IndexOutOfRangeException
        MessageBox.Show($"Invalid Data format: {exIDX.Message}")
    Catch exIO As MalformedLineException
        MessageBox.Show($"Invalid Data format at line {exIO.Message}")
    End Try

    If Not String.IsNullOrEmpty(fileTemp) Then
        hs.SetDeviceValueByRef(124, fileTemp, True)
    End If
End Using


text:
Q: AWS opensearch: Cannot update advanced option `override_main_response_version` I have an AWS opensearch with vanilla settings.
I needed to change the advanced options to enable override_main_response_version=true so that filebeat could work. But whichever way I try, it just does not work. Any workarounds?
Method 1: terraform:
resource "aws_elasticsearch_domain" "this" {
...
  advanced_options = {
    "override_main_response_version" = "true"
  }
...
}

This results in
Unrecognized advanced option 'override_main_response_version' passed in advancedOptions

Method 2: awscliv2
aws opensearch update-domain-config --advanced-options 'override_main_response_version=true' --domain-name whatever

which results in:
An error occurred (ValidationException) when calling the UpdateDomainConfig operation: Unrecognized advanced option 'override_main_response_version' passed in advancedOptions.

I don't see any way on the AWS console to change this option.
Please help!

A: This option can be enabled from opensearch's dev tools:
PUT /_cluster/settings
{
"persistent" : {
"compatibility.override_main_response_version" : true
}
}


text:
Q: Does PHP shell_exec add parentheses to the command? I'm trying to run a cat command using the shell_exec function, to be more precise something like this:
cat <(echo "foo") bar.xml > foo-bar.xml

But I'm getting a syntax error like the following one:
sh: 1: Syntax error: "(" unexpected

I'm completely lost since this works fine locally and when the command is executed manually in the server, but when running the php script it returns the syntax error. Any clues?
Original code being used:
$shell_cmd = "cat <(echo \"{$this->xmlHeader}\") ";
$shell_cmd .= '\'' . $path . $filename . '\'' . " ";
$shell_cmd .= " > " . '\'' . $path . "hfb/" . strtolower(str_replace($this->replace_values, '', $hfbName)) . ".xml" . '\'';
shell_exec($shell_cmd);

A: The problem here is likely to be which shell is used. It's not really documented, but I believe shell_exec will use /bin/sh, which will often be a minimal Posix-compliant shell (or a more complex shell emulating that compliance). That's very useful, because it means system scripts will always work the same way, regardless of what other shells are installed or configured for particular users.
When you log in directly, however, you're probably using bash, which has extra features such as the <(...) syntax for getting a named file descriptor from a command.
The best approach in this case is to make your command use only standardised facilities, which will be available in /bin/sh.
In particular, you are using cat to glue together a literal string from echo and a file:
cat <(echo "foo") bar.xml

That can be expressed instead by first echoing the string, and then outputting the file:
echo "foo"; cat bar.xml

To gather both into one output, place them in braces:
{ echo "foo"; cat bar.xml; } > foo-bar.xml

Alternatively, you can give cat an argument of - to concatenate standard input with one or more other files, so you could pipe the value from echo into it:
echo "foo" | cat - bar.xml > foo-bar.xml


text:
Q: Bootstrap: Reducing NavBar width and all its drop down option panels and text size I am using Bootstrap css for Nav Bar and it comes up very fine.
But the width appears to be big and I want to reduce it ( also ensure that it gets equally reduced/adjusted in other viewports also) and also reduce the options panels/text size that comes under the Nav Bar dropdown.
I'm using the following css class
navbar navbar-default navbar-fixed-top navbar-inverse
and the Nav Bar is coming in black ( which is giving the wow effect) and something that is needed but all the options under dropdown is coming as white. How to make this white background to black? Any bootstrap class already in place?
If navbar-inverse can make the top nav bar as black then there must be some class to provide the same effect for the dropdown panel options under the same Nav Bar
I want to avoid custom css at this point to achieve this.
Thanks,
Faraz

A: there is no way to change anything unless you want to create a custom css file, or edit the bootstrap css files.
If you are looking for something very simple, i have found this fantastic
http://pikock.github.io/bootstrap-magic/app/index.html#!/editor


text:
Q: Cauchy sequences form a ring Let $R$ be a ring with the $I$-adic filtration. Recall that a sequence $x_n$ of elements in $R$ is Cauchy if for every $N$, there is a $k$ such that for all $i,j\ge k$ one has $x_i-x_j\in I^N$. A sequence converges to zero if for every $N$, there is a $k$ such that for all $i\ge k$ one has $x_i\in I^N$.
I'd like to understand why the set of all Cauchy sequences forms a ring and why the set of all zero-convergent sequences forms an ideal in that ring.
It is obvious that the two above-mentioned sets are closed under addition. However, it is not clear to me why the first set is closed under multiplication and why the second one is closed under "scalar multiplication".
For example, let $x_n, y_n$ be Cauchy sequences. Then $\forall N$ $\exists k: \forall i,j\ge k, x_i-x_j\in I^N$ and WLOG we may assume that $\forall N$ $\exists k: \forall l,m\ge k, y_l-y_m\in I^N$. Now we for every $N$ we need to find a $K$ such that for all $i,j,l,m\ge K$, $(x_i-x_j)(y_l-y_m)=x_iy_l+x_jy_l-x_iy_m+x_jy_m\in I^N$. But $I^N$ consists of elements of the form $\sum a_1\dots a_n$, where each $a_i$ lies in $I$, and it is unclear why e.g. $x_iy_l\in I^N$. A similar question arises in the case of zero-convergent sequences.

A: It's not exactly you have to check for multiplication, but
$$\forall N\,\exists K\,\forall i, j\ge K,\;x_iy_i-x_jy_j\in I^N.$$
We know there exists $k$, such that $\;\forall i, j\ge k$, $\;x_i-x_j$  and $y_i-y_j\in I^N$. Hence for all such $i,j$, we have
$$x_iy_i-x_jy_j=x_i(y_i-y_j)+(x_i-x_j)y_j\in x_i I^N
+y_jI^N\subset I^N+I^N=I^N.$$


text:
Q: how can I prepend to a document.title string? myWebsite
document.title += ` ${date}`; // myWebsite 10/12/17

How can i do it the other way around
I will like the date to display prior to the title 10/12/17 myWebsite
Lodash, solution is fine.

A: You are using addition assignment (+=), which appends the new string to the end of the existing string. Instead of using the addition assignment, you should manually order the strings.
You can set the the expressions in the correct order in the template string:
document.title = `${date} ${document.title}`;

Or use string concatenation:
document.title = date + ' ' + document.title;


text:
Q: Is there a metaphorical word or phrase for a potential trouble maker? More specifically, someone who might open "undesirable doors" and fill you with profound regret for letting him/her into your life.

The idiom I'm trying to find would be used in the following situations:

*

*A married man hesitates about going on a date with a woman he met recently and thinks: "I'd better keep away from her.  She looks like a real ...................

*A new neighbour has been acting too friendly but, in your judgement, his personality looks like trouble.  You decide to put up a barrier because chances are he is a ...............

Is there a metaphor for that?
I'm not looking for the word "psychopath" or one of its synonyms.

A: 'ticking time bomb'--do not approach it and use extreme care. A person or situation that will probably become dangerous or harmful in the future.--Merriam-Webster.com

A: The first phrase that comes to my mind is an accident waiting to happen. It is a relatively common idiom:

You could also extend it to s/he looks like a problem waiting to happen.
Another alternative would be the simple s/he looks like trouble which you've already used in your question. Finally, you could also say s/he looks like a troublemaker but that is more specific. It implies that they would actively  cause trouble.

A: This question seems to be asking for a term for a person for whom you have a hunch that they may be a troublemaker, but no real proof. Some of the answers thus far seem to be glomming "looks like/seems like" onto synonyms for troublemaker.
If you only have a feeling that they might cause trouble in the future, they may be a

loose cannon

or

wild card

A: A religious phrase (especially for the first example) is an occasion of sin

an external set of circumstances—whether of things or persons—which either because of their special nature or because of the frailty common to humanity or peculiar to some individual, incite or entice one to sin. [Wikipedia]

More secular terms

*

*trouble (included in question)

*troublemaker

*nothing-but-trouble

*asking for trouble

*bad actor

*mischief-maker

*can of worms

*hassle

*tsuris

*an accident waiting to happen

*a car wreck

*stirring up a hornet's nest

A: They could be a bad hat or (more old-fashioned) a bad egg.

A: A married man hesitates about going on a date with a woman he met recently and thinks: "I'd better keep away from her. She looks like she may be the scourge of all happiness.
A new neighbor has been acting too friendly but, in your judgement, his personality looks like trouble. You decide to put up a barrier because chances are he will turn out to be the scourge of the neighborhood.

A: Wolf in sheep's clothing.
Pandora's Box.
Poke in the Eye. Shot in the foot.
A bridge too far.
A can of worms.

A: The word is troublemaker.
Since you are saying that the person looks like (appears to be) a troublemaker, you are not claiming that the person is a troublemaker.  You are saying only that the person is potentially a troublemaker.

*

*She looks like a real troublemaker.

*Chances are that he is a troublemaker.
(Yes, there is a difference between (a) saying that a person has the potential of becoming a troublemaker and (b) saying that a person seems to be a troublemaker. But that difference is probably not important in your context. If you are talking about what the person seems like, then it is pretty clear that you do not know the person well enough to say that the person is a potential troublemaker (i.e., s?he is not currently a troublemaker, but has the potential of becoming one).


text:
Q: Summation on multiplication of two numbers that equal to a specified sum Suppose I have N terms like $a_ix_i$ and coefficient $x$ is a constant for each $i$. How should I find all combinations of $a_i$ such that $\sum_{i=0}^Na_ix_i=S$?
$a_i\in \{0,1,2,...,\}$ $x_i\in \{2,1,6,.,3\}$
How about a matrix like
\begin{bmatrix}
    a_{11}x_{11}       & b_{12}x_{12} & x_{13} & \dots & c_{1,n}x_{1n} \\
    a_{21}x_{21}       & b_{22}x_{22} & x_{23} & \dots & c_{2,n}x_{2n} \\
\\
    a_{d1}x_{d1}       & b_{d2}x_{d2} & x_{d3} & \dots c_{d,n}& x_{dn}
\end{bmatrix}
that I have to select one term from each columns to sums to $S$?
Any specific algorithm or optimization model for these problems?
Any hint what should I looking for?
Thanks
Edit: To anyone who faces the same problem. Comments in this question helped me achieve what I wanted.


text:
Q: Is it possible to expose 2 ports in Kubernetes pod? I have the following scenario -

The position simulator will get its longitude and latitude data based on time from a gps tracker. So this position simulator has a connection to activemq, but to receive the raw data, is it possible to expose another port of this service to receive the live tracking data?

A: If you want to expose for example you deployment on two or more ports you can do it at least two ways.

*

*Proper configuration in YAML.
This method is well described in Kubernetes documentation.

For some Services, you need to expose more than one port. Kubernetes lets you configure multiple port definitions on a Service object. When using multiple ports for a Service, you must give all of your ports names so that these are unambiguous. For example:

Example:
apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  selector:
    app: MyApp
  ports:
    - name: http
      protocol: TCP
      port: 80
      targetPort: 9376
    - name: https
      protocol: TCP
      port: 443
      targetPort: 9377
    - name: <another-name>
      protocol: TCP
      port: XXX
      targetPort: XXX

*Using kubectl expose.

$ kubectl exposed <resource(deployment/Replicaset/etc)> <deployment-name> --port=XXX,XYZ,ABC --target-port=XXX
$ kubectl expose deployment nginx --port=80,8080,6000 --target-port=8080
service/nginx exposed
$ kubectl describe svc nginx
Name:              nginx
Namespace:         default
Labels:            run=nginx
Annotations:       <none>
Selector:          run=nginx
Type:              ClusterIP
IP:                10.0.74.75
Port:              port-1  80/TCP
TargetPort:        8080/TCP
Endpoints:         10.48.0.13:8080
Port:              port-2  8080/TCP
TargetPort:        8080/TCP
Endpoints:         10.48.0.13:8080
Port:              port-3  6000/TCP
TargetPort:        8080/TCP
Endpoints:         10.48.0.13:8080
Session Affinity:  None
Events:            <none>

As mentioned in Kubernetes docs
targetPort: is the port the container accepts traffic on,
port: is the abstracted Service port, which can be any port other pods use to access the Service


text:
Q: while loop exiting instead of looping when criteria not met i'm writing a function as part of a larger overall class project, and i'm having multiple issues with this looping statement, could any of you tell me how it's not looping even though its not meeting the exit criteria? i get what i need up until the loop, i'm trying to get it to ask you to select an item to add, print out the print statement, then start over and if you select the same item twice, add it to the cart
print("**********ITEMS**********")
print("1................Shirts - $10")
print("2.................Pants - $20")
print("3.................Shoes - $40")
print("4.................Dress - $50")
print("Complete Purchase")
cart = []
items = 0
def addItems():
    items = int(input("please add an item to your cart: "))
    while items > 0:
        if items == 1:
            print("Shirts,{}x,${}".format(+1, +10))
            cart.count("Shirt")
            cart.append("Shirt")
            print(cart)
            return cart
        elif items == 2:
            print("Pants,{}x,${}".format(+1, +20))
            #cart.count("Pants")
            cart.append("Pants")
            return cart
        elif items == 3:
            print("Shoes,{}x,${}".format(+1, +40))
            #cart.append("Shoes")
            cart.count("Shoes")
            return cart
        elif items == 4:
            print("Dress,{}x,${}".format(+1, +50))
            #cart.append("Dress")
            cart.count("Dress")
            return cart
        elif items > 5:
            break
        #return cart
   # print(cart.count("Shirt") * 10 + cart.count("Pants") * 20 + cart.count("Shoes") * 40 + cart.count("Dress") * 50)

addItems()

this is my output below
please add an item to your cart: 1
Shirts,1x,$10
['Shirt']

Process finished with exit code 0

A: You should remove 'return cart' from your if-elif ladder and add it to outside of the while loop. Also you could take input from the user in while loop in addition to the previous one, at the end of the while loop.
def addItems():
    items = int(input("please add an item to your cart: "))
    while items > 0:
        if items == 1:
            print("Shirts,{}x,${}".format(+1, +10))
            cart.count("Shirt")
            cart.append("Shirt")
            print(cart)
        elif items == 2:
            print("Pants,{}x,${}".format(+1, +20))
            #cart.count("Pants")
            cart.append("Pants")
        elif items == 3:
            print("Shoes,{}x,${}".format(+1, +40))
            #cart.append("Shoes")
            cart.count("Shoes")
        elif items == 4:
            print("Dress,{}x,${}".format(+1, +50))
            #cart.append("Dress")
            cart.count("Dress")
        elif items > 5:
            break
        items = int(input("please add an item to your cart: "))
    return cart


text:
Q: Basic sanity check: dimension of Lie groups / tangent spaces A potential typo in an exercise prompted me to question my knowledge of manifolds. So what I need is a sanity check.
Here is what I used to think before I got unsure:
If $M$ is an $n$-manifold then the dimension of the tangent space $T_p M$ at any point $p$ is equal to $n$. As a consequence, since $GL_n$ and its subgroups are manifolds, it must be that if $G$ is an $n$-dimensional matrix group then its Lie algebra $\mathfrak g$ must have dimension $n$ also. (since Lie algebra is defined to be the tangent space at $I$)

Is this correct or not?

A: Yes, that's correct. ${}{}{}{}{}{}{}{}$

A: Yep. Sanity checks are often a good idea.


text:
Q: Reallocating dynamically allocated struct I searched for an answer but didn't manage to find one.
I have a dynamically allocated struct, which means the structure itself will be allocated and some of its members. Like:
typedef struct dataUse
{
    char *num;
    char *name;
    char *position;
    char *eMail;
    float upload;
    float download;
} DataUse;

DataUse *ptr = NULL;

Now I have functions to reallocate memory for *ptr and also for *name, *position, *eMail. The size of name, position and eMail varies of course.
Now I understand, that reallocating something will either keep the original address of the data and increase the memory size or if it can't allocate to the same space, it will copy its contents and assign the pointer a new address.
Now in my case, if I reallocate my struct (*ptr) and want to increase its size and the latter happens, meaning my structs contents will be copied and new address will be signed, what will happen to *name, *position and *email? Can I still access them and the old contents via ptr->num. Will I have some kind of memory loss?
I'd just like someone to verify what will happen and explain, how it would look in memory if I realloc the whole struct. I'v seen, how structs look like in memory I've read a ton of posts, but sometimes it will get a bit confusing after adding some more pointers and going deeper levels (using double pointer for instance).
And what would happen, if I'd do it with double pointers - **ptr2 to hold pointers that will point to structs and then realloc **ptr2 to hold even more pointers?

A: If I understand your question correctly, you have allocated an instance of DataUse and store the address in ptr. Now you are reallocating it.
Pointers stores absolute address, so reallocating struct containing pointers won't lose the data.
So the instance of DataUse lies in somewhere in the memory, its address stored in ptr. The data of num lies in some other place, its address stored in the num field in DataUse. When copying the instance of DataUse to another place, the num field is also copied, so the address of string num and name etc remains unchanged and are still in the new copy of num, name fields.
You just reallocate the struct, i.e. the positions where you store addresses are changed, but the addresses held in num, name, ... remains unchanged.

A: If we assume ptr[i] is valid (e.g. an array of at least i+1 DataUse has previously been allocated using malloc()), and the size of the memory that ptr points to is increased using realloc(), then the address of  ptr[i].num will change if ptr has changed, but the value of ptr[i].num will not.

A: Consider the following snippets:
DataUse *ptr= malloc(sizeof(DataUse));    // allocate non-zeroed memory

The above allocates memory for your structure. Note that it is not zeroed, so anything that should be zeroed must be zeroed by you.
ptr->name= malloc(strlen(this_name)+1);
strcpy(ptr->name, this_name);

The above initializes name.
free(ptr_name);
ptr->name= malloc(strlen(new_name)+1);
strcpy(ptr->name, new_name);

The above places a new name in name. It first frees the allocated memory.
char *tmpname= realloc(ptr->name, strlen(new_name)+1);
if (tmpname) {
    ptr->name= tmpname;
    strcpy(ptr->name, new_name);
}
else printf("Out of memory);

The above does (about) the same, but uses realloc. Note that ptr->name MUST be zero if it was not used before.


text:
Q: How can I set the exit code of uninstallation in Inno-Setup? I would like to set the exit code for my uninstallation in Inno Setup. By doing this I want the Inno Setup to show some sort of "uninstallation failed" dialog box to the user.
I know that defining custom exit code for installation can be done via GetCustomSetupExitCode function.
Is it possible to notify Inno Setup that the custom uninstallation procedure has failed and to prevent Inno Setup from showing the silly "Uninstall Successful" message no matter what happens?

A: I did a code review of the Uninstall.pas in InnoSetup and there is currently no way to do what you would like to do.

A: One possibility is to Implement your own Pascal Script. Probably in DeinitializeUninstall() event, (check the manual to know exactly in which step you want it), you can add these code:
[Code]
var error: Boolean;

procedure ExitProcess(exitCode:integer);
  external 'ExitProcess@kernel32.dll stdcall';

procedure TheEventYouFeelIsBetterHere():
begin
 if error then begin
   MsgBox('Installation Failed!', mbError, MB_OK);
   ExitProcess(1);
 end;
end;


text:
Q: How to find the maximum torque to apply to a robot joint to have realistic movement? I am a computer science student. I am trying to simulate a locomotion of a legged robot.
The weight and dimensions of the robot:

*

*A rectangular torso has 1 Kg, (0.15m*0.3m*0.03m) (width * length * height)

*Four cylinder legs, each one is about 0.2 Kg (0.04m length, 0.01m radius)

Moment of inertia of each leg: (computed them from wiki page )

*

*Ix =Iy = 0.000126667

*Iz = 0.00001

My question is, how to know what is the maximum of torque and angular velocity to get the joint rotate in a realistic way. Here is a video of what I mean by not realistic.
I know that in a linear movement: Force = Mass * Acceleration. So we can find approximately the force. But in a joint ?
Sorry for the question, it may be stupid but I didn't studied physic since high school!


text:
Q: Dynamically naming a table in postgresql function So I have a table that for some design reasons cannot use a foreign key to map to other entities. So I am working on a function that is called to safely delete entries from the media table. As it stands at the moment I have written the function to have basic functionality using this resource as my guide on how to dynamically insert a table name into a query (http://www.postgresql.org/docs/current/static/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN). As it stands my query is written as follows
DECLARE
    rows_returned numeric;
    is_media boolean;
BEGIN
    DELETE FROM solo_media WHERE entity_id = row_to_delete;

EXECUTE "DELETE FROM $1  WHERE id = $2;" INTO rows_returned USING table_name, row_to_delete;
END;

And when it is ran (with table_name and row_to_delete being parameters being passed in) I get the error

ERROR:  column "DELETE FROM $1  WHERE id = $2;" does not exist
  LINE 1: SELECT "DELETE FROM $1  WHERE id = $2;"
                 ^
  QUERY:  SELECT "DELETE FROM $1  WHERE id = $2;"
  CONTEXT:  PL/pgSQL function "safe_del" line 7 at EXECUTE statement

when calling it with
SELECT safe_del(tableName, rowNumber);

A: As Milen A. Radev pointed out I was using the wrong characters to identify my string, I switched it over to dollar escaped strings, and resolved the issues.


text:
Q: Correspondence between an order of rational function field and a Dedekind cut In the first page of Real Algebraic Geometry by Jacek Bochnak, Michel Coste, Marie-Francoise Roy, they briefly connect an order of the rational function field $R(X)$ with a Dedekind cut $(I,J)=(\{x\in\mathbb{R}\mid x<X\}, \{x\in\mathbb{R}\mid x>X\})$. But I don't understand how they can use the "symbol" $X$ as a real number. Can somebody translate it into a language like "$f\ge_{a} g \iff \mbox{some statement about $a$ where $a\in\mathbb{R}$}$"? Thank you.
Here's a snapshot of the first and part of the second page.

A: They don't use $X$ as a real number, they use $x \in \mathbb{R}$ as rational function in $\mathbb{R}(X)$, and use order relation $<$ in $\mathbb{R}(X)$.


text:
Q: Iterating through and comparing two Pandas Dataframes I've been working on a little project to sift through backup job reports and was using a couple of Pandas Dataframs to attempt to accomplish this. Now, I understand that manually iterating through a dataframe isn't ideal - but I'm not sure if there's a better method considering what I'm trying to achieve. I'm also rather new to Python and Pandas in general.
So I have a list of backup jobs, uniquely defined by their backup type, system name, and system type. This list is stored in objects_df.
Next, I have a list of every job run and its success or failure status. This is stored in report_df and is a few thousand rows.
I want to 'flag' a job in report_df once it has failed 3 consecutive times. I only care about 'flagging' the first time that happens.
And here's the ugly piece of code I'm trying to use to make this all happen:
for index, row in objects_df.iterrows():
    count = 0
    for index2, row in report_df.iterrows():
        if(objects_df['Task Type'][index].equals(report_df['Task Type'][index2]) and objects_df['Object Name'][index].equals(report_df['Object Name'][index2]) and objects_df['Object Type'][index].equals(report_df['Object Type'][index2])):
            if(row['Task Status'] == "Succeeded" and count < 3):
                count = 0
            if(row['Task Status'] == "Failed"):
                count += 1
            if(count == 3):
                report_df.at[index2, 'flag'] = True
                break

As you can see, it goes through my list of objects and for every match it finds in the report, it starts counting failures. Once it reaches 3 consecutive failures it flags it in the report_df.
Unfortunately, this code has been giving me all sorts of problems and doesn't really seem to mark the expected rows as 'flag = true'. Instead, I'm getting duplicate rows and flags on successful runs getting marked as 'true'.
Is there a way to clean this code up or perhaps a better way to approach this project altogether? Even if I do get this working, I'm afraid it'll take forever to go through all the data.
Thanks!

A: Have you investigated Dataframe.compare: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.compare.html
I think your task is most easily split into 2 steps:

*

*compare the two dataframes

*process the resulting dataframe for instances of 3 or more non-equal comparisons

The second step being a different problem. Similar question: https://stackoverflow.com/a/41488980/9190640


text:
Q: Not able to connect with MQTT server using AWSIoT SDK I am using AWSIoT sdk to connect with MQTT server But not able to connect
Using method from SDK
let uuid = UUID().uuidString
// Connect to the AWS IoT data plane service over websocket
iotDataManager.connectUsingWebSocket(withClientId: uuid, cleanSession: true, statusCallback: mqttEventCallbackWebsocket(_:))

Getting response in debug
2022-06-12 17:31:04:108 IoTSampleSwift[14948:966200] AWSIoTMQTTClient: connecting via websocket.
2022-06-12 17:31:04:108 IoTSampleSwift[14948:966200] Using AWSCredentials.
2022-06-12 17:31:04:110 IoTSampleSwift[14948:966200] user metadata is : ?SDK=iOS&Version=2.27.9
connection status = 1
Connecting...
2022-06-12 17:31:04:110 IoTSampleSwift[14948:966200] Metrics collection is: Enabled
2022-06-12 17:31:05:743 IoTSampleSwift[14948:966690] Websocket did open and is connected.
2022-06-12 17:31:05:744 IoTSampleSwift[14948:966922] <<<NSThread: 0x281546f80>{number = 42, name = (null)}>> Initializing MQTTEncoder and MQTTDecoder streams
2022-06-12 17:31:05:744 IoTSampleSwift[14948:966922] opening encoder stream.
2022-06-12 17:31:05:744 IoTSampleSwift[14948:966922] opening decoder stream.
2022-06-12 17:31:06:068 IoTSampleSwift[14948:966923] WebSocket closed with code:1001 with reason:Stream end encountered
connection status = 5
Connection Error
2022-06-12 17:31:06:069 IoTSampleSwift[14948:966922] MQTT session error, code: 2
2022-06-12 17:31:06:071 IoTSampleSwift[14948:966922] closing encoder stream.
2022-06-12 17:31:06:071 IoTSampleSwift[14948:966922] closing decoder stream.
2022-06-12 17:31:07:076 IoTSampleSwift[14948:966922] MQTTSessionEventConnectionClosed: MQTT session closed.
connection status = 5
Connection Error


text:
Q: Play/Pause/Download Video In FlatList I am trying to implement a very common usecase.
The idea is simple, download/play a video which is being shown currently in the flatlist, pause/dont download the rest.
This is my FeedCard -> MyFlatListItem
class FeedCard extends PureComponent {

    constructor(props){
        super(props);
        this.state = {
            pauseVideo: true
        };
    }

    playThisVieo = (playVideo) => {
      this.setState({
          pauseVideo: !playVideo
      });
    };

    render() {
        return (
            <Card>
                <CardItem cardBody>
                    <View style={styles.preview}>
                        <Video
                            source={{ uri: this.props.videoURL}}
                            ref={(ref) => {
                                this.player = ref;
                            }}
                            rate={1.0}
                            volume={1.0}
                            muted={false}
                            paused={this.state.pauseVideo}
                            resizeMode="stretch"
                            repeat={true}
                            playInBackground={false}
                            playWhenInactive={false}
                            ignoreSilentSwitch={"ignore"}
                            progressUpdateInterval={250.0}
                            onLoadStart={() => this.player.seek(0)}
                            onLoad={this.setDuration}
                            onProgress={this.setTime}
                            onEnd={this.onEnd}
                            onError={this.videoError}
                            onBuffer={this.onBuffer}
                            onTimedMetadata={this.onTimedMetadata}
                            style={{
                                position: 'absolute',
                                top: 0,
                                left: 0,
                                bottom: 0,
                                right: 0,
                            }}
                        />
                    </View>
                </CardItem>
            </Card>
        );
    }
}

Now all I have to do is renderThisItem In FlatList and then in onViewableItems, only play that video which is being shown.
constructor(props){
    super(props);
    this.viewabilityConfig = {viewAreaCoveragePercentThreshold: 70};
}

 <FlatList
        horizontal={false}
        data={this.props.feeds}
        renderItem={this.renderFeeds}
        viewabilityConfig={this.viewabilityConfig}
        onViewableItemsChanged={this._onViewableItemsChanged}
 />

 renderFeeds = (feed) => {
    return (
        <FeedCard
            ref={(ref) => this.feedCardRef = {...this.feedCardRef, [`REF-FLATLIST${feed.item.feedID}`]: ref}} //Saving Refs Here
            videoURL={feed.item.videoURL}
            //Other Props
        />
    );
};

    _onViewableItemsChanged = (props) => {
        const changed = props.changed;
        const viewableItems = props.viewableItems;
        console.log(changed);
        console.log(viewableItems);
        changed.forEach(item => {
            if (!item.isViewable) {
                this.feedCardRef[`REF-FLATLIST${item.key}`].playThisVideo(item.isViewable);
            }
        });
        viewableItems.forEach(item => {
            if (item.isViewable) {
                this.feedCardRef[`REF-FLATLIST${item.key}`].playThisVideo(item.isViewable);
            }
        });
    };

Now the above works well for playing video only if its the one being shown in the screen, but I also want to download the video only if that video is being currently shown in the screen. How do I control the download of a video? I couldnt find anything in the readme.

A: play the video which is visible
constructor(props)
{
     super(props);
     this.videoRefs = [],
}

<FeedCard
            ref={(videoRef) => {this.videoRefs[feed.item.feedID] = videoRef}; }
            videoURL={feed.item.videoURL}

        />

==============
_onViewableItemsChanged = (props) => {
        const changed = props.changed;
        const viewableItems = props.viewableItems;

        changed.forEach(item => {
            if (!item.isViewable) {
                 this.videoRefs[item.id].pauseVideo();
            }
        });
        viewableItems.forEach(item => {
            if (item.isViewable) {
                 this.videoRefs[item.id].playVideo();
            }
        });
    };


text:
Q: How to take 3 random letters from first name , 2 from last name and phone number and 1 symbol from the given string 'specialChar' public class testingstring {

   public static void main(String[] args)
   {
       Scanner userInput = new Scanner (System.in) ;

       String specialChar = "!@#$%^&*()" ;

       System.out.println("Enter your first name: ");
       String firstName = userInput.next() ;

       System.out.println("Enter your last name: ") ;
       String lastName = userInput.next() ;

       System.out.println("Enter your phone number: ") ;
       String phoneNum = userInput.next() ;

   }
}

The program should randomly generate 8 characters long password as follows:

*

*3 random letters from the first name

*2 random letters from the last name

*2 random digits from the mobile phone number

*1 random character from the variable 'specialChar'

A: 1/loop n times
int index = (new Random()).nextInt(specialChar.length());
then put specialChar.charAt(index) in  a result array for each string.

A: Break the problem into smaller pieces.  Say the first name is "Patrick".  How do you go about picking three random letters from the string "Patrick"?  Write a small piece of code to do that and test it.  Then add it to your program in the right place.
Use a similar logic to pick from the last name and the string of special characters.

A: You can do something like this.
import java.util.Scanner;

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

String[] Arr = new String[4];
Scanner S = new Scanner(System.in);
int[] N = new int[4];
char[] Pass = new char[8];

System.out.println("What is your first name?");
Arr[0] = S.nextLine();
System.out.println("What is your last name?");
Arr[1] = S.nextLine();
System.out.println("What is your mobile phone?");
Arr[2] = S.nextLine();
Arr[3] = "!@#$%^&*()";

for (int pos = 0; pos < 4; pos++) {
    N[pos] = Arr[pos].length() - 1;
    switch (pos) {
        case 0:for (int count = 0; count < 3; count++)
            Pass[count] = Arr[0].charAt((int) Math.round(Math.random()*N[0]));
            break;
        case 1:for (int count = 3; count < 5; count++)
            Pass[count] = Arr[1].charAt((int) Math.round(Math.random()*N[1]));
            break;
        case 2:for (int count = 5; count < 7; count++)
            Pass[count] = Arr[2].charAt((int) Math.round(Math.random()*N[2]));
            break;
        case 3:for (int count = 7; count < 8; count++)
            Pass[count] = Arr[3].charAt((int) Math.round(Math.random()*N[3]));
            break;
    }}
System.out.print("Your new password: ");
for (int pos = 0; pos < 8; pos++) {
    System.out.print(Pass[pos]);
}}}


text:
Q: Android: Access content:// file from intent In my Android App I authorise the user to share a zip-file with my application (in most cases the user will only use Dropbox for sharing).
So I tried for hours to figure out how to access the content:// file my App is receiving from Dropbox.
I'm using this code:
Intent intent = MainActivity.this.getIntent();
Uri dataUri = intent.getData();
Bundle bundle = new Bundle();
if(dataUri != null){
  String dataUriString = dataUri.toString();
  File rootDataDir = MainActivity.this.getFilesDir();
  if(unzipFile(dataUriString, rootDataDir.toString())){
     //true
  }else{
     //false
  }
  bundle.putString("receive_data", dataUri.toString());
}
return bundle;

In dataUriString we have something like:

"content://com.dropbox.android.FileCache/filecache/...contenID.."

But if I try to access the file as a normal it won't work:
public boolean unzipFile(String inputPath, String outputPath) {
        try{
            byte[] buffer = new byte[1024];
            File file = new File(inputPath);
            ZipInputStream zis = new ZipInputStream(new FileInputStream(file));
            ZipEntry zipEntry = zis.getNextEntry();
            while(zipEntry != null){
                String fileName = zipEntry.getName();
                File newFile = new File(outputPath+ "/import/" + fileName);
                try (FileOutputStream fos = new FileOutputStream(newFile, false)){
                    int len;
                    while ((len = zis.read(buffer)) > 0) {
                        fos.write(buffer, 0, len);
                    }
                }
                zipEntry = zis.getNextEntry();
            }
            zis.closeEntry();
            zis.close();
            return true;
        }catch(IOException err){
            return false;
        }
    }

    private String getRealPathFromURI(Context context, Uri contentUri) {
        Cursor cursor = null;
        try {
            String[] proj = { MediaStore.Images.Media.DATA };
            cursor = context.getContentResolver().query(contentUri,  proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } catch (Exception e) {
            Log.e("ReactNative", "getRealPathFromURI Exception : " + e.toString());
            return "";
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

So how do I have to work/handle content:// files?
Thanks for any help!!

A:
But if I try to access the file as a normal it won't work

That is because it is not a file. Similarly, Android: Access content:// file from intent is not a file.

So how do I have to work/handle content:// files?

Use ContentResolver (from getContentResolver() on a Context) and openInputStream() to get an InputStream on the content identified by the Uri.


text:
Q: Cable fault in Token ring I'm not sure what will happen when we have a cable fault in token ring network!
The Internet Encyclopedia, G O :

If a cable is cut, the token ring network can continue operate because
  of redundant path.

Sybex: Network+ Study Guide 4th edition (page 14) :

A single cable fault can bring down the entire network.

Any help for clarification is appreciated.

A: As with anything, it depends. It depends on how it's designed. You can build a ring with redundant paths (can survive the loss of a single link), or without (won't survive.) Building redundancy into everything is a best practice, but sometimes it is compromised to cut costs, decrease implementation time, etc.
But, this sounds like an academic question, since you're quoting references. Do you actually have a TR network? How is it built?


text:
Q: Adding A VPN with a Pre-shared key in PowerShell I have the following PowerShell script to create a VPN connection on windows but I don't know how to input the Pre-shared key as an argument. Does anyone know how to do this? I tried looking up Microsoft's documentation on this and could not find an answer to my problem.
Add-VpnConnection -Name "Test VPN" -TunnelType L2tp -ServerAddress "**********" -RememberCredential "False" -L2tpPsk "MySharedKey"

I also do not know how to make this into a multi line script instead of a single line script. Assistance would be much appreciated to make it more readable.
Thanks in Advance,
Vishal


text:
Q: ListAdapter in Android 1.5 and 1.6: are there any differences? I made an application that uses a ListAdapter to display some items. In my getView method I use LinearLayout#setPadding() to define the indention of each view depending of some object specific states.
This worked fine in Android 1.5. Last week I decided to move to 1.6 since it's better suitable for different screen sizes. It all worked fine, but the ListAdapter looks really weird now. The padding isn't working correctly anymore.
Does anybody know if there is a difference in the ListAdapter or setPadding implementation between Android 1.5 and Android 1.6?
===EDIT: Code added===
@Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TextView text = (TextView) View.inflate(lexs, R.layout.law_list_book_view, null);

            if (items.get(position) instanceof Chapter) {
                LinearLayout chapterView = new LinearLayout(lexs);
                chapterView.setOrientation(LinearLayout.HORIZONTAL);
                chapterView.setGravity(Gravity.CENTER);

                ImageView img = new ImageView(lexs);
                img.setPadding(0, 0, 5, 0);
                chapterView.addView(img);

                chapterView.addView(text);
                text.setTextColor(Color.BLACK);
                text.setText((CharSequence) items.get(position).getName() + ": " + ((Chapter) items.get(position)).getTitle());
                text.setMinWidth(320);
                switch (((Chapter) items.get(position)).getLevel()) {
                    case 0:
                        text.setTextColor(Color.rgb(0, 0, 0));
                        break;
                    case 1:
                        text.setTextColor(Color.rgb(50, 50, 50));
                        chapterView.setPadding(10, 0, 0, 0);
                        break;
                    case 2:
                        text.setTextColor(Color.rgb(100, 100, 100));
                        chapterView.setPadding(20, 0, 0, 0);
                        break;
                    case 3:
                        text.setTextColor(Color.rgb(150, 150, 150));
                        chapterView.setPadding(30, 0, 0, 0);
                        break;
                    case 4:
                        text.setTextColor(Color.rgb(175, 175, 175));
                        chapterView.setPadding(40, 0, 0, 0);
                        break;
                    default:
                        text.setTextColor(Color.rgb(200, 200, 200));
                        chapterView.setPadding(50, 0, 0, 0);
                        break;
                }

                if (((Chapter) items.get(position)).isExpanded()) {
                    img.setImageResource(R.drawable.minus);
                } else {
                    img.setImageResource(R.drawable.plus);
                }

                if (((Chapter) items.get(position)).isSearched()) {
                    text.setBackgroundColor(Color.MAGENTA);
                }
                text.setTextSize(15);
                return chapterView;
            } else {
                LinearLayout paragraphView = new LinearLayout(lexs);
                paragraphView.setOrientation(LinearLayout.HORIZONTAL);
                paragraphView.setGravity(Gravity.CENTER);
                paragraphView.setPadding( (((Chapter) ((Paragraph) items.get(position)).getRoot()).getLevel() * 10) + 15 + 8 , 0, 0, 0);

                DisplayMetrics metrics = new DisplayMetrics();
                lexs.getWindowManager().getDefaultDisplay().getMetrics(metrics);

                ImageView paragraphImg = new ImageView(lexs);
                paragraphImg.setImageResource(R.drawable.paragraph);
                paragraphView.addView(paragraphImg);

                LinearLayout textLayer = new LinearLayout(lexs);
                textLayer.setGravity(Gravity.LEFT);
                textLayer.setMinimumWidth(metrics.widthPixels / 2);
                text.setTextColor(Color.BLACK);
                textLayer.addView(text);
                textLayer.setOnClickListener(new BookViewOnClickListener(position));
                paragraphView.addView(textLayer);
                text.setText("Artikel " + (CharSequence) items.get(position).getName());

                LinearLayout buttonLayer = new LinearLayout(lexs);
                buttonLayer.setGravity(Gravity.RIGHT);
                ImageButton mark = new ImageButton(lexs);
                if (WorkspaceView.createView(lexs).isFavorite((Paragraph) items.get(position))) {
                    mark.setBackgroundResource(R.drawable.article_not_favorite);
                } else {
                    mark.setBackgroundResource(R.drawable.article_favorit);
                }
                mark.setOnClickListener(new BookViewOnClickListener(position));
                buttonLayer.addView(mark);
                buttonLayer.setPadding(0, 0, 10, 0);
                buttonLayer.setMinimumWidth(metrics.widthPixels / 2);
                paragraphView.addView(buttonLayer);
                text.setTextSize(15);

                if (((Paragraph) items.elementAt(position)).isSearched()) {
                    text.setBackgroundColor(Color.RED);
                }

                return paragraphView;
            }

        }

===EDIT 2: Screenshot added===

I know that this elements of the list are all level 0 elements and should therefore have no padding (I used logcat to verify the level of the elements. they are all 0). the level of the elements i use in the switch case to check the padding (see code)

A: You have the API Differences page to check that but honestly I don't think it's a SDK issue. Try posting your code so we can reproduce.
EDIT:
Screenshot after trying to reproduce the issue:

This looks good, what's your issue again?

A: You might want to check out the more friendly UI Framework Changes in Android 1.6.


text:
Q: How to get ASP.NET MVC application's base url in Startup.cs file? I am looking for a way to get the root url of my web application so I wouldn't have to use a hardcoded string where I need it.
So far I've tried to get it this way:
var request = HttpContext.Current.Request;

var url = string.Format("{0}://{1}",
          request.Url.Scheme,
          request.Url.Authority);

but unfortunately this doesn't give me the desired result when executed from the Startup class, I got http://127.0.0.1

A: Given a full URL such as "http://example.com/MyApplication/Controller/Action", you can get some of this information from the System.Web.Hosting.HostingEnvironment.ApplicationHost object. You can get the following:
ApplicationVirtualPath -> "/MyApplication"
SiteName => "Default Web Site"
However, you will not be able to get the domain name before an actual request comes in. This is because an IIS website can accept requests for many different domains, some of which are only known via DNS and never configured anywhere.
For example, your website could respond to both mydomain.com and www.mydomain.com. Which is the correct one that you want to put in your link?
You can configure your IIS website to only accept connections that request a particular host, but that cannot be retrieved from an ASP.NET application.
Reference : Getting a web application's URI during startup

A: This worked for me:
var request = HttpContext.Current.Request;
var url = request.Url.Scheme + "://" + request.Url.Authority + request.ApplicationPath.TrimEnd('/');

A: Try this:
var url = string.Format("{0}://{1}", request.Url.Scheme, request.Url.Host);


text:
Q: Future in indirect speech In my English book for Russian students, I have found a confusing sentence:
A second conference will be held tomorrow morning and Brigg's agent said that an interview ________ (give) by the actor over the coming days.
The key says that the answer is will be given but I don't really understand why not would be given. Isn't it a reported speech sentence with the future clause where we need to replace will with would?
Really need your explanation:( Thanks.

A: I think the confusion might stem from the fact that we often change will to would in reported speech:

"I will go to Zurich tomorrow," he said.
  He said that he would go to Zurich tomorrow.

This is often referred to as "future-in-the-past".
However, I find that to be less and less true all the time, at least in US English, particularly when we're talking about future plans that are still true:

In 1998, Elaine said, "I will go to France next year."
  In 1998, Elaine said that she would go to France next year.

BUT

Today, Zahra said, "The house will be completed in 2020."
  Today, Zahra said that the house will be completed in 2020.

A: I think that the clue lies in the words "over the coming days". Sometimes you have to take meaning from the entire sentence. These words indicate to me an impending certainty. If they were not there then I would have used 'would be given' and would always has a little doubt to it. But, because you have 'over the coming days' then it makes sense to use 'will be given'.
Furthermore, the first part of the phrase is in the future perfect: A second conference will be held. the second part of the sentence is indtroduced by an 'and', so perhaps a future perfect construction overrides the indirect speech aspect. Though I am not completely sure on that. However, 'will be given' is absolutely the correct answer here.


text:
Q: Amort Table using javamoney 1.3 library I want to use javamoney for making an amort table for loans.
I thought of using PresentValueOfAnnuityPayment but was unable to find it in javamoney 1.3.
Any suggestions?
EDIT:
I added this dependency in project but still am unable to find PresentValueOfAnnuityPayment or any other class from this https://github.com/JavaMoney/javamoney-lib/blob/master/calc/src/main/java/org/javamoney/calc/common/PresentValueOfAnnuityPayment.java repo
    <dependency>
        <groupId>org.javamoney.lib</groupId>
        <artifactId>javamoney-calc</artifactId>
        <version>1.0</version>
        <type>pom</type>
    </dependency>

A: Use Maven and create a pom.xml file with dependency:
<dependency>
  <groupId>org.javamoney</groupId>
  <artifactId>moneta</artifactId>
  <version>1.3</version>
  <type>pom</type>
</dependency>


text:
Q: How to prevent opening multiple popup windows? My problem is next.
I want to prevent opening second popup window, while first one is active. I want achieve this on more than 2 windows (modals), let's say 5 or 6.
Does anyone know how can i achieve that?
I appreciate your help.
Here is the code:
-HTML:

<button class="trigger_1">Image 1</button>
<button class="trigger_2">Image 2</button>
<button class="trigger_3">Image 3</button>

<button class="close x_1">Close [ x ]</button>

<button class="close x_2">Close [ x ]</button>

<button class="close x_3">Close [ x ]</button>

-CSS:
/* Popup 1 */
#popup_1 {
position: fixed;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
width: 33%;
height: auto;
background-color: #fff;
-webkit-box-shadow: 0 0 0 10px rgba(51,51,51,0.1);
-moz-box-shadow: 0 0 0 10px rgba(51,51,51,0.1);
-ms-box-shadow: 0 0 0 10px rgba(51,51,51,0.1);
box-shadow: 0 0 0 10px rgba(51,51,51,0.1);
z-index: 100;
display: none; }

/* Popup 2 */
#popup_2 {
position: fixed;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
width: 33%;
height: auto;
background-color: #fff;
-webkit-box-shadow: 0 0 0 10px rgba(51,51,51,0.1);
-moz-box-shadow: 0 0 0 10px rgba(51,51,51,0.1);
-ms-box-shadow: 0 0 0 10px rgba(51,51,51,0.1);
box-shadow: 0 0 0 10px rgba(51,51,51,0.1);
z-index: 100;
display: none; }

/* Popup 3 */
#popup_3 {
position: fixed;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
width: 33%;
height: auto;
background-color: #fff;
-webkit-box-shadow: 0 0 0 10px rgba(51,51,51,0.1);
-moz-box-shadow: 0 0 0 10px rgba(51,51,51,0.1);
-ms-box-shadow: 0 0 0 10px rgba(51,51,51,0.1);
box-shadow: 0 0 0 10px rgba(51,51,51,0.1);
z-index: 100;
display: none; }

/* Popup img */
img {
float: left;
margin-top: 0;
margin-left: 0;
width: 100%;
height: auto; }

/* Button placeholder */
#button_placeholder {
float: left;
margin-top: 0;
margin-left: 0;
width: 100%;
height: auto; }

/* Button placeholder button */
#button_placeholder .close {
margin: 15px auto;
padding: 7px 9px;
font-size: 16px;
color: #fff;
background-color: #ff48a1;
-webkit-transition: background-color 0.5s ease;
-moz-transition: background-color 0.5s ease;
-ms-transition: background-color 0.5s ease;
transition: background-color 0.5s ease;
border: none;
outline: none;
display: block;
cursor: pointer; }

/* Button placeholder button (hover effect) */
#button_placeholder .close:hover {
background-color: #333; }

-JavaScript:
// When everything is ready...
$( document ).ready(function() {

// Modal 1 mechanism:
$('.trigger_1').click(function(e) {
e.preventDefault();
modal1();
});

$('.x_1').click(function() {
$('#popup_1').fadeOut() });

function modal1() {
$('#popup_1').fadeIn(); }
// End.

// Modal 2 mechanism:
$('.trigger_2').click(function(e) {
e.preventDefault();
modal2();
});

$('.x_2').click(function() {
$('#popup_2').fadeOut() });

function modal2() {
$('#popup_2').fadeIn(); }
// End.

// Modal 3 mechanism:
$('.trigger_3').click(function(e) {
e.preventDefault();
modal3();
});

$('.x_3').click(function() {
$('#popup_3').fadeOut() });

function modal3() {
$('#popup_3').fadeIn(); }
// End.

});
// End.

Regards, Milan.

A: Put these condition to prevent multiple popup opening:
function modal1() {
    if ($("#popup_2").is(":hidden")){
        $('#popup_1').fadeIn();
    }
    else{/*do something*/}
}

function modal2() {
    if ($("#popup_1").is(":hidden")){
        $('#popup_2').fadeIn();
    }
    else{/*do something*/}
}

Better way to do it is by using classes:
function modal(element){
    if ($(".pop_up_open").length == 0){
         $(element).fadeIn();
         $(element).addClass("pop_up_open");
    }
    else{/*do something*/}
}
function modalClose(){/*this function will run when you want to close function*/
         $(".pop_up_open").fadeOut();
         $(".pop_up_open").removeClass("pop_up_open");
}

Updated Fiddle
Instead of many function use these function to pop_up a element you want to open and close.
$(document).ready(function () {
    $('.trigger_1').click(function (e) {
        e.preventDefault();
        modal("#popup_1");
    });
    $('.x_1').click(function () {
        modalClose();
    });
    $('.trigger_2').click(function (e) {
        e.preventDefault();
        modal("#popup_2");
    });
    $('.x_2').click(function () {
        modalClose();
    });
    $('.trigger_3').click(function (e) {
        e.preventDefault();
        modal("#popup_3");
    });
    $('.x_3').click(function () {
        modalClose();
    });
});


text:
Q: Spring Cloud Netflix Zuul. SQLSyntaxErrorException: Table 'rate' doesn't exist I am trying to configure rate limiting in my Spring Cloud Netflix Zuul using JPA repository.
However at the start I receive this Exception:

java.sql.SQLSyntaxErrorException: Table 'kirillbq_bl_acc.rate' doesn't
  exist

My application.yaml:
zuul:
  routes:
    my-service:
      path: /
  ratelimit:
    enabled: true
    repository: JPA
    policy-list:
      my-service:
        - limit: 2
          refresh-interval: 60
          type:
            - origin
  strip-prefix: true

I have a spring-boot-starter-data-jpa dependency in a project also.
I assume that Zuul needs a 'Rate' table to store an information about requests however I can not find any information about the structure of such table. What it should be?

A: I have found this information: https://www.programcreek.com/java-api-examples/?code=marcosbarbero/spring-cloud-zuul-ratelimit/spring-cloud-zuul-ratelimit-master/spring-cloud-zuul-ratelimit-core/src/main/java/com/marcosbarbero/cloud/autoconfigure/zuul/ratelimit/RateLimitAutoConfiguration.java#
There is Rate.java class in config folder with a structure of 'Rate' table:
@Entity
public class Rate {

    @Id
    private String key;
    private Long remaining;
    private Long remainingQuota;
    private Long reset;
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy HH:mm:ss")
    private Date expiration;

    // constructor, getters and setters
}

After this table was created all works fine. Zuul saves information about requests in this table.


text:
Q: XMPPFramework - XMPP Connection staying alive for a long time - applicationDidEnterBackground I am using xmppframework to develop an iOS chat application. The issue is, I expect the XMPP connection to go offline when the app is minimised/not active in some time.
But to my surprise, the user is not going offline. I believe thats my issue. The reason, I want the user to go offline is that when the user is offline, and the user receives a push notification (through APNS), I have programmed in such a way that the XMPP connection is reestablished when the user clicks on the push notification  and launches the app.
This works fine when the user goes offline
But when the user is online ( say 12 hrs the user is online) for a long time after the app is minimised (which is happening to me at the moment), when I try to send a message to the user, the user is not receiving the internal push notification nor the messages which I am sending though the user status is ONLINE .This mostly happens in iPhone 4 running in version iOS7.
Below is the applicationDidEnterBackground code
- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSMutableArray *tempaaray=[DatabaseAccess getBedageValueFromConversation];
NSLog(@"getBedageValueFromConversation is :%lu",(unsigned long)tempaaray.count);

//================XMPP
// Use this method to release shared resources, save user data, invalidate timers, and store
// enough application state information to restore your application to its current state in case
// it is terminated later.
//
// If your application supports background execution,
// called instead of applicationWillTerminate: when the user quits.

DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);

#if TARGET_IPHONE_SIMULATOR
DDLogError(@"The iPhone simulator does not process background network traffic. "
           @"Inbound traffic is queued until the keepAliveTimeout:handler: fires.");
#endif

if ([application respondsToSelector:@selector(setKeepAliveTimeout:handler:)])
{
    [application setKeepAliveTimeout:600 handler:^{

        DDLogVerbose(@"KeepAliveHandler");

        // Do other keep alive stuff here.
    }];
}
}

Can I add the below line in the applicationDidEnterBackground delegate method
if (![xmppStream isDisconnected]) {
    [self disconnect];
}

This will forcefully disconnect the user and make the user go offline every time the user minimises the app. And once he comes online, messages will resume. Or do I need to localise this code for only iPhone4 and iOS7 users?
Or is there any other good way of tackling this issue?
Please let me know


text:
Q: CodeIgniter Pagination How to add page number as class of every
* Hi I am working with a app where I get the Codeigniter Pagination through ajax. Problem is on every response, by default Page 1 is selected.
I am trying to replace the current class with $("#user_pagination ul.pagination li").removeClass("current"); which works fine but problem is to set the current class to the current page. I've the variable index which has the current page number, now if I had a class with page number like
2
, it would be very easy for me to add the current class.
Is there any way to do that using CodeIgniter Pagination class?
This is example of my html

 1

 2

 »

If there is any way to select the target
 which has string 2 inside its child , and addClass to that
? That would also solve the problem.

A: If i understand you right, this code can help you find tag
 which has string 2 inside its child :
$("#user_pagination ul.pagination li a:contains('2')").parent('li')


text:
Q: How to fix 500 (Internal Server Error) Vue js - Laravel (Edited) Im doing a project using Vuejs and laravel for the university and i want support when i send the information to the api
Im using axios to do the post but they give a me a error: 500 (Internal Server Error). But i cant see the error, i think i have all good in my code.
This is my submit method
submitFiles() {
      for (let i = 0; i < this.files.length; i++) {
        if (this.files[i].id) {
          continue;
        }
        let formData = new FormData();
        formData.append("file", this.files[i]);

        axios
          .post("/files/upload-file", formData, {
            headers: {
              "Content-Type": "multipart/form-data"
            }
          })
          .then(
            function(data) {
              this.files[i].id = data["data"]["id"];
              this.files.splice(i, 1, this.files[i]);
              console.log("success");
            }.bind(this)
          )
          .catch(function(data) {
            console.log("error");
          });
      }
    }
  }

This is my route post(Edited)

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::group(['middleware' => 'auth'], function () {
    Route::get('files', 'FileEntriesController@index');
});

Route::get('files/create', 'FileEntriesController@create');
Route::post('files/upload-file', 'FileEntriesController@uploadFile');

Route::get('/home', 'HomeController@index')->name('home');

Route::get('{path}','HomeController@index')->where('path', '([A-z\d-\/_.]+)?');

And this is my controller
public function uploadFile(Request $request) {
        $file = Input::file('file');
        $filename = $file->getClientOriginalName();

        $path = hash( 'sha256', time());

        if(Storage::disk('uploads')->put($path.'/'.$filename,  File::get($file))) {
            // $input['user_id'] = $user_id;
            $input['filename'] = $filename;
            $input['mime'] = $file->getClientMimeType();
            $input['path'] = $path;
            $input['size'] = $file->getClientSize();
            $file = FileEntry::create($input);

            return response()->json([
                'success' => true,
                'id' => $file->id
            ], 200);
        }
        return response()->json([
            'success' => false
        ], 500);
    }

I expected to past the information to the database but it show me the error 405 (Method Not Allowed)
EDITED
In ispect option in the section network i can find this:
{message: "Class 'App\Http\Controllers\Input' not found",…}
exception: "Symfony\Component\Debug\Exception\FatalThrowableError"
file: "C:\laragon\www\vue-laravel-app\app\Http\Controllers\FileEntriesController.php"
line: 11
message: "Class 'App\Http\Controllers\Input' not found"

A: All POST/PUT/PATCH requests in web.php are protected with CSRF-protection.
You seem to be not passing any token with your request headers or may be is it in the body? if not it'll result in Method Not Allowed error.
It would be better idea to use API routes for it as csrf-protection is disabled on them.


text:
Q: Modifying Serial ID to include numbers based on data in another cell [Excel 2010] I'm trying to create new serial IDs based on the data in two cells in MS Excel 2010.
The first cell contains the current serial ID e.g. A^B
The second cell contains a quantity e.g. 4
The result I want to produce in the third cell should identify the number in the second cell and concatenate the value sequentially in the third cell i.e the out of the first and second cell identified in the example above should be
A^B^1
A^B^2
A^B^3
A^B^4 (all in different cells in a column)
I have 500 serial numbers with a varying amount of quantities each therefore, I would like to request help with a routine or way which can help me create the third cell quickly.
Thank you.

A: You say the third cell shoudl be concatenated but then go on to say is should be in different cells....  If you want them concatenated then a UDF should be fairly straight forward..
something like:
Function myfunction(Ftext As String, Ntimes As Integer) As String

    Dim chk As Integer
    chk = 1

    Do While chk <= Ntimes
        myfunction = myfunction & Ftext & chk & " "
        chk = chk + 1
    Loop

    myfunction = Trim(myfunction)

End Function

You would just use this in the worksheet like any other function
=myfunction(cell1,cell2)

A: Here's an example using a macro to fill in all the cells:
Sub CreateSerialNumbers()

    Dim i As Integer, j As Integer

    With Sheets("Sheet1") 'Change to your sheet name
        For i = 2 To Cells(Rows.Count, 1).End(xlUp).Row 'Assume we start in row 2 and work to the bottom of the sheet
            For j = 1 To .Cells(i, 2).Value
                .Cells(i, j + 2).Value = .Cells(i, 1).Value & "^" & j
            Next j
        Next i
    End With

End Sub

This assumes your data starts in row 2, and that the serials are in column A and the numbers are in column B.


text:
Q: How to combine date from one field with time from another field - MS SQL Server In an extract I am dealing with, I have 2 datetime columns. One column stores the dates and another the times as shown.
How can I query the table to combine these two fields into 1 column of type datetime?
Dates
2009-03-12 00:00:00.000
2009-03-26 00:00:00.000
2009-03-26 00:00:00.000

Times
1899-12-30 12:30:00.000
1899-12-30 10:00:00.000
1899-12-30 10:00:00.000

A: *

*If both of your fields are datetime then simply adding those will work.
eg:
Declare @d datetime, @t datetime
set @d = '2009-03-12 00:00:00.000';
set @t = '1899-12-30 12:30:00.000';
select @d + @t

*If you used Date & Time datatype then just cast the time to datetime
eg:
Declare @d date, @t time
set @d = '2009-03-12';
set @t = '12:30:00.000';
select @d + cast(@t as datetime)

A: This was my solution which ignores the date value of the time column
CAST(Tbl.date as DATETIME) + CAST(CAST(Tbl.TimeFrom AS TIME) as DATETIME)

Hope this helps others

A: This is an alternative solution without any char conversions:
DATEADD(ms, DATEDIFF(ms, '00:00:00', [Time]), CONVERT(DATETIME, [Date]))

You will only get milliseconds accuracy this way, but that would normally be OK. I have tested this in SQL Server 2008.

A: Convert the first date stored in a datetime field to a string, then convert the time stored in a datetime field to string, append the two and convert back to a datetime field all using known conversion formats.
Convert(datetime, Convert(char(10), MYDATETIMEFIELD, 103) + ' ' + Convert(char(8), MYTIMEFIELD, 108), 103)

A: Convert both field into DATETIME :
SELECT CAST(@DateField as DATETIME) + CAST(@TimeField AS DATETIME)

and if you're using Getdate() use this first:
DECLARE @FechaActual DATETIME = CONVERT(DATE, GETDATE());
SELECT CAST(@FechaActual as DATETIME) + CAST(@HoraInicioTurno AS DATETIME)

A: You can simply add the two.

*

*if the Time part of your Date column is always zero

*and the Date part of your Time column is also always zero (base date: January 1, 1900)
Adding them returns the correct result.
SELECT Combined = MyDate + MyTime FROM MyTable

Rationale (kudos to ErikE/dnolan)

It works like this due to the way the date is stored as two 4-byte
  Integers with the left 4-bytes being the date and the right
  4-bytes being the time. Its like doing $0001 0000 + $0000 0001 =
  $0001 0001

Edit regarding new SQL Server 2008 types
Date and Time are types introduced in SQL Server 2008. If you insist on adding, you can use Combined = CAST(MyDate AS DATETIME) + CAST(MyTime AS DATETIME)
Edit2 regarding loss of precision in SQL Server 2008 and up (kudos to Martin Smith)
Have a look at How to combine date and time to datetime2 in SQL Server? to prevent loss of precision using SQL Server 2008 and up.

A: I had many errors as stated above so I did it like this
try_parse(concat(convert(date,Arrival_date),' ',arrival_time) as datetime) AS ArrivalDateTime

It worked for me.

A: Finding this works for two dates where you want time from one and date from the other:
declare @Time as datetime = '2021-11-19 12:34'
declare @Date as datetime = '2021-10-10'
SELECT @time + datediff(day, @Time, @Date)

A: This worked for me
CAST(Tbl.date as DATETIME) + CAST(Tbl.TimeFrom AS TIME)

(on SQL 2008 R2)

A: If the time element of your date column and the date element of your time column are both zero then Lieven's answer is what you need. If you can't guarantee that will always be the case then it becomes slightly more complicated:
SELECT DATEADD(day, 0, DATEDIFF(day, 0, your_date_column)) +
    DATEADD(day, 0 - DATEDIFF(day, 0, your_time_column), your_time_column)
FROM your_table

A: If you're not using SQL Server 2008 (i.e. you only have a DateTime data type), you can use the following (admittedly rough and ready) TSQL to achieve what you want:
DECLARE @DateOnly AS datetime
DECLARE @TimeOnly AS datetime

SET @DateOnly = '07 aug 2009 00:00:00'
SET @TimeOnly = '01 jan 1899 10:11:23'

-- Gives Date Only.
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, @DateOnly))

-- Gives Time Only.
SELECT DATEADD(Day, -DATEDIFF(Day, 0, @TimeOnly), @TimeOnly)

-- Concatenates Date and Time parts.
SELECT
CAST(
    DATEADD(dd, 0, DATEDIFF(dd, 0, @DateOnly)) + ' ' +
    DATEADD(Day, -DATEDIFF(Day, 0, @TimeOnly), @TimeOnly)
as datetime)

It's rough and ready, but it works!

A: DECLARE @Dates table ([Date] datetime);
DECLARE @Times table ([Time] datetime);

INSERT INTO @Dates VALUES('2009-03-12 00:00:00.000');
INSERT INTO @Dates VALUES('2009-03-26 00:00:00.000');
INSERT INTO @Dates VALUES('2009-03-30 00:00:00.000');

INSERT INTO @Times VALUES('1899-12-30 12:30:00.000');
INSERT INTO @Times VALUES('1899-12-30 10:00:00.000');
INSERT INTO @Times VALUES('1899-12-30 10:00:00.000');

WITH Dates (ID, [Date])
AS (
    SELECT ROW_NUMBER() OVER (ORDER BY [Date]), [Date] FROM @Dates
), Times (ID, [Time])
AS (
    SELECT ROW_NUMBER() OVER (ORDER BY [Time]), [Time] FROM @Times
)
SELECT Dates.[Date] + Times.[Time] FROM Dates
    JOIN Times ON Times.ID = Dates.ID

Prints:
2009-03-12 10:00:00.000
2009-03-26 10:00:00.000
2009-03-30 12:30:00.000

A: To combine date from a datetime column and time from another datetime column this is the best fastest solution for you:
select cast(cast(DateColumn as date) as datetime) + cast(TimeColumn as datetime) from YourTable

A: SELECT CAST(CAST(@DateField As Date) As DateTime)  + CAST(CAST(@TimeField As Time) As DateTime)

A: Another way is to use CONCATand CAST, be aware, that you need to use DATETIME2(x) to make it work. You can set x to anything between 0-7 7 meaning no precision loss.
DECLARE @date date = '2018-03-12'
DECLARE @time time = '07:00:00.0000000'
SELECT CAST(CONCAT(@date, ' ', @time) AS DATETIME2(7))

Returns 2018-03-12 07:00:00.0000000
Tested on SQL Server 14

A: simply concatenate both , but cast them first as below
select cast(concat(Cast(DateField as varchar), ' ', Cast(TimeField as varchar)) as datetime) as DateWithTime from TableName;

A: select s.SalesID from SalesTbl s
        where cast(cast(s.SaleDate  as date) as datetime) + cast(cast(s.SaleCreatedDate as time) as datetime) between @FromDate and @ToDate

A: The existing answers do not address the datetime2 datatype so I will add mine:
Assuming that you want to add a time value to a datetime2 value where:

*

*The datetime2 value could contain non-zero time component and/or fractional seconds

*The time value could contain the value 23:59:59.9999999 which is 86,399.9999999 seconds, 86,399,999,999.9 microseconds or 86,399,999,999,900 nanoseconds¹

Due to the limitations of dateadd function¹ you must add them in two steps:

*

*Convert the time value to seconds and use dateadd(second, ...)

*Extract the nanoseconds from the time value and use dateadd(nanosecond, ...) to add them to the date calculated above

declare @dv datetime2 = '2000-01-01 12:34:56.7890123';
declare @tv time = '23:59:59.9999999';
select dateadd(
    nanosecond,
    datepart(nanosecond, @tv),
    dateadd(
        second,
        datepart(hour, @tv) * 60 * 60 + datepart(minute, @tv) * 60 + datepart(second, @tv),
        @dv
    )
);
-- 2000-01-02 12:34:56.7890122

¹ Nanosecond values might not fit in int datatype which dateadd function expects.

A: I ran into similar situation where I had to merge Date and Time fields to DateTime field. None of the above mentioned solution work, specially adding two fields as the data type for addition of these 2 fields is not same.
I created below solution, where I added hour and then minute part to the date. This worked beautifully for me. Please check it out and do let me know if you get into any issues.
;with tbl
as
(
    select StatusTime = '12/30/1899 5:17:00 PM', StatusDate = '7/24/2019 12:00:00 AM'
)
select DATEADD(MI, DATEPART(MINUTE,CAST(tbl.StatusTime AS TIME)),DATEADD(HH, DATEPART(HOUR,CAST(tbl.StatusTime AS TIME)), CAST(tbl.StatusDate as DATETIME)))
from tbl
Result: 2019-07-24 17:17:00.000

A: SELECT CAST(your_date_column AS date) + CAST(your_time_column AS datetime) FROM your_table

Works like a charm


text:
Q: Prove if $(f,g)=1$ , then $(f^m,g^n)=1$
If $(f,g)=1$ , then prove for any $m,n\in \mathbb{Z}^+$, $(f^m,g^n)=1$ . $(f,g)=\gcd(f,g)$.

My try: Split $f$ to product of some irreducible polynomial. Like $f=ap_1^{\alpha_1}\cdots p_t^{\alpha_t} $. So do $g$. Then their irreducible polynomials won't have two same.  So  we can conclude $(f^m,g^n)=1$.
But it seems a little bit verbose for this simple question . Any more concise ways?

A: Suppose that there is an irreducible polynomial $p$ such that $p\mid f^m$ and $p\mid g^n$. Then, since $p$ is irreducible, $p\mid f^m\implies p\mid f$ and, for the same reason $p\mid g$. But that's impossible, since we're assuming that $\gcd(f,g)=1$. Therefore, $\gcd(f^m,g^n)=1$.