text:
Q: Mix count and exist in one query Suppose that we have a table and save on it customerid and orderid.
What is the best approach for take count of all order and check exist of certain customerid in one query ?
I know that this query is wrong but I forced write that because Stackoverflow did not allow me post short question!
For example :
(table name tbTest)
SELECT
    COUNT(ORDERID),
    EXIST(SELECT ID FROM tbTest WHERE customerid = {n})
FROM tbTest

A: Did you mean
SELECT CustomerID, COUNT(OrderID)
FROM dbo.tbTest
GROUP BY CustomerID;

Or maybe
DECLARE @CustomerID INT;

SET @CustomerID = 20;

SELECT COUNT(*)
FROM dbo.tbTest
WHERE CustomerID = @CustomerID;

A: Please try with the follwoing
SELECT  COUNT(ORDERID),
        CASE
            WHEN EXISTS(SELECT ID FROM tbTest WHERE customerid = {n}) then 'Exist'
            ELSE 'Not Exist'
        END
FROM tbTest


text:
Q: Putting a background on the linear layout and takes almost 3/4 of the screen I have tried all kinds of help from other posts (setting widths to 0dp etc.) but nothing seems to work.
I have 2 layouts and the first one still seems to dominate. If I put background colors on the textviews, they are behaving themselves and end correctly. However put a background on the linear layout and it is almost 3/4 of the screen!?
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:id="@+id/rowkRow"
    android:background="@color/RowBkgColor" android:gravity="center_vertical"
    android:minHeight="60dp">
    <ImageView android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:id="@+id/rowleftImage"
        android:padding="3dip" android:gravity="left" android:layout_weight="0" />

    <LinearLayout android:orientation="vertical"
        android:layout_weight="0" android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:id="@+id/rowtext1"
            android:padding="3dip" android:gravity="left" android:typeface="sans"
            android:textStyle="bold" android:text="First Text" android:textSize="40dp"
            android:textColor="#FF333344" android:visibility="visible"
             />
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:id="@+id/rowtext3"
            android:padding="3dip" android:gravity="center" android:typeface="sans"
            android:textStyle="bold" android:text="First Text" android:textSize="10dp"
            android:textColor="#FF333344" android:visibility="visible"
            android:background="#606060"
             />
    </LinearLayout>

    <LinearLayout android:orientation="vertical"
        android:layout_weight="1" android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:id="@+id/rowtext4"
            android:padding="3dip" android:gravity="right" android:text="Fourth Text"
            android:textSize="10dp" android:textStyle="bold" android:textColor="@color/RowTextColor"
            android:visibility="visible" />
        <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:id="@+id/rowtext2"
            android:padding="3dip" android:gravity="left" android:text="Second Text"
            android:textSize="17dp" android:textStyle="bold" android:textColor="@color/RowTextColor"
            />
    </LinearLayout>

    <ImageView android:id="@+id/rowrightImage"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:padding="3dip" android:layout_weight="0" android:gravity="right" />
</TableRow>

A: Do the following things. U can solve your problem.

*

*set the android:layout_width of the children to "0dp"

*set the android:weightSum of the parent

*set the android:layout_weight of each child proportionally (e.g. weightSum = "5", three children: layout_weight="1", layout_weight="3", layout_weight="1")

redpajama_set_name: RedPajamaStackExchange


text:
Q: Difference between bash-script and cocoa code with OpenSSL I try get SHA1-sugnature with bash-script and cocoa-code.
Bash-script:
echo -n "RF001" | openssl dgst -sha1

gives me:
3eb0c58821e30a235a402308acff357e6f3d9f41

Cocoa:
const unsigned char buffer[] = "RF001";
size_t buffer_size = sizeof(buffer);

uint8_t md[SHA_DIGEST_LENGTH];
SHA1(buffer, buffer_size, md);

NSData* data = [NSData dataWithBytes:md length:SHA_DIGEST_LENGTH];
NSLog([data description], nil);

writes to console:
<3ab9d9cc ece56e3f 48d00c3f f2a9216a 5b74bbce>

Why are not these two results same?

A: It was error in Cocoa-snippet.
There is good code:
const char* buffer = "RF001";

uint8_t md[SHA_DIGEST_LENGTH];
SHA1((uint8_t*)buffer, strlen(buffer), md);

NSData* data = [NSData dataWithBytes:md length:SHA_DIGEST_LENGTH];
NSLog([data description], nil);


text:
Q: Change GRUB2 boot device I have a MacBook Pro, and I use rEFIned to dual-boot Ubuntu and Mac OS X. In case I ever messed anything up, I installed Ubuntu on an external hard drive. However, I messed up the setup so I installed GRUB onto the hard drive. Now when I boot GRUB without my external hard drive connected, GRUB goes into grub rescue with "Cannot find device." I can still boot any of my OSes if the hard drive is plugged in.
How can I fix this? Will uninstalling GRUB from the hard drive help, or do I have to configure rEFIned differently?

A: If I understand your setup, GRUB is useless unless the external hard disk is plugged in, so the easiest and safest solution is simply to ignore the Linux/GRUB entry in rEFInd when the external disk is disconnected. If there's some reason why this is undesirable or impossible, please elaborate.


text:
Q: How to determine on which side of the wall object is placed? I can't seem to figure out how to detect on which side of the wall object is placed.
When z axis is positive it works fine in both cases (left side wall and bottom wall)
Image of the situation
But when object is placed on right side wall or top wall the z axis value should be negative for it to be in the room and that's what I can't figure out. How to determine on which side of the wall the object is?
Image of the situation
And here's the code that I'm using to place the object
private void placeObjectToWall(GameObject obj){
        GameObject wall = getRandomGameObject (walls);
        obj.transform.parent = wall.transform;
        float forward = 0;
        if(wall.transform.rotation.y%180!=0){
            forward = obj.transform.localScale.x/2;
        }else{
            forward = obj.transform.localScale.z/2;
        }
        obj.transform.localPosition = new Vector3(0,0,forward);
}

A: For determine the side to the left or right wall, you can make a Vector3 from the center of your object to the center the right wall and other Vector3 from the center of your object to the center the left one.
If these Vector3 has the same direction, the object is outside the walls, but if they don't have the same direction, the object is inside the walls.
For determine the side to ceiling and floor walls, you can do the same but with these walls, with the same conclusions.
Here you have these vector representations on your images.

Note that when I say "the same direction" I mean that these vectors are both positive or negative, not that the are the same.


text:
Q: Does chemical bonding decrease the entropy of the universe? I have read in many credible texts ( including "a brief history of time" ) that nature always increases entropy, that is, the entropy in the universe increases. But I learnt that atoms and molecules form bonds to attain stability by filling their orbitals.
So doesn't this violate that entropy should always increase. I mean if all the atoms are trying to attain stability ( order ) then why does entropy ( chaos ) increase?

A: The formation of chemical bonds releases energy, which heats the universe, which increases its total entropy more than enough to compensate.
As an example, consider the oxidation of aluminum (Al) in air, which occurs essentially immediately. Every chunk of aluminum you've ever seen has been coated with an oxidized layer (alumina, $\mathrm{Al}_2\mathrm{O}_3$) with a thickness of at least a few nanometers. But, as you imply, why would the oxidation reaction
$$4\mathrm{Al}+3\mathrm{O}_2\to 2\mathrm{Al}_2\mathrm{O}_3,$$
occur spontaneously? After all, it involves the conversion of oxygen gas to a solid, which requires a notable decrease in entropy (630 J/K per mole of product; gases carry a lot of entropy because the molecules are free to move around with a variety of positions and speeds).
The resolution is that the reaction is an exothermic one that heats things up (the sample and the surrounding environment). That is, the bonds release energy as they form. The formation of alumina releases about 1700 kJ for the same mole of product, which heats the sample and its surroundings, which in turn increases their entropy (by around 5600 J/K) because the molecules can assume a wider range of positions and speeds. As a result, the general rule of total entropy maximization for all spontaneous processes still holds true.

A: All the statements about the entropy of the universe share a common problem: there is no way to measure such a quantity (to check this statement, try to list all the known experimental methods to measure entropy differences and you can decide if they could be applied to the entire universe). Even the theoretical definition is not very easy. There are many definitions of entropy, from thermodynamics, from statistical mechanics, from information theory, from theory of complexity, from dynamical system theory, ... and they are not all equivalent or they become equivalent only under additional conditions.  Which one could be  applied to the universe? And one is speeking about the equilibrium entropy or some non-equilibrium extension of the concept? The former looks questionable, unless one is convinced that we live in a universe at equilibrium. The latter goes back to the problem of which definition to use.
In thermodynamics people are used to speak about a "thermodynamical" universe which is the union of a particular system plus the surrounding environment, provided such environment could be well characterized from the thermodynamic point of view. For example, system+environment could be an  isolated system. Such thermodynamic "universe" is less problematic as the whole known universe.
Much more on the earth, the presence of ordered structures in interacting systems is not in contradiction with the principle of increase of entropy, once one remembers that such principle is valid only for an isolated system at fixed energy, volume and number of particles. Under such constraints it is possible to find macrostates where the majority of the underlying microstates corresponds to ordered configurations.


text:
Q: Why does NSCalendar have two init methods with similar parameter types that accepts one of the calendar identifier constants? Why does NSCalendar have two init methods with similar parameter types that both accept one of the calendar identifier constants?  What is the point of having two init methods that do the exact same thing?  Does anyone know the reasoning behind why Apple would add this information to the documentation this way or why the class is even created this way?
Here is the first init method:
init?(calendarIdentifier ident: String)

Here is the second init method:
init?(identifier calendarIdentifierConstant: String)

Link to Apple's NSCalendar Class Reference

A: That seems to be a bug in the Swift 2 import of the Objective-C interface.
In Objective-C there are – at it is usual with Foundation classes –
both a instance method
- (id)initWithCalendarIdentifier:(NSString *)string
// Initializes a newly-allocated NSCalendar object for the calendar specified by a given identifier.

and a class (factory method):
+ (NSCalendar *)calendarWithIdentifier:(NSString *)calendarIdentifierConstant
// Creates and returns a new NSCalendar object specified by a given identifier.

and the following two statements are (almost) equivalent:
NSCalendar *cal = [[NSCalendar alloc] initWithIdentifier:@"..."];
NSCalendar *cal = [NSCalendar calendarWithIdentifier:@"..."];

In Swift there are only initializers, and both should be mapped
to the same Swift initializer (as it is the case with other Foundation
classes). Apparently that does not work correctly, but the result
is identical:
let cal1 = NSCalendar(calendarIdentifier: NSCalendarIdentifierChinese)
let cal2 = NSCalendar(identifier: NSCalendarIdentifierChinese)
print(cal1 == cal2) // true

