text:
Q: Create categorical numpy array for output labels of array containing variable length sequence I am trying to create a variable-sequence length data for LSTM model.So, i created a list of numpy arrays of variable length.
For example, one array is of length => (11,20) and other is of length => (9,20).Here 20 is the number of features and 11/9 denote sequence length
Each array has zeros and a numerical value(class index) at the end.
If audio file belongs to class index = 1 and number of frames are 8 then
y will be [0,0,0,0,0,0,0,1]
I wanted to know that when model.fit is called on each variable length audio data, then last Dense layer() will have output shape equal to number of frames the audio has
So, how can I create a variable output shape of Dense layer(8 or 9 or 11)
I do not want to pad sequences instead give a 'None' in LSTM input layer shape.
But, on converting into categorical, I get error:    setting array element with sequence.
Here , 11 is number of classes
y_train=to_categorical(y_train,11)
y_test=to_categorical(y_test,11)

Tensorflow version : 1.3.0
Keras version : 2.0.9

A: As you said in the question:

Each array has zeros and a numerical value(class index) at the end.
If audio file belongs to class index = 1 and number of frames are 8 then y will be [0,0,0,0,0,0,0,1]

First Step Input:
[update] One approach to deal with variable input size is to use dynamic_rnn. Read more here
Another way we deal with this problem, as we do in text classification is using padding.
So say we create embeddings of size 10, so each word will have a 10 size vector input.
A sentence input of say 5 words, will actually be a input of 5 * 10.
Now, since TF/Keras accepts fixed size inputs. We pad the inputs.
So we take a fixed input length of number of words (say 20 for this case).
Words that occur after 20 are dropped.
If a Sentence has 5 words it will have 15 paddings after that.
Now the input will be passed through the embedding layer and final input will be (None, 20, 10) representing (Batch_size, Sequence_length, embedding_dimension).
Your problem can also be converted into similar input.

For example, one array is of length => (11,20) and other is of length => (9,20).Here 20 is the number of features and 11/9 denote sequence length

Here assume sequence length to be 15 or so.. and assume 20 to embedding dimension.
You will have to pad your input of size 9/11 to be consistent at say 15 (you can experiment with this number).
20 is your embedding dimension, features.
So Final input shape will be (None, 15, 20).
Next Step Output:
You can now directly one hot encode your output class for each input.
For input of 9,20 you have 1 one hot encoded output vector.
Earlier you were thinking that for one input of length 9 and feature of 20
output should be of length 9, and first 8 output's should be 0 and 9th should be the class.
This won't be needed anymore as 1 input of size (9,20) will give 1 output.
Let me know if more explanation is needed, all the best :)


text:
Q: Sharing Sessions on different Asp.Net pages of different Applications in same domain Basically we are working on various web applications which are updated according to the time needs and Now the situation arises are as follows:-
 We have one Product based website which consists of several webpages which are belongs to different Web applications. In each application there is session management done. but stored in sql server and then transferred to various pages. Now it slows the application at some point of time because every time on page loads it gets or sets the session variable from sql server. So to reduce the sql server hit, I think that the shared session between these application will reduce the server hits and It is helpful in speeding up the website. So Is any method available for this or we can do any thing else for this. So help me...

redpajama_set_name: RedPajamaStackExchange


text:
Q: How using types.d.ts file in React & TypeScript project i have React & TypeScript project.
Here is i have folder structure in some component like:
 - ComponentFolder
  - index.tsx
  - types.d.ts
  - ChildComponent
    - index.tsx

I know that if i will put my types in types.d.ts file which in root of my component directory, I can use these types in childComponents in this directory.
So i tried;
my types.d.ts file:
export type CommonProps = {
  openItem: string;
  getValue: (e: React.MouseEvent) => void;
};

and in child component:
import * as React from "react";

const ChildComponent: React.FC<CommonProps> = (props) => {
  return (
    <div>
      {props.openItem}
    </div>
  );
};

export default ChildComponent;

But getting error:
cannot find CommonProps error.

How i know if i have some file d.ts in the directory i can use these types in this directory without import.
where i mistaken?

A: Remove the export keyword.
type CommonProps = {
  openItem: string;
  getValue: (e: React.MouseEvent) => void;
};


text:
Q: How to use Provider.of(...) inside a singleton in Flutter? I've this widget somewhere deep inside my widget tree:
Widget build(BuildContext context) {
return ChangeNotifierProvider(
  builder: (context) => TimersModel(context: context),
  child: Scaffold(...

TimersModel get the context:
class TimersModel extends ChangeNotifier {
  final BuildContext context;
  NotificationsService _notificationsService;

  TimersModel({@required this.context}) {
    _notificationsService = NotificationsService(context: context);
  }

And instantiates this NotificationsService singleton for the first and only time:
class NotificationsService {
  static FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin;

  final BuildContext context;

  static NotificationsService _instance;

  factory NotificationsService({@required BuildContext context}) {
    _instance ??= NotificationsService._internalConstructor(context: context);
    return _instance;
  }

  NotificationsService._internalConstructor({@required this.context}) {

As you can see, this is a singleton for the FlutterLocalNotificationsPlugin
Problem is that if I call Provider.of<TimersModel>(context)... from this singleton, although it's getting the right context, it's always throwing ProviderNotFoundError.
If I place a breakpoint on this code from Provider:
static T of<T>(BuildContext context, {bool listen = true}) {
    // this is required to get generic Type
    final type = _typeOf<InheritedProvider<T>>();
    final provider = listen
        ? context.inheritFromWidgetOfExactType(type) as InheritedProvider<T>
        : context.ancestorInheritedElementForWidgetOfExactType(type)?.widget
            as InheritedProvider<T>;

    if (provider == null) {
      throw ProviderNotFoundError(T, context.widget.runtimeType);
    }

    return provider._value;
  }

The context ChangeNotifierProvider and type TimersModel are right. But provider is always null.
I know the singleton is not a widget and, of course, it's not in the widget tree.
But shouldn't I be able to call Provider.of<TimersModel>(context)... from anywhere as long as I provide the right context and type?
Or should this work and I'm doing something wrong?

A: As Provider does the lookup by type, try giving your ChangeNotifierProvider a type when you return it in your build method:
return ChangeNotifierProvider<TimersModel>(...);

I can imagine that Provider simply doesn't find an instance for TimersModel because you didn't declare a provider of that type.


text:
Q: Passwordless ssh tunnel I have my local machine (a mac), and I want to access server B (linux). Server B needs to be accessed through server A (linux). I have set up a tunnel by modifying the .ssh/config file in my local machine as follows:
Host serverB
 HostName serverB.com
 User Ant
 ProxyCommand ssh -q -Y serverA.com -W %h:%p

This used to work correctly[0]. Next, I set up passwordless login from local to serverA and from serverA to serverB using ssh keys. This means that I can do
> ssh Ant@serverA.com
(serverA)> ssh Ant@serverB.com
(serverB)>

and everything works properly. Now what I want is to be able to connect to server B without passwords; but if I do
> ssh Ant@severB.com

I am asked the passwords to severA and B to keep going. This is the output of ssh -v Ant@serverB:
OpenSSH_7.6p1, LibreSSL 2.6.2
debug1: Reading configuration data /Users/Ant/.ssh/config
debug1: /Users/Ant/.ssh/config line 16: Applying options for serverB
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 48: Applying options for *
debug1: Executing proxy command: exec ssh -q -Y serverA.com -W serverB.com:22
debug1: identity file /Users/Ant/.ssh/id_rsa type 0
debug1: key_load_public: No such file or directory
debug1: identity file /Users/Ant/.ssh/id_rsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/Ant/.ssh/id_dsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/Ant/.ssh/id_dsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/Ant/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/Ant/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/Ant/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/Ant/.ssh/id_ed25519-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_7.6
debug1: permanently_drop_suid: 501
Ant@serverA.com's password:

I can see that it is trying to use the key login but something is going wrong. Let me also add that my RSA key is saved into a non-standard location, so I added this to my .ssh/config file:
IdentityFile ~/.ssh/key_serverA

Any thoughts?
[0]: For some reason this does not work anymore, as the username is wrong. It prompts me for my password at local_username@serverA.com rather than Ant@serverA.com

A: The User option in a Host section is only applied for connections matching that host, and not necessarily for any commands started for proxying, etc., for which ssh config settings will be independently applied.
So either the ProxyCommand should explicitly have Ant@serverA, or there should be another Host block that serverA matches, setting User Ant for it.

A: This solution was proposed by the author of the question:

I found a solution. The problem was that, for some reason, ssh tried
to access serverA using local_username rather than Ant (the username
on serverA and serverB). To solve the issue I modified the config
tunnel command by explicitly adding my username:
Host serverB
 HostName serverB.com
 User Ant
 ProxyCommand ssh -q -Y Ant@serverA.com -W %h:%p

This fixed the issue and now passwordless login works with serverB
too! :-)


text:
Q: Problem with pgf library in TexLive I am using TexLive, and I am writing a paper with someone else.  He has sent me all of his files.  He uses tikz to draw commutative diagrams.
I am trying to compile his files, but I get an undefined control sequence error every time that \pgfsetarrowoptions is called in the pgflibraryarrows.new.code file.
It also doesn't seem to like the \tikzset command (same error), and I also get the following message:

! Package pgfkeys Error: I do not know the key '/tikz/align' and I am
  going to  ignore it. Perhaps you misspelled it.

It is working just fine for him, so there must be something wrong with the tikz / pgf library set up on my machine.
Here is the document header of the main .tex file:
% Math packages
\usepackage{latexsym,amssymb,amsgen,amsmath,amsxtra,amsfonts,mathtools}
\usepackage{mathrsfs}
\usepackage[mathscr]{euscript}

% TikZ
\usepackage{tikz}
\usepgflibrary{arrows.new}
\usetikzlibrary{backgrounds,shapes,decorations.pathmorphing,arrows.new}
\tikzset{>=to new, arrow head=3pt}

It's not telling me that it can't find the tikz package.  Is it possible that I need to reinstall or update it?  If so, how should I go about this?


text:
Q: Null value for column when selecting using dot or bracket notation but not when using UDF I'm trying to clean up some nested data and extract the fields I care about.
My schema for the nested value is:
 |-- maritalstatus: struct (nullable = true)
 |    |-- id: string (nullable = true)
 |    |-- text_: string (nullable = true)
 |    |-- text__extensions: array (nullable = true)
 |    |    |-- element: string (containsNull = true)
 |    |-- extension: array (nullable = true)
 |    |    |-- element: string (containsNull = true)

I want to extract the text_ field as its own column.
I have tried:
df.select(col("maritalstatus.text_")).show()
and df.select(col("maritalstatus")["text_"]).show() but it returns:
+-----+
|text_|
+-----+
| null|
| null|
 ...
| null|
+-----+

When I define a UDF as:
def getMaritalStatus(ms):
    return ms.text_
gms = udf(getMaritalStatus, StringType())

and do df.select(gms(col("maritalstatus")).show() it returns the data that i expect
Interestingly, I have another nested struct field that has a similar structure but with numbers as keys instead of names, and I am able to use the df.select(col("birthdate")["0"]).show() notation
Birthdate's schema:
root
 |-- birthdate: struct (nullable = true)
 |    |-- 0: date (nullable = true)
 |    |-- 1: integer (nullable = true)

Is there anyway to extract maritalstatus.text_ without using the UDF? I've heard UDF is not as performant as other approaches?
cassandra table structure:
CREATE TABLE keyspace.patient (
    id text PRIMARY KEY,
    active boolean,
    active_extensions list<text>,
    address list<frozen<address>>,
    birthdate frozen<tuple<date, int>>,
    birthdate_extensions list<text>,
    communication list<frozen<patient_communication>>,
    contact list<frozen<patient_contact>>,
    contained list<frozen<tuple<text, text, text>>>,
    deceasedboolean boolean,
    deceasedboolean_extensions list<text>,
    deceaseddatetime frozen<tuple<timestamp, text, int>>,
    deceaseddatetime_extensions list<text>,
    extension list<text>,
    gender text,
    gender_extensions list<text>,
    generalpractitioner list<text>,
    identifier list<frozen<identifier>>,
    implicitrules text,
    implicitrules_extensions list<text>,
    language text,
    language_extensions list<text>,
    link list<frozen<patient_link>>,
    managingorganization text,
    maritalstatus frozen<codeableconcept>,
    meta frozen<meta>,
    modifierextension list<text>,
    multiplebirthboolean boolean,
    multiplebirthboolean_extensions list<text>,
    multiplebirthinteger int,
    multiplebirthinteger_extensions list<text>,
    name list<frozen<humanname>>,
    photo list<frozen<attachment>>,
    telecom list<frozen<contactpoint>>,
    text_ frozen<narrative>
) WITH bloom_filter_fp_chance = 0.01
    AND caching = {'keys': 'ALL', 'rows_per_partition': 'NONE'}
    AND comment = ''
    AND compaction = {'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold': '32', 'min_threshold': '4'}
    AND compression = {'chunk_length_in_kb': '64', 'class': 'org.apache.cassandra.io.compress.LZ4Compressor'}
    AND crc_check_chance = 1.0
    AND dclocal_read_repair_chance = 0.1
    AND default_time_to_live = 0
    AND gc_grace_seconds = 864000
    AND max_index_interval = 2048
    AND memtable_flush_period_in_ms = 0
    AND min_index_interval = 128
    AND read_repair_chance = 0.0
    AND speculative_retry = '99PERCENTILE';

and the codeableconcept is
CREATE TYPE keyspace.codeableconcept (
    extension list<text>,
    text_ text,
    text__extensions list<text>,
    id text,
    coding list<frozen<coding>>
);

A: #using pyspark sql
you can query nested data using "." and for array use explode function.
df=df.select("maritalstatus.*").show(1,False)
or
df=df.select("martialstatus.text_").alias("text_new").show(1,False)

A: You can use the [name] to access nested values in the column, or you can use .getItem function to do the same.  Column could be either explicitly wrapped into col, or you can use syntax dataframe[column_name] instead.  If we take sample data, like this:
from pyspark.sql.functions import col

rdd = sc.parallelize([('{"maritalstatus": {"id": "some_id", "text_": "some_text", "text__extensions": ["1", "2"], "extension": ["e1", "e2"]}}')])
df = spark.read.json(rdd)

then all three calls:
df.select(df['maritalstatus']['text_']).show()
df.select(col('maritalstatus')['text_']).show()
df.select(col('maritalstatus').getItem('text_')).show()

will produced the same result:
+-------------------+
|maritalstatus.text_|
+-------------------+
|          some_text|
+-------------------+


text:
Q: "ValidatioError: Value ... is not a valid choice" in Django even with a valid choice I have a model with a object_type field where the choices should be numbers and the human readable a string like below:
OBJECT_TYPES = (
    (0, "analog-input"),
    (1, "analog-output"),
    (2, "analog-value")
)

class MyModel(models.Model):
    object_type = models.CharField(
        max_length=20,
        choices=OBJECT_TYPES,
        blank=True,
        null=True
    )

However, when I try to create an object and assign an integer value to object_type I get a ValidationError that the object_type is not a valid choice and I can't understand how to configure it properly. I have tried with CharField, TextField and IntegerField.
obj = MyModel.objects.create(object_type=2)
obj.full_clean()

ValidationError: {'object_type': ["Value '2' is not a valid choice."]}

A: Since this is a CharField, the keys should be strings, so '0', not 0:
OBJECT_TYPES = (
    ('0', "analog-input"),
    ('1', "analog-output"),
    ('2', "analog-value")
)
an alternative is to work with an IntegerField:
OBJECT_TYPES = (
    (0, "analog-input"),
    (1, "analog-output"),
    (2, "analog-value")
)

class MyModel(models.Model):
    object_type = models.IntegerField(
        choices=OBJECT_TYPES,
        blank=True,
        null=True
    )


text:
Q: How to have relationship in Laravel 5.7 based on a json data key saved in a table column? I am using this Staudenmein package in Laravel and referring to this answer given by the package owner himself.
I have two tables, pets and notifications with models Pet and Notification.
The notifications table has a column called data which is of JSON dataType and stores JSON data
{"pet_id":"4","pet_type_id":1,"lost_report_id":3,"pet_sighting_id":21,"latitude":"22.676846","longitude":"88.338509"}

The key pet_id denotes the id column of the pets table. I need a relationship so that I can fetch the name of the pet from pets table.
By referring to the answer link given above, I wrote my Notification model like this:-
namespace App\Models;

use DB, App, Auth, Hash, Lang, Mail, Config, Exception, Validator, Globals;
use Illuminate\Database\Eloquent\Model;

use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;

use App\User;
use App\Models\AdminConfig;
use App\Models\ReceivedAppNotification;

class Notification extends Model
{

    protected $casts = [
           'data' => 'json'
        ];

    public function notificationPet()
    {
        return $this->belongsTo('App\Models\Pet', 'data->pet_id');
    }
}

When I am running the query like this:-
$notificationQuery = Notification::with('notificationPet')
                             ->whereRaw("FIND_IN_SET('$userId', in_app_notification_receiver)")
                             ->where(array(
                                  'status'     => Globals::SMALL_CHAR_ACTIVE,
                                  'is_delete'  => Globals::SMALL_CHAR_NO,
                               ))->get()->toArray();

I get the notificationPet relationship as empty, ie. the data-set is like this:-
Array
(
    [id] => 10
    [title] =>
    [message] =>
    [data] => Array
        (
            [pet_id] => 4
            [latitude] => 22.676846
            [longitude] => 88.338509
            [pet_type_id] => 1
            [lost_report_id] => 3
            [pet_sighting_id] => 34
        )

    [no_of_in_app_notification_receiver] => 2
    [no_of_push_notification_receiver] => 1
    [from_user] => 22
    [in_app_notification_receiver] => 2,23
    [push_notification_receiver] => 2
    [status] => a
    [is_delete] => n
    [push_notification_sent] => n
    [created_date] => 2020-03-19 13:23:17
    [modified_date] => 2020-03-19 13:23:17
    [created_at] => 2020-03-19 13:23:17
    [updated_at] => 2020-03-19 13:23:17
    [notification_pet] =>
)

However, I have a record in pets table with id = 4, already. So the relationship should not be empty.
What am I doing wrong?

A: Change:
 protected $casts = [
           'data' => 'json'
        ];

To:
 protected $casts = [
           'data' => 'array'
        ];


text:
Q: Separate QByteArray hex values to separate int's How can I parse these "\" separated HEX values in the QByteArray into 8 separate int's?
QByteArray mainArray = "\xFF\xFF\x01\x04\x01\x0B\x03\xEC";
int num1;
int num2;
int num3;
...

A: The \x escape sequence represents a hexadecimal value within string literals and character literals. The two hexadecimal digits following the \x will be parsed as a single byte. For example:
QByteArray foo1 = "\x46\x6f\x6f";
QByteArray foo2 = "Foo";

Q_ASSERT(foo1 == foo2); // 'foo1' and 'foo2' are equal

If you wish to access the hexadecimally represented values in your mainArray, simply use the QByteArray::at or the subscript operator as follows:
QByteArray mainArray = "\xFF\xFF\x01\x04\x01\x0B\x03\xEC";
int num1 = mainArray[0]; // 0xFF
int num2 = mainArray[1]; // 0xFF
int num3 = mainArray[2]; // 0x01
// ...

One thing to keep in mind, the value type of QByteArray is char which is a signed type, therefore the \xFF on most systems will be -1 insead of 255. To fix the mentioned issue, here is a possible solution:
QByteArray mainArray = "\xFF\xFF\x01\x04\x01\x0B\x03\xEC";
int num1 = 0xff & mainArray[0];
int num2 = 0xff & mainArray[1];
int num3 = 0xff & mainArray[2];
// ...


text:
Q: Eigen3 : How to verify if AVX2 or AVX512F code is being generated? I am developing an program that involves a lot of low latency hard-real time matrix operations. I am using Eigen 3 library for the same.
I wish to use AVX-512F SIMD vectorization in production for performance acceleration.
I am currently experimenting on Ubuntu and have used vcpkg package manager to install Eigen3 library. Currently my computer supports AVX2 and I will enable AVX-512F from BIOS later.
I am using
objdump -d main.o | grep zmm
objdump -d main.o | grep ymm
objdump -d main.o | grep xmm

command to analyze which registers are being used.
objdump -d main.o | grep zmm returns empty output.
objdump -d main.o | grep ymm returns empty outout.
objdump -d main.o | grep xmm returns register access and operation instruction.
I wish to know is my g++ compiler generating AVX1 (AVX-128) code for Eigen3 library.
How do I verify if proper AVX2 or AVX-512F SIMD code is being generated.
Small Snippet of objdump
3d84:   0f 28 08                movaps (%rax),%xmm1
3d87:   0f 29 4d d0             movaps %xmm1,-0x30(%rbp)
3d8b:   0f 29 45 e0             movaps %xmm0,-0x20(%rbp)
3d8f:   0f 28 45 d0             movaps -0x30(%rbp),%xmm0
3d93:   0f 12 45 e8             movlps -0x18(%rbp),%xmm0
3d9f:   0f 28 08                movaps (%rax),%xmm1
3da2:   0f 29 4d b0             movaps %xmm1,-0x50(%rbp)
3da6:   0f 29 45 c0             movaps %xmm0,-0x40(%rbp)
3daa:   0f 28 45 b0             movaps -0x50(%rbp),%xmm0
3dae:   0f 58 45 c0             addps  -0x40(%rbp),%xmm0
3db2:   0f 29 45 80             movaps %xmm0,-0x80(%rbp)
3db6:   0f 28 45 80             movaps -0x80(%rbp),%xmm0
3dba:   0f 28 4d 80             movaps -0x80(%rbp),%xmm1
3dbe:   0f c6 c1 01             shufps $0x1,%xmm1,%xmm0

Update
Code
#include <eigen3/Eigen/Core>
#include <eigen3/Eigen/Dense>
using namespace Eigen;
int main()
{
//  Matrix4f a, b, cadd, cmul, ci, ct, d;
//  a = Matrix4f::Random();
//  b = Matrix4f::Random();
    MatrixXf a(100, 100),b(100, 100),cadd(100, 100), cmul(100, 100), ci(100, 100), ct(100, 100);
    a = MatrixXf::Random(100, 100);
    b = MatrixXf::Random(100, 100);
    cadd = a + b;
    cmul = a * b;
    ci = cadd.inverse();
    ct = cadd.transpose();
}

Build Command
g++ -Wall -fexceptions -I/home/user/vcpkg/installed/x64-linux/include -c /home/user/Desktop/VectorClass/main.cpp -o obj/Debug/main.o
g++ -L/home/user/vcpkg/installed/x64-linux/debug/lib -o bin/Debug/VectorClass obj/Debug/main.o  -mavx2 -mtune=native -host=native -march=native

Final Object Dump
objdump -d main.o | grep ymm
14f:    c5 fe 7f 45 98           vmovdqu %ymm0,-0x68(%rbp)
231:    c5 fd 7f 85 50 fe ff     vmovdqa %ymm0,-0x1b0(%rbp)

objdump -d main.o | grep zmm
 a1:    62 f1 7c 48 28 74 24     vmovaps 0x80(%rsp),%zmm6
 ac:    62 f1 4c 48 58 44 24     vaddps 0x40(%rsp),%zmm6,%zmm0
 b4:    62 f1 7c 48 29 44 24     vmovaps %zmm0,0xc0(%rsp)
228:    62 f1 7c 48 28 7c 24     vmovaps 0x180(%rsp),%zmm7
230:    62 f1 7c 48 29 7c 24     vmovaps %zmm7,0x100(%rsp)
2d0:    62 f1 7d 48 6f 05 00     vmovdqa32 0x0(%rip),%zmm0        # 2da <main+0x2da>
2dd:    62 f2 7d 48 16 44 24     vpermps 0xc0(%rsp),%zmm0,%zmm0
2e5:    62 f1 7c 48 29 44 24     vmovaps %zmm0,0x180(%rsp)

Build Command
g++ -Wall -fexceptions -I/home/user/vcpkg/installed/x64-linux/include -c main.cpp -o main.out -mavx512f -mfma -mtune=native -host=native  -march=native -mprefer-vector-width=512 -O3 -fno-math-errno -ffinite-math-only -fno-rounding-math  -funsafe-math-optimizations


text:
Q: CMake add a library which is a group of other libraries I have a core library which branches off into several other libraries. In CMakeLists.txt it looks a bit like this
ADD_LIBRARY (core ...)
ADD_LIBRARY (branch1 ...)
ADD_LIBRARY (branch2 ...)
...
TARGET_LINK_LIBRARIES (branch1 core)
TARGET_LINK_LIBRARIES (branch2 core)
...

I have some executables which may depend on any or all of the branches. For those that depend on all the branches, instead of writing
ADD_EXECUTABLE (foo ...)
TARGET_LINK_LIBRARIES (foo branch1 branch2 ...)

I tried
ADD_LIBRARY (all-branches)
TARGET_LINK_LIBRARIES (all-branches branch1 branch2 ...)

then
TARGET_LINK_LIBRARIES (foo all-branches)

This works but CMake spits out a warning.
You have called ADD_LIBRARY for library all-branches without any source files. This typically indicates a problem with your CMakeLists.txt file

I understand the message, but it's not an error. What does CMake think is an acceptable way to build a meta-library like this?

A: I added a new type of library, the INTERFACE library to the upcoming CMake 3.0.0 release. That is designed as the solution to this problem:
http://www.cmake.org/cmake/help/git-master/manual/cmake-buildsystem.7.html#interface-libraries
add_library(all_branches INTERFACE)
target_link_libraries(all_branches INTERFACE branch1 branch2)

add_executable(myexe ...)
target_link_libraries(myexe all_branches)

A: In CMAKE the add_executable and add_library are very similar. They just tell to CMAKE that it should create a MAKE instruction for a library or executable based on the list of src files that you provide after the name of the library/executable and options (such as SHARED, etc).
What you can do is to add the names of your libs that you want to link in a name variable that you increase such as
SET(TARGET_LIBS ${TARGET_LIBS} myFirstLib)
SET(TARGET_LIBS ${TARGET_LIBS} myNextLib)

and then simply:
target_link_libraries(myExe  ${TARGET_LIBS})

In this way you can easily define groups of libraries that may be needed for different sub projects without creating a meta-lib.


text:
Q: Is it possible to send Magento Event Observer result to Custom API? I wonder, is it possible to send Magento Event Observer result to custom API?
I'm trying to create an API to get new order via XML-RPC. Are there any examples around?
Thanks!

A: I haven't used any Magento Web Services, via XML-RPC. However, I have used normal SOAP Core API & SOAP V2 Web Services of Magento, and if you are using either of these two processes, then there is a solution for you.
For Magento Core API, the required method name is "sales_order.list", and for the SOAP V2, the required method name is "salesOrderList". The return type will be array of orders. The main useful thing in this Web Service method, is that there is an option to use filters. Now this filter will help you a lot in getting the new orders from a specified date & time, so you can pretty much use it to your own requirement.
For the V2 Web Services method "salesOrderList", you can use the filter as:-
<salesOrderList>
    <sessionId>51ba5b3ff707f874fd76369d65bb1b7f</sessionId>
    <complex_filter>
        <key>created_at</key>
        <value>
            <key>gt</key>
            <value>2011-07-14 13:38:56</value>
        </value>
    </complex_filter>
</salesOrderList>

What the above sample code will do is that it will fetch / retrieve those orders in array format, which have been created after 01:38:56 PM of 14th July, 2011.
Hope it helps.


text:
Q: flot graph not rendered on PDF using PDFKit I am using flot to generate graphs in my application. The graphs are rendered correctly. The web page is then converted to a pdf using PDFKit. On conversion, the coordinates[X,Y] of the graph are displayed correctly While the graph itself is not rendered.
Problem seems to be with the canvas tag-
<canvas class="base" width="600" height="300"></canvas>
<canvas class="overlay" width="600" height="300" style="position: absolute; left: 0px;   top: 0px;"></canvas>

Any clues on which direction to look to solve the problem will be very helpful.
Cheers!

A: PDFKit uses wkhtmltopdf to do the actual rendering right?  So you might need to dig into PDFKit and make sure it's specifying the right options for wkhtmltopdf, specifically --redirect-delay <time> might be useful.


text:
Q: Can I rely on arguments being evaluated before being passed in python? I'm writing a rudimentary mocking framework just so I can test some calls to peewee.
I know in peewee, you can make where() calls like
model.select().where(model.id == target_id). ...
In order to detect which fields of the model are being compared, I will be overriding the comparison operators of the field.  Then I would inject that model in place of a peewee model.  It would provide the same interface as the peewee model(only as much as needed, though) but instead of accessing a database, it would record comparisons and calls; but it would all depend on the arguments being evaluated before the method is called.
I've run an example using anaconda, and for whatever python comes with Linux Mint, and they seem to operate as I would like.  I'm not sure if it's a fluke of runtime, or maybe python really does evaluate comparisons just before they are needed.
So, regarding the following, can I rely on model.id == target_id, ... running the comparison before the first where() is called?  Can I rely on model.name == target_name running its comparison before the second where() is called and after the first where()?
mockModel.select()
         .where(model.id == target_id, model.number == target_number)
         .where(model.name == target_name)
         ...

A: Yes. From the docs:

The primary must evaluate to a callable object (user-defined functions, built-in functions, methods of built-in objects, class objects, methods of class instances, and all objects having a __call__() method are callable). All argument expressions are evaluated before the call is attempted.

A: Method parameters are resolved as they are being marshalled for the call. Since the second where hasn't been looked up when the first where is called, its parameters have not yet been resolved. The sequence for this statement
mockModel.select()\
         .where(model.id == target_id, model.number == target_number)\
         .where(model.name == target_name)

is

*

*lookup mockModel

*lookup select on that object

*it has no parameters, so call it and get its result object

*lookup where on the result object

*its a function so evaluate its parameters left to right

*call the function and get its result object

*lookup where on the result object

*its a function call, so evaluate its parameters left to right

*call the function


text:
Q: LemmonSlider Destroy Method How can I call the destroy method on LemmonSlider?
http://jquery.lemmonjuice.com/plugins/slider-variable-widths.php
I tried calling:
jQuery( '#abc-carousel-secondary' ).destroy();

after:
jQuery( '#abc-carousel-secondary' ).lemmonSlider({
    'infinite' : true
});

to initialize the slider. My goal is to swap in new li elements therefore creating the need to reinitialize the plugin.
Thoughts?
Thanks

A: It only depends of the jquery plugin's code here. And it seems that LemmonSlider doesn't implement such a method. So your best try is first to simply initialize lemmonSlider with your default HTML. Then swap your li elements. Then simply reinitialize lemmonSlider with the same code.
jQuery(document).load(function(){

    function initSlider(){
        jQuery( '#abc-carousel-secondary' ).lemmonSlider({
            'infinite' : true
        });
    }

    // First init lemmonSlider when all images are loaded
    initSlider();

    jQuery('#swapButton').click(function(){
        // Swap your li elements
        // Then re-init lemmonSlider
        initSlider();
    });

});


text:
Q: long running service in specified time with android WorkManager Imagine there is a switch in my application. when user switch it on, I want to run a Broadcast Receiver after five hours from that moment ,then stop the Broadcast Receiver after 8 hours.
for example if user enable the switch at 09:00 , service will enable Broadcast Receiver at 14:00 and will disable it at 22:00. in fact I want to enable the Broadcast Receiver between two time using android Work Manager but I don't know how. should I use OnetimeworkRequestBuilder or PeriodicWorkRequestBuilder and how? any suggestion?
and I show a notification to user when Broadcast Receiver is enable so I think its better to use Work Manager

A: You can't be specific with WorkManager. You need to use AlarmManager:
Note: The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running. For normal timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler.
https://developer.android.com/reference/android/app/AlarmManager
These are the cases for WorkManager:
https://developer.android.com/guide/background
Article on AlarmManager vs WorkManager vs Service vs Background Thread:
https://android-developers.googleblog.com/2018/10/modern-background-execution-in-android.html


text:
Q: php sending array from an input value through ajax I'm saving an array like this
<input type="hidden" value="Array ( [0] => cb_05 [1] => cb_06 [2] => cb_07 [3] => cb_08 [4] => cb_09 [5] => type ) " id="price_id" name="price_id">

I need to grab the array and send it through a post in jquery
var price_id = $("#price_id").val();

$.post("class.php",{price_id:price_id},function(data){

        alert(data);

    });

When I do foreach in the class it doesn't see it as an array, I think it's because it's being sent as a string, is there a way around this?

A: You can use a data- attribute and jQuery data() method to work with array
<anyElement id="price_id" data-priceArray="<?php echo json_encode($array) ?>"/>
<!-- will look like-->
<anyElement id="price_id" data-priceArray="["1","2","3","4"]"/>

JS
var price_id = $("#price_id").data('priceArray');
/* is now a js array*/
  alert(price_id[3])

$.post("class.php",{price_id:price_id},function(data){
        alert(data);
});

A: php doesn't automatically recognize a string that came from print_r() as being an array. You need to use specific functions to serialize the array into something php can recognize. json_encode() is a good function to use for that.
But, json_encode() may produce a string that will have quotes and other characters in it that will break your html, so we need to encode it one more time with an encoding that is free of such characters. we use base64_encode() for that.
<input type="hidden" value="<?=base64_encode(json_encode($source_array))?>" id="price_id" name="price_id">

later, when you receive the ajax or form post
$reified_array = json_decode(base64_decode($_POST['price_id']));
foreach ($reified_array as $val) { ... }

json_decode
json_encode
base64_encode


text:
Q: angular2 bind model value to radio button I have a model which takes boolean value: rational_thinker: boolean; I set it's value from my frontend through radio boxes as following:

<input #btn1 type="radio" value='true' [(ngModel)]='rational_thinker' name="rational_thinker" class="mdl-radio__button" (click)="getRationalThinker(btn1.value)">
    True

<input #btn2 type="radio" value='false' [(ngModel)]='rational_thinker' name="rational_thinker" class="mdl-radio__button" (click)="getRationalThinker(btn2.value)">
    False

and method that sets the value:
getRationalThinker(value){
    this.rational_thinker=value;
}

After initial save the value is stored to my backend, and when I retrieve it again I want the corresponding radio button to be pre-selected, right now it appears blank.
How can I achieve that?
UPDATE:

A: Use [value]='true' and [value]='false'.
If you use the vanilla value='true' the contents of the property are not interpreted by angular but taken to be a string. This way, you have a string "true" which is not strictly equal to the boolean true (which I assume your model has from the server).
Using [value] instead makes angular interpret the contents as code, so if the contents are true or false, they will be taken as booleans and match with your model (hence become pre-selected correctly).
Edit: switched [ngValue] with [value] as [ngValue] seems to only work with select elements...

A: I believe is a type issue:
value='true' [(ngModel)]='rational_thinker'

Here, the 'true' from the value is string type, while the true from your model is boolean type.
You could maybe solve this by:
In Component:
public rationalThinkerModel: boolean = true;

In Template:
<input #btn1 type="radio" value='rationalThinkerModel' [(ngModel)]='rational_thinker' name="rational_thinker" class="mdl-radio__button" (click)="getRationalThinker(btn1.value)">
    True

<input #btn2 type="radio" value='!rationalThinkerModel' [(ngModel)]='rational_thinker' name="rational_thinker" class="mdl-radio__button" (click)="getRationalThinker(btn2.value)">
    False

Update:
Try adding this instead:
[checked]="(rational_thinker === true) ? 'true' : 'false'"


text:
Q: why ongenerate route calling my dashboard screen's init method?.....even though i'm still on login or signup screen? i'm using flutter_bloc as a state management and the problem lies within this route file, it's calling dashboard's init method as soon as app starts, which i don't want.
(this is routing)
class AppRouter {
  Route onGenerateRoute(RouteSettings routeSettings) {
    switch (routeSettings.name) {
      case SplashScreen.routeName:
        return MaterialPageRoute(builder: (_) => SplashScreen());

      case IntroScreen.routeName:
        return MaterialPageRoute(builder: (_) => IntroScreen());

      case LoginScreen.routeName:
        return MaterialPageRoute(builder: (_) => LoginScreen());

      case SignUpScreen.routeName:
        return MaterialPageRoute(builder: (_) => SignUpScreen());

      case DashboardScreen.routeName:
        return MaterialPageRoute(builder: (_) => DashboardScreen());

      default:
        return MaterialPageRoute(
          builder: (_) => Scaffold(
            body: Center(
              child: Text('No route defined for ${routeSettings.name}'),
            ),
          ),
        );
    }
  }
}

(this is startup logic)
class Init {
  Future<String> initialize() async {
    await _registerServices();
    await _loadSettings();
    return await _loadInitialRoute();
  }

  late final SharedPreferences _prefs;
  late final SessionManager _sessionManager;
  late final AuthRepositoryImpl _authRepository;
  late final bool _userSeenIntro;
  late final String? _presistentSession;

  Future<void> _registerServices() async {
    _prefs = await SharedPreferences.getInstance();
    _sessionManager = SessionManager();
    _authRepository = AuthRepositoryImpl.instance;
  }

  Future<void> _loadSettings() async {
    _userSeenIntro = _prefs.getBool(AppConstants.IS_USER_SEEN_INTRO) ?? false;
    _presistentSession = await _sessionManager.getSessionToken();
    await _authRepository.recoverSession(_presistentSession);
  }

  Future<String> _loadInitialRoute() async {
    if (_userSeenIntro && _presistentSession != null) {
      print('inside dashboardscreen.routename');
      return DashboardScreen.routeName;
    } else if (_userSeenIntro && _presistentSession == null) {
      return LoginScreen.routeName;
    } else {
      _prefs.setBool(AppConstants.IS_USER_SEEN_INTRO, true);
      return IntroScreen.routeName;
    }
  }
}

this is my onGenerate routes and i don't know why flutter calling my dashboard's init method and even build method too
this is my startup logic I'm setting initial route in material app on the basis of sharedPrefernces


text:
Q: Cypress can't include value from outside in .get() function in custom command I want to create a custom parent command in Cypress with get() function inside. I need to provide the locator of the element from the outside of the custom command. Here is my code.

// cypress>support>commands.js
Cypress.Commands.add('testCommand', (testVariable) => {
    cy.get(testVariable).click();
})

Because I am using TypeScript I need to add the command inside the index.ts

// cypress>support>index.ts

testCommand(): Chainable<Element>

But when I want to call this custom command - I am not able to provide any parameter inside the function.

A: You have to define all the parameters for you custom command in the TypeScript definition:
// cypress>support>index.ts

testCommand(testVariable: string): Chainable<Element>


text:
Q: $\operatorname{Aut}(G)=G(k)$ for a smooth algebraic group over $k$ Let $G$ be a smooth algebraic group over a field $k$. Then $Aut(G)=\mathbf{G}(k)$, where $\mathbf{G}$ is the trivial right $G$-torsor.
My attempt:
Given a $k$-rational point $\operatorname{Spec}(k) \xrightarrow{g} G$, then one obtains an automorphism of $G$ by composing the structure morphism $G \rightarrow \operatorname{Spec}(k)$ with $g$.
For the other direction I am getting confused, and haven't been able to come up with a decent approach.
Any help please?

A: That is not true. For example $\textrm{Aut}(SL_2) = PGL_2(k)$. In any linear algebraic group, $\textrm{Inn}(G) \cong (G/Z)(k)$, where $Z$ is the center, and the full automorphism group is an extension of that by it's outer automorphisms.
In view of the edit:
An automorphism or torsors $ \varphi: \mathbf{G} \to \mathbf{G}$ is $G$-equivariant, hence $\varphi(g)=\varphi(e\cdot g)=\varphi(e)\cdot g$ where "$\cdot$" denotes right multiplication. Following the identity element, what can you conclude?


text:
Q: Gradle WAR with compiled classes under WEB-INF/classes I'm trying to port a legacy Java webapp project into gradle.
This is a snippet of my build.gradle
def customBuildPath = 'build/classes'

war {
    from(customBuildPath) {
        into 'WEB-INF/classes'
    }

    from('WebContent') {
        include 'Web/**/*'
        into ''
    }
}

dependencies {

    compile fileTree(dir: 'projectlibs/lib', include:'*.jar')
    compile fileTree(dir: 'build/classes', include:'**')
}

To maintain the custom structure I want to put all my *.class files under WEB-INF/classes and it works, but I find also the same *.class files under WEB-INF/lib.
My goal it to keep jars and classes in separated war folder.
Any thoughts?
Edit: Added dependencies{} to the build.gradle snippet.

A: Problem get solved with commenting out builded classes from the dependencies:
def customBuildPath = 'build/classes'

war {
    from(customBuildPath) {
        into 'WEB-INF/classes'
    }

    from('WebContent') {
        include 'Web/**/*'
        into ''
    }
}

dependencies {

    compile fileTree(dir: 'projectlibs/lib', include:'*.jar')
//    compile fileTree(dir: 'build/classes', include:'**')
}


text:
Q: Tweets posted with MGTwitterEngine lose location coordinates? I am using sendUpdate:withLatitude:longitude: to post a tweet containing the user's location in an iPhone app. However, this metadata seems to get lost in the process, in that no such tweets that I view have any indication of any location data at all. Is there another step I have to go through in order to properly post geotagged tweets?

A: Why don't you check if Twitter account is enabled to show location data. When you signed up Twitter, this feature is usually turned on, but the user can opt out very easily. If this is disabled, even if you send proper latitude and longitude, they are ignored and your tweet will not show location.
Also, make sure your device properly gives you the right coordinate information. If it's not working properly, the coordinate values are often 0.00000000, 0.00000000 which is still accepted as valid.
MGTwitterEngine is kind enough to check if you're providing proper values, but it doesn't catch 0.00000000, 0.00000000 coordinate, because it passes the following evaluation
if (latitude >= -90.0 && latitude <= 90.0 && longitude >= -180.0 && longitude <= 180.0) {
    [params setObject:[NSString stringWithFormat:@"%.8f", latitude] forKey:@"lat"];
    [params setObject:[NSString stringWithFormat:@"%.8f", longitude] forKey:@"long"];
}


text:
Q: Dyanmic dropdown data is loading really slow in PHPusing MySQL I am fetching some 1000 records precisely from MySQL using PHP in a drop-down box, data loads on page reload and it is showing in console too, but whenever I click data shows in drop-down really slowly/delay.
PS: Cannot opt for caching Redis or other.
SQL Query is like- 'select user from table'    //users are 1000
PHP Script:
<select name="wname" id="Publication" class="form-control"  required>
              <option value=" ">Select Publication</option>

               <?php
               $select = "";
               while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
                 ?>

               <option value="<? echo $row['Id']; ?>"<? if($row['Id']==$select){ echo "selected"; } ?>>
                                     <?

                                       echo $row['users'];

                                       ?>

      <?php
    }
     ?>
        </option>
            </select>

A: Can you use a different approach?
You must be render the dropdown as a search box. When your user starts typing, you make an ajax call to the DB, for example at start of 3rd chars.
E.g.
When your user type "sin" you populate with "sineverba" and "sinology", when user continues with "sine" you print only "sineverba" and so on.


text:
Q: How to return from preference screen to main activity? I have one main activity and one preferenceActivity. On my first activity I call menu and go on preferenceActivity by calling startActivityForResult.
                case R.id.settings:
                startActivityForResult(new Intent(this, SettingsActivity.class), LAUNCH_SETTINGS);
                return true;

Then I change my settings and want to return on main activity and see main activity with new settings applyed. In onPause() method do following (as I right understand this method will be called when I press back button, right?)
   @Override
     protected void onPause() {
         super.onPause();
         setResult(RESULT_OK, new Intent(this, MainActivity.class));
         finish();
     }

On main activity
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == LAUNCH_SETTINGS) {
            if (resultCode == RESULT_OK) {
                new RefreshList().execute(ACTION_SELECT);
                Log.d(TAG, "On activity result");
            }
        }
    }

But my acyncTask do not called and log not printed. How correctly I can do this?
Thanks!

A:
On my first activity I call menu and go on preferenceActivity by calling startActivityForResult.

Using startActivityForResult() with a PreferenceActivity is rather unusual. PreferenceActivity is designed to be used with startActivity(). If the one starting the PreferenceActivity cares about preference changes, it should register a preference change listener with the SharedPreferences object.

Then I change my settings and want to return on main activity and see main activity with new settings applyed.

I recommend that you use a SharedPreferences.OnSharedPreferenceChangeListener instead. Or, simply re-read the preferences you care about in the original activity's onStart() or onResume() method.

In onPause() method do following (as I right understand this method will be called when I press back button, right?)

No, that will not work. onPause() is too late to call setResult().


text:
Q: File 'root/lib/armeabi-v7a/include/opencv2/flann/sampling.h' uses reserved file or directory name 'lib' When I try to build an Android App Bundle I have this error while building the Bundle file:
File 'root/lib/armeabi-v7a/include/opencv2/flann/sampling.h' uses reserved file or directory name 'lib'.
Any solution please


text:
Q: single char from socket, one at a time I'm working on a small telnetish game in C with text based gui.
I need to get a single char from a socket without '\n' needed so i can get control over keys.
I have something like
16     char buffer[256];
17     bzero(buffer,256);
18     n = read(sock,buffer,255);

but read() accepts only char *.
recv() is better but you still need to pass '\n' to get it.
I found a way to turn off telnet line mode, but that's not working for me, and/or I don't understand it.
write(s,"\377\375\042\377\373\001",6);

From what I have found on a forum there might be a way to do it with ncurses.
What is the best way to do it?
what I'm at
 12 void doprocessing (int sock)
 13 {
 14     int n;
 15     int i;
 16     char buffer;
 17     n = recv(sock,&buffer,1,0);
 18     if (n < 0)
 19     {
 20         perror("ERROR reading from socket");
 21         exit(1);
 22     }
 23     printf("MSG: %c\n",buffer);
 24     n = write(sock,"MSG SENT\n",18);
 25 }

A:
read() accepts only char *.

char * and char[] are mostly equivalent in C, certainly for this purpose. Clearly you didn't even try it.

recv() is better but you still need to pass '\n' to get it.

No, recv() is identical to read() for sockets unless the fourth argument is non-zero, and you don't need to pass \n to get it.

I found a way to turn off telnet line mode, but that's not working for me, and/or I don't understand it.

write(s,"\377\375\042\377\373\001",6);

This is IAC DO LINEMODE (255 253 36), which shouldn't be sent at all by a client, followed by IAC WILL ECHO (255 251 1). The correct command is IAC WILL LINEMODE (255 251 36) or "\377\373\042", and there will be a reply IAC DO LINEMODE (255 253 36 or "\377\375\042") which is IAC DO LINEMODE where the server gives you permission to begin negotiation of the linemode. I suggest you study RFC1116 for further details, it is rather complicated, and needs to be read in conjunction with RFC854 and others.


text:
Q: Difference between HF Communication and VHF Communication I am new to Radio Communication. I don't understand what was the challenge in establishing VHF Communication system w.r.to HF Communication System that made the former one to arrive later. (Talking as per the order of development of Aeronautical Communication System)

A: At the simplest level, the limitation was devices (vacuum tubes) that would operate at higher frequencies.  This evolution of communication technology to higher and higher frequencies continues even as you are reading this sentence. Few people dreamed 10 years ago that we would have inexpensive mass-market consumer gear that operates at 5GHz and higher.


text:
Q: How to keep business rule in case of two different aggregates? I have a some domain modeling case: There is two domain concepts Worksite and Contract. Every Contract belongs to some Worksite. I've already found out that both concepts are own aggregates but there is still business rule that the validity period of Contract must always be inside the duration period of Worksite. So how to keep that consistency true?
Okay, when I create a new Contract I can do it as follows:
public class Worksite {

   private Period period;

   public Contract createContract( Period period, ... ) {

     if ( !this.period.inside( period ) ) ) {
       throw new SomeException();
     }

     ...

     return new Contract( new ContractId( .. ), this.id(), period, ... );

  }

}

but what can I do, when someone modifies Worksites' or Contract's period afterwards? Both have different consistency boundary so I can't do it in same transaction.. or is this the case when I need to break the rule?

A: So caution number one -- carving up your model into aggregates is an optimization.  Aggregates doesn't make the model more correct.  What they do is reduce the amount of state that the model needs to consider in any given change, and they give you the option of making concurrent changes to unrelated bits of state.

Every Contract belongs to some Worksite.

That suggests that the contract entities and the related worksite entity could be part of the same aggregate.  That should be the first avenue you explore: what's the cost of keeping the related state together?
Second thing to be sure to understand: is the model the authority that decides this information, or is the model just checking that consistent decisions have been made elsewhere (or that data entry has been done correctly).
If contracts and worksite periods are determined outside the model, then the model probably shouldn't be rejecting the changes.  Who are you going to believe, the model or the ink on the contract?
Greg Young had an interesting suggestion in this space: stop over engineering.  In many cases, you can get a lot of business value from having the solution detect inconsistencies and escalate them to a human being, rather tha trying to immediately resolve them in code.  What's the cost/benefit of doing the extra work to get immediately consistent results, rather than a correction after escalation?
On the other hand, if the model really is the authority for deciding where the periods are, then you definitely want both periods in the same aggregate, and you should be reviewing the domain model to make sure you really understand where that data belongs.
(Side hint: aggregates are information, not physical things.  You may want to explore the ubiquitous language of your domain to see if "worksite" is the right noun to have in your model; where does the period of the worksite come from?)

A: You should not break the rule if that's what the business needs.
Considering that there are two separate aggregates then eventual consistency must come into play.
So, what happens when somebody modifies the period of a contract? We must ensure that the period is still inside the Worksite, but that information is inside other aggregate.
The solution is that, when someone tries to modify the period of a contract we start a process of verification and only after the process is finished we actually change the contract's period.
We do this by puting the aggregate in a special state named for example period_verification_started, without changing the old period. Then we start a Saga/Process manager that loads the Worksite from repository, it gets its period then it forwards it to the Contract aggregate. The Contract aggregate checks the invariant then it changes the period or rejects the change request by setting its status accordingly.
On the other side, if a Worksite needs to change its period, then the same strategy could be employed by starting a Saga that loads all the relevant Contracts from repository and if the invariant holds only then the period is "commited".
If an Event-driven architecture is used all this is done simpler by the Sagas listening to the relevant events and by sending commands to the two Aggregates.


text:
Q: django+uwsgi+docker while connecting to upstream I made infrastructure via docker.
To deploy django, used uwsgi and nginx.
Here is my configuration file.
[docker-compose.yml]
version: '3.7'

services:
  nginx:
    build:
      context: .
      dockerfile: docker/nginx/Dockerfile
    container_name: nginx
    hostname: nginx
    ports:
      - '80:80'
    networks:
      - backend
    restart: on-failure
    links:
      - web_service
    depends_on:
      - web_service

  web_service:
    build:
      context: .
      dockerfile: docker/web-dev/Dockerfile
    container_name: web_service
    hostname: web_service
    ports:
      - '8000:8000'
    networks:
      - backend
    tty: true
    volumes:
      - $PWD:/home

networks:
  backend:
    driver: 'bridge'

[docker/web-dev/Dockerfile]
FROM python:3.6.5

COPY Pipfile ./home
COPY Pipfile.lock ./home
WORKDIR /home
RUN pip3 install pipenv
RUN pipenv install --system
RUN apt-get update && apt-get install -y vim && apt-get install -y git
RUN pip3 install uwsgi && pip3 install git+https://github.com/Supervisor/supervisor
CMD ["uwsgi", "--ini", "docker/config/uwsgi.ini"]

[docker/nginx/Dockerfile]
FROM nginx:latest

COPY . ./home
WORKDIR home
RUN rm /etc/nginx/conf.d/default.conf
COPY ./docker/config/nginx.conf /etc/nginx/conf.d/default.conf

[nginx.conf]
upstream django {
    server web_service:8001;
}
server {
    listen 80;
    server_name 127.0.0.1;
    charset utf-8;

    location / {
        uwsgi_pass django;
        include /etc/nginx/uwsgi_params;
    }

    location /media {
        alias /home/example/media;
    }

    location /static {
        alias /home/example/static;
    }
}

[uwsgi.ini]
[uwsgi]

chdir = /home
module = example.wsgi:application
master = true
process = %(%k * 3)
socket = 127.0.0.1:8001
vaccum = true
chmod-socket=664

I set nginx '/' to django and django is listening via port 8000.
Also uwsgi is listening via 8001 and connect nginx and django.
But when I connect to http://localhost, it throw upstream error.
Error showed in web browser -> 502 Bad gateway
Error showed in docker log ->
connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.0.1, server: 127.0.0.1, request: "GET / HTTP/1.1", upstream: "uwsgi://172.31.0.3:8001", host: "localhost"
I searched in google few hours, But can't found any way.
Is there any solution here?
Thanks.


text:
Q: jQuery Sortable - attach div So I have an accordion setup as follows:-
button.accordion {
background-color: #eee;
color: #444;
cursor: pointer;
padding: 18px;
width: 100%;
text-align: left;
border: none;
outline: none;
transition: 0.4s;
}

button.accordion.active, button.accordion:hover {
    background-color: #ddd;
}

button.accordion:after {
    content: '\02795';
    font-size: 13px;
    color: #777;
    float: right;
    margin-left: 5px;
}

button.accordion.active:after {
    content: "\2796";
}

div.accordion_panel {
    padding: 0 18px;
    background: #d7d7d7;
    display: none;
}

div.accordion_panel.show {
    background: #d7d7d7 !important;
    display: block;
}

and the html implementation of it as follows:-

    <button class="accordion">Work Experience</button>

Employer Name: <input type="text" class="form-control  spec_one" name="Employer[]">

Position: <input type="text" class="form-control  spec_one" name="Position[]">

    <button class="accordion">Work Experience</button>

Employer Name: <input type="text" class="form-control  spec_one" name="Employer[]">

Position: <input type="text" class="form-control  spec_one" name="Position[]">

    <button class="accordion">Work Experience</button>

Employer Name: <input type="text" class="form-control  spec_one" name="Employer[]">

Position: <input type="text" class="form-control  spec_one" name="Position[]">

I've basically been trying to make a sortable collapsible accordion, but as I am using bootstrap the accordion built into jQuery UI does not work.
What I am essentially trying to do is make the heading button "Work Experience" sortable, but the underlying div that is shown when its click also needs to be sorted with it. I've tried wrapping the button and div in an LI but then when the button is clicked, the LI expands to cover the viewable contents of the div (as it should). I want to confine the sort to the button, but have the button and the div move with the sort. How can I do this?


text:
Q: Add the upper and lower 64-bits of a 128-bit xmm register I have two packed quadword integers in xmm0 and I need to add them together and store the result in a memory location. I can guarantee that the value of the each integer is less than 2^15. Right now, I'm doing the following:
int temp;
....

   movdq2q mm0, xmm0
   psrldq xmm0, 8
   movdq2q mm1, xmm0
   paddq mm0,mm1
   movd temp, mm0

Is there a better way to do this?

A: First off, why are you using quadwords to represent values that would fit in a 16-bit format?  Leaving that aside, a couple solutions:
pshufd xmm1, xmm0, EEh
paddq  xmm0, xmm1
movd   temp, xmm0

or
movdqa xmm1, xmm0
psrldq xmm1, 8
paddq  xmm0, xmm1
movd   temp, xmm0

or
movhlps xmm1, xmm0
paddq   xmm0, xmm1
movd    temp, xmm0

Note that you don't actually need to use paddq, you can get away with one of the narrower adds if you prefer.
edit summing four double quadwords -- what you have is pretty much fine.  Given that you know that all the data in them fits into the low doubleword of each slot, you could try something like:
shufps  xmm0, xmm2, 88h
shufps  xmm4, xmm6, 88h
paddd   xmm0, xmm4
psrlq   xmm1, xmm0, 32
paddd   xmm0, xmm1
movhlps xmm1, xmm0
paddd   xmm0, xmm0
movd    temp, xmm0

which may or may not prove to be faster.
As for EMMS, it's just another instruction. After any code that touches the MMX registers, before any code that uses the x87 floating-point instructions you need to have emms.


text:
Q: Where clause not working in laravel 5.2 i have problem the problem is Where Clause not work in my project, i make sure to follow instruction on laravel documentation but the data in my table is not show on my datatable, i hope you can help me.

AbsenController@index

public function index()
{
    $absen = Absen::get()->where('level', '=', 'Siswa');
    return view('absen.index')->with('data', $absen);
}

index.blade.php

@foreach($data as $index => $value)

              {{ $index+1 }}
              {{ $value->nama }}
              {{ $value->keterangan }}

                {!! Form::open(['route' => ['siswa.destroy', $value->id],
                   'method' => 'DELETE']) !!}
                  {{ Form::submit('Hapus', ['class' => 'btn btn-danger']) }}
                  id) }}" class="btn
                 btn-warning">Edit
                {!! Form::close() !!}

            @endforeach