In Swift 3 there is only one initializer, taking an NSCalendar.Identifier
parameter:
let cal = NSCalendar(identifier: .chinese)

(or the new value type
let cal = Calendar(identifier: .chinese)

which takes an enumeration parameter).

A: In Objective-C, there are two renditions, calendarWithIdentifier convenience method that returns autorelease object and initWithCalendarIdentifier that returns a +1 object. The distinction of the autorelease object and the +1 object has little practical implication nowadays (and really only comes into play if you were allocating and releasing many of them inside a loop, which you're unlikely to be doing with this class).
In Swift, they both resolve to init?, the first with a parameter called identifier and the other whose parameter is calendarIdentifier.
Note, in Swift 3, this confusion is eliminated, both converted to init?(identifier:).


text:
Q: How to print elements of a 2D array with different lengths in an aligned manner? I have a 2-D array:
board_grid = [
    ["4",     "167",    "2",    "5",  "167",  "16",   "3",   "8",  "9"  ],
    ["13789", "13789",  "3789", "79", "4",    "189",  "2",   "6",  "5"  ],
    ["89",    "689",    "5",    "2",  "3",    "689",  "1",   "4",  "7"  ],
    ["389",   "389",    "1",    "6",  "5",    "2",    "48",  "7",  "48" ],
    ["6",     "78",     "78",   "1",  "9",    "4",    "5",   "3",  "2"  ],
    ["2",     "5",      "4",    "3",  "8",    "7",    "6",   "9",  "1"  ],
    ["5",     "246789", "6789", "79", "267",  "3",    "478", "1",  "468"],
    ["1378",  "123678", "3678", "4",  "1267", "156",  "9",   "25", "68" ],
    ["179",   "124679", "679",  "8",  "1267", "1569", "47",  "25", "3"  ]
]

I want to transform this array into a string, such that all elements are displayed as the same as above (i.e., each element of the same row/column are perfectly aligned). The square brackets, double quotes, commas don't necessarily have to be printed. Just newlines and whitespaces are enough to make each element distinguishable.
I actually want to display this string in the alert block.
The attempt I have tried:
function board_grid_to_display_string(board_grid) {
    var V_PADDING = " "; // Insert after each square
    var H_PADDING = '\n'; // Insert after each row
    var V_BOX_PADDING = "  "; // Box vertical padding
    var H_BOX_PADDING = '\n'; // Box horizontal padding

    var display_string = "";
    var i = 0;

    for (var r = 0; r < 9; ++r) {
        for (var c = 0; c < 9; ++c) {
            var square = board_grid[r][c];
            // Add the square and vertical padding
            display_string += square + V_PADDING;
            // Vertical edge of a box, insert vertical box padding
            if (i % 3 === 2) {
                display_string += V_BOX_PADDING;
            }
            // End of a line, insert horizontal padding
            if (i % 9 === 8) {
                display_string += H_PADDING;
            }
            // Horizontal edge of a box, insert horizontal box padding
            if (i % 27 === 26) {
                display_string += H_BOX_PADDING;
            }
            i++;
        }
    }

    return display_string;
}

A: Following flattens the whole array to reduce down the longest string length then uses String.proptotype.padEnd() to add extra spaces as needed.
The outer map is joined with the line break and the inner map pads each element and is joined with a single space between each column. You can adjust as needed

// get maximum element string length
const mLen = grid.flat().reduce((a,c) => Math.max(c.length,a), 0);

const res = grid.map(arr => arr.map(s => s.padEnd(mLen,' ')).join(' ')).join('\n')

console.log(res)
<script>
const grid = [
    ["4",     "167",    "2",    "5",  "167",  "16",   "3",   "8",  "9"  ],
    ["13789", "13789",  "3789", "79", "4",    "189",  "2",   "6",  "5"  ],
    ["89",    "689",    "5",    "2",  "3",    "689",  "1",   "4",  "7"  ],
    ["389",   "389",    "1",    "6",  "5",    "2",    "48",  "7",  "48" ],
    ["6",     "78",     "78",   "1",  "9",    "4",    "5",   "3",  "2"  ],
    ["2",     "5",      "4",    "3",  "8",    "7",    "6",   "9",  "1"  ],
    ["5",     "246789", "6789", "79", "267",  "3",    "478", "1",  "468"],
    ["1378",  "123678", "3678", "4",  "1267", "156",  "9",   "25", "68" ],
    ["179",   "124679", "679",  "8",  "1267", "1569", "47",  "25", "3"  ]
]

</script>

A: I don't think that's the best idea but

*

*Get the greatest number

*Count how many digit have this number

*for each value in your array -> add many space in string

For your exemple, your greatest number is 246789 so it have 6 digits.
Take any number in array like 48 (it have 2 digits)
6 - 2 = 4
Add 4 spaces before this value

A: You could pad the strings after geeting the max length of each column.

const
    board_grid = [["4", "167", "2", "5", "167", "16", "3", "8", "9"], ["13789", "13789", "3789", "79", "4", "189", "2", "6", "5"], ["89", "689", "5", "2", "3", "689", "1", "4", "7"], ["389", "389", "1", "6", "5", "2", "48", "7", "48"], ["6", "78", "78", "1", "9", "4", "5", "3", "2"], ["2", "5", "4", "3", "8", "7", "6", "9", "1"], ["5", "246789", "6789", "79", "267", "3", "478", "1", "468"], ["1378", "123678", "3678", "4", "1267", "156", "9", "25", "68"], ["179", "124679", "679", "8", "1267", "1569", "47", "25", "3"]],
    alignment = 'padEnd',
    sizes = board_grid.reduce((r, a) => a.map((v, i) => Math.max(v.length, r[i] || 0)), []),
    result = board_grid.map(a => a.map((s, i) => s[alignment](sizes[i])));

result.forEach(a => console.log(...a));
.as-console-wrapper { max-height: 100% !important; top: 0; }


text:
Q: Navigation bar with large title shrinks when webview is loaded In viewcontroller, I'm loading a webview(WKWebview) with large navigation title enabled. The problem is its showing the large navigation bar and title perfectly before the webview gets loaded once the webview got loaded it shrinks to normal. Anyhelp would be appreciated.
Thanks in advance...!

A:
Swift4, Swift5 :

*

*The reason of this issue is your navigationBar height is changing when you webView starts loading the page. so using viewLayoutMarginsDidChange() we can change navigationBar height.

*viewLayoutMarginsDidChange() Called to notify the view controller that the layout margins of its root view changed. This method will get called every time when navigationBar height changes.

Below code worked for me
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {

    private var webView: WKWebView!
    var didChange = false //Set true when we have to update navigationBar height in viewLayoutMarginsDidChange()

    override func viewLayoutMarginsDidChange() {
        if didChange {
            print("Height : - \(self.navigationController?.navigationBar.frame.size.height)")
        // set NavigationBar Height here
           self.navigationController!.navigationBar.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 96.0)
            didChange.toggle()
            }
        }

    override func viewDidLoad() {
        super.viewDidLoad()

    let appearance = UIBarButtonItem.appearance()
    appearance.setBackButtonTitlePositionAdjustment(UIOffset.init(horizontal: 0.0, vertical: -60), for: .default)

    self.navigationItem.title = "WebView"
    self.navigationController?.navigationBar.isTranslucent = true
    self.navigationController?.navigationBar.tintColor = UIColor.black
    self.navigationController?.navigationBar.prefersLargeTitles = true

    webView = WKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height))
    webView.navigationDelegate = self
    view = webView

    let myURL = URL(string:"https://google.com")
    let myRequest = URLRequest(url: myURL!)
    webView.load(myRequest)

    }

    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        print("Did Start")
      //webView page starts loading
        didChange = true
    }

}

A: This solution works for me, but instead of using
self.navigationController!.navigationBar.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 96.0)

We could use:
self.navigationController?.navigationBar.sizeToFit()

A: Simple solution that works for me
override func viewLayoutMarginsDidChange() {
    guard !webView.isLoading else { return }
    navigationController?.navigationBar.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: 96.0)
}


text:
Q: d3 - Using D3 v3 and D3 v4 on the same page Following from this guide: https://chewett.co.uk/blog/2021/how-to-load-multiple-d3-versions-at-once/ , I have imported D3 v3 and D3 v4 into my project (please note as well, I am using Yesod)
<script src="https://d3js.org/d3.v4.js">
<script>
  d3v4 = window.d3;
  window.d3 = null;
<script src=https://d3js.org/d3.v3.min.js">
<script>
  d3v3 = window.d3;

I am trying to draw both of the following graphs on the page:
https://www.d3-graph-gallery.com/graph/histogram_basic.html
https://www.d3-graph-gallery.com/graph/pie_basic.html
In the script, I have changed references from d3 to d3v4 for the Histogram, and d3v3 for the Pie Char.
Histogram
var svg = d3v4.select("#my_dataviz")
   .append("svg")
     .attr("width", width + margin.left + margin.right)
     .attr("height", height + margin.top + margin.bottom)
   .append("g")
     .attr("transform",
           "translate(" + margin.left + "," + margin.top + ")");

 // get the data
 d3v4.csv("https://raw.githubusercontent.com/holtzy/data_to_viz/master/Example_dataset/1_OneNum.csv", function(data) {
...

Pie Chart
var svg = d3v3.select("#piechart")
    .append("svg")
    .append("g")

svg.append("g")
    .attr("class", "slices");
svg.append("g")
    .attr("class", "labels");
svg.append("g")
    .attr("class", "lines");

var width = 960,
    height = 450,
    radius = Math.min(width, height) / 2;

var pie = d3v3.layout.pie()
    .sort(null)
    .value(function(d) {
        return d.value;
    });
...

Here is a pastebin of the full Javascript document https://pastebin.com/TLV3eFpf
My issue is, when I run this file, I get the following error (the histogram is not rendered, but the pie chart is):
Uncaught TypeError: path.merge is not a function
    axis https://d3js.org/d3.v4.js:623
    call https://d3js.org/d3.v3.min.js:3
    <anonymous> http://localhost:3000/static/tmp/autogen-zMHMAOmj.js:1
    fixCallback https://d3js.org/d3.v4.js:11497
    send https://d3js.org/d3.v4.js:11470
    call https://d3js.org/d3.v4.js:792
    respond https://d3js.org/d3.v4.js:11395

Would anyone be able to help me out?


text:
Q: Problem: fixed-effect model matrix is rank deficient so dropping (time-series analysis) I have struggled with this statistical analysis.
My dataset is 5 replicates of plot, Mon to Fri of date, C or T of treat, and separated time (ex, Mon to Wed as beginning of week, Thu as end of week, and Fri as very end of week). There is dependant variable in v1 column.
What I want to test is whether treatment effect is significant depending on time, and also date effect.
Here are reproducible codes.
data <- data.frame("v1" = rnorm(100)) #generate data
data$plot <- as.factor(rep(1:5,10)) #add plot as random effect
data$date <- as.factor(rep(c("Mon","Tue","Wed","Thu","Fri"),each = 20)) #date
data$time <- as.factor(rep(c(1,1,1,2,3), each = 20)) #time
data$treat <- as.factor(rep(c("C","T"), 50)) #treatment

summary(lmer(v1 ~ treat*date*time + (1|plot), data))

Summary returns this error message:
fixed-effect model matrix is rank deficient so dropping 20 columns / coefficients
Anova(lmer(v1 ~ treat*date*time + (1|plot), data))

Check the effect by running Anova function:
There is no value in time and interactive effect of time
fixed-effect model matrix is rank deficient so dropping 20 columns / coefficients
Analysis of Deviance Table (Type II Wald chisquare tests)

Response: v1
                 Chisq Df Pr(>Chisq)
treat           0.0063  1     0.9370
date            4.2765  4     0.3699
time                    0
treat:date      2.8640  4     0.5808
treat:time              0
date:time               0
treat:date:time         0

I'm trying to find the reason why this has happened, but I'm not so sure what the problem is.
It seems model structure error or the way what I'm doing is wrong.
Has anyone idea? I don't have a strong statistical background, so I feel so lost in this analysis.
Thanks for your help!


text:
Q: Handling bad lines in bigquery I am using the google.bigquery.python api in order to automatically load a dataset from a GCS bucket to Bigquery on a daily basis. I specified a schema for this dataset and it worked untill I had one day this error:
ERROR - {u'state': u'DONE', u'errors': [{u'reason': u'invalid', u'message': u'Invalid argument: xxxxxxxxxxx@gmail.com', u'location': u'File: 0 / Line:1283011 / Field:44'},
{u'reason': u'invalid', u'message': u'Invalid argument: xxxxxxxxxxx@gmail.com', u'location': u'File: 0 / Line:1338016 / Field:44'}, {u'reason': u'invalid', u'message': u'Too many errors encountered. Limit is: 0.'}], u'errorResult': {u'reason': u'invalid', u'message': u'Too many errors encountered. Limit is: 0.'}}

My question is: how can I tell bigquery to delete automatically lines which don't fit the schema?

A: Sorry can't comment on Paul's answer as I have less than 50 reputations.
Re: whether setting this positive lets bad rows into the data or only ignores and suppresses the error
The bad rows will be ignored and will not go into the loaded data.

A: If you are using the bq command line client, the option is --max-bad-records.  This tells BQ how many bad records to ignore before failing a load job. The default is zero. I don't recall whether setting this positive lets bad rows into the data or only ignores and suppresses the error.  You might want to manually test it.
From: https://cloud.google.com/bigquery/bq-command-line-tool

--max_bad_records Type: integer Description: The maximum number of bad rows to skip before the load job is aborted and no updates are
  performed. If this value is larger than 0, the job will succeed as
  long as the number of bad records do not exceed this value. This is
  useful if you would like to load files that may have bad records. The
  default value for this parameter is 0 (all rows are required to be
  valid).
Valid Values: Any integer
Usage: bq load --max_bad_records=3 <destination_table> <data_source_uri> [<table_schema>]

In the python API this field is called maxBadRecords.  You can search for maxBadRecords in the python BigQuery API repo on Github and you'll see it is in the jobs API configuration for a load job.


text:
Q: Sorting multidimensional array by key alphabetically Trying to sort by this multidimensional array by screen name:
//Looping through this for each member of a group
unset($member_info);
$member_info->id           =   $member->id;
$member_info->screen_name  =   $member->screen_name;
$member_info->first_name   =   $member->first_name;
$member_info->last_name    =   $member->last_name;
$member_info->email        =   $member->email;

//Sort member_info by screen name
$member_array = sort_by_array_key($member_info,$member_info->screen_name,'ASC');
$member_list[] = $member_array;

Sort function:
function sort_by_array_key($array,$sort_key,$dir = 'ASC') {
    usort($array, function($a,$b) use ($sort_key){
        return strnatcasecmp($a["$sort_key"], $b["$sort_key"]);
    });
    if ( $dir == 'DESC' ) { return array_reverse($array); }
    else { return $array; }
}

As an example, screen names are currently in this order even after I run the sort function:
newUser
Chris
Carlos
Jason

I am probably applying the sort at the wrong time but after looking at other similar examples here I was having trouble with this, any help is appreciated, thanks!

A: First of all, you're sorting an individual item there, where you probably want to sort the actual list, $member_list. Also, you're trying to sort an array where you initialize an object. Either initialize an array or sort an object.
If I assume you really want to play with arrays, like you imply on the subject, this might be something you're trying to do:
<?php

$member_info = Array();
$member_info['id']           =   '1';
$member_info['screen_name']  =   'Chris';
$member_info['first_name']   =   '';
$member_info['last_name']    =   '';
$member_info['email']        =   '';

$member_list[] = $member_info;

$member_info = Array();
$member_info['id']           =   '2';
$member_info['screen_name']  =   'Carlos';
$member_info['first_name']   =   '';
$member_info['last_name']    =   '';
$member_info['email']        =   '';

$member_list[] = $member_info;

$member_info = Array();
$member_info['id']           =   '3';
$member_info['screen_name']  =   'Jason';
$member_info['first_name']   =   '';
$member_info['last_name']    =   '';
$member_info['email']        =   '';

$member_list[] = $member_info;

//Sort member_list by screen name
$member_list = sort_by_array_key($member_list,'screen_name','ASC');

function sort_by_array_key($array,$sort_key,$dir = 'ASC') {
    usort($array, function($a,$b) use ($sort_key){
        return strnatcasecmp($a["$sort_key"], $b["$sort_key"]);
    });
    if ( $dir == 'DESC' ) { return array_reverse($array); }
    else { return $array; }
}

print_r($member_list);

/*
Array
(
    [0] => Array
        (
            [id] => 2
            [screen_name] => Carlos
            [first_name] =>
            [last_name] =>
            [email] =>
        )

    [1] => Array
        (
            [id] => 1
            [screen_name] => Chris
            [first_name] =>
            [last_name] =>
            [email] =>
        )

    [2] => Array
        (
            [id] => 3
            [screen_name] => Jason
            [first_name] =>
            [last_name] =>
            [email] =>
        )

)
*/

A: ksort - "Sorts an array by key, maintaining key to data correlations. This is useful mainly for associative arrays."
See the manual


text:
Q: Server to client message not getting delivered Client code
  #include  <stdio.h>
#include    <stdlib.h>
#include    <netinet/in.h>
#include    <arpa/inet.h>
#include    <sys/socket.h>
#include    <string.h>
#include    <time.h>
#define     MAX 1024
int main ( int argc, char ** argv)
{

    printf("Check point 1\n");
    if (argc != 2)
    {
        printf("Error!! Provide a correct port\n");
        exit (0);
    }

    unsigned char buff[MAX];
    int port = atoi(argv[1]);
    int sockfd;
    struct sockaddr_in myAddr, Addr;
    unsigned char temp[MAX];
    char buffer [MAX];

    socklen_t addr_size;
    addr_size = sizeof(Addr);

    //_os_getime();
    printf("Check point 2\n");
    if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0))< 0)
    {
        printf ( "%d", sockfd);
            perror("socket failed");
            exit(EXIT_FAILURE);
    }

    memset(&myAddr,'\0', sizeof(myAddr));
    myAddr.sin_family = AF_INET;
    myAddr.sin_port = htons(port);
    myAddr.sin_addr.s_addr =inet_addr("127.0.0.1");

    printf ("Check point 3");
    strcpy(buff, "ABCDE\n");
    if((sendto(sockfd, buff, MAX, 0 , (struct sockaddr*) &myAddr, sizeof(myAddr)))<0)
    {
        perror("Sending failed--");
            exit(EXIT_FAILURE);

    }

    printf ("Check point 4");

    if((recvfrom(sockfd, buffer, sizeof(buffer), 0 , (struct sockaddr*) &Addr, &addr_size))<0)
    {
        perror("Receiving failed");
            exit(EXIT_FAILURE);
    }

    printf ( "%s", buff);

    close(sockfd);
    return 0;

}

Server Code
#include    <stdio.h>
#include    <stdlib.h>
/*
#include    <modes.h>
#include    <events.h>
#include    <process.h>
#include    <alarm.h>
#include    <signal.h>
#include    <module.h>
#include    <sg_codes.h>
#include    <sgstat.h>
#include    <sys/types.h>
*/
#include    <netinet/in.h>
#include    <arpa/inet.h>
#include    <sys/socket.h>
#include    <string.h>
#include    <time.h>
#define     MAX 1024

int main (int argc, char ** argv)
{
    if (argc != 2)
    {
        printf("Error!! Provide a correct port\n");
        exit (0);
    }

    int port = atoi(argv[1]);
    char buff[MAX];
    char buffer [MAX];
    int sockfd, clientfd;
    struct sockaddr_in myAddr, Addr;

    socklen_t addr_size;

    if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0))< 0)
    {
        printf ( "%d", sockfd);
            perror("socket failed");
            exit(EXIT_FAILURE);
    }

    memset(&myAddr,'\0', sizeof(myAddr));
    myAddr.sin_family = AF_INET;
    myAddr.sin_port = htons(port);
    myAddr.sin_addr.s_addr =inet_addr("127.0.0.1");
    if ((bind (sockfd, (struct sockaddr*) &myAddr, sizeof(myAddr)))<0)
    {
        perror("Binding failed");
            exit(EXIT_FAILURE);
    }

    addr_size = sizeof(Addr);

    int recv = recvfrom(sockfd, buff, MAX, 0 , (struct sockaddr*) &Addr, &addr_size);
    printf ( "%s", buff);

    strcpy(buffer, "EFGH");
    if((sendto(sockfd, buffer, MAX, 0 , (struct sockaddr*) &myAddr, sizeof(myAddr)))<0)
    {
        perror("Sending failed");
            exit(EXIT_FAILURE);

    }
    close(sockfd);

    return 0;
}

This is a simple code on socket programming
When I am starting the server and then the client, the message ABCDE is sent to server and message is getting printed at the server and the server is getting terminated.
But at the client side the code is not getting terminated and getting executed only till checkpoint 2. I am not understanding why checkpoint 3 is not getting printed even though the next line is working.
And ofcourse, the message from server to client is also not getting printed


text:
Q: MySQL workbench crashes whenever I try and access a table I'm trying to learn how to use MySQL. I installed the latest version of MySQL and MySQL workbench, however every time I try and access a table I've made the app immediately just crashes. The error report makes no sense to me.
I'm using a macbook air m1 and I've double checked I have the correct versions installed.
Is this a common issue and does anyone have any suggestions?
Thanks
I was advised to try reinstalling MySQL, which I did and there was no improvement. I've tried restarting my machine, but I have no idea what to try other than that.