The record is not showing in my datatable

But i have one record in my table
Thanks

A: You are fetching records before filtering with where..
You should do:
$absen = Absen::where('level', '=', 'Siswa')->get();

instead.


text:
Q: Compute probability from expected values
Random variable $X$ can take the following values: $-2,-1,0,1,2$. Find the probabilities of having such values if $E(X)=E(X^3) = 0$, $E(X^2) = 1$ and $E(X^4) = 2$.

$E(X) = -2P(X=-2)-1P(X=-1)+0P(X=0) + 1P(X=1) + 2P(X=2)=0$
$E(X^3) = -8P(X=-2)-1P(X=-1)+0P(X=0) + 1P(X=1) + 8P(X=2)=0$
$E(X^2) = 4P(X=-2)+1P(X=-1)+0P(X=0) + 1P(X=1) + 4P(X=2)=1$
$E(X^4) = 16P(X=-2)+1P(X=-1)+0P(X=0) + 1P(X=1) + 16P(X=2)=2$
Solving this equations I get $0.042, 0.333, 0, 0.042, 0.333$
What is wrong with the approach?


text:
Q: Reducing Alphabet in nested for loops by reducing string by one char each line As a beginner, I'm given a loop assignment, and one of the loops is to output the alphabet, first from a-z, then b-z, then c-z, and so on, each on individual lines.
I've printed the alphabet by
for(char c = 'a'; c <= 'z'; c++)

And then a print statement produces the entire alphabet, but I'm at a loss as how to neatly implement another for loop to reduce the starting char and printing the new string of chars on a separate line.

A: Try this,
char input = 'a';
    while (input != 'z') // this will continue upto z == z
    {
        for (char c = input; c <= 'z'; c++) // get the input value and iterate upto z
        {
            System.out.print(c + " "); // print the values
        }
        System.out.println(""); // for next line
        input++; // this for next char like b,c,d....z
    }

A: for(char j = 0; j < 26; j++) {
    for(char c = (char)('a' + j); c <= 'z'; c++) {
        System.out.print(c);
    }
    System.out.println("");
}

A: here is the example code that should work for your purpose:
for(char outer='a'; outer <= 'z'; outer ++)
    {
    for(char inner = outer; inner <= 'z'; inner++)
       {
       System.out.print(""+inner); //print the character
       }
    System.out.println(""); // next line
    }

Basically, you have to cycle through the alphabet in the first for loop and you take the current value of the outer for loop as a starting value for the inner for loop.
And just a note: try to get used to give your variables names some sense - it does help!

A: You could add an if statement at the end that returns it to 'b' when it's total iteration is less than 3. Then again, this question looks like an assignment.


text:
Q: Can anyone explain how to use OpenACC in GCC? I am using WSL Ubuntu. And use GCC to compile my C++ code.
I am trying to use OpenACC to parallelize my code. I heard that I can use OpenACC with GCC.
So after I install Ubuntu, I installed GCC.
And then I typed as follows:
$ g++ -fopenacc -o t testfile.cpp