text:
Q: Using grep to display second character in string? I have a string that is always 3 characters... the first one and the last one are always the same.
example:
▁▅█
Is there a simple way to only display the one in the middle? (which is the only one that changes)

A: You could also use sed instead of grep:
sed 's/.\(.\)./\1/'

This says:

*

*s/ ... match the expression up to the next / character.

*. ... match the first character (any).

*\(.\) ... match the next character and remember it.

*. ... match the third character (any).

*/ ... denotes the end of the expression.

*\1 ... replace the entire string that matched with the character that was remembered.

*/ ... end of replacement text.

Thus:
$ echo "abc" | sed 's/.\(.\)./\1/'

Will print:
b

A: Yes, try doing this, and pick your preferred method =) :
With grep:
echo "ixi" | grep -oP "^.\K."

With cut:
echo "ixi" | cut -c2

With bash parameter expansion :
x='ixi'; echo ${x:1:1}

With sed:
echo "ixi" | sed 's/.\(.\)./\1/'

or
echo "ixi" | sed 's/\(^.\|.$\)//g'

With perl:
echo "ixi" | perl -lne 'print $& if /^.\K./'

With ruby:
echo "ixi" | ruby -ne 'print $_.split(//)[1]'

With awk:
echo 'ixi' | awk '{split($0, a, ""); print a[2]}'

With python:
echo "ixi" | python -c 'print list("'$(cat)'")[1]'

or
python -c 'import sys; print list(sys.argv[1])[1]' ixi

NOTE

*

*\K restart the match to zero (see pcre doc)

*$(cat) in python is a shell hack to get STDIN

A:         ︙
or
echo "ixi" | awk '{print substr($0,2,1)}'

or
expr "ixi" : '.\(.\).'

A: For variety, here's one way with dd:
echo ixi | dd bs=1 skip=1 count=1 2>/dev/null

If your grep doesn't support perl (-P), you could do it like this:
echo ixi | grep -o . | sed -n 2p

These alternatives only work for one-line input.

A: you can also do this way, by using the looking around technique,
so the second char "x" following the examples above using "ixi",
echo ixi | grep -oP "(?<=^.)."


text:
Q: _strset_s crashes The following code crashes while executing _strset_s I have given 80 as length in _strset_s. What could be the problem?. I enabled run time stack frame checkb option  /RTCs
char strToken[80];
_strset_s(strToken, 80, '\0' );

A: You can let the compiler do the filling by using
char strToken[80] = {0};

This will zero all the bytes of the string.

A: The input to _strset_s has to be null terminated according to MSDN. Since your string is not initialized to anything, it violates this invariant.

If str is a null pointer, or the size argument is less than or equal to 0, or the block passed in is not null-terminated, then the invalid parameter handler is invoked,

The default "invalid parameter handler" is to crash, again from MSDN:

The default invalid parameter invokes Watson crash reporting, which causes the application to crash and asks the user if they want to load the crash dump to Microsoft for analysis.

So I'd try Null terminating strToken first (or better yet do what Bo Persson suggests in his answer)
char strToken[80];
strToken[79] = '\0';
_strset_s(strToken, 80, '\0' );


text:
Q: Java-MyBatis with HQL/other generic SQL engine or an API to convert SQL I am working on a project which uses Activiti1 Library and, for these reason, I am using MyBatis API to execute some native queries against Activiti data base.
The problem is: For some builds I am using Oracle and, for other, MySQL database then, as the dialect of this two data bases is different, it would be necessary to use the MyBatis multi vendor support, however, I didn't like it, because I have to deal with specific statments of each type of data base which makes the maintance a hard task, mainly if necessary to add another data base in the future.
So I would like to know if somehow it is possible to use HQL together with MyBatis or if there are another generic SQL engine that can be used in this case.
Or if someone know a free Java API that converts MySQL queries to Oracle queries. I tried to use Hibernate translation, however it didn't work, because Activiti classes is not using JPA, so it is not mapped :(.
Thanks in advance!
Sandro

A: In Activiti, we do use the multi-vendor support of MyBatis. However, there are only a few cases where we really needed. Do you have that much 'special' queries?


text:
Q: SystemJS Setting(Vue.js + React.js + Pascal + php) Делаю проект. Как мне настроить SystemJS под:

*

*Vue.js

*React.js

*php

*Pascal
У меня есть вот такой код под React.js:
SystemJS.config({
  baseURL:'https://unpkg.com/',
  defaultExtension: true,
  packages: {
    ".": {
      main: './app.js',
      defaultExtension: 'js'
    }
  },
  meta: {
    '*.js': {
      'babelOptions': {
        react: true
      }
    }
  },
  map: {
    'plugin-babel': 'systemjs-plugin-babel@latest/plugin-babel.js',
    'systemjs-babel-build': 'systemjs-plugin-babel@latest/systemjs-babel-browser.js',
    'react': 'react@17.0.1/umd/react.development.js',
    'react-dom': 'react-dom@17.0.1/umd/react-dom.development.js'
  },
  transpiler: 'plugin-babel'
});

SystemJS.import('./app')
  .catch(console.error.bind(console));

Проблема в том что я не знаю как настроить под остальные,ещё хочу желательно чтобы у меня php тоже работал с SystemJS.


text:
Q: Jquery Autocomplete w/ Categories search, limited to Category chosen by user The jquery Autocomplete demo page with category shows the following :

I want the user to choose the category (Products or People) in a separate button (dropdown list), and then the jquery search to return only the matches in the category chosen by user.
Expected result :
screenshot 2
I am new to jquery, but according to my research I think this could be possible using "functions" as inputs, as said in the answer here (even though the question was different) :
Jquery UI Autocomplete: search from multiple attributes of one array
However I don't know what to do next.
My current code is the code from official doc :
<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete - Categories</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">

Search:
<input id="search">

A: Using the example data, there was a bit more work to be done to setup the data to work better for this. If you have control over the data format, you can prepare it before hand to work better.
Working example: https://jsfiddle.net/Twisty/uy5f2fta/
HTML
Search:
<select id="categories">
  <option value="none"></option>
</select>
<input id="search">

jQuery
var data = [{
  label: "anders",
  category: ""
}, {
  label: "andreas",
  category: ""
}, {
  label: "antal",
  category: ""
}, {
  label: "annhhx10",
  category: "Products"
}, {
  label: "annk K12",
  category: "Products"
}, {
  label: "annttop C13",
  category: "Products"
}, {
  label: "anders andersson",
  category: "People"
}, {
  label: "andreas andersson",
  category: "People"
}, {
  label: "andreas johnson",
  category: "People"
}];

$(function() {
  // Set Variables
  var cats = [],
    labels = {},
    sel = $("#categories"),
    search = $("#search");

  // Sift out specific Categories
  $.each(data, function(k, v) {
    if (v.category !== "") {
      cats.push(v.category);
      console.log("Found Cat: " + v.category);
    }
  });
  $.unique(cats);
  console.log("All Cats: ", cats);

  // Set Categories into Select element
  $.each(cats, function(k, v) {
    sel.append("<option value='" + v + "'>" + v + "</option>");
  });

  // Create Object of various data
  labels.none = [];
  $.each(cats, function(k, v) {
    labels[v] = [];
  });
  for (var i = 0; i < data.length; i++) {
    $.each(cats, function(k, v) {
      if (data[i].category == "") {
        labels.none.push(data[i].label);
      }
      if (data[i].category == v) {
        labels[v].push(data[i].label);
      }
    });
  }
  $.each(labels, function(k, v) {
    $.unique(labels[k]);
  });
  console.log("All Labels: ", labels);

  // Set Autocomplete with variable data based on category selection
  search.autocomplete({
    delay: 0,
    source: function(req, res) {
      var cat = sel.val();
      var data = labels[cat];
      var results = [];
      $.each(data, function(k, v) {
        if (v.indexOf(req.term) == 0) {
          results.push(v);
        }
      });
      res(results);
    }
  });
});

I first sifted out the categories that we knew would be in the data. This was then used to populate the Select element with a special "none" option. You could go back and adjust the none data to include all labels.
Next we parse all the labels and sort them into an object that has child arrays with the name of each category as the index. We will populate each array with the data for that category.
Finally, we use a function for the source so that we can pick which data set we want to read from. req.term is the data that was entered in the field, and we need to return an array of the matching data. The use of indexOf() is helpful here. This will return 0 when the term is at the beginning of the string. We then pass the resulting array to our res callback function.
So using your example, if category is "none" and we type "an", we get a resulting 'anders', 'andreas', and 'antal'. If we then type "and", the results drop to 'ansders' and 'andreas' as expected.


text:
Q: Fundamental Theorem of Calculus Piecewise Function help? Let:
$$f(x)=
\begin{cases} 0,  &  x < -4 \\
5,  \qquad\quad& \llap{-4 \le{}} x < -1 \\
-2, &  \llap{-1 \le{}} x < 3 \\
0,&  x \ge 3\end{cases}$$
$$g(x) = \int_{-4}^x f(t)dt$$
I need to determine the value of each of the following:
$g(-7)
,g(-3)
,g(0)
,g(4)$
I already know $g(-7) = 0$ and $g(-3) = 5$
I don't know how I know that, I just followed the basics of reading a piecewise, but the last two do not work the same way, and I don't understand how to find $g'(x)$ in order to make sense of the last two. There's no function to get a derivative from. I have spent hours trying to figure out how to do this, and need someone to help me start from scratch on this, because it makes absolutely no sense to me.
I also need to know how to find the absolute maximum, and what value of $x$ it occurs at. Again, no clue how to approach it. There's no function of $f(x)$ to derive anything from, so how is this done?

A: Guide:
Just split the integral over different region and integrate them.$$g(0) = \int_{-4}^{0}f(t) \, dt = \int_{-4}^{-1}f(t) \, dt + \int_{-1}^0 f(t) \, dt$$
$$g(4) = \int_{-4}^{4}f(t) \, dt = \int_{-4}^{-1}f(t) \, dt + \int_{-1}^3 f(t) \, dt + \int_3^4 f(t) \, dt$$
Try to complete the above computation by replacing $f(t)$ with the right expression and evalute them.
Notice that $g$ increases from $-4$ to $-1$ and then it decreases. Hence the maximum occur when $x=-1$. Find $g(-1)$.


text:
Q: Is there any benefitis on using a Boundfield over Template Field For ASP.NET GridView:
I want to know if there are  any benefits on using a Boundfield over Template Field.
The only benefit that I can think of ,is using boundfield simpler and it needs less code.
I'm  plannning to get rid of all bound fields in my code and replacing them with Template fields, mostly because I don't like using hardcoded column index to get values from bound field.
string name=GridViewCurrentRow.Cells[13].Text