As far as I know, -fopenacc should enable me to use OpenACC inside my code.
However, I got an message saying:
lto-wrapper: fatal error: could not find accel/nvptx-none/mkoffload in /usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/9/:/usr/lib/gcc/x86_64-linux-gnu/ (consider using '-B')

So I guess I missed something.
Does anyone know how to use OpenACC with GCC?

Edited:
I tried:
sudo apt-get install gcc-9-offload-nvptx

And then the error message is now changed to:
lto1: error: '-fcf-protection=full' is not supported for this target
mkoffload: fatal error: x86_64-linux-gnu-accel-nvptx-none-gcc-9 returned 1 exit status

compilation terminated.

lto-wrapper: fatal error: /usr/lib/gcc/x86_64-linux-gnu/9//accel/nvptx-none/mkoffload returned 1 exit status
compilation terminated.

/usr/bin/ld: error: lto-wrapper failed

collect2: error: ld returned 1 exit status

A: I got one step further with:
gcc-10 -O2 -ffast-math -fopenacc -fopt-info-all-omp -fcf-protection=none -foffload=nvptx laplace2dkernels.c

but just to find the next problem:
gcc-10: fatal error: GCC is not configured to support nvptx as offload target
compilation terminated

So it seems they only compiled it for AMD GCN.
If you use
gcc-10 -O2 -ffast-math -fopenacc -fopt-info-all-omp -fcf-protection=none -foffload=nvptx-none laplace2dkernels.c