I would rather use FindControl("ControlID") method of Row class and this seem to be only doable if I use a template field.
Am I missing something or are there any concerns ? Please share.

A:
You can use FindControl("ControlID") with both BoundField and TemplateField as its a GridViewRow's class not the both Fields.

While on other hand:

*

*BoundField is used when you only want to display text/data as default.

*TemplateField gives you more control on customization of your data row in GridView in different designs and styles. It allows you multiple options of HTML and Web Controls.

BoundField and TemplateField.


text:
Q: For any point $(a,b) \in\mathbb R^2$ that fulfills the condition $a+b=1$ calculate $\lim_{(x,y)\rightarrow (a,b)} \frac{y \sin(\pi \cdot x)}{x+y-1}$ I do not know how to even start. I suspect that these limits does not exist because $x+y-1 \rightarrow 0$ but I am not sure.
I will be very thankful for any hints.


text:
Q: Make Modal Update So, I am new to Programming.
i'am trying to make a modal update in laravel,but i don't know how to catch the data on my edit form, i'am trying to search the internet for so long to find a solution. so I hope you all can give me some solution to make update modal.
this my view

@extends('layouts.main')

@section('container')

      @foreach ($users as $user)

            @if ($user->profile)
                profile) }}">
            @else

            @endif

                Update Photo

{{ auth()->user()->name }}

Upload Photo

        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>

        <form action="{{  route('updateprofile', $user->id) }}" method="POST" enctype="multipart/form-data">
            @csrf
            @method('put')

                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-arrow-bar-up ikon-upload" viewBox="0 0 16 16">
                            <path fill-rule="evenodd" d="M8 10a.5.5 0 0 0 .5-.5V3.707l2.146 2.147a.5.5 0 0 0 .708-.708l-3-3a.5.5 0 0 0-.708 0l-3 3a.5.5 0 1 0 .708.708L7.5 3.707V9.5a.5.5 0 0 0 .5.5zm-7 2.5a.5.5 0 0 1 .5-.5h13a.5.5 0 0 1 0 1h-13a.5.5 0 0 1-.5-.5z"/>
                          </svg>
                        Upload Photo
                        <input class="file-photo" type="file" id="profile" name="profile" onchange="previewImage()">

                                Username:
                                <input type="text" class="form-control" name="name" id="name" value="{{ old('name', $user->name) }}" @error('name') is-invalid @enderror>

                        @error('name')

                                {{ message }}

                        @enderror

                                Tanggal Lahir:
                                <input type="date" class="form-control" name="tanggal_lahir" id="tanggal_lahir" value="{{ auth()->user()->tanggal_lahir }}" @error('tanggal_lahir') is-invalid @enderror>

                        @error('tanggal_lahir')

                                {{ message }}

                        @enderror

                                Tempat Lahir:
                                <input type="text" class="form-control" name="tempat_lahir" id="tempat_lahir" value="{{ old('tempat_lahir', $user->tempat_lahir) }}" @error('tempat_lahir') is-invalid @enderror>

                        @error('tempat_lahir')

                                {{ message }}

                        @enderror

                                Jenis Kelamin:

                                    <input class="form-check-input" type="radio" name="jenis_kelamin" id="jenis_kelamin" value="pria">

                                      Pria

                                    <input class="form-check-input" type="radio" name="jenis_kelamin" id="jenis_kelamin" value="wanita" checked>

                                      Wanita

                        @error('jenis_kelamin')

                                {{ message }}

                        @enderror

                                Agama:
                                <select name="agama" id="agama" class="form-select" aria-label="Default select example" @error('agama') is-invalid @enderror required>
                                    <option value="" hidden="">Pilih Agama</option>
                                    <option value="Islam">Islam</option>
                                    <option value="Hindu">Hindu</option>
                                    <option value="Budha">Budha</option>
                                    <option value="Kristen">Kristen</option>
                                    <option value="Khatolik">Khatolik</option>
                                    <option value="Konghucu">Khonghucu</option>
                                </select>

                @error('agama')

                                {{ message }}

                        @enderror

                    <input type="hidden" name="id" id="id">
                    <button type="submit" class="btn btn-secondary" data-bs-dismiss="modal">Update</button>

        </form>

 @endforeach

this my route.
<?php

use App\Http\Controllers\ClassesController;
use App\Http\Controllers\QuestionsController;
use App\Http\Controllers\PostsController;
use App\Http\Controllers\MemberController;
use App\Http\Controllers\PasswordController;
use App\Http\Controllers\EmailController;
use App\Http\Controllers\TimeController;
use App\Models\Kelas;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\LoginController;
use App\Http\Controllers\ProfileController;
use SebastianBergmann\CodeCoverage\Report\Html\Dashboard;
use Symfony\Component\HttpKernel\Profiler\Profile;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('home', ['title' => 'Login']);
});

Route::get('/login', [LoginController::class, 'index'])->name('login')->middleware('guest');
Route::post('/login', [LoginController::class, 'authenticate']);
Route::post('/logout', [LoginController::class, 'logout']);

Route::get('/setup-password/{token}', [PasswordController::class, 'edit'])->name('setup-password-get');
Route::post('/setup-password', [PasswordController::class, 'update'])->name('setup-password');

Route::group(['middleware' => ['auth', 'ceklevel:admin']], function () {
    Route::get('/groups/members/{kelas:slug}/addmember', [EmailController::class, 'show']);
    // Route::get('/groups/quiz/index', [TimeController::class, 'index']);
    Route::get('/groups/quiz/index', [TimeController::class, 'create']);
    Route::get('/groups/quiz/question', [QuestionsController::class, 'create']);
    Route::get('/email', [EmailController::class, 'kirim']);
});

Route::group(['middleware' => ['auth', 'ceklevel:admin,user']], function () {
    Route::get('/home', function () {
        return view(('home.index'), ['title' => 'home']);
    });
    Route::get('edit', 'ProfileControler@edit')->name('edit');
    Route::get('/classes', [ClassesController::class, 'index']);
    Route::get('/classes/index/checkSlug', [ClassesController::class, 'checkSlug']);
    Route::get('/groups/{kelas:slug}/posts', [PostsController::class, 'show']);
    Route::get('/groups/members/{kelas:slug}/member', [MemberController::class, 'show']);
    Route::get('/profile', [ProfileController::class, 'index'])->name('profile');
    Route::get('/groups/{kelas:slug}/join', [PostController::class, 'join']);
});

Route::post('updateprofile', 'ProfileController@updateprofile')->name('updateprofile');
Route::post('/profile', [ProfileController::class, 'upload']);
Route::post('/groups/quiz/question', [QuestionsController::class, 'store'])->middleware('auth');
Route::post('/groups/quiz/index', [TimeController::class, 'store']);
Route::resource('/profile', ProfileController::class)->middleware('auth');
Route::resource('/classes/index', ClassesController::class)->middleware('auth');
Route::resource('/groups/members/addmember', EmailController::class)->middleware('auth');

// Route::post('kirim', [EmailController::class, 'kirim']);

And i build controller like this

<?php

namespace App\Http\Controllers;

use App\Models\Kelas;
use App\Models\User;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;