>laplace2dkernels.c:74:9: optimized: assigned OpenACC seq loop parallelism
>/usr/bin/ld: /tmp/ccYd0cZe.crtoffloadtable.o: warning: relocation against >`__offload_vars_end' in read-only section `.rodata'

It compiles but then when running it misses:
libgomp: while loading libgomp-plugin-gcn.so.1: libgomp-plugin-gcn.so.1: cannot open shared object file: No such file or directory

I do not need to install those libraries because I want to get it to run with my Nvidia card.
With the PGI compilers everything worked fine.
NOTE: I am also using WSL and special NVIDIA drivers to allow for GPU passthrough.

A: Here's what worked for me for a Tiny C++ stencil code with OpenACC directives, after installing gcc-10-offload-nvptx:
g++ -c -g -O -fopenacc -foffload=nvptx-none -fcf-protection=none -foffload=-misa=sm_35 -fno-stack-protector stencil_acc.cxx

g++ -o stencil_acc -g -O -fopenacc -foffload=nvptx-none -fcf-protection=none -foffload=-misa=sm_35 -fno-stack-protector util.o stencil_acc.o


text:
Q: R/ Can you teach me what 'b/St.Er.|P[|Z|>z]' mean saying?
hat 'b/St.Er.|P[|Z|>z]' mean saying?? I can't understand ...
And are these all coefficients valide statistically when \alpha is 5% ??

A: The columns seems to be b/St.Er. = Coefficient/(Standard Error). Then, the p-value is the P(|Z| > |b/St.Er.|), where Z ~ N(0,1). It is the Wald test (https://www.ssc.wisc.edu/sscc/pubs/MM/MM_TestEffects.html)


text:
Q: Get attribute from a xml using xslt I have a xml.in this xml I have a node named video like below
  <product>
 <id>676872</id>
  <weightingram>510</weightingram>
  <volume>0</volume>
  <discountgroup />
 <name>Product name (500 g)</name>
  <vat>10,49</vat>
  <webbestprice extra="webbestprice">0</webbestprice>
  <webreturn extra="webreturn">0</webreturn>
  <weboutdate extra="weboutdate">01-01-2013 00:00:00</weboutdate>
  <webaltitem extra="webaltitem" />
  <filters extra="filters">
    <ISP_WebItem FILTER="Type" FILTERNAME="type" UNITCODE=""/>
    <ISP_WebItem FILTER="Type2" FILTERNAME="500" UNITCODE="g"/>
  </filters>
  <videos extra="videos">
    <YoutubeVideoURL RowNumber="33" ProductID="676872" YoutubeUrl="http://www.youtube.com/watch?v=EjoEIHVk9qM" YoutubeImage="https://img.youtube.com/vi/EjoEIHVk9qM/2.jpg"/>
  </videos>
</product>

the above xml is getting by using
<textarea>
<xsl:copy-of select="."/>
</textarea>

I need to get the value of  attribute YoutubeUrl from this xml.I tried something like
 <xsl:value-of select="./videos/YoutubeVideoURL[@YoutubeUrl] "/>

but it is not working.Thanks in advance for help.

A: Try this code
<xsl:template match="YoutubeVideoURL">
   <xsl:value-of select="@YoutubeUrl"/>
</xsl:template>

(or)
if you have specified the template that is matching to "/" root then use the below syntax.
<xsl:template match="/">

 .....
   <textarea>
      <xsl:copy-of select="." />
   </textarea>
   <p>
   <xsl:value-of select="//videos//YoutubeVideoURL//@YoutubeUrl"/>
   </p>
</xsl:template>

Copy-of will copy the xml element specified in the select expression. So TextArea will have that xml element with its structure. And you are using value-of to retrive the xml attribute which needs an element selection. So, its not related.
You can use either of the solution mentioned in this ans.

A: You can write like this
Your sample XML file
<?xml version="1.0" encoding="UTF-8"?>
<videos extra="videos">
    <YoutubeVideoURL RowNumber="1" ProductID="12452" YoutubeUrl="http://www.youtube.com/watch?v=efhrtgdbo" YoutubeImage="https://img.youtube.com/vi/efhrtgdbo/2.jpg"/>
</videos>

And your sample XSL file
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml"/>
    <xsl:template match="YoutubeVideoURL">
        <xsl:value-of select="@YoutubeUrl"/>
    </xsl:template>
</xsl:stylesheet>

Final output

http://www.youtube.com/watch?v=efhrtgdbo

That's it

A: In your value-of you are looking for any videos/YoutubeVideoURL that have an attribute of @YoutubeUrl. If you are looking to get the value of @YoutubeUrl then you need to take it out of the predicate like so.
<xsl:value-of select="./videos/YoutubeVideoURL/@YoutubeUrl" />

This of course assumes that your paths and templates are already set up correctly to locate this value at it's current position.


text:
Q: Ubuntu Studio Nvidia drivers compatibility I am currently using Mint on a machine that is configured as an audio workstation although it also does a wide variety of other tasks.
I am thinking of trying Ubuntu Studio instead.
I have read that Ubuntu Studio uses the stock linux-lowlatency kernel. I have found this kernel to be incompatible with nvidia drivers when used on Mint. (I am using the liquorix kernel)
So my question is - does Ubuntu Studio work well and easily with Nvidia drivers or are there many hoops to jump through?
Does it update without breaking nvidia drivers? Does it require driver installation that is more complex than the process for installing other software?
EDIT this post is not answered by How to download all required Ubuntu drivers as it doesn't address Ubuntu Studio and the low-latency kernel specifically. I have already found the low latency kernel to be incompatible with nvidia drivers when used in Mint so I'm asking if that is different in Ubuntu Studio.
EDIT please note I am NOT asking about compatibility with regular Ubuntu - I am asking about Ubuntu Studio and whichever lowlatency kernel it uses by default. Regular Ubuntu does not use a lowlatency kernel by default.

A: I have now tested Ubuntu Studio and can confirm that the included lowlatency kernel 4.15 works with the nvidia drivers.
Loads of special features of Ubuntu Studio totally didn't work - but the graphics did.
However the ubuntu studio installer and live usb stick does not work with an nvidia card, I had to install with my monitor plugged into my mobo's graphics and swap it after I had installed and installed the nvidia driver.
This was NOT my experience on Mint, where i couldn't get the lowlatency kernel to work with nvidia. When trying to solve that I found a number of peoples saying it is incompatible. I now think they are wrong, but don't know what my original problem on Mint actually was. (probably DKMS)

A: The entire reason the lowlatency kernel exists (as opposed to the RT kernel of yore) is twofold:

*

*The lowlatency kernel is less likely to be compromised by an attacker taking control via a realtime permissions, thereby locking out the rest of the system. Lowlatency kernels allow the user to continue to interact with the system while providing the lowest latency possible to processes requiring realtime access.

*It is easier to maintain than RT or realtime kernels, and is therefore guaranteed to have the same driver compatibility as the generic kernel included with other Ubuntu flavors.

So, your question is most likely answered with point #2 above.


text:
Q: MySql trying to improve query performance but got error on a column This is really 2 questions in one but I'll try to make it as much to the point as possible.
I showed my initial query to a friend that told me the performance could be improved further with a sub select (using MySql Here).
Unfortunately I could not get his query to work since I had a Error Code: 1054
Unknown column 'e.id' in 'where clause'
His query below: would appreciate if someone tells me why it cannot recognise e.id.
SELECT e.id AS event_id, er.name AS event_name, er.revision AS revision, er.start_date AS event_dates
 FROM `events` AS e
 INNER JOIN
 (
    SELECT event_id, revision, start_date
    FROM event_revisions
    WHERE YEAR(start_date) = YEAR(CURDATE())
    AND revision = (
       SELECT MAX(er_tmp.revision)
       FROM event_revisions AS er_tmp
       WHERE er_tmp.approved = 1
       AND e.id = er_tmp.event_id
    )
 ) AS er ON (e.id = er.event_id)
 INNER JOIN member_events AS me ON (me.event_id = e.id)
 WHERE
  e.enabled = 1 AND
  e.deleted = 0
 GROUP BY event_id
 ORDER BY event_dates

This is my original query:
SELECT e.id AS event_id, er.name AS event_name, er.revision AS revision, er.start_date AS event_dates
FROM `events` AS e
INNER JOIN event_revisions AS er ON (e.id = er.event_id)
INNER JOIN member_events AS me ON (me.event_id = e.id)
WHERE
    e.enabled = 1 AND
    e.deleted = 0 AND
    er.revision = (
        SELECT MAX(er_tmp.revision)
        FROM event_revisions AS er_tmp
        WHERE er_tmp.approved = 1
        AND  e.id = er_tmp.event_id
    )
    AND YEAR(er.start_date) = YEAR(CURDATE())
GROUP BY event_id
ORDER BY event_dates

The second question is: why would his query be faster than mine?
Any input it is highly appreciated.

A: AD 1. Because sub select:
 SELECT MAX(er_tmp.revision)
    FROM event_revisions AS er_tmp
    WHERE er_tmp.approved = 1
    AND  e.id = er_tmp.event_id

is "called" for each row in Your's query.
(AD 2) and as @Dor told You, You are using alaias from sub query


text:
Q: Swift how to get cell from prepare for segue in collectionView Im using autolayout and for the life of me cannot set the proceeding view controller image view with the previous view controller collection view cell's image. Im using
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    performSegue(withIdentifier: "openDetailView", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "openDetailView" {
        let cell = sender as? ImageCollectionViewCell
        let detailVC = segue.destination as! DetailedImageViewController
        detailVC.imageToPresent = cell?.imageView.image

    }
}

This is the class that I have already set up to receive the image
class DetailedImageViewController : UIViewController{

var imageToPresent: UIImage!
@IBOutlet weak var imageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    imageView.image = imageToPresent
}

}
The segue performs as expected but the image DOES NOT show in detailedImageViewController. Thanks in advance.