class ProfileController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('profile.index', [
            'title' => 'Profile',
            'users' => User::where('id', auth()->user()->id)->get()
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\User  $user
     * @return \Illuminate\Http\Response
     */
    public function show(User $user)
    {

        return view('profile.index', [
            'title' => 'profile',
            'user' => $user
        ]);

        // $user = User::all();
        // return view('profile.index', compact('user'));

        // return view('profile.index', [
        //     'title' => 'profile',
        //     'user' => $user
        // ]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\User  $user
     * @return \Illuminate\Http\Response
     */
    public function edit(User $user, Request $request)
    {
        // return view('profile.index', [
        //     'user' => $user
        // ]);

        $profile = Kelas::findOrfail($request->get('id'));
        echo json_encode($profile);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\User  $user
     * @return \Illuminate\Http\Response
     */
    public function updateprofile(Request $request, User $user)
    {

        $profile = array('kelas' => $request->post('kelas'));
        $save = DB::table('Users')->where('id', '=', $request->post('id'))->update($profile);

        // return $request->file('profile')->store('profile');
        // $path = Storage::putFile('profile', $request->file('profile'));
        // $path = $request->file('profile')->storeAs('profile', 'gambar');
        // $file = $request->file('profile');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\User  $user
     * @return \Illuminate\Http\Response
     */
    public function destroy(User $user)
    {
        //
    }
}

This My Controller
<?php

namespace App\Http\Controllers;

use App\Models\Kelas;
use App\Models\User;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;

class ProfileController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('profile.index', [
            'title' => 'Profile',
            'users' => User::where('id', auth()->user()->id)->get()
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\User  $user
     * @return \Illuminate\Http\Response
     */
    public function show(User $user)
    {

        return view('profile.index', [
            'title' => 'profile',
            'user' => $user
        ]);

        // $user = User::all();
        // return view('profile.index', compact('user'));

        // return view('profile.index', [
        //     'title' => 'profile',
        //     'user' => $user
        // ]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\User  $user
     * @return \Illuminate\Http\Response
     */
    public function edit(User $user, Request $request)
    {
        // return view('profile.index', [
        //     'user' => $user
        // ]);

        $profile = Kelas::findOrfail($request->get('id'));
        echo json_encode($profile);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\User  $user
     * @return \Illuminate\Http\Response
     */
    public function updateprofile(Request $request, User $user)
    {

        $profile = array('kelas' => $request->post('kelas'));
        $save = DB::table('Users')->where('id', '=', $request->post('id'))->update($profile);

        // return $request->file('profile')->store('profile');
        // $path = Storage::putFile('profile', $request->file('profile'));
        // $path = $request->file('profile')->storeAs('profile', 'gambar');
        // $file = $request->file('profile');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\User  $user
     * @return \Illuminate\Http\Response
     */
    public function destroy(User $user)
    {
        //
    }
}

I didn't know well about javascripts.
i dont't know how to next step, so i hope you all ca help me.
Thanks Before

A: your button Update have attribute data-bs-dismiss="modal" , this is for hide the modal remove that attribute. And when you have form at modal you cant only use <button type="submit> to post your form you can add action onclick to the button for submit the form like this
<button type="submit" class="btn btn-secondary" onclick="document.getElementById('form-submit').submit();">Update</button>
and add attribute id to html <form> tag like this
<form id="form-submit" action="{{  route('updateprofile', $user->id) }}" method="POST" enctype="multipart/form-data">


text:
Q: Authorize tag not triggering authentication in ASP.NET MVC5 WebAPI I have an ASP.NET MVC5 application with WebAPI and Individual Accounts built with VS.2015 Community Edition.
I created the Identity database with Code Migrations and it has a default administrator user created in it.
I noticed that the Login link is no longer present in the MVC site (why?) and that all authentication seems to have moved to WebAPI.
Trying to figure things out I noticed there is a Values Controlled installed by the template that has the Authorize attribute applied to the entire controller thus requiring authentication.
I fired the MVC application and proceeded to request the /api/values/5 request which should cause the Get method of the VAlues Controller to fire IF the user is authenticated. Well, to my surprise when I use Postman to fire the GET request I get the return value given by the method without even being authenticated! In fact, since there is no Login I thought that perhaps any attempts to request a "protected" controller method would result in some sort of user authentication dialog but NOTHING, it simply returned the value as if the Authorize attribute was not there.


text:
Q: Flutter how to protect from null values when getting attribute values of snapshot I have data coming back from firestore which is either coming back null or temporarily coming back null.
I do a check to make sure the snapshot has data like this:
parentSnapshot.data != null && parentSnapshot.hasData

I also tried to protect for the attribute being null using a ternary like this:
var isParent = parentSnapshot.data['isParent'] ?? false;

But for some reason I still keep getting:
The method '[]' was called on null
Reciever: null
Tried calling: []("isParent")

It needs to be null safe so if that attribute is not found then the variable always returns false so I control what is displayed.
Here is the full code:
return StreamBuilder<Object>(
        stream: Firestore.instance.collection(parent).document(
            widget.menuItemsList[index]['name']).snapshots(),
        builder: (BuildContext context, AsyncSnapshot parentSnapshot) {

          if (parentSnapshot.data != null && parentSnapshot.hasData) {
            var isParent = parentSnapshot.data['isParent'] ?? false;

            if (isParent){
              return GridButtons(widget.menuItemsList[index]['name'], animation, index, parent, collection, parentSnapshot, widget.menuItemsList, widget.listKey);
            } else {
              return SizedBox(width: 0, height: 0,);
            }

          } else {
            return SizedBox(width: 0, height: 0,);
          }
        }
    );

Thanks for your help

A: I think below code will help you
we have to check length also
if condition only accepts Boolean values in dart language
if (parentSnapshot.hasData && parentSnapshot.data != null && parentSnapshot.data.length > 0 ) {
            var isParent = parentSnapshot.data['isParent'] != null ? true : false;

            if (isParent){
              return GridButtons(widget.menuItemsList[index]['name'], animation, index, parent, collection, parentSnapshot, widget.menuItemsList, widget.listKey);
            }


text:
Q: How to return the Promise.all fetch api json data? How to I consume the Promise.all fetch api json data? It works fine to pull it if I don't use Promise.all. With .all it actually returns the values of the query in the console but for some reason I'm not able to access it. Here is my code and how it looks in the console after it resolves.
Promise.all([
    fetch('data.cfc?method=qry1', {
        method: 'post',
        credentials: "same-origin",
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: $.param(myparams0)
    }),
    fetch('data.cfc?method=qry2', {
        method: 'post',
        credentials: "same-origin",
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: $.param(myparams0)
    })
]).then(([aa, bb]) => {
    $body.removeClass('loading');
    console.log(aa);
    return [aa.json(),bb.json()]
})
.then(function(responseText){
    console.log(responseText[0]);

}).catch((err) => {
    console.log(err);
});

All I want is to be able to access data.qry1. I tried with responseText[0].data.qry1 or responseText[0]['data']['qry1'] but it returned undefined. This below is the output from console.log responseText[0]. The console.log(aa) gives Response {type: "basic" ...
    Promise {<resolved>: {…}}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Object
data: {qry1: Array(35)}
errors: []

A: The simplest solution would be to repeat the use of Promise.all, to just wait for all .json() to resolve.
Just use :
Promise.all([fetch1, ... fetchX])
.then(results => Promise.all(results.map(r => r.json())) )
.then(results => { You have results[0, ..., X] available as objects })

A: Aparently aa.json() and bb.json() are returned before being resolved, adding async/await to that will solve the problem :
.then(async([aa, bb]) => {
    const a = await aa.json();
    const b = await bb.json();
    return [a, b]
  })

Promise.all([
    fetch('https://jsonplaceholder.typicode.com/todos/1'),
    fetch('https://jsonplaceholder.typicode.com/todos/2')
  ]).then(async([aa, bb]) => {
    const a = await aa.json();
    const b = await bb.json();
    return [a, b]
  })
  .then((responseText) => {
    console.log(responseText);

  }).catch((err) => {
    console.log(err);
  });

Still looking for a better explaination though

A: Instead of return [aa.json(),bb.json()] use return Promise.resolve([aa.json(),bb.json()]). See documentation on Promise.resolve()
.

A: I came across the same problem and my goal was to make the Promise.all() return an array of JSON objects.
let jsonArray = await Promise.all(requests.map(url => fetch(url)))
    .then(async (res) => {
        return Promise.all(
            res.map(async (data) => await data.json())
        )
    })

And if you need it very short (one liner for the copy paste people :)
const requests = ['myapi.com/list','myapi.com/trending']
const x = await Promise.all(requests.map(url=>fetch(url))).then(async(res)=>Promise.all(res.map(async(data)=>await data.json())))

A: You can just throw await in front of your Promise instead of awaiting each individual fetch
await Promise.all([
    fetch('https://jsonplaceholder.typicode.com/todos/1'),
    fetch('https://jsonplaceholder.typicode.com/todos/2')
  ]).then(async([aa, bb]) => {
    const a =  aa.json();
    const b =  bb.json();
    return [a, b]
  })
  .then((responseText) => {
    console.log(responseText);

  }).catch((err) => {
    console.log(err);
  });

Hope this helps

A: Using Promise.all to fetch the json responses of each of the API's-
CODE:
Promise.all([
  API_1_Promise,
  API_2_Promise,
  API_3_Promise])
  .then(allResults => console.log(allResults))
  .catch(err => console.log(err))

In which API_1_Promise,API_2_Promise,API_3_Promise is defined as
API_1_Promise = fetch(`API_URL_1`, {  *Add required headers* }).then(response => response.json())

API_2_Promise = fetch(`API_URL_2`, {  *Add required headers* }).then(response => response.json())

API_3_Promise = fetch(`API_URL_3`, { *Add required headers* }).then(response => response.json())

RESPONSE:
This will print the array of responses from all the API calls
In console-->
[JSON_RESPONSE_API1, JSON_RESPONSE_API2, JSON_RESPONSE_API3]


text:
Q: Postfix not recieving mail from actual email but does from sendmail? Ok so I'm trying to forward mail from my ubuntu server (lets call it example.com) to a external gmail account using postfix.
The problem is when I send mail using another gmail and yahoo account to monkey@example.com, and I check var/log/mail.info, nothing shows up.
However when I use sendmail in the terminal and send to the same address I get the following written into the log as well as the mail actually sending and ending up in my inbox:
Jan  4 00:02:48 Machine postfix/local[6520]: 6C82DB80C4A: to=<root@example.com>, relay=local, delay=0.01, delays=0/0/0/0.01, dsn=2.0.0, status=sent (delivered to command: procmail -a "$EXTENSION")
Jan  4 00:02:48 Machine postfix/qmgr[6497]: 6C82DB80C4A: removed
Jan  4 00:09:58 Machine postfix/pickup[6496]: B206CB80C46: uid=0 from=<root>
Jan  4 00:09:58 Machine postfix/cleanup[6540]: B206CB80C46: message-id=<20140104050958.B206CB80C46@Machine>
Jan  4 00:09:58 Machine postfix/qmgr[6497]: B206CB80C46: from=<root@example.com>, size=265, nrcpt=1 (queue active)
Jan  4 00:09:59 nightMachine postfix/smtp[6542]: B206CB80C46: to=<destemail@gmail.com>, orig_to=<monkey@example.com>, relay=gmail-smtp-in.l.google.com[74.125.142.26]:25, delay=14, delays=13/0/0.22/0.69, dsn=2.0.0, status=sent (250 2.0.0 OK 1388812199 qd7si6471164igb.62 - gsmtp)
Jan  4 00:09:59 Machine postfix/qmgr[6497]: B206CB80C46: removed

Is there a reason for this? How would  I fix it?
I was following this tutorial.
postfix/virtual:
monkey@example.com destemail@gmail.com

Main.cf:
# See /usr/share/postfix/main.cf.dist for a commented, more complete version

# Debian specific:  Specifying a file name will cause the first
# line of that file to be used as the name.  The Debian default
# is /etc/mailname.
#myorigin = /etc/mailname

smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
biff = no

# appending .domain is the MUA's job.
append_dot_mydomain = no

# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h

readme_directory = no

# TLS parameters
smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
smtpd_use_tls=yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache

# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.

myhostname = Machine
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = /etc/mailname
mydestination = example.com, Machine, localhost.localdomain, localhost
relayhost =
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_command = procmail -a "$EXTENSION"
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
home_mailbox = mail/

#added the following for mail server :O!!
virtual_alias_domains = example.com
virtual_alias_maps = hash:/etc/postfix/virtual

result when I do a dig example.com mx query in terminal:
;; ANSWER SECTION:
example.com.        21600   IN      MX      10 mail.example.com.

telnet example.com 25
Connected to example.com.
Escape character is '^]'.
220 Machine ESMTP Postfix (Ubuntu)

A: You've set your MX record to "mail.example.com". That means that when any mailserver tries to send mail to you, they will do a DNS lookup to find mail.example.com. Since that doesn't exist, the sending system doesn't know where to send the email.
To fix this, do either of the following two things:

*

*Remove your MX record entirely. As long as you don't have an MX record, the sending system will instead do a DNS lookup for example.com, and since that does resolve to the server running your mailserver, that will work.

*In addition to the MX record, create an A or CNAME record for mail.example.com.

It should look like his for an A record:
mail     A     127.0.0.1

(except, of course, the IP address should be the actual IP of the server, not the loopback address)
and like this for a CNAME:
mail     CNAME example.com.


text:
Q: React native: disable tab press for some icons (without removing icons) on bottom tabs navigation in my react native bottom tabs I want to disable some tabs based on a few conditions, say I want to disable Profile tab WITHOUT removing actual tab screen or icon, so is there a way to intercept user pressed tab icon, check if pressed tab is Profile and if it is DO NOTHING instead of navigate to Profile screen?
Thanks in advance.
My tab component:
<Tab.Navigator
        screenOptions={({ route }) => ({
        headerShown: false  ,
        swipeEnabled: true,
        tabBarHideOnKeyboard: true,
        tabBarActiveTintColor: "#E13545",
        tabBarInactiveTintColor: "rgb(125,125,125)",
        tabBarShowLabel: false,
        tabBarLabelStyle: {
    fontSize: 10,
    margin: 0,
    padding: 0,
    textTransform: "none",
    fontFamily: "AirbnbCerealBook"
  },
  tabBarItemStyle: {
    paddingVertical: 0
  },
  tabBarStyle: [
    {
        width:root.uiStore.width+4,height:60,backgroundColor:'white',borderTopWidth:0,position:'absolute',left:0,bottom:0,right:0,borderTopWidth:1,borderTopColor:'rgba(0,0,0,0.1)',borderRightWidth:1,borderRightColor:'rgba(0,0,0,0.1)',borderLeftWidth:1,borderLeftColor:'rgba(0,0,0,0.1)',elevation:10,overflow:'hidden',borderTopLeftRadius:35,borderTopRightRadius:35,
    },
        null
  ],
    })}
        >
        <Tab.Screen name="Home" component={STACK1} />
        <Tab.Screen name="Favorites" component={STACK2} />
        <Tab.Screen name="Discounts" component={STACK3} />
        <Tab.Screen name="Profile" component={STACK4}/>
    </Tab.Navigator>


text:
Q: How to run react app in subdirectory on xampp? I've created a react project.
It runs normally in htdocs directory on xampp server, but in a subdirectory doesn't display the react page.
I want to know a method to run my react app in a subdirectory on xampp server.

A: *

*Go to \xampp\apache\conf\httpd.conf

*Open httpd.conf

*Find tag DocumentRoot "C:/xampp/htdocs"

*change the path to the subdirectory you need.

Hope this helps.


text:
Q: How to control tenant based job execution across multiple instances of azure app service Requirement is -

*

*Currently we are having one instance of app-service in which spring scheduled batch jobs are running which are reading, processing and writing records for multiple tenants.

*We need to have multiple instances of the same app-service but need some logic to control the job execution per tenant on across instances.

*Is there any way to know how many instances are there of current app-service in azure.


text:
Q: Comparing an arrayList to itself using foreach and not including duplicates I'm comparing an arrayList to itself using foreach.
I have an arrayList containing tips for waiters, each object has a date "dd-MM-yyy" and an amount (double),
Now i want to add all transactions for the same day, so i get a total for the day that can be divided between the waiters.
Without duplicates.
I've looked all over especially here, but I can't seem to find a solution.
I really hope you guys can help, I know it's a bit embarrassing, seeing as the problem being so simple, but I've been working on it for a couple of days now and I'm stuck.
I had a longer algorithm but it wouldn't work and I couldn't find any solutions online, so i broke it all down to it's most basic components and checked for each step and pretty early on this problem occured:
I'm using a local arrayList to make sure that I'm not comparing the same days to eachother over and over again.
The if(!alreadyMade.contains(tips1.getTime()) followed by alreadyMade.add(tips1.getTime()) seems to be producing duplicates, which in my mind makes no sense.
All I want is to add all the transactions for the same day from the same arrayList.
public void dist(){
    double day = 0;
    List<String> alreadyMade = new ArrayList<>();
    for (Tips tips : data.getTips()) {
        for (Tips tips1 : data.getTips()) {
            if(tips.getTime().equals(tips1.getTime())) {
                if (!alreadyMade.contains(tips1.getTime())){
                    alreadyMade.add(tips1.getTime());
                    day += tips.getTips();
                }
            }
        }
        System.out.println(day);
        day = 0;
    }
}

I wanted the print to be for a single day, but it is printing a lot of numbers that doesn't make sense

A: I think you're trying to do something like this:
        Map<String,Double> alreadyMade = new HashMap<>();
    for (Tips tips : new ArrayList<Tips>()) {
        // If this time doesn't exist in the map then add it to the map with the
        // value tips.getTips().  If this time does exist in the map then add
        // the value of tips.getTips() to the value that is already in the map.
        alreadyMade.merge(tips.getTime(), tips.getTips(), (Double a, Double b) -> a + b);
    }
    // go through each map entry.  The keys are the times and the values are the tip totals for that time.
    for (Map.Entry<String, Double> entry : alreadyMade.entrySet()) {
        System.out.println("Time: " + entry.getKey() + " Tips: " + entry.getValue());
    }

Note: I couldn't test this because I'm running Java 7 and this map function isn't available until java 8.

A: In Java 8+ you can use the stream API to group by the time:
Map<Date, Integer> alreadyMade = data.getTips().stream()
  .collect(groupingBy(Tip::getTime, summingInt(Tip::getTips)));

A: I would do it like the following:
This is your Tip class(I think)
public class Tip{
    Date date;
    float tip;
    public Tip(Date date, float tip){
        this.date = date;
        this.tip = tip;
    }
}

And this is the ("Algorithm")
//To Format the Dates
SimpleDateFormat ft = new SimpleDateFormat("dd-MM-yyyy");

//Input
ArrayList<Tip> tips = new ArrayList<Tip>();

//Just some Data for testing
tips.add(new Tip(ft.parse("11-04-2019"), 2.40F));
tips.add(new Tip(ft.parse("25-04-2019"), 3.30F));
tips.add(new Tip(ft.parse("25-04-2019"), 0.90F));

//Output
ArrayList<Date> dates = new ArrayList<Date>();
ArrayList<Float> sum = new ArrayList<Float>();

for(Tip tip : tips){  //Go through each Tip
  int match = dates.indexOf(tip.date);  //Look if the date is already in the array (if not -> -1)

  if(match == -1){  //If not add it
    dates.add(tip.date);
    sum.add(tip.tip);
  }else {  //If yes set it
    sum.set(match, sum.get(match) + tip.tip);
  }

}

//Output to console
for(int i = 0; i < dates.size(); i++){
  System.out.println(ft.format(dates.get(i)).toString() + " " + String.valueOf(sum.get(i)));
}

There is also a solution with maps or pairs but I never worked with them (not a professional coder). Also make sure to try-catch the ParseException. I Hope thats what you meant. :)


text:
Q: Angular 10 @Input by reference Im having problem to get value change from a component property.
In this simple example, I have an ngFor that create instance of TextField Component passing fields[i].value as property.
I value has a default, its correctly printed on input but the changes are not reflected on the original model.
<ng-container *ngFor="let field of fields.all(); let i = index;">
                        <dynamic-text-field

                            [id]        = "field.name"
                            [name]      = "field.name"
                            [label]     = "field.label"
                            [note]      = "field.translate_help"
                            [(val)]     = "fields[i].value"
                        >

                        </dynamic-text-field>
 </ng-container>

export class TextField
{

    @Input() id         : string = "";
    @Input() name       : string = "";
    @Input() note       : string = "";
    @Input() label      : string = "";
    @Input() val        : string = null;

    [...]
}

<mat-label translate> {{ label | translate }} </mat-label>
<input  matInput placeholder="" [(ngModel)]="val" name="{{name}}" />

A: I'm guessing thats because an @Input is not really a two-way binding.
In addition, it looks like your fields[i].value is a primitive (string).
This might be a workaround that is not ideal, but you can try passing an object as val and then, in your TextField component, refer to the value by something like [(ngModel)]="val.value". That way, val is an object, so it's passed by the reference to a child component - any updates to the model will be available in the parent component.
The other way could be to pass a callback function to the child component that you'd call on model update - something like:
                        <dynamic-text-field

                            [id]        = "field.name"
                            [name]      = "field.name"
                            [label]     = "field.label"
                            [note]      = "field.translate_help"
                            [val]       = "fields[i].value"
                            (valueChange)="onValueChange($event)"
                        >

                        </dynamic-text-field>

with:
<mat-label translate> {{ label | translate }} </mat-label>
<input  matInput placeholder="" [ngModel]="val" (change)="valueChange.emit($event.value)" name="{{name}}" />

with:
export class TextField
{

    @Input() id         : string = "";
    @Input() name       : string = "";
    @Input() note       : string = "";
    @Input() label      : string = "";
    @Input() val        : string = null;
    @Output() valueChange = new EventEmitter<string>();

    [...]
}

and then trigger whatever logic you need in the parent's onValueChange method


text: Q: Rotationally symmetric hypersurfaces with mean curvature bounded away from 0 I know that the rotationally symmetric hypersurfaces in $\mathbb{R}^n$ with constant mean curvature are the hyperplane, sphere, cylinder, catenoid, nodoid, and unduloid. Are there any significant restrictions on rotationally symmetric hypersurfaces with mean curvature bounded away from 0?


text:
Q: SQL select from 2 tables with 2 conditions Hi i have two tables in mysql and i want to select from both of them and list things with both condicions true.
Friends :
id         iduser     idfriend
0             44            56
1             44            102
2             10             66
3              10            85
4              44            10

Users:
id         name                email                   isonline
44         john          john@gmail.com                   1
10         joe           joe@yahoo.com                    1
185        mark          mark@so.com                      0

Example :  im user 44 and i want to get all my friends which are online
So i would exec some sql like :
SELECT * FROM friends WHERE iduser=44 AND SELECT FROM * FROM users WHERE isonline=1

I know i cant do it this way and i also search stackowerflow and i found some which didnt work for me
I just want to get something like : (if im user 44)
10     Joe      joe@yahoo.com
And i dont want to get myself
Thank you for all answers

A: This should work:
select u.* from friends f
join users u on f.idfriend = u.id
where f.iduser = 44 and u.isonline = 1

A: SELECT * FROM friends f
INNER JOIN users u
ON f.idfriend = u.id
WHERE f.iduser = 44 AND u.isonline = 1

A: You can do this with JOINS . Joins are used to make a link between two tables generally using a relation. In your case, the relation is user(id) and friends(iduser). Once the join is done, you can select fields from both tables.
SELECT u.* FROM friends f
INNER JOIN users u
ON f.idfriend = u.id
WHERE f.iduser = 44 AND u.isonline = 1


text:
Q: Conversion of 16 Byte Array Response to Decimal I am working on an application in which I received a 16 byte array response. In that response there will be 1 bit set to indicate a position value. For example I may get:
0000 01000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000
Which would represent that device #5 has responded (first bit represents device #0).
Is there a simple way to get convert a byte array of this length to it's decimal value?

A: Decimal class is not an appropriate way to represent such data. What you're probably looking for is BitArray class.

A: If I understand your problem correctly, you can use a for-loop and the counter would be your device number.
Edit: Added Code Sample
int n = 0;

// Loop trough the byte array.
for(n = 0; n < bytearray.Length; n++)
{
   // Exit the loop as soon as the indexed byte from the array is 1.
   if(bytearray[n] != null && bytearray[n] == 1)
   {
      break;
   }
}

// Here you can string your device name together.
string deviceName = "device #" + n;

Remark: Actually I don't understand your example.  Why do you say 16 bytes, but each group apprears to be of 4 bits. How did you get the device number 5 from that bytearray?

A: Try something like this:
byte[] yourByteArr = { 0, 0, 32, 0, };

var firstSetBit = (new BitArray(yourByteArr)).Cast<bool>()
    .Select(Tuple.Create<bool, int>).FirstOrDefault(x => x.Item1);
int indexOfFirstSetBit = firstSetBit != null ? firstSetBit.Item2 : -1;

If it could not be that no bits are set, just do:
int indexOfFirstSetBit = (new BitArray(yourByteArr)).Cast<bool>()
    .Select(Tuple.Create<bool, int>).First(x => x.Item1).Item2;


text:
Q: What is "RFIS" tag I read somewhere about "RFIS" tag. I know what is "RFID" but does something called "RFIS" exist? I tried to search but all suggestions are RFID related. Would be nice if you have any clue share it please.
It could be just a mistake, so just simply it should have been RFID! or maybe this is something very new and no one knows about it!
This is a part of title:
"a body area network composed of compass and tilt sensors and RFIS tags"

A: According to Acronyms Dictionary, it can be as well:
RFIS    Remote Frequency Indicator Selector
RFIS    RWS/Fire-Control Interface Software
RFIS    Radio Frequency Interface Subsystem/System

I have a hard time believing that someone could make a typo in PhD project title.

A: Almost certainly a typo. Note that the s key is right next to the d.
But it may also refer to the new "Radio Frequency ISentification" technology, of course :-).
edit after your question update
The abstract talks about "intelligent guide to help blind people to solve puzzles". It's easily imaginable that RFID could be used to identify the puzzle pieces.

A: There is every indication that it is a "typo" as others have suggested.
The original text is as below, in relation to a 'pervasive systems' research incentive at a European university. Anyone else may find it in the same way that I did :-) :

*

*Have you ever tried to solve a puzzle blind folded? As strange as it may sound, it can be done if somebody next to you can act as your eyes; sees what you need to see and think for you. This is exactly what this project aims at doing but instead of having a person next to you, a body area network composed of compass and tilt sensors and RFIS tags will help you.
The idea is through grouping, object identification, and recognizing interaction between hand and puzzle pieces to build an intelligent guide to help blind people to solve puzzles. Each puzzle piece needs to be identified, its association with other pieces needs to be recognized and guidance and feed back (in forms of voice or hepatic feedback ) should be given to the player while choosing puzzle pieces and trying to put the pieces in the right place with right orientation.
The term has no special meaning in "pervasive systems" .
The term is used in this document in answer to Q2.10

*

*
*

*Pervasive computing using RFIS, multi-touch.

but it seems more likely to be a typo here than a new acronym.

It is common for people to make keyboard errors with no awareness of having done so.
In another lifetime I worked for NZ Telecom. A newspaper article complained about the poor quality of city telephone service. Amongst other things they complained about excessive "wrong numbers". They provided an example list of target companies whose numbers had (allegedly) been dialled, and the companies which had been reached instead. Out of a list of about 10 companies I was able to show that in all except one or two cases there was a logical connection between the intended number and the actual number of the company dialled. Sometimes a transposition (eg 32 instead of 23), sometimes an adjacent digit dialled (as in teh [<- whoops :-) ] case here of RFID and RFIS and sometimes an added or omitted leading digit.


text:
Q: Three Envelopes Problem
Possible Duplicate:
The Monty Hall problem

Three envelopes are presented in front of you by an interviewer. One contains a job offer, the other two contain rejection letters. You pick one of the envelopes. The interviewer then shows you the contents of one of the other envelopes, which is a rejection letter. The interviewer now gives you the opportunity to switch envelope choices. Should you switch?

A: yea u should
P of correct envelope the first time you picked is 1/3
That 1/3 has not changed so by switching you essentially make a switch with a P of 1/2.
Or something along those lines.


text:
Q: What is the InterCheck process that occasionally uses 96% CPU on my Mac? I heard my computer's fan spinning fast, so I checked Activity Monitor and saw that a process called InterCheck was using close to 96% CPU. What is this process and why's it using so much CPU?
In the Inspect window, it said that the parent process is launchd.

A: It's a real-time scanning process by Sophos Anti-Virus that scans your computer's running processes in the background.
The parent process is launchd so that when you accidentally kill the Intercheck process, it gets restarted.


text:
Q: Let $X \sim exp(\lambda)$ be independent of $Y \sim exp(\lambda)$ compute $E[X|X+Y]$ Let $X \sim exp(\lambda)$ be independent of $Y \sim exp(\lambda)$ compute $E[X|X+Y]$
I have tried to do this in a couple different ways and all of them have either led to an indefinite integral or a bad answer (illogically $-\lambda$).
Let $Z := X+Y$
The first way I tried to do it was,
$
\begin{align}
E[X|Z] &= \int_0^{\infty} x p_{x|z}dx\\
\end{align}$
Then I found $p_{x|z}$ to be
$
\begin{align}
p_{x|z} &= \frac{P(X=x, X+Y=z)}{P(Z=z)}\\
&= \frac{P(X=x)P(Y=z-x)}{P(Z=z)}\\
&= \frac{\lambda^2 e^{-\lambda x} e^{-\lambda (z-x)}}{\lambda e^{-\lambda z}}\\
&= \lambda
\end{align}$
So,
$
\begin{align}
E[X|Z] &= \int_0^{\infty} x p_{x|z}dx\\
&= \int_0^{\infty} x \lambda dx
\end{align}$
Which doesn't coverage, can anyone help?

A: Aside from the fact that, by being continous random variables, none of them have probability mass functions, the distribution of $Z$ is not exponential (and certainly not with rate $\lambda$. The probability density function for $Z$ is:
$$\begin{align}f_Z(z)&=\int_\Bbb R f_{X,Y}(s, z-s)\mathsf d s
\\[1ex] &=\mathbf 1_{z\in[0;\infty}\int_\Bbb R \lambda e^{-\lambda s}\mathsf 1_{s\in[0;\infty)}\cdot\lambda e^{-\lambda (z-s)}\mathsf 1_{z-s\in[0;\infty)}\mathsf d s
\\[1ex] &= \mathbf 1_{z\in[0;\infty)}\int_0^z \lambda^2 e^{-\lambda z}\mathsf d s
\\[1ex] f_Z(z) &= \lambda^2 z e^{-\lambda z}\mathbf 1_{z\in[0;\infty)}\end{align}$$
You may use this to find the conditional probability density function for $X$ given $Z$.

 $$f_{X\mid Z}(x\mid z) =\dfrac{\lambda e^{-\lambda x}\cdot \lambda e^{-\lambda (z-x)}}{\lambda^2 ze^{-\lambda z}}\mathbf 1_{0\leq x\leq z} = \tfrac 1z \mathbf 1_{z\in[0;\infty),x\in [0;z]}$$

Of course there is an easier way: $\mathsf E(X+Y\mid Z)= Z$, so you may use Linearity of Expectation and an argument from symmetry.


text:
Q: Chrome Extension App Open exe on File System I am struggling to find an answer to this question so I was hoping somebody experienced with Chrome apps and extensions could point me in the right direction.
I've not written any extensions or apps before so I am just trying to get to grips with it.
I am currently developing a POS system for my company and it's basically done and ready to go. On completion of a transaction I need to open the Till drawer connected via USB to the clients machine. All the machines will be owned by us therefore I can manually add the extension and app to the machine as well as the exe that opens the till.
I have found some sample apps that I am currently working on and I am successfully passing message between my extension and app. The next stage is to then open the exe via the app.
Can someone please clarify if opening an exe via an app is possible and if so presumably I would do this by adding filesystem permissions
"permissions": [
    "fileSystem"
  ],

Then do I need to use the read methods of the api?
Similarly if it is possible to open an exe, do I access this using
file///C:/path/to/exe
If it is not possible to open an exe, I could potentially install xampp on the customer machine and have a php script execute the exe file. In this instance I would need to post data from the app to the PHP page.
I believe I could use Jquerys post function to do this.
Any help/alternative solutions or resources you are aware that could help me solve the issue would be most appreciated.

A: It isn't possible by design (for security reasons) to launch an exe directly from an extension without writing some extra native software and your own installer for it. The installer has to drop a special configuration file which specifies a path to your executable, and then your extension can then launch your executable and get a messaging channel to send and receive messages to it.
For details on how to do this, see the "Native Messaging" section at:
https://developer.chrome.com/extensions/messaging


text:
Q: Is it a good practice to use a static variable in a Test Class and use that in the actual class instead of Test.isRunningTest()? I've read about using a static variable from a class in the test class but I'm wondering if this is legal enough to do.
@isTest
public class myTestClass{
    public static Boolean mySwitch = false;
    public static testMethod void myTestMethod1(){
        // code //
    }
    public static testMethod void myTestMethod2(){
        mySwitch = true;
        // code //
    }
}

public class actualClass{
    public void method1(){
        if(Test.isRunningTest){
            //always true if its hitting from a test class.
        } else if(Test.isRunningTest && myTestClass.mySwitch){
            //do something from myTestMethod2
        }
    }
}

A: You cannot reference a test class from a production class. You have the pattern reversed on where the Boolean flag should be.
You should avoid code which runs only out of a test context wherever possible. There are a few exceptions, such as:

*

*Disabling a trigger framework to save on run times if they become prohibitive

*Disabling batch chaining or other aspects of asynchronous processing

In these cases, you still should not use Test.isRunningTest() (at least according to our coding guideline where I work). Instead, you should use a @TestVisible flag in your production code.
public with sharing class MyClass
{
    @TestVisible static Boolean shouldDoStuff = true;
    public static void doStuff()
    {
        if (!shouldDoStuff) return;

        // actual logic
    }
    public static void doNonGatedStuff()
    {
        doStuff();

        // other logic
    }
}
@IsTest class MyClass
{
    @IsTest static void testDoStuff()
    {
        MyClass.shouldDoStuff = false;

        // rest of test
    }
}

Sometimes you will see this logic reversed. For example our typical flag for trigger handlers is called bypassTrigger, which would obviously default to false. You set it to true before inserting some records for setup, then bookend it back to false so that any further operations will still run the trigger.

A: No, it is not valid. You cannot access any variables or methods inside a class marked @isTest outside of a test context. Instead, you need to place the static variable inside the actual class, then modify it in the test class:
@isTest
public class myTestClass{
    public static testMethod void myTestMethod1(){
        // code //
    }
    public static testMethod void myTestMethod2(){
        actualClass.mySwitch = true;
        // code //
    }
}

public class actualClass{
    @TestVisible static Boolean mySwitch = false;
    public void method2(){
      if(mySwitch){
          //do something from myTestMethod2
      }
    }
}

You can use @TestVisible to prevent accessing the variable outside of testing context.