A:
You need to set the imageToPresent into a UIImageview in order to show the image.
class DetailedImageViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!

    var imageToPresent : UIImage!

    override func viewDidLoad() {
        super.viewDidLoad()
        imageView.image = imageToPresent
    }
 ...

A: It's not a best practice to avoid optional unwrapping in this case. Try to use this code and check the errors if they happen.
 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "openDetailView" {
        guard let cell = sender as? ImageCollectionViewCell else {
            assertionFailure("Failed to unwrap sender. Try to set a breakpoint here and check what sender is")
            return
        }
        let detailVC = segue.destination as! DetailedImageViewController
        guard let cellImage = cell.imageView.image else {
            assertionFailure("The cell has no image in image view")
            return
        }
        detailVC.imageToPresent = cellImage
    }
}


text:
Q: Parsing Schema got error when using PHP SoapClient I 'm trying to use PHP SoapClient to consume eBay web service. Just following the eBay official sample:
$client = new SoapClient('http://developer.ebay.com/webservices/latest/ebaysvc.wsdl');

I get an error as below:

SoapFault exception: [WSDL] SOAP-ERROR: Parsing Schema: unexpected in simpleType in E:\xampp\htdocs\mysite\system\application\libraries\Ebaysvc.php:102 Stack trace: #0

Does anyone know how to solve this?

A: Please use this url for the wsdl http://developer.ebay.com/webservices/753/eBaySvc.wsdl
I don't knew why the changed the url. Thank to Pakistan for that Post http://www.adeelsarfaraz.com/how-to-remove-the-fatal-error-soap-error-parsing-schema-unexpected-in-sequence-error/


text:
Q: Setting MinThreads in ThreadPool I have faced the time out issue in the StackExchange.Redis. And the exception is like below.

Timeout performing GET CacheXXXX, inst: 18, mgr: Inactive, err: never,
  queue: 44, qu: 0, qs: 44, qc: 0, wr: 0, wq: 0, in: 65536, ar: 0,
  clientName: XXXXX, serverEndpoint:
  Unspecified/XXXXX.redis.cache.windows.net:6380, keyHashSlot: 1612,
  IOCP: (Busy=0,Free=1000,Min=8,Max=1000), WORKER:
  (Busy=39,Free=8152,Min=8,Max=8191) (Please take a look at this article
  for some common client-side issues that can cause timeouts:
  http://stackexchange.github.io/StackExchange.Redis/Timeouts)

I'm trying to change the min threads in ThreadPool as below in application start (global.asax)
 protected void Application_Start()
       {
           int minWorker, minIOC;
           ThreadPool.GetMinThreads(out minWorker, out minIOC);
           minWorker = 200;
           ThreadPool.SetMinThreads(minWorker, minIOC);
       }

So i changed the  Worker threads to resolve this error.
But below is the exception :

Timeout performing GET CacheABCD, inst:
  0, mgr: Inactive, err: never, queue: 5, qu: 4, qs: 1, qc: 0, wr: 1,
  wq: 1, in: 0, ar: 0, clientName: XXXXX, serverEndpoint:
  Unspecified/XXXXX.redis.cache.windows.net:6380, keyHashSlot:
  13995, IOCP: (Busy=0,Free=800,Min=400,Max=800), WORKER:
  (Busy=31,Free=769,Min=8,Max=800) (Please take a look at this article
  for some common client-side issues that can cause timeouts:
  http://stackexchange.github.io/StackExchange.Redis/Timeouts)

In the above code i have changed only Worker threads. But IOCP is changed, Worker threads is not changed.
Please help.


text:
Q: JFile not found after adding code for JFactory in custom module I created a custom donation module where I post some form data from default.php to another php script called checkout.php.
Now I have added some code to insert data into a database in checkout.php
//setup db
$db =& JFactory::getDBO();

//create database table if needed
$createTable = "CREATE TABLE IF NOT EXISTS `#__idealdonaties` ( " .
    "`id` int(10) NOT NULL, " .
    "`donateur_id` varchar(40) NOT NULL, " .
    "`naam` varchar(100) NOT NULL, " .
    "`email` varchar(250), " .
    "`bedrag` varchar(100) NOT NULL, " .
    "`status` int(1) DEFAULT 0, .
    PRIMARY KEY (`id`), KEY `donateur_id` (`donateur_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
$db->setQuery($createTable);
$db->query();

//insert data into table
$insertData = "INSERT INTO `#__idealdonaties` ( `donateur_id`, `naam`, `email`, `bedrag`, `status` ) " .
    "VALUES (`" . $brq_invoicenumber . "`, `" . $cust_name . "`, `" . $cust_email . "`, `" . $brq_amount . "`, 0)";
$db->setQuery($insertData);
$db->query();

but got an error:

Fatal error: Class 'JFactory' not found in /home/sitesosimple/public_html/modules/mod_idealdonatie/checkout.php on line 87

Now I have fixed that error (after some searching) by adding the code:
define( '_JEXEC', 1 );
define( 'JPATH_BASE', realpath(dirname(__FILE__).'/../../' ));
require_once ( JPATH_BASE .'/includes/defines.php' );
require_once ( JPATH_BASE .'/includes/framework.php' );

$mainframe = JFactory::getApplication('site');

But now I get a whole new error:

Fatal error: Class 'JFile' not found in /home/sitesosimple/public_html/modules/mod_roknavmenu/lib/RokNavMenu.php on line 73

For some reason the roknavmenu module can't locate the JFile Class though I changed nothing in that php file nor did I do anything with the file.php script which includes the JFile class.
I already copied a new version of file.php into the /public_html/libraries/joomla/filesystem folder. But to no avail.

A: Not sure if it's the right sollution, but it seemed to have worked.
I removed the line: $mainframe = JFactory::getApplication('site');.


text:
Q: Is canonical cover always unique for any relationship? Suppose I have the following relationship
C -> B
CB -> AC
CAE -> FB
D -> E
CA -> B

Canonical cover given in my book is C -> AB, CE -> F, D -> E
But Canonical cover can also be C - AB, D - EF? Can we have two different canonical cover for one relationship?

A:
But Canonical cover can also be C - AB, D - EF?

No, it cannot be a canonical cover for your set of functional dependencies (FD). A canonical cover of F is a "minimal" set of functional
dependencies equivalent to F, having no redundant dependencies or redundant parts of dependencies.
The canonical cover you suggest is not equivalent to F. For instance the functional dependency CAE->FB is not fully covered in the canonical cover suggested by you and hence it is not a canonical cover.
On the other hand the one given in your book C -> AB, CE -> F, D -> E is a canonical cover and the only canonical cover possible for this set of FD's.

Can we have two different canonical cover for one relationship?

Yes we can. To find canonical cover we do -

*

*First ensure singleton right-hand side (RHS)

*Second remove any extraneous left-hand side (LHS) attribute

*Third remove any redundant functional dependency

We can have different canonical cover for one relationship because of the third step above. I will explain this with an example.
Given FD's as:
X→YZ
Y→XZ
Z→XY

First ensure singleton RHS. So we have :

*

*X→Y

*X→Z

*Y→X

*Y→Z

*Z→X

*Z→Y

Second No extraneous LHS. Already satisfied.
Third Remove any redundant FD. Now we can remove (2),(3) and (6) as redundant dependencies and have the minimal cover set as:
1:
X→Y,
Y→Z,
Z→X

or we can remove (1),(4) and (5) as redundant dependencies and have the minimal cover set as:
2:
Z→Y,
Y→X,
X→Z

Hence, in this case we have two canonical covers for the same relationship.

A: Yes, a set of functional dependencies (not a relationship) can have multiple canonical covers. Date gives a step-by-step derivation in the answer to exercise 10.12 in An Introduction to Database Systems, 7th ed., p346f.
Date doesn't use the term canonical cover. He uses irreducible cover, more or less.


text:
Q: how to deform element from top and bottom Is there any way in css to deform the element from top and bottom as shown in below image? I don't wanna use background-image for this.

A:

.box {
  background: #363742;
  position: relative;
  overflow: hidden;
  height: 200px;
}

.box:before,
.box:after {
  border-radius: 1000px / 50px;
  position: absolute;
  background: #fff;
  height: 80px;
  content: '';
  right: -50px;
  left: -50px;
  top: -50px;
}

.box:after {
  bottom: -50px;
  top: auto;
}


text:
Q: Axios calls in actions Redux I am very new to Redux so please bear with me now.
My friend suggested that instead of having my axios calls inside of my componentDidMount() I should place them in an action file. Here's the snippet:
  componentDidMount() {
    axios.get('http://xxxx/customers').then(res => {
      this.setState({
        res,
        customer: res.data
      })
    })

    axios.get('http://xxxx/events').then(res => {
      this.setState({
        res,
        event: res.data
      })
    })

    axios.get('http://xxxx/locks').then(res => {
      this.setState({
        res,
        lock: res.data
      })
    })
  }

And I understand that to change the application's state I need to dispatch and action:

But the thing is that I am really uncertain how to set this all up. If anyone has some tips I'll be really happy to take them.

A: basically you should avoid updating the states using setState directly if you are using redux in project
here is a sample react-redux-axios for the reference,which will give a good understanding regarding flow.
https://github.com/johibkhan2/react-redux-singlePageApp

A: The picture illustrates the basic architecture of redux and how redux works. There are three main things that come up in redux : actions, reducers, store.
Actions and nothing but functions which dispatches some data and depending on that the state changes. Next is the reducer, reducers are pure functions which don't have side effects.Then comes the store which consists of a kind of bucket in which all your state variables are stored which helps in the rendering of data.
So now what you could do is make a call to API inside of actions and then call that function from ComponentDidMount. This action must dispatch some data and thus you must consider using redux-thunk for the purpose, which is used for async calls in redux.
This could be the very basic things that can help you get going. You might consider taking this course. This according to me is the best course for learning react and redux.

A: You might not need redux. For simple async state management this pattern might be helpful with async/await. You can do something like this:
async componentDidMount() {
    const res1 = await axios.get('http://34.248.65.20:3000/customers')
    const customer = res1.data

    const res2 = await axios.get('http://34.248.65.20:3000/events')
    const event = res2.data

    const res3 = await axios.get('http://34.248.65.20:3000/locks')
    const lock = res3.data

    this.setState({
        customer,
        event,
        lock
    })
}

Redux is only useful if you need access to this data throughout your application. Otherwise it just adds a lot of boilerplate. If you do need access to the API data throughout your app, ignore this answer.

A: There is another library like Redux, the Dynadux.
You can create more sophisticated stores and simply in the componentDidMount you can call store.fetchEntities() without need the await.


text:
Q: How to chose the optimal HSV values for InRange thresholding in OpenCV I have two related questions:

*

*I'm doing color object detection in OpenCV with the inRange threshold function. I'm getting excellent results if I manually choose the lower and upper HSV bounds, but this is very sensitive to the lighting conditions. Is there an algorithm that can determine the optimal threshold bounds given the HSV values of the target and the background?
As an example, here are the values I'm working with:
Target HSV value: [15, 37, 51]
Background HSV value: [90, 21, 211]

*inRange is simple pixel-by-pixel filter. It doesn't change the threshold conditions dynamically. Is there a color equivalent of adaptive threshold or Otsu threshold? Or an algorithm that can make use of the a priori HSV values of the target and the background?

A: If most of the image is more or less the same (for example most of it is a background) than you can do the following:

*

*Calculate median (M) of pixel values in image. Some people use mean instead but I prefer median for its robustness.

*Calculate median absolute deviation (MAD) of pixel values in image. Again I prefer it over standard deviation for its robustness.
Everything that will fall in range between (M - k * MAD) and (M + k * MAD) will be the background (or object). Choose value of constant 'k' according to your application (I guess it will be somewhere between 1 and 5).
Little tip, if this is your first time using MAD: 1 standard deviation is approximately equal to 1.5 MAD in case of normal distribution.


text: Q: How to handle incoming files via Apache Mina SSHD SFTP Client in Java I want to listen any updates of the file system but on the client-side. I know that I can do the same thing on server-side via SftpEventListener but I'm not sure if there is any option to implement this on the client-side via the aforementioned listener or somehow else.


text:
Q: Invalid content was found starting element 'or' in mule-config.xml while using mule-restlet transport Firstly, please take a look at a snippet in mule-config.xml:
<model name="userModel">
        <service name="userService">
            <inbound>
                <inbound-endpoint address="http://localhost:63080"/>
            </inbound>
            <outbound>
                <filtering-router>
                    <outbound-endpoint address="vm://userController"/>
                    <or>
                        <restlet:uri-template-filter pattern="/users/{userId}" verbs="GET"/>
                        <restlet:uri-template-filter pattern="/users" verbs="POST"/>
                        <restlet:uri-template-filter pattern="/users" verbs="PUT"/>
                        <restlet:uri-template-filter pattern="/users/{userId}" verbs="DELETE"/>
                    </or>
                </filtering-router>
            </outbound>
        </service>
        <service name="userController">
            <inbound>
                <inbound-endpoint address="vm://userController"/>
            </inbound>
            <!-- TODO: How to implement UserController -->
            <component class="com.ggd543.mulerestletdemo.user.UserController"/>
        </service>
    </model>

When I deploy it to $MULE_HOME/apps, mule complain :

PS: My mule version is 3.1.2 and i am using mule-transport-restlet-2.0.jar
Is there any wrong in my mule-config.xml ?

A: Change <or> to <or-filter> will work. The doument (http://www.mulesoft.org/documentation/display/RESTLET/User%27s+Guide#User%27sGuide-URITemplateRouting) is too old. WTF


text:
Q: SQL Server: copy all tables into new tables I am having a problem.
I am trying to create an easy way to make a copy of Table1 to Table2. Now I know the Select Into, but in this there is say table 1 through table 100 and I am trying to create a duplicate of all of them. SSIS or SQL is OK.
The reason for the copy is say I have 2 tables within a classes database.  Alegra 101 and 102, I am trying to create algebra 103   this will work for all of the tables, like Health 101 and 102, assume there are around 100 different classes with a 101 level and a 102 level that need a 103.

A: Not a big fan of dynamic SQL, but you might get away with something like this.
Maybe you should give some more insight in to why you might want to "copy" tables - others may have more suitable solutions for you.
DECLARE @CMD NVARCHAR(4000) = ''

SELECT @CMD = @CMD + 'SELECT * INTO [dbo].[Copy_' + TABLE_NAME + ']' + ' FROM ' + TABLE_SCHEMA + '.' + TABLE_NAME + ';' + CHAR(13)
FROM INFORMATION_SCHEMA.TABLES AS t
--  Add your filtering criteria as a WHERE clause

PRINT @CMD  --  to check the code generated

-- EXEC SP_EXECUTESQL @CMD ***UNCOMMENT WHEN READY***

In light of you adding the reason for your needs, I would seriously reconsider my model. Instead of having n tables, (1 per subject\class) - a more suitable model would be to keep all homogeneous data in the same table.
CREATE TABLE Class
(
    ClassID     INT,
    YearOfClass INT,
    ...
    ...
    ClassSubject    VARCHAR(50) -- This could be an FK to a ClassSubject Table
)

Where ClassSubject is populated with values 'Algebra 101', 'Algebra 102' etc...
This will save you from having to create tables every time a new subject is added - and having to adjust all your stroed procs accordingly. Amoung many other benefits, aggregations also become simpler.


text:
Q: Auto Panning to Cursor Position using ArcGIS API for JavaScript Does anyone know if it's possible using the ArcGIS JS API to make it so the map auto-pans based on the user's cursor position if they get within a close distance to the edge of the map viewing area?
This would allow the user to continue editing and not have to do some other action (such arrow keys, or a pan icon) to get the map to pan to an area they want to continue to edit in.  I've been looking for some examples of this and I can't seem to find any.

A: Here's an example of a simple way to do this:  http://jsbin.com/IsokUWEV/1/edit
The map will pan when you get within ten pixels of an edge.


text:
Q: PHP Form checkbox question I have a form that takes the following inputs:
Name: IBM
Surface(in m^2): 9
Floor:      (Checkbox1)
Phone:    (Checkbox2)
Network:  (Checkbox3)
Button to send to a next php page.
All those values above are represented in a table when i press the submit button.
The first two (name and surname) are properly displayed in the table.
The problem is with the checkboxes.  If i select the first checkbox the value in the table should be presented with 1.  If its not selected the value in the table should be empty.
 echo "$Name	"; // works properly
 echo "$Surface	"; // works properly
 echo "....no idea for the checkboxes	;

Some part of my php code with the variables:
<?php
if (!empty($_POST))
{
$name= $_POST["name"];
$surface= $_POST["surface"];
$floor= $_POST["floor"];
$phone= $_POST["telefoon"];
$network= $_POST["netwerk"];

if (is_numeric($surface))
{
    $_SESSION["name"]=$name;
    $_SESSION["surface"]=$surface;
    header("Location:ExpoOverzicht.php");
}
else
{
    echo "
Wrong input, Pleasee fill in again
";
}

if(!empty($floor) && ($phone) && ($network))
{
    $_SESSION["floor"]=$floor;
    $_SESSION["phone"]=$phone;
    $_SESSION["network"]=$network;
    header("Location:ExpoOverzicht.php");
}
}

?>

Second page with table:
<?php

$name= $_SESSION["name"];
$surface= $_SESSION["surface"];
$floor= $_SESSION["floor"];
$phone= $_SESSION["phone"];
$network= $_SESSION["network"];

echo "
";

echo "name	";
echo "surface	";
echo "floor	";
echo "phone	";
echo "network	";
echo "total price	";

for($i=0; $i <= $_SESSION["name"]; $i++)
{
    echo "
";

        echo "$name	"; // gives right output
        echo "$surface	"; // gives right output
        echo "...	"; //wrong output (ment for checkbox 1)
        echo "...	"; //wrong output (ment for checkbox 2)
        echo "...	"; //wrong output (ment for checkbox 3)
        echo "....	";

    echo "
;";
}
echo "
";

<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" id="form1">

Vul de gegevens in

        Name:
        <input type="text" name="name" size="18"/>

        Surface(in m^2):
        <input type="text" name="surface" size="6"/>

        Floor:
        <input type="checkbox" name="floor" value="floor"/>

        Phone:
        <input type="checkbox" name="phone" value="phone"/>

        Network:
        <input type="checkbox" name="network" value="network"/>

        <input type="submit" name="verzenden" value="Verzenden"/>

There might be a few spelling mistakes since i had to translate it.
Best regards.

A: Instead of directly assigning your checkbox variables, see if they have been checked or not first.
$verdieping = isset($_POST["floor"]) ? $_POST["floor"] : 0;
$telefoon = isset($_POST["telefoon"]) ? $_POST["telefoon"] : 0;
$netwerk = isset($_POST["netwerk"]) ? $_POST["netwerk"] : 0;

This way, if the user hasn't ticked a checkbox, you have a value of '0' assigned to it instead of an undefined variable.

A: If you declare a checkbox with:
<input type="checkbox" name="mycheckbox" value="1">

you can check the value after submitting the form by:
if(!empty($_POST["mycheckbox"])) {
    // checkbox was checked
}
else {
    // checkbox was not checked
}

A: In this php page you can write like this, it may be solution of your question
if (!empty($_POST))
{
$standnaam = $_POST["name"];
$oppervlakte = $_POST["surface"];
$verdieping = $_POST["floor"];
$telefoon = $_POST["telefoon"];
$netwerk = $_POST["netwerk"];

if (is_numeric($oppervlakte))
{
    $_SESSION["name"]=$standnaam;
    $_SESSION["surface"]=$oppervlakte;
    header("Location:ExpoOverzicht.php");
}
else
{
    echo "
Wrong input, Pleasee fill in again
";
}

if(!empty($verdieping) && ($telefoon) && ($netwerk))
{
    $_SESSION["floor"]=$verdieping;
    $_SESSION["phone"]=$telefoon;
    $_SESSION["network"]=$netwerk;
    header("Location:ExpoOverzicht.php");
}
}


text:
Q: Failed to create job with prefix beam_bq_job_LOAD while writing to bigquery Apache Beam dataflow? When I run my pipeline that writes data to bigquery, I got this error:
Error message from worker: java.lang.RuntimeException: Failed to create job with prefix beam_bq_job_LOAD_campaignprocessinguser10311348175a423790_5ed64e7c6f85472190b06e6791e16333_55b5a9b937ae9d5800e61ae94bab532c_00001_00000, reached max retries: 3, last failed job: null.
    org.apache.beam.sdk.io.gcp.bigquery.BigQueryHelpers$PendingJob.runJob(BigQueryHelpers.java:200)
    org.apache.beam.sdk.io.gcp.bigquery.BigQueryHelpers$PendingJobManager.waitForDone(BigQueryHelpers.java:153)
    org.apache.beam.sdk.io.gcp.bigquery.WriteTables$WriteTablesDoFn.finishBundle(WriteTables.java:378)