text:
Q: how to change people picker value in infopath form after every form updating I have a state machine workflow and related task. Task can be edited until it satisfy some conditions. Task formed by infopath. These task contains one people picker field. I assign 3 fields with these values:
private void createTask_Operator_MethodInvoking(object sender, EventArgs e)
{
 this.createTask_Id = Guid.NewGuid();

 this.createTask_Properties.ExtendedProperties["ows_TaskDisplayName"] = "user1";
 this.createTask_Properties.ExtendedProperties["ows_TaskAccountId"] = @"SP\user1";
 this.createTask_Properties.ExtendedProperties["ows_TaskAccountType"] = "User";
}

It is works, I can see in my form value these user. But when I change the user(for example: "user2") and submit the form, I cannot retrieve my manually changed field value, it always returns values of "user1".
private void onTaskChanged_Operator_Invoked(object sender, ExternalDataEventArgs e)
{
  this.onTaskChanged_AfterProperties = this.onTaskChanged.AfterProperties;
  this.onTaskChanged_BeforeProperties = this.onTaskChanged.BeforeProperties;

  // here I cannot retrieve changed field value, always returns: SP\user1
  this.workflowProperties.Item["UserName"] =
      this.onTaskChanged_AfterProperties.ExtendedProperties["TaskAccountId"].ToString();
  this.workflowProperties.Item.Update();
}

Please, if you faced such problem, help me with that...

A: I'm having a little trouble understanding your problem, but here are two answers. To successfully set the value of a people picker field, you have to correctly populate all three fields: DisplayName, AccountId, and AccountType. AccountType is always "User", but the other two have to align with your AD or wherever you're getting your user data from. To get data from a people picker, the best solution often includes the double eval trick: eval(eval(person, "concat(my:AccountId, ';')"), "..") This handles multiple entries correctly, if you mean that you're only getting the first in the list.


text:
Q: Can't Boot after up upgrade to 12.04 I have as asus 1005pe which I tried to upgrade from 10.04 to 12.04. It seems to stop loading at user bootsplash and hangs forever. Unfortunately, the machine doesn't have a cd drive and won't start from a usb disk, so using a live image is not an option.
My only hope is that I can get into a terminal screen. Please help.

A: I don't have enough reputation to comment (my previous answer has been converted to a comment for some reason), but want to help, so I'm writing another answer.
If you can boot to command line, try opening the /var/log/syslog and see if there are any suspicious errors listed at the time of your last unsuccessful boot.
nano /var/log/syslog

You could also try to disable the automatic boot to desktop manager by editing your GRUB file
sudo nano /etc/default/grub

change the "quiet splash" to "" and then run
sudo update-grub

If you have lightdm installed, you may have to also do
sudo touch /etc/init/lightdm.override

to disable the LightDM autostart.
If you manage to boot to CLI without the recovery mode with these settings, run
startx

or (if you have gdm installed)
sudo service gdm start

or (if you have lightdm installed)
sudo service lightdm start

from your home folder and see if you can enter the X window system that way.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is a c# WebService with nullabele int BasicProfile 1.1 conform I want to implement a WebService that should be BasicProfile 1.1 conform.
The WebMethod should be something like this:
byte[] Test(int? count)

Is this call BasicProfile 1.1 conform?
How can I check BasicProfile 1.1 conformability?


text:
Q: syntax error, unexpected 'something' (T_VARIABLE) Why I'm getting this error?

syntax error, unexpected '$flag' (T_VARIABLE)

    while(odbc_fetch_row($result))
    {
        $name = odbc_result($result,"CharName");
        $lvl = odbc_result($result,"CharLevel");
        $class = odbc_result($result,"CharClass");
        $flag = 0;
        for($i=0;$i<count($gms);$i++)
        {
            if($name = $gms[$i]
                $flag = 1;
        }
    }

A: you have a syntax error here
if($name = $gms[$i]

change to
if($name == $gms[$i])

wich is causing T_VARIABLE error, just close bracket and add = and you are ready to go

A: You have not closed bracket after if condition
if($name = $gms[$i]

A:  for($i=0;$i<count($gms);$i++)
        {
            if($name == $gms[$i])//closing paranthesis and '==' to compare
                $flag = 1;
        }

A: You missed a ) paranthesis. Change this line from
if($name = $gms[$i]
        $flag = 1;

To,
if($name = $gms[$i])
        $flag = 1;


text:
Q: Why is rails server listing on tcp I am working on a project which is an updated version of a new project. Using vagrant to load virtual environment and when i run
RAILS_ENV=development bundle exec rails s

The following is returned:
=> Booting Puma
=> Rails 5.0.0.1 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
Puma starting in single mode...
* Version 3.6.0 (ruby 2.3.3-p222), codename: Sleepy Sunday Serenity
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://localhost:3000
Use Ctrl-C to stop

When i visit the browser I have tried localhost:3000 and 127.0.0.1:3000 but keep getting:
ERR_CONNECTION_REFUSED

On the previous version of this project on a different repository loaded it was accessible via these URL's. This project has been updated to Rails 5 but dont know why it is listening on TCP rather than HTTP. Any suggestions?

A: As it has been already suggested, make sure that the server is bounden to 0.0.0.0 so that all interfaces can access it.
You might try:
RAILS_ENV=development bundle exec rails s -b 0.0.0.0


text:
Q: Flutter onPressed() vs onTap() I've been using Flutter for about 8 weeks.
It's awesome, no question.
However, there has been something bugging me since I've started, and that is, why do some widgets have an onTap method whilst others have onPressed? Google has not been able to give me any answers.
If this is not relevant or on-topic enough for Stack Overflow, sorry about that, please point me to the right community to ask.

A: The Source of differents between onTap and onPressed is GestureDetector used in buttons.
onTap should give you response in the first moment touching the screen.
onPressed should be equvalent to .onTapDown property - the last moment touching the screen.

A: In my experience, onTap() is used for any gesture capture and onPressed() especially for buttons.
Just like in real life, when you have to use a button, you'll press it.
Hope this will solve your troubles even though I'm not totally sure about that.

A: Currently they both are same. Just use onPressed with Buttons and onTap with other widgets.
Flutter is still new so there are lots of overlaps. May be in future updates they will make it more streamline . Like they will merge many widgets which are almost same.


text:
Q: Pandas group by is dropping the dimnension on which the grouping is done I have 2 pandas dataframes. Each has a dimension and a metric. I need to aggregate the metric based on the dimension in each table and join them based on the dimension.
So:
A
dim1 met1
 a     100
 a     200
 b      50

B
    dim2 met2
     a     70
     a     20
     c      50

I use pandas.groupby() on each dataframe, but when I check the result of the groupby by doing .dtypes, I see that the dim1 dim2 is no longer present in the aggregated output.
So now, when I try to join based on dim1=dim2, I get message that dim1,dim2 does not exist.
What did I do wrong?

A: The default behaviour with pandas groupby API is to have the grouper become an index in the output.
You can circumvent this by specifying as_index=False when grouping. For more information, see the docs.

as_index : boolean, default True
For aggregated output, return object with group labels as the index.
  Only relevant for DataFrame input. as_index=False is effectively
  "SQL-style" grouped output

Not applicable when grouping Series.


text:
Q: Thermodynamic temperature In Feynman's lectures an argument for efficiency of engines goes as: If an engine absorbs heat $Q_1$ at temperature $T_1$ and heat $Q_2$ at temperature $T_2$, and both times give the same heat $Q$s at thermodynamic temperature $1\,\mathrm{K}$ then $\frac{Q_1}{T_1}=\frac{Q_2}{T_2}$.
Does this imply that no matter from which temperature the body absorbs heat the heat it gives to the standard temperature will always be constant? Because then only it makes sense for the relationship to hold for any two temperatures $T_1$ and $T_2$.

A: I am not familiar with this part of Feynman's lecture, but based on the information you provided I think his point was regarding entropy.  Specifically:
$$S = \frac{Q}{T}$$
Where $S$ is entropy [J/K], $Q$ is heat [J], and $T$ is temperature [K] (stricly speaking it should be $\Delta S=\Delta Q/T$ for the change in the amount of entropy and thermal energy due to it being transferred, but I'm trying to be consistent with your notation).  This tells you how much entropy is transferred by $Q$ joules of heat at temperature $T$.  If in both cases (1 and 2) the heat engine rejected the same amount of heat, $Q_{s}$, to the cold bath at the same temperature, $T_{s}=1K$, then that means for both cases the heat engine rejected the same amount of entropy, $Q_{s}/T_{s}$, into the cold bath.  At steady state operation a heat engine accumulates no entropy (by definition of "steady state" it means no quantity--entropy included--changes over time).  This means that the heat engine must dispose of all entropy absorbed or generated by rejecting it into a cold bath (this is why all heat engines require a cold reservoir).  Therefore, if the heat engine rejected the same amount of entropy in both cases, it must have absorbed the same amount of entropy from the hot bath for both cases (no entropy generation assuming Carnot heat engines).  So, the entropy absorbed was the same for case 1 and case 2:
$$S_{1}=S_{2}$$
And so, it follows that
$$\frac{Q_{1}}{T_{1}}=\frac{Q_{2}}{T_{2}}$$
It is entirely possible, however, for the heat engine to absorb a different amount of entropy in a different cycle (either from absorbing a different $Q$, or from a different $T$, or both).  In this case, the heat it gives to the standard temperature (the cold bath) would be different.


text:
Q: Flutter Web How to Convert Uint8List to File I am having trouble on converting Uint8List image to File on flutter web since dart:io is not supported on the web, i need it to be file in order to upload it to FirebaseStorage, is there any workaround for this ? thankyou

A: Since dart:io isn't avalible on web, you can use the universal_io package.
Add it to your pubspec.yaml.
import 'package:universal_io/io.dart';

File createFileFromBytes(Uint8List bytes) => File.fromRawPath(bytes);


text:
Q: Explain how this stochastik function works In the book "Clojure for Finance" I found a function like that:
(defn stochastic-k [last-price low-price high-price]
  (let [hlrange (- high-price low-price)
        hlmidpoint (/ hlrange 2)
        numerator (if (> last-price hlmidpoint)
                    (- last-price hlmidpoint)
                    (- hlmidpoint low-price))]
     (/ numerator hlrange)))

The author describes it as:

stochastic-k: This gives us our percentage of price movement of the high/low price.

(Quote and code from "Clojure for Finance", by Timothy Washington)
I tried the function in the REPL, but it's output doesn't make sense to me:
user=> (println (stochastic-k 18 13 23))
13/10

So the result is 1.3, but I would actually expect 1.0, because 18 is the midpoint of the range from 13 to 23, as far as I can tell.
Can anyone explain to me how the function is supposed to work?

A: There appears to be a bug in the implementation in my opinion. I think the numerator should be like:
numerator (if (> last-price hlmidpoint)
                    (- last-price hlmidpoint)
                    (- hlmidpoint last-price))

And then the function would produce a fraction representing how much does the last-price differ from the average price in the range.


text:
Q: Importing urllib in Python 3.5 I have the following code:
import urllib
import wget as wget
request = urllib.request.Request(url)

For the last line PyCharm shows a warning:

Cannot find reference 'request' in '__init__.py'

The code works finde though, I receive a reply from the server I query.
The import import wget as wget is being shown as unused. When I remove that import, I get the following exception at runtime:

AttributeError: module 'urllib' has no attribute 'request'

Can somebody explain to me

*

*How these two things are connected

*Why urllib.request.Request is obviously wrong(?) despite being documented here?

A: Because request is a submodule, you have to write its name so Python will also import it
import urllib.request

Reasoning:
If you have a module with many submodules, loading all of them might be an expensive thing to do and might create problems with things that are unrelated to your program.
Imagine there's a module called urllib.foo that only works on Windows and you are working on Linux. If the import system were to import all submodules, it could crash on your system even if you don't want to use it.
The wget module you are using imports the urllib.request to use for itself, so python will cache its import and it will be part of the urllib object.

A: urllib itself does not import urllib.request. Module wget probably does an import urllib.request. From there on, urllib.request actually is referenceable.
Suggested solution: write import urllib.request, and then it should work without the import wget.


text:
Q: Java 8 Stream String Null Or Empty Filter I've got Google Guava inside Stream:
this.map.entrySet().stream()
.filter(entity -> !Strings.isNullOrEmpty(entity.getValue()))
.map(obj -> String.format("%s=%s", obj.getKey(), obj.getValue()))
.collect(Collectors.joining(","))

As you see there is a statement !String.isNullOrEmpty(entity) inside the filter function.
I don't want to use Guava anymore in the project, so I just want to replace it simply by:
string == null || string.length() == 0;

How can I do it more elegant?

A: You can create your own Strings class with your own predicate:
public class Strings {
  public static boolean isNotNullOrEmpty (String str) {
    return str != null && !str.isEmpty();
  }
}

Then in your code:
.filter(Strings::isNotNullOrEmpty)

But as @fge mentionned, you can't use that on a Map.Entry<?,?>...

A: In java 11 there is a new method Predicate::not.
So you can filter out empty string :
list.stream()
  .filter(Objects::nonNull)
  .filter(Predicate.not(String::isEmpty))

A: You can break down the filter into two steps:
this.map.entrySet().stream()
    .filter(entity -> entity.getValue() != null)
    .filter(entity -> !entity.getValue().isEmpty())
    .map(obj -> String.format("%s=%s", obj.getKey(), obj.getValue()))
    .collect(Collectors.joining(","))

On a side note, most Map.Entry.toString() implementations do exactly what you're doing in map(), so you could theoretically just do map(Map.Entry::toString). But I wouldn't rely on that unless you're producing a toString() or something that doesn't require documented or deterministic behavior.
Also, I know you want to abandon Guava, but here's a solution that might make you reconsider:
Joiner.on(',').withKeyValueSeparator("=")
      .join(Maps.filterValues(map, Predicates.not(Strings::isNullOrEmpty)));

A: You can write your own predicate:
final Predicate<Map.Entry<?, String>> valueNotNullOrEmpty
    = e -> e.getValue() != null && !e.getValue().isEmpty();

Then just use valueNotNullOrEmpty as your filter argument.

A: If you prefer to use commons-lang3, StringUtils has

*

*isEmpty()

*isNotEmpty()

*isBlank()

*isNotBlank()
These methods can be used in filters as method references:
this.stringList.stream().filter(StringUtils::isNotBlank);

or as lambdas:
this.stringList.stream().filter(s -> StringUtils.isNotBlank(s));

A: It works for me: list.stream().filter(el-> el != null && !el.toString().trim().isEmpty()).collect(Collectors.toList());


text:
Q: Circular template dependecy of variadic class templates I'm trying to build a 'non-centralized' graph structure where nodes and edges cross-point themselves. Quite similar to this: Circular template reference structure.
Although, I'm trying to support that nodes can hold several edges types of varying 'arity'. And that, reciprocally, edge's many nodes types.
¿Is there a way to achieve this with generic programming / metaprogramming without relaying on inheritance?
The following approach that I tried highlights the problem:
#include <iostream>
#include <tuple>
#include <list>

using namespace std;

template<class ...EdgeTypes>
class node
{
  public:
    std::tuple<std::list<EdgeTypes*>...> edges_;

    template<size_t I>
    using container_value_type_i = typename std::tuple_element<I, decltype(edges_) >::type::value_type;

    template< std::size_t I>
    void addEdge(const container_value_type_i<I>& e)
    { std::get<I>(edges_).push_back(e); }
};

template<template<class...> class ...V>
class edge
{

  public:

    std::tuple<V<edge>*...> vertices_;
    //           ^^^^
    // its forcing that all nodes have the same number of 'edges types' (one)
    // and that they are of the same 'arity' as edge object

    template<size_t I>
    using vertex_type_i = typename std::tuple_element<I, decltype(vertices_) >::type;

    template< std::size_t I>
    void addNode(const vertex_type_i<I>& e)
    { std::get<I>(vertices_) = e; }

};

int main()
{
  edge<node> unary_edge;
  edge<node, node> binary_edge;

  node<edge<node>> unary_node_of_unary_edges;

  unary_node_of_unary_edges.addEdge<0>(&unary_edge);
  unary_edge.addNode<0>(&unary_node_of_unary_edges);

  node<edge<node, node>> unary_node_of_binary_edges;

  unary_node_of_binary_edges.addEdge<0>(&binary_edge);

  // This won't compile as edge type of node's edges are not the same as unary_edge
  //unary_edge.addNode<0>(unary_node_of_binary_edges);

  node<edge<node>, edge<node, node>> binary_node_of_unary_edges_and_binary_edges;

  binary_node_of_unary_edges_and_binary_edges.addEdge<0>(&unary_edge);
  binary_node_of_unary_edges_and_binary_edges.addEdge<1>(&binary_edge);

  // This won't compile as nodes's edges are not all the same type
  //unary_edge.addNode<0>(&binary_node_of_unary_edges_and_binary_edges);
  return 0;
}

A: You could encode the entire airity structure of the graph in the type system, but I doubt that is useful.
Type erasure is always an option.   Ignoring that, you could use templates for both edge type and node type, and max airity.
template<template<class...>class Z>
struct ztemplate{
  template<class...Ts>
  using z=Z<Ts...>;
};
template<class zE, class Indexes>
class Node;
using zNode=ztemplate<Node>;
template<class zN, class Indexes, class Count>
class Edge;
using zEdge=ztemplate<Edge>;

template<class zE, std::size_t...Is>
class Node<zE,std::index_sequence<Is...>>{
  std::tuple< std::list< zE::template z<zNode, std::index_sequence<Is...>, std::integral_constant<std::size_t,Is>>... > edges;
};
template<class zN, std::size_t...Is, std::size_t A>
class Edge<zN,std::index_sequence<Is...>, std::integral_constant<std::size_t,A>>{
  std::array< zN::template z<zEdge, std::index_sequence<Is...>>*, A> nodes;
};

or somesuch.


text:
Q: Can a git pre-commit hook add a file to the repo? I'm keeping a text file of my git log in my working directory, and I have a script that updates it after a commit. This is fine, but the effect of this is that the version that is inside the repo is always one commit behind.
Is it possible to write a pre-commit hook that would call a script and add a file to the repo, in effect saving the text version of the log with the current commit info inside it?
I'm new to git hooks and have no idea whatsoever how this would work, if it's even possible. I appreciate the help!

A: Short answer: no. The log contains the SHA1 of the commit, which depends on the contents of the commit. If you change the log, you'll change the commit, and it'll still be invalid.
I wonder why you're trying to do this, really. Within the repository, git log is just as good as cat saved-git-log. If you want this as a changelog, for released versions, simply create it as part of your build/deploy process, for example something like this:
tarname=my-project-$(git describe HEAD).tar
git log > changelog.txt
git archive --format=tar HEAD > $tarname
tar -Af $tarname changelot.txt
gzip $tarname

A: I just pull the full logs from an RSS feed on Bitbucket/Github. It seems that would be the simplest way to achieve what you're asking especially when using Heroku.


text:
Q: CudaMemcpyDeviceToHost failing with error code unspecified launch failure I have a bool in the host which is copied to the device and then copied back to the host in a loop. This is my code.
bool h_done = true;
bool* d_done;

    while(h_done != false){

      err = cudaMemcpy(d_done, &h_done, sizeof(bool), cudaMemcpyHostToDevice);
      ......
      bfs<<<blocksPerGrid, threadsPerBlock>>>(h_edges, h_vertices, d_current_depth, d_done);
      err = cudaMemcpy(&h_done, d_done, sizeof(bool), cudaMemcpyDeviceToHost);
     ......
     }

The code fails at the point where the bool has to be copied back from the device to the host with the following error.
Failed to copy d_done to host(error code unspecified launch failure)!

What am I doing wrong here.

A: Perhaps you are doing it elsewhere, but based on your provided code, you aren't doing:
d_done=(bool *)cudaMalloc(sizeof(bool))

Other great examples exist here:

https://docs.nvidia.com/cuda/cuda-c-programming-guide/#device-memory


text:
Q: Automapper override values which are not in source Hi have a problem with auomapper where i try to use the Automapper.Mapper(src, dest) without loosing the values in the dest after doing the mapping.
I have a class which has a list of objects like below
public class UpdateShipmentDetailDto
    {
        public bool IsDocument { get; set; }

        public List<UpdateItemDetailDto> ItemDetails { get; set; } = new();

    }

which i want to map to
public class SCS_OUT_Manifest
    {
        public Guid ManifestId { get; set; }

        public ICollection<SCS_OUT_ManifestItem> SCS_OUT_ManifestItems { get; set; } = new List<SCS_OUT_ManifestItem>();
    }

The UpdateItemDetailDto class looks like this
public class UpdateItemDetailDto
    {
        public Guid ItemId { get; set; }
        public string ItemDescription { get; set; }
        public int Qty { get; set; }
        public Guid UnitsId { get; set; }
        public decimal ItemValue { get; set; }
    }

And the SCS_OUT_ManifestItem class looke like
 public class SCS_OUT_ManifestItem
    {
        public Guid ItemId { get; set; }
        public Guid ManifestId { get; set; }
        public string ItemDescription { get; set; }
        public int Qty { get; set; }
        public Guid UnitsId { get; set; }
        public decimal ItemValue { get; set; }
}

Im performing a maaping like below, which map from ItemDetails (which is a list) to SCS_OUT_ManifestItems (which is also a ICollection).
 _mapper.Map(updateShipmentDetailDto.ItemDetails, manifest.SCS_OUT_ManifestItems);

The problem after mapping is done the properties which in the destination collection are set to the default values.
for example the ManifestId inthe SCS_OUT_ManifestItem manifest.SCS_OUT_ManifestItems which is not in updateShipmentDetailDto.ItemDetails is set to its default Guid value 00000000-0000-0000-0000-000000000000.
But if i run this in a loop like below it works.
foreach (var item in manifest.SCS_OUT_ManifestItems)
            {

                _mapper.Map(updateShipmentDetailDto.ItemDetails.Single(s => s.ItemId == item.ItemId), item);

            }

Please help! thanks in advance

A: Try map your lists and your itens and use the same name ÏtemDetails" in both lists.
var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<UpdateItemDetailDto, SCS_OUT_ManifestItem>();
    cfg.CreateMap<UpdateShipmentDetailDto, SCS_OUT_Manifest>();
});
var _mapper = config.CreateMapper();

var updateShipmentDetailDto = new UpdateShipmentDetailDto();
var updateItemDetailDto = new UpdateItemDetailDto();
var manifest = new SCS_OUT_Manifest();
updateItemDetailDto.ItemId = Guid.NewGuid();
updateItemDetailDto.UnitsId = Guid.NewGuid();
manifest.ManifestId = Guid.NewGuid();

updateItemDetailDto.ItemDescription = "test";
updateItemDetailDto.Qty = 10;
updateItemDetailDto.ItemValue = 25.50M;
updateShipmentDetailDto.ItemDetails = new List<UpdateItemDetailDto>();
updateShipmentDetailDto.ItemDetails.Add(updateItemDetailDto);

_mapper.Map(updateShipmentDetailDto.ItemDetails, manifest.ItemDetails);

Console.WriteLine($"DTO Guid: {updateShipmentDetailDto.ItemDetails[0].ItemId}, Desc: {updateShipmentDetailDto.ItemDetails[0].ItemDescription}");
foreach (var item in manifest.ItemDetails)
{
    Console.WriteLine($"Guid: {item.ItemId}, Desc: {item.ItemDescription}");
}
Console.WriteLine($"Guid Manifest: {manifest.ManifestId}");


text:
Q: How to detect circle defects? Is there any way to tell if a circle has such defects? Roundness does not work. Or is there a way to eliminate them?

    perimeter = cv2.arcLength(cnts[0],True)
    area = cv2.contourArea(cnts[0])
    roundness = 4*pi*area/(perimeter*perimeter)
    print("Roundness:", roundness)

A: The "roundness" measure is sensitive to a precise estimate of the perimeter.  What cv2.arcLength() does is add the lengths of each of the polygon edges, which severely overestimates the length of outlines. I think this is the main reason that this measure hasn't worked for you. With a better perimeter estimator you would get useful results.
An alternative measure that might be more useful is "circularity", defined as the coefficient of variation of the radius. In short, you compute the distance of each polygon vertex (i.e. outline point) to the centroid, then determine the coefficient of variation of these distances (== std / mean).
I wrote a quick Python script to compute this starting from an OpenCV contour:
import cv2
import numpy as np

# read in OP's example image, making sure we ignore the red arrow
img = cv2.imread('jGssp.png')[:, :, 1]
_, img = cv2.threshold(img, 127, 255, 0)

# get the contour of the shape
contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
contour = contours[0][:, 0, :]

# add the first point as the last, to close it
contour = np.concatenate((contour, contour[0, None, :]))

# compute centroid
def cross_product(v1, v2):
    """2D cross product."""
    return v1[0] * v2[1] - v1[1] * v2[0]

sum = 0.0
xsum = 0.0
ysum = 0.0
for ii in range(1, contour.shape[0]):
    v = cross_product(contour[ii - 1, :], contour[ii, :])
    sum += v
    xsum += (contour[ii - 1, 0] + contour[ii, 0]) * v
    ysum += (contour[ii - 1, 1] + contour[ii, 1]) * v

centroid = np.array([ xsum, ysum ]) / (3 * sum)

# Compute coefficient of variation of distances to centroid (==circularity)
d = np.sqrt(np.sum((contour - centroid) ** 2, axis=1))
circularity = np.std(d) / np.mean(d)

A: This make me think of a similar problem that I had. You could compute the signature of the shape. The signature can be defined as, for each pixel of the border of the shape, the distance between this pixel and the center of the shape.
For a perfect circle, the distance from the border to the center should be constant (in an ideal continuous world). When defects are visible on the edge of the circle (either dents or excesses), the ideal constant line changes to a wiggly curve, with huge variation when on the defects.
It's fairly easy to detect those variation with FFT for example, which allows to quantify the defect significance.
You can expand this solution to any given shape. If your ideal shape is a square, you can compute the signature, which will give you some kind of sinusoidal curve. Defects will appear in a same way on the curve, and would be detectable with the same logic as with a circle.

I can't give you an code example, as the project was for a company project, but the idea is still here.

A: Here is one way to do that in Python/OpenCV.

*

*Read the input

*Threshold on white (to remove the red arrow)

*Apply Hough Circle

*Draw the circle on the thresholded image for comparison

*Draw a white filled circle on black background from the circle parameters.

*Get the difference between the thresholded image and the drawn circle image

*Apply morphology open to remove the ring from the irregular boundary of the original circle

*Count the number of white pixels in the previous image as the amount off defect

Input:

import cv2
import numpy as np

# Read image
img = cv2.imread('circle_defect.png')
hh, ww = img.shape[:2]

# threshold on white to remove red arrow
lower = (255,255,255)
upper = (255,255,255)
thresh = cv2.inRange(img, lower, upper)

# get Hough circles
min_dist = int(ww/5)
circles = cv2.HoughCircles(thresh, cv2.HOUGH_GRADIENT, 1, minDist=min_dist, param1=150, param2=15, minRadius=0, maxRadius=0)
print(circles)

# draw circles on input thresh (without red arrow)
circle_img = thresh.copy()
circle_img = cv2.merge([circle_img,circle_img,circle_img])
for circle in circles[0]:
    # draw the circle in the output image, then draw a rectangle
    # corresponding to the center of the circle
    (x,y,r) = circle
    x = int(x)
    y = int(y)
    r = int(r)
    cv2.circle(circle_img, (x, y), r, (0, 0, 255), 1)

# draw filled circle on black background
circle_filled = np.zeros_like(thresh)
cv2.circle(circle_filled, (x,y), r, 255, -1)

# get difference between the thresh image and the circle_filled image
diff = cv2.absdiff(thresh, circle_filled)

# apply morphology to remove ring
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
result = cv2.morphologyEx(diff, cv2.MORPH_OPEN, kernel)

# count non-zero pixels
defect_count = np.count_nonzero(result)
print("defect count:", defect_count)

# save results
cv2.imwrite('circle_defect_thresh.jpg', thresh)
cv2.imwrite('circle_defect_circle.jpg', circle_img)
cv2.imwrite('circle_defect_circle_diff.jpg', diff)
cv2.imwrite('circle_defect_detected.png', result)

# show images
cv2.imshow('thresh', thresh)
cv2.imshow('circle_filled', circle_filled)
cv2.imshow('diff', diff)
cv2.imshow('result', result)
cv2.waitKey(0)
cv2.destroyAllWindows()

Input without Red Arrow:

Red Circle Drawn on Input:

Circle from HoughCircle:

Difference:

Difference Cleaned Up:

Textual Result:
defect count: 500


text:
Q: My VBA code does not work in Office 2007 I developed and tested some VBA code using Office 2013 and was working perfectly. BUT when I ran it on Office 2007, the code breaks at this line...
ActiveSheet.Range("D6").Value = "=" & Worksheets("Formula").Range("AlarmsStatusFormula").Value

the error msg I received was Run-time error 1004: Application-defined or object-defined error. D6 is part of the same table that contains a column called "Message".
AlarmStatusFormula contains this formula
IF(OR(ISNUMBER(SEARCH({"Recover"," NR"},[Message]))),"FOUND","")

Note the AlarmStatusFormula named range has the workbook scope.
Can it be something to do with the way Excel 2007 handles named ranges vs 2013?
Can you please help with this?

A: In Excel 2007 it should be TableName[Message] rather than just [Message]


text:
Q: How to include additional characters into query result cleanly? I'm trying to set my query result to follow format needed by javascript array. generally, the format should look like this:
[
"mydata1",
"mydata2",
]

Thus, based on my limited SQL query knowledge, this is the result that I was able to achieve so far based on this query:
SELECT '"',mydata, '",' FROM Table WHERE ID = 44946
OR ID = 12345

However, the results will appear in 3 different columns, and it will leave some space between them.
"   2859440635959   ",
"   2749566484535   ",

Then I'll have to open notepad and remove all the spaces.
Is there any other query workaround or anything that may simplify this process?

A: SELECT '"',mydata, '",' FROM Table

Based on this statement, you are creating 3 columns, namely ", mydata and ",.
In order to select a column with additional values (format). You can use concatenate function whereas, "your_data," is being concatenated as a column named RESULT.
SELECT CONCAT('"', mydata, '",') as RESULT from Table


text:
Q: how to serialize entities that have a one to many relationship and a pagination in entity framework? I have a two Model for two table having foreign key relationship. I have to get record from both table in single request.
The structure of model is as follows:-

*

*EmployeeRecord.cs

public partial class EmployeeRecord
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public tblEmployeeRecord()
        {
            this.countries = new HashSet<tblCountry>();
        }

        public int EmployeeId { get; set; }
        public string Name { get; set; }
        public string userName { get; set; }
        public string userRole { get; set; }
        public string id { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Country> countries { get; set; }

    }

2.Country.cs
 public partial class Country
    {
        public int CountryId { get; set; }
        public int EmployeeId { get; set; }
        public string CountryName { get; set; }

       public virtual EmployeeRecord employeeRecord { get; set; }
    }

*EmployeeController.cs

 public class EmployeeRecordsController : ApiController
    {
        private EstorageEntitiesforCombineView db = new EstorageEntitiesforCombineView();

        // GET: api/EmployeeRecords
        public IEnumerable<EmployeeRecord> GetEmployeeRecords([FromUri]PagingParameterModel pagingparametermodel)
        {
             var source= db.EmployeeRecords.OrderBy(a => a.EmployeeId);

            // Get's No of Rows Count
             if (pagingparametermodel.userRole == "HR")
            {
                 source= (from a in db.EmployeeRecords
                        where a.userRole == "HR"
                        select a).OrderBy(a => a.EmployeeId);
            }
            else if(pagingparametermodel.userRole == "eStorage Admin")
            {
                source = (from a in db.EmployeeRecords
                          where a.userRole == "eStorage Admin"
                          select a).OrderBy(a => a.EmployeeId);

            } else if(pagingparametermodel.userRole == "SharedService")
            {
                source = (from a in db.EmployeeRecords
                          where a.userRole == "SharedService"
                          select a).OrderBy(a => a.EmployeeId);

            }
             if(pagingparametermodel.toSearch == 1 && pagingparametermodel.userRole == "ALL")
            {
                source = (from b in db.EmployeeRecords
                          where b.Name.StartsWith(pagingparametermodel.name)
                          select b).OrderBy(a => a.EmployeeId);

            }else if (pagingparametermodel.toSearch==1) {
                source= (from b in db.EmployeeRecords
                        where b.Name.StartsWith(pagingparametermodel.name) && b.userRole==pagingparametermodel.userRole
                        select b).OrderBy(a => a.EmployeeId);

            }
            int count = source.Count();

            // Parameter is passed from Query string if it is null then it default Value will be pageNumber:1
            int CurrentPage = pagingparametermodel.pageNumber;

            // Parameter is passed from Query string if it is null then it default Value will be pageSize:20
            int PageSize = pagingparametermodel.pageSize;

            // Display TotalCount to Records to User
            int TotalCount = count;

            // Calculating Totalpage by Dividing (No of Records / Pagesize)
            int TotalPages = (int)Math.Ceiling(count / (double)PageSize);

            // Returns List of Customer after applying Paging
            var items = source.Skip((CurrentPage - 1) * PageSize).Take(PageSize).ToList();

            // if CurrentPage is greater than 1 means it has previousPage
            var previousPage = CurrentPage > 1 ? "Yes" : "No";

            // if TotalPages is greater than CurrentPage means it has nextPage
            var nextPage = CurrentPage < TotalPages ? "Yes" : "No";

            // Object which we are going to send in header
            var paginationMetadata = new
            {
                totalCount = TotalCount,
                pageSize = PageSize,
                currentPage = CurrentPage,
                totalPages = TotalPages,
                previousPage,
                nextPage
            };

            // Setting Header
            System.Web.HttpContext.Current.Response.Headers.Add("Paging-Headers", Newtonsoft.Json.JsonConvert.SerializeObject(paginationMetadata));
            // Returing List of Customers Collections
            return items;

        }
}

I want the response as follows :-
[{
        "tblCountries": [
            {
                "CountryId": 265,
                "EmployeeId": 350,
                "CountryName": "INWEST"
            }
        ],
        "EmployeeId": 350,
        "Name": "ABC",
        "userName": "abc@mail.com",
        "userRole": "HR",
        "id": nbh546652n45
 }]

But the response is as follows:-
[{
        "tblCountries": [],
        "EmployeeId": 350,
        "Name": "ABC",
        "userName": "abc@mail.com",
        "userRole": "HR",
        "id": nbh546652n45
 }]

I have also tried, Include(a => a.countries) as follows:-
source= (from a in db.EmployeeRecords
            where a.userRole == "HR"
           select a).Include(a => a.countries).OrderBy(a => a.EmployeeId);

But i am getting following error:-
<ExceptionMessage>
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace/>
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Object graph for type 'System.Collections.Generic.HashSet`1[[eStorageApi.Models.tblCountry, eStorageApi, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' contains cycles and cannot be serialized if reference tracking is disabled.
</ExceptionMessage>
<ExceptionType>
System.Runtime.Serialization.SerializationException
</ExceptionType>

Tried including these LOCs into webApiConfig.cs:-
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling= Newtonsoft.Json.ReferenceLoopHandling.Ignore;
config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None;

Still getting the same error.

A: Project your domain model into something else before returning it from your api. This better controls the response data format and if a property gets added (such as ssn) it doesn't get inadvertently exposed. This also has the added benefit of fixing your cyclical references.
return items.Select(i => new {
    i.Name,
    i.Username,
    ...
    Countries = i.Countries.Select(c => new {
            c.CountryId,
            c.CountryName,
            ...
        }
};

A: You need to do the relationship between employeeRecord and countries. Try with this:
 source= db.EmployeeRecords.Include(e => e.countries).Select(c => c.employeeRecord)
           .Where(a => a.userRole == "HR");

And when you do the request you need specify text: Application/Json


text:
Q: JavaFX wait after setting imageview I need to wait after setting an Imageview, but if I use
Thread.sleep(1000)

after setting the imageView the whole application sleeps for one second but the imageView will not be set during this period of time.
I would like to know how can I pause the whole application after setting the imageview.
For instance, it's a game of cards (briscola), and after the computer played a card, or I played a card the application should pause to show which cards are on the plate and who won the hand.
Thanks in advance.
UPDATE:
This is what I tried with the tasks, with no success as the images
    private void setImages(BriscolaModel model) {
    Set<Map.Entry<Player, BriscolaCard>> entries = model.getPlate().entrySet();

    // set images

    Task<Integer> task = new Task<Integer>() {
        @Override protected Integer call() throws Exception {
            for(Map.Entry<Player, BriscolaCard> entry : entries){
                plate.getImageViews().add(new ImageView(new Image(getClass().getClassLoader().getResourceAsStream(entry.getValue().getRelativePath()),200,100,true, false)));
            }
            plate.getCards().getChildren().setAll(plate.getImageViews());
            return 0;
        }
    };

    Thread th = new Thread(task);
    th.start();

    // clear images

    Task <Integer> clearTask = new Task<Integer>() {
        @Override
        protected Integer call() throws Exception {
            clearImages();
            return 0;
        }
    };
    Thread clearThread = new Thread(clearTask);
    if(entries.size()==2){
        Platform.runLater(clearTask);
    }else {
        clearThread.start();
    }
}

2nd UPDATE:
This seem to work better (i randomly see the images for some milliseconds before being cleared), but how can I set the minimum time to wait before the Platform.runLater() ?
private void setImages(BriscolaModel model) {
    Set<Map.Entry<Player, BriscolaCard>> entries = model.getPlate().entrySet();

    for (Map.Entry<Player, BriscolaCard> entry : entries) {
        plate.getImageViews().add(new ImageView(new Image(getClass().getClassLoader().getResourceAsStream(entry.getValue().getRelativePath()), 200, 100, true, false)));
    }
    plate.getCards().getChildren().setAll(plate.getImageViews());

    Task<Void> waitTask = new Task<Void>() {
        @Override
        protected Void call() throws Exception {
            clearImages();
            return null;
        }
    };

    if(entries.size() == 2){
        Platform.runLater(waitTask);
    }

}

A: I found the solution, thanks to Rahul Singh for the suggestions!
private void setImages(BriscolaModel model) {
    Set<Map.Entry<Player, BriscolaCard>> entries = model.getPlate().entrySet();
    plate.getImageViews().clear();

    for (Map.Entry<Player, BriscolaCard> entry : entries) {
        plate.getImageViews().add(new ImageView(new Image(getClass().getClassLoader().getResourceAsStream(entry.getValue().getRelativePath()), 200, 100, true, false)));
    }
    plate.getCards().getChildren().setAll(plate.getImageViews());

    Task<Void> waitTask = new Task<Void>() {
        @Override
        protected Void call() throws Exception {
            Timeline timeline = new Timeline(new KeyFrame(
                    Duration.millis(2000),
                    ae -> clearImages()));
            timeline.play();
            return null;
        }
    };

    if(entries.size() == 2){
        Platform.runLater(waitTask);
    }

}


text:
Q: Javascript is disabled in your browser when logging with google through selenium I'm trying to login through gmail(Oauth2) with selenium test but all the time I'm getting the same error

You've reached this page because we have detected that JavaScript is disabled in your browser.The page you attempted to load cannot display properly if scripts are disabled.
  Please enable scripts and retry the operation or go back in your browser.

The JavaScript is enabled in Mozzila but i'm still getting this error. Is there any propertie that need to be set in selenium or is it problem in login with Oauth2?

A: The problem was with the Selenium web driver event. Instead of just driver.click the allow button after Oauthredirection I was calling driver.submit, so gmail was blocking this as security issue and redirect to no script found URL.


text:
Q: Transforming linear dynamical system to reduce magnitude of eigen values Consider a linear dynamical system
$\dot{x} = Ax + Bu$ with eigen values of high magnitude (can be both positive or negative), say in 900's. Can the system be transformed to reduce the magnitude of eigen values, say 900 reduces to 9 and vice versa.
My approach to was to consider a transformation matrix $T$ such that $z = Tx$, where $T$ is transformation matrices. Then the new dynamical system is
$\dot{z} = T\dot{x} = TAx + TBu = TAT^{-1}z + TBu$.
I was however not sure what should be the structure of $T$  be to minimizes the magnitude of eigen values of the system. Any lead in solving the problem will be appreciated.

A: A similarity transform can only change the eigenvectors and not the eigenvalues. The only way to achieve what you want would be to change the time scale, so $z(\tau)=x(\alpha\,t)$.

A: You can do it, although the change of coordinates is generally just continuous (the term topological equivalence may come in handy).
Let me exemplify it for a simple scalar problem. Consider $\dot x=ax$, the solution is $x(t)=\exp(at)x(0)$.
Now let $z=x^{b/a}$. Then the solution is transformed to $z(t)=[\exp(at)x(0)]^{b/a}=(\exp(at))^{b/a}x(0)^{b/a}=\exp(bt)z(0)$, which is the solution of $\dot z = bz$.
Of course a problem is the exponent $b/a$...
As commented previously, if you want a differentiable change of coordinates then the answer is negative, you cannot change the eigenvalues.


text:
Q: Pycharm - cannot import math module I have a problem because i can't import math module in pycharm and I need arctan2 function, from IDLE console I can do it and use functions.
When I go to the File/Settings/Project Interpreter section, I have that list:

When I want to add math package, I cannot found it

I reinstalled pycharm, and that didn't work for me
pycharm version: 2017.2.3
python version: 3.6.2
What can cause that? What other libraries contain trigonometry functions like arctan2?

A: The solution that seemed to work for you:
Choose the same python.exe for PyCharm as it's registered in your PYTHONPATHvariable. If it is not listed, you can add it manually in Settings -> Python Interpreter

A: Follow these steps:

*

*(Ctrl + Alt + S)

*Click (Project: xxxx),

*Choose (Project Structure) and select (home / yourUser / PycharmProjects / XXXX / venv / bin) and right-click (Excluded) or (Alt + E).

*Now click (+ Add Content Root) and see if it points to the following location (/ home / yourUser / PycharmProjects / XXXXX / venv / bin) and click OK.
Now close the IDE and open it again.


text:
Q: Set selected tab without selectedIndexChanged event firing Is there a way to set the selected tab of a tabControl without the selectedIndexchanged event firing?
e.g. Here the event fires when selecting myTabPage2 because myTabPage1 is the default:
Private Sub setupTabControl
    If blnHasAccount=true then
       MyTabControl.selectedTab=myTabPage1
    else
       MyTabControl.selectedTab=myTabPage2
    End if
End sub

Private Sub MyTabControl_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyTabControl.SelectedIndexChanged
    'Do stuff (but only when user has actually changed the tab themselves)
End Sub

A: When you set the new tabpage you could remove the event handler
Try
    RemoveHandler MyTabControl.SelectedIndexChanged, AddressOf Me.MyTabControl_SelectedIndexChanged
    .. do your works to change page here
    .. and then reconnect
Finally
    AddHandler MyTabControl.SelectedIndexChanged, AddressOf Me.MyTabControl_SelectedIndexChanged
End Try

It's important to enclose everything in a Try Finally to recover correctly from exceptions

A: One could falsify and check ComboBox.Enabled as a flag to use in the SelectedIndexChanged event while making changes then set back to true when done. Such events will still fire however (should they?) but at least you can assure status of the Global 'ComboBox' Variable.


text:
Q: Parsing nested XML using XMLin I spent a couple of hours trying to figure out how to make sense of this nested XML using XMLin but with no luck. I also tried the examples on this site; how can I get passed lca-data and iterate over prefix?
Dumper output is here:  http://pastebin.com/a4N8AtX1
Simple code:
$url = "http://www.localcallingguide.com/xmllocalprefix.php?npa=514&nxx=307";
$xml = new XML::Simple;
$data = $xml->XMLin(&getURL($url), ForceArray => [qw( lca-data prefix )]);

print Dumper( $data );

foreach $e (@{$data->{prefix}}) {
  print STDERR $e->{npa} . "\n";
}

No output comes out of it...
Thanks a mil in advance

A: First - really - read the manpage for XML::Simple. Especially pay attention to the bit that says:

The use of this module in new code is discouraged. Other modules are available which provide more straightforward and consistent interfaces.

Also - don't use & in front of subroutine calls - they're a bad idea in general - there's some very specific reasons to use them, and that isn't one.
And you should always use strict and warnings especially when posting code for someone else to look at.
Given your task seems to be outputting each npa element to STDERR I would suggest you could approach it like this instead - using XML::Twig instead of XML::Simple
#!/usr/bin/local/perl
use warnings;
use strict;

use LWP::Simple;
use XML::Twig;

my $url =
    'http://www.localcallingguide.com/xmllocalprefix.php?npa=514&nxx=307';

my $twig = XML::Twig->new(
    'twig_handlers' => {
        'npa' => sub { print STDERR $_->text, "\n"; }
    }
);
$twig->parse( get($url) );

Which sets a handler to 'trigger' on each npa subelement and print it - it does this as your XML is being parsed, which means you can do some quite neat tricks like modifying it as you're parsing (e.g. deleting or moving elements around).
If you're looking to simply iterate on an element, then you can either do it that way - which has a nice advantage of not using lots of memory, as XML can. (XML::Twig has purge which lets you discard any processed XML).
Otherwise, there's the 'children' or 'get_xpath' options:
my $twig = XML::Twig->new()->parse( get($url) );
foreach
    my $prefix ( $twig->root->first_child('lca-data')->children('prefix') )
{
    print $prefix ->first_child_text('npa'), "\n";
}

### alternatively:

foreach my $prefix ( $twig->root->get_xpath('./lca-data/prefix') ) {
    print $prefix ->first_child_text('npa'), "\n";
}

If you wanted to use a subroutine to process and purge you could do this:
sub process_prefix {
    my ( $twig, $prefix ) = @_;
    print $prefix ->first_child_text('npa'), "\n";
    $twig->purge;    #clears already parsed data - good if your XML is large!
}

my $url =
    'http://www.localcallingguide.com/xmllocalprefix.php?npa=514&nxx=307';

my $twig =
    XML::Twig->new( 'twig_handlers' => { 'prefix' => \&process_prefix } )
    ->parse( get($url) );

Well done on using a parser for XML parsing. But take a look at XML::Twig or XML::LibXML instead of XML::Simple - they're both much better tools for the job. (XML::Twig even has the simpify method which ... pretty much replicates XML::Simple if you really need it for backwards compatibility)
But the solution to your question as asked is:
foreach $e (@{ $data->{'lca-data'}[0]{'prefix'} } {


text:
Q: Como identificar valores duplicados en gridView Estoy cargando un GridView con varios registros desde el formulario, un campo es E-mail, al final del proceso envío un correo a las direcciones agregadas en esa columna.
El problema es que normalmente se va a repetir el campo E-mail por tanto se envía el correo tantas veces se repita en el GridView al mismo destinatario.
Estoy tratando de evitarlo de esta manera pero no funciona:
 For Each row As GridViewRow In GridView1.Rows
        If row.Cells(0).Text = row.Cells(0).Text Then
            'Duplicado
        Else
            'Enviar Correo
        End If
    Next

A: Se me ocurren dos formas:
Usando una lista
Recorres los registros de tu GridView agregando cada correo a una lista nueva. Una vez que tu lista está llena la ordenas en orden alfabético (eso lo puedes hacer con el método Sort).
Así los registros duplicados aparecen de forma contigua y será fácil identificarlos. Para enviar los correos recorres la lista verificando que el elemento actual sea diferente del inmediato anterior, de lo contrario significa que está duplicado.
Usando HashSet
HashSet es una estructura diseñada especialmente para manejar colecciones de objetos sin repeticiones.
Creas una instancia de HashSet. Recorres los registros de tu GridView y los agregas al HashSet. Al finalizar el HashSet contendrá todos los correos solo una vez. Bastará con recorrer sus elementos para enviar los correos.

A: Es que en tu lógica estas comparando si un registro es igual a uno mismo, es como hacer un 1 = 1, te va a dar siempre true.
Pensalo más simple, recorre con el foreach tus mails y carga en un List de string los correos a los que enviaste. Despues es simplemente validar antes de enviar el correo si ya fue enviado a esa dirección.
 Dim listCorreosEnviados As New List(Of String)
 Dim enviarCorreo As Boolean

    For Each row As GridViewRow In GridView1.Rows
        enviarCorreo = True
        //Si ya envie correos, verifico en el listado que no este repetido.
        If listCorreosEnviados.Count > 0 Then
            For Each correo As String In listCorreosEnviados
                If row.Cells(0).Text = correo Then
                    enviarCorreo = False
                End If
            Next

            If enviarCorreo = True Then
                //Envio el correo
            End If

        Else
          //Envio el correo
        End If

        //Por cada mail enviado, agrego el correo al listado
        listCorreosEnviados.Add(row.Cells(0).Text)
    Next

Saludos.


text:
Q: Utilize a ActionListener object from a separate JFrame class to main class I am building a GUI program in which specific code takes place when a certain condition is meant (JButton is pressed). I have a seperate class that constructs my Jframe called "MyFrame" .
Essentially I want to know the proper way to use my use a ActionListener/ ActionEvent from my "MyFrame" class in conjunction when a JButton is pressed in which it would correlate properly in the main class.
For example i am able to initiate specific code when a JButton is pressed in my MyFrame class through the actionPerformed provided method by java in my Myframe class,  I am just puzzled on how I can make the same thing work through my main class as well.
Any assistance would be appreciated
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Main {

    public static void main(String[] args) {
        MyFrame mf;

        mf= new MyFrame();
        Expenses exp ;
        BudgetSystem system ;
        ActionEvent e ;
    }
}

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

 class MyFrame extends JFrame implements ActionListener {
    JFrame myFrame;
    JPanel myPanel;
    JLabel greetText ;
    JButton addReportButton;
    JButton exitButton;

    ActionListener event ;
    BorderLayout layout ;

    MyFrame() {
        myFrame = new JFrame();
        myPanel = new JPanel();
        greetText = new JLabel();
        addReportButton = new JButton();
        exitButton = new JButton();

        myPanel.setBorder(null);
        myFrame.setPreferredSize(new Dimension(400,300));
        greetText.setText("Please choose one of the following options to begin:" );
        myPanel.add(greetText);
        myFrame.add(myPanel);
        addReportButton.setText("Add a budget report");
        addReportButton.addActionListener(this);
        myPanel.add(addReportButton);
        exitButton.setText("Close Program");
        exitButton.addActionListener(this);
        myPanel.add(exitButton);
        myFrame.setVisible(true);
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.setLocationRelativeTo(null);
        myFrame.pack();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        /*
        if (e.getSource()==addReportButton)
        {
            JOptionPane.showMessageDialog(myFrame,"This button Works!");
        }
        else if (e.getSource()== dummyButton)
        {
            JOptionPane.showMessageDialog(myFrame,"This is the dummy button ! , you are targeting specific buttons now ! ... YOU ROCK :) ");
        }else
        JOptionPane.showMessageDialog(myFrame,"This is does not work :( ");

         */
    }
}

I tried to make a specific ActionEvent object in main but that did not work properly.
I also tried to use a MyFrame object to access the actionPerformed method in java but that doesnt seem to work either.

A: If your goal is to add listeners to a JButton from another class, one option is to give the class that holds the JButton a public method that allows this to happen, for instance:
public void addMyButtonListener(ActionListener listener) {
    myButton.addActionListener(listener);
}

This would allow any object that holds an instance of the class that holds the JButton to call this method and pass in a listener.
For instance:
import java.awt.Dimension;
import java.awt.event.ActionListener;

import javax.swing.*;

public class AddOutsideActionListener {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            SomeGUI mainPanel = new SomeGUI();
            mainPanel.addMyButtonListener(e -> {
                String message = "Message from the main method";
                String title = "Message";
                int type = JOptionPane.PLAIN_MESSAGE;
                JOptionPane.showMessageDialog(mainPanel, message, title, type);
            });

            JFrame frame = new JFrame("Some GUI");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(mainPanel);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }

}

class SomeGUI extends JPanel {
    public static final int PREF_W = 600;
    public static final int PREF_H = 400;
    private JButton myButton = new JButton("My Button");

    public SomeGUI() {
        add(myButton);
        setPreferredSize(new Dimension(PREF_W, PREF_H));
    }

    public void addMyButtonListener(ActionListener listener) {
        myButton.addActionListener(listener);
    }
}


text:
Q: upload chromdriver to AWS Lambda Layer (Ruby 2.5) I tried upload AWS Lambda Layer to upload chromedriver within 50MB.
but it didn't work..
(chromedriver zip packege upload is worked, but if i inspect lambda directory, it could't found.)
def test(event:, context:)
    p Dir["/opt/**/*.*"]
end
=>
[
  "/opt/lib/ascii_and_mic.so",
  "/opt/lib/cyrillic_and_mic.so",
  ...
  (but not found chromedriver zip package)
]

anyone know how to upload chromedriver to AWS Lambda Layer?

*

*P.S : AWS Lambda is based Ruby 2.5

A: What about using gem webdrivers ?
It loads needed version of chromedriver (or any driver you need to your browser) automatically.

A: Make sure that the zip you are uploading follows the following structure and path
Ruby – ruby/gems/2.5.0 (GEM_PATH), ruby/lib (RUBY_LIB)
More info can be found here - https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html
See - Including Library Dependencies in a Layer section

A: For creating the archive for the layer do this:
bundle install --path vendor/bundle
cd vendor/bundle
mkdir ruby/gems
mv ruby/2.5.0 ruby/gems/
zip -r layer.zip ruby/gems/2.5.0/


text:
Q: Multiple Like Clauses Codeigniter I am trying to implement a search box for my website. In my user accounts table, I've divided the accounts into three, namely homeowners, admins, and deactivated users. I want the search function to be able to search across multiple columns (search by username, first name, last name, address, combination of first name and last name). However in my model, my WHERE clause seems to be ignored. In my search_homeowner function, I limit the results to display only the homeowners, but I get results that show the admin ones. I can't seem to have multiple LIKEs so I tried OR like. Here's the code.
Model:
function search_homeowner($searchquery) {

    $this->db->select('*')->from('accounts')->where('role', 0)-> where('isActive', 1);
    $this->db->like('firstname',$searchquery,'after');
    $this->db->or_like('lastname',$searchquery,'after');
    $this->db->or_like('username',$searchquery,'after');
    $this->db->or_like('address',$searchquery,'after');

    $query = $this->db->get();
    if($query->num_rows() > 0) {
        return $query->result();
    } else {
        return $query->result();
    }
}

Controller:
function search_homeowner() {
     $this->load->model('model_accounts');
     $searchquery = $this->input->post('search');

     if(isset($searchquery) and !empty($searchquery)) {
        $data['users'] = $this->model_accounts->search_homeowner($searchquery);
        $data['main_content'] = 'view_adminaccounts';
        $data['homeownerlinks']='';
        $this->load->view('includes/admin_accounts_template', $data);
     } else {
        redirect('admin_accounts/homeowner');
     }
}

A:  $whereaccounts=array('role'=>0,'isActive'=>1);
 $this->db->select('*')->from('accounts')->where($whereaccounts);
 $this->db->where('firstname', 'LIKE', '%' . $searchquery . '%');
 $this->db->where('lastname', 'LIKE', '%' . $searchquery . '%');
 $this->db->where('username', 'LIKE', '%' . $searchquery . '%');
 $this->db->where('address', 'LIKE', '%' . $searchquery . '%');
 $query = $this->db->get();

A: The or_like ci method you are using after which is prints "searchstring%". If you removed that it will be printed like this "%searchstring%". So please try like this
   function search_homeowner($searchquery) {
        $this->db->select('*')->from('accounts')->where('role', 0)-> where('isActive', 1);
        $this->db->like('firstname',$searchquery);
        $this->db->or_like('lastname',$searchquery);
        $this->db->or_like('username',$searchquery);
        $this->db->or_like('address',$searchquery);

        $query = $this->db->get();
        if($query->num_rows() > 0) {
            return $query->result();
        } else {
            return $query->result();
        }
    }


text:
Q: The environment variable "GOOGLE_APPLICATION_CREDENTIALS" in Google machines Background
I have a virtual machine running a code using Google SDK for diffrent products (like Google PubSub). According to Google documentation, my machine should have an environment variable called GOOGLE_APPLICATION_CREDENTIALS and its values should be pointing to a clear text file that holding the service account of the application.
I have done it and it's working for me.
The Problem
It sounds like an unsafe practice to store such a key, in plain text, inside a virtual machine. If the machine has been hacked, this key will be one of the first targets of the attacker.
I was expected to find a solution to "hide" this key file or just encrypt it with a key that my application will be able to read.
I found some code examples (C#), that allow the programmer to pass the credentials manually to the SDK functions. But, it's not a standard way to do it and it's being changed from one product to another (seems impossible in some products).
What is the best practice to do it?

A: Have a good read at the following:
https://cloud.google.com/docs/authentication/production
This describes a concept called "Application Default Credentials".  The concept here is that a Compute Engine (a virtual machine) has a default service account (that you can configure) associated with it.  Applications running on the Compute Engine can thus make requests from that Compute Engine to other GCP services and the requests to those services will implicitly appear to come from the service account configured against the Compute Engine.
The key phrase in the article is:

If the environment variable GOOGLE_APPLICATION_CREDENTIALS isn't set, ADC uses the default service account that Compute Engine, Google Kubernetes Engine, App Engine, Cloud Run, and Cloud Functions provide.


text:
Q: Cloudwatch Logs Subscription to Kinesis I have subscribed cloudwatch log group to kinesis data stream. The kinesis data stream has 2 shards. A lambda function is a consumer of the kinesis stream. I keep pushing logs to the cloudwatch log group. In the lambda event I see irregular number of data records from kinesis. The number varies from 1 to 17K.
Question 1: On what basis are the batches sent from cloudwatch to kinesis to lambda?
At times there are WriteProvisionedThrouhputExceeded exceptions. Assume the logs are throttled and not sent to kinesis.
Question 2: If so, will the cloudwatch retry sending those messages to kinesis on its own or not? In that case what should be done?


text:
Q: How to copy updated lines from another TortoiseSVN solution to my current solution? I am using Tortoise SVN. I want to update my solution using another solution. They have the same folder structure. Copy file if not exists. If there is conflict in file, I can update manually. Thank you.

A: Better to create a new branch and add all those "another solution" files to it. Push those changes. Switch back to your development branch. Then merge that new branch you just created into your development branch!
If you use any client for source control, things would look pretty simple.


text:
Q: NullReferenceException in array of objects I'm working on a program in c# in which I've got an array of objects of a class. I've got a constructor in the class that should give the attached string a value of "" to make sure they're empty so information can be passed in easily. I then have the array created like so:

participants[8][8] grid = new participants[8][];

But I'm being thrown a NullReferenceExcetption error. Here is my code for your reference.
using System;

namespace TreasurehuntCsharp
{
    class square
    {
        public string strX = "";
        public int y = 0;
        public int x = 0;
    }

    class participants
    {
        public string name = "";
        public string contact = "";
        public participants()
        {
            name = "";
            contact = "";
        }
    }

    class Program
    {

        //Method for user to choose a square
        static void Input(square Coord)
        {
            //Variables
            bool correct = false;

            //Inputs

            Console.WriteLine("Please enter the coordinates of the square you would like to select: \r\n");

            do
            {
                //X coordinate
                Console.WriteLine("X: ");
                Coord.strX = Console.ReadLine().ToLower();
                //Convert letter to array coordinate
                switch (Coord.strX)
                {
                    case "a":
                        Coord.x = 0;
                        correct = true;
                        break;
                    case "b":
                        Coord.x = 1;
                        correct = true;
                        break;
                    case "c":
                        Coord.x = 2;
                        correct = true;
                        break;
                    case "d":
                        Coord.x = 3;
                        correct = true;
                        break;
                    case "e":
                        Coord.x = 4;
                        correct = true;
                        break;
                    case "f":
                        Coord.x = 5;
                        correct = true;
                        break;
                    case "g":
                        Coord.x = 6;
                        correct = true;
                        break;
                    case "h":
                        Coord.x = 7;
                        correct = true;
                        break;
                    default:
                        Console.WriteLine("Please enter a letter from A to H");
                        correct = false;
                        break;
                }
            } while (correct != true);

            correct = false;

            do
            {
                //Y coordinate
                Console.WriteLine("Y: ");
                Coord.y = Convert.ToInt32(Console.ReadLine());
                if (Coord.y >= 1 && Coord.y <= 7)
                {
                    correct = true;
                }
                else
                {
                    Console.WriteLine("Please input an integer value from 1 to 7.");
                    correct = false;
                }
            } while (correct != true);
        }

        static void ParticipantDetails(participants User)
        {
            Console.WriteLine("Please input your name and Contact number: ");

            //User name input
            Console.WriteLine("Name: ");
            User.name = Console.ReadLine();

            //User contact number input
            Console.WriteLine("Number: ");
            User.contact = Console.ReadLine();
        }

        static void Main(string[] args)
        {
            //Objects
            square Coord = new square();
            participants User = new participants();

            //Initialise 2D array
            participants[][] grid = new participants[8][];

            //Variables
            bool correct = false;

            do
            {
                //Methods
                Input(Coord);
                ParticipantDetails(User);

                //Input data to array
                if (grid[Coord.x][Coord.y].name == "" && grid[Coord.x][Coord.y].contact == "")
                {
                    grid[Coord.x][Coord.y].name = User.name;
                    grid[Coord.x][Coord.y].contact = User.contact;
                    Console.WriteLine(grid[Coord.x][Coord.y]);
                    correct = true;
                }
                else
                {
                    Console.WriteLine("That square is already filled. Please try again.");
                    correct = false;
                }
            } while (correct == false);
        }
    }

A: You did not initialize all the dimensions of the array.
//Initialise 2D jagged array
participants[][] grid = new participants[8][];

// You can do that in a for loop
grid[0] = new participants[8];
grid[1] = new participants[8];
grid[2] = new participants[8];
...
grid[7] = new participants[8];

// For loop equivalent
for (int i = 0; i < grid.Length; i++)
{
    grid[i] = new participant[8];
}

A better way for your case (since all the sub-arrays have the same number of elements), would be to use multidimensional-arrays
participants[,] grid = new participants[8,8];

// and access like this
grid[Coord.x, Coord.y]

A: You created an array of arrays.
 participants[][] grid = new participants[8][];

It is an array with 8 entries.  Each of the entries is supposed to be an array of participants, but it hasn't been created.
What you need to do is to create 8 arrays and assign them to the elements of the grid array.
        participant[][] grid = new participant[8][];
        for (int i = 0; i < grid.Length; i++)
            grid[i] = new participant[8];

Here I assume that each element of the grid array is also going to contain 8 elements, but it's up to you.


text:
Q: Why Don't DomainService Constructor Overloads Show Up as DomainContext Constructor Overloads? I wrote an overload for my DomainService class.  Problem is, when I recompile, it's not showing up as an overload for my DomainContext.  What's wrong?  Here is a code sample:
[EnableClientAccess]
public class FoodDomainService : LinqToEntitiesDomainService<FoodEntities>
{
    public FoodDomainService(CultureInfo cultureInfo)
    {
        Thread.CurrentThread.CurrentCulture = cultureInfo;
    }
}

And this doesn't work:
FoodDomainContext _foodContext = new FoodDomainContext(Thread.CurrentThread.CurrentCulture);

I get an error that there is no overload matching that.  Am I not allowed to do this?  Do I need an attribute of some kind?

A: You are not allowed to do this. When newing up the context from your Silverlight client, you are not directly intantiating your service. Instead, you instantiate a proxy class that was generated by RIA Services, and that proxy class will then call your service. This is why you don't see your constructor: because RIA did not generate it in your proxy.
Doing what you're trying to do would also implicate that there is a round-trip to the server at the time of newing up that FoodDomainContext class, which is not going to happen, because you need to complete the initialisation of that object before you can do so.
Anyway, instead of that you can create a method called SetCurrentCulture() and then call it after initializing the proxy.

A: This will not work because DomainContext is generated on client code of silverlight, click on view all folders or jump to definition and you will see that code generated will not contain your extra constructor.
Instead you will have to create a method in your domain service and pass information to server.
public SetCultreInfo(int lang,...)
{
   ..  set culture info
}

On your client, inside constructor you should call,
public MyDomainContext()
{
    this.SetCulture(....);
}


text:
Q: Take backup of all install apk file into sdcard programmatically in Android I want to take back up of my all install application in my sdcard so I write below code
public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
    mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
    final List pkgAppsList = getPackageManager().queryIntentActivities( mainIntent, 0);
    for (Object object : pkgAppsList) {
        ResolveInfo info = (ResolveInfo) object;
        File file =new File( info.activityInfo.applicationInfo.publicSourceDir);
        InputStream myInput;
        System.out.println("SDSD "+file.toString());

        String sdpath = Environment.getExternalStorageDirectory().getPath();
        try {
            File exist=new File(Environment.getExternalStorageState()+file.toString());
            System.out.println("1 "+ exist.exists());
            // Set the output folder on the Scard
            File directory = new File(sdpath + "/Back");
            // Create the folder if it doesn't exist:
            if (!directory.exists()) {
            directory.mkdirs();
            }
            // Set the output file stream up:
            myInput = new FileInputStream(Environment.getExternalStorageState()+ file.toString());
            OutputStream myOutput = new FileOutputStream(directory.getPath()+ file.toString());
            // Transfer bytes from the input file to the output file
            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
            }
            // Close and clear the streams
            myOutput.flush();
            myOutput.close();
            myInput.close();
            Toast.makeText(MainActivity.this, "Backup Done Succesfully!", Toast.LENGTH_LONG)
            .show();
            } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            }
       }
}

}

when i run above code it give me message like
01-11 09:52:35.296: W/System.err(966): java.io.FileNotFoundException: /mounted/data/app/com.example.gridwithcheckbox-1.apk (No such file or directory)
01-11 09:52:35.315: W/System.err(966):  at org.apache.harmony.luni.platform.OSFileSystem.open(Native Method)
01-11 09:52:35.315: W/System.err(966):  at dalvik.system.BlockGuard$WrappedFileSystem.open(BlockGuard.java:232)
01-11 09:52:35.315: W/System.err(966):  at java.io.FileInputStream.<init>(FileInputStream.java:80)
01-11 09:52:35.315: W/System.err(966):  at java.io.FileInputStream.<init>(FileInputStream.java:132)
01-11 09:52:35.315: W/System.err(966):  at com.example.backupdemo.MainActivity.onCreate(MainActivity.java:46)
01-11 09:52:35.315: W/System.err(966):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-11 09:52:35.315: W/System.err(966):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
01-11 09:52:35.315: W/System.err(966):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
01-11 09:52:35.315: W/System.err(966):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
01-11 09:52:35.315: W/System.err(966):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
01-11 09:52:35.315: W/System.err(966):  at android.os.Handler.dispatchMessage(Handler.java:99)
01-11 09:52:35.315: W/System.err(966):  at android.os.Looper.loop(Looper.java:123)
01-11 09:52:35.315: W/System.err(966):  at android.app.ActivityThread.main(ActivityThread.java:3683)
01-11 09:52:35.315: W/System.err(966):  at java.lang.reflect.Method.invokeNative(Native Method)
01-11 09:52:35.315: W/System.err(966):  at java.lang.reflect.Method.invoke(Method.java:507)
01-11 09:52:35.315: W/System.err(966):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-11 09:52:35.315: W/System.err(966):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-11 09:52:35.315: W/System.err(966):  at dalvik.system.NativeStart.main(Native Method)

and i also mention permission to manifest file
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

so any idea how can i solve it?
Using Tamilan Code i make get logcat like following
01-11 10:46:19.685: V/file--(14637):  com.example.tabpager-2.apk----TabPAger
01-11 10:46:19.685: D/file_name--(14637):  TabPAger
01-11 10:46:19.685: I/System.out(14637): No such file or directory
01-11 10:46:19.685: V/file--(14637):  it.anddev.tutorial-1.apk----KeyboardWidgetTutorial
01-11 10:46:19.695: D/file_name--(14637):  KeyboardWidgetTutorial
01-11 10:46:19.695: I/System.out(14637): No such file or directory
01-11 10:46:19.695: V/file--(14637):  com.example.crudopration-2.apk----CrudOpration
01-11 10:46:19.695: D/file_name--(14637):  CrudOpration
01-11 10:46:19.695: I/System.out(14637): No such file or directory
01-11 10:46:19.705: V/file--(14637):  net.leolink.android.simpleinfinitecarousel- 1.apk----SimpleInfiniteCarousel
01-11 10:46:19.705: D/file_name--(14637):  SimpleInfiniteCarousel

A: Try this..
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        final List pkgAppsList = getPackageManager().queryIntentActivities( mainIntent, 0);
        int z = 0;
        for (Object object : pkgAppsList) {

            ResolveInfo info = (ResolveInfo) object;

            File f1 =new File( info.activityInfo.applicationInfo.publicSourceDir);

            Log.v("file--", " "+f1.getName().toString()+"----"+info.loadLabel(getPackageManager()));
                try{

                    String file_name = info.loadLabel(getPackageManager()).toString();
                    Log.d("file_name--", " "+file_name);

                   // File f2 = new File(Environment.getExternalStorageDirectory().toString()+"/Folder/"+file_name+".apk");
                   // f2.createNewFile();

                    File f2 = new File(Environment.getExternalStorageDirectory().toString()+"/Folder");
                    f2.mkdirs();
                    f2 = new File(f2.getPath()+"/"+file_name+".apk");
                    f2.createNewFile();

                    InputStream in = new FileInputStream(f1);

                    OutputStream out = new FileOutputStream(f2);

                    byte[] buf = new byte[1024];
                    int len;
                    while ((len = in.read(buf)) > 0){
                        out.write(buf, 0, len);
                    }
                    in.close();
                    out.close();
                    System.out.println("File copied.");
                }
                catch(FileNotFoundException ex){
                    System.out.println(ex.getMessage() + " in the specified directory.");
                }
                catch(IOException e){
                    System.out.println(e.getMessage());
                }
        }


text:
Q: Log Analytics & Application insights Log Query Search Tables to Sql Database. I was wondering if there is a way to export data from tables or whole tables generated by Log-query-searches in Log Analytics and Application Insights to an exact same Table In an Azure Sql Database?
I'm thinking like a Export/Import kind of deal. or even like doing it with a webjob or something like that.
Is there any way to do this?

A: There are a couple of options:

*

*Use the rest api to issue queries and store the result in sql server. This can be done using a web host or an azure function (triggered by a schedule?)

*Use Continuous export to export the data to azure blob storage. From there you can read the blobs and store the data to sql using a web host or an azure function (triggered by a blob creation?). A better fit might be to use Azure Data Factory to copy the data from blob to sql server.

Keep in mind you will have to define the sql table schemas yourself to represent the json data. There might not be a straight forward conversion as it is json.
What is the idea behind having the data in sql server anyway? Depending on your use case there might be better options available.


text:
Q: htmlspecialchars() expects parameter 1 to be string, object given for join query I have a column named user_id in avtivities table. Now i want to fetch the names of user whose user_id stored in activities_table. So far i tried this
$activity_user=DB::table('users')
                ->join('activities','users.id','activities.user_id')
                ->select('users.name')->first();

but when i try to call it on view like this
{{ $activity->user_id ? $activity_user : ""}}

i got this error
htmlspecialchars() expects parameter 1 to be string, object given (View: C:\xampp\htdocs\task-management-system\resources\views\super_admin\home.blade.php)

A: {{ $activity->user_id ? $activity_user : ""}}

In this $activity_user is object and you're showing object, So instead use $activity_user use this $activity_user->name now your code looks like,
{{ $activity_user ? $activity_user->name : ""}}

Note: Make sure whatever you print in {{ }} should be string.
Update
If you want to get multiple data then.
$activity_user=DB::table('users')
                ->join('activities','users.id','activities.user_id')
                ->select('users.name')->get();

View file

@if(!empty($activity_user))
    @foreach($activity_user as $user)
        {{ $user ? $user->name : ""}}
    @endforeach
@endif


text:
Q: How to remove/hide Google Maps Search Icon when zooming out? The autofill search function is working great on my map and zooms into the searched address and places a custom pin centered, however the pin stays there at all zoom levels. My goal is to have the pin remove/hide when the user zooms back out past level 18 zoom. My guess is that an google.maps.event.addListener with 'zoom_changed' might work but I have no idea where or how to place it within this code. Thank you for any help in advance.
    // Create the search box and link it to the UI element.
    var input = document.getElementById('pac-input');
    var searchBox = new google.maps.places.SearchBox(input);
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

    // Bias the SearchBox results towards current map's viewport.
    map.addListener('bounds_changed', function() {
      searchBox.setBounds(map.getBounds());
    });

    var markersS = [];
    // Listen for the event fired when the user selects a prediction and
    // retrieve more details for that place.
    searchBox.addListener('places_changed', function() {
      var places = searchBox.getPlaces();

      if (places.length == 0) {
        return;
      }

      // Clear out the old markersS.
      markersS.forEach(function(marker) {
        marker.setMap(null);
      });
      markersS = [];

      // For each place, get the icon, name and location.
      var bounds = new google.maps.LatLngBounds();
      places.forEach(function(place) {
        if (!place.geometry) {
          console.log("Returned place contains no geometry");
          return;
        }
        var icon = {
          url: '.../HOME.png',
          anchor: new google.maps.Point(41.5, 64),
        };

       // Create a marker for each place and also set Zoom Condition.
        google.maps.event.addListener(map, 'zoom_changed', function() {
        var zoomS = map.getZoom();
        if (zoomS>=18) {
            markersS.push(new google.maps.Marker({
            map: map,
            icon: icon,
            title: place.name,
            position: place.geometry.location,
            //animation: google.maps.Animation.DROP
            }));
          }
        else if (zoomS<18) {
            markersS.forEach(function(marker) {
            marker.setMap(null);
            });
            markersS = [];
          }
        });

        if (place.geometry.viewport) {
          // Only geocodes have viewport.
          bounds.union(place.geometry.viewport);
        } else {
          bounds.extend(place.geometry.location);
        }
      });
      map.fitBounds(bounds);

    });

A: Zoom is in your initMap function. Just use a conditional statement.


text:
Q: Is there merit to adding flat properties additional to a duplicate nested If I have a document designed like this:
  Question:
    properties:
      _id: string
      asker: User
      title: string
      description: string
      respondent: User

Is there performance merit to adding a duplicate property like this:
  Question:
    properties:
      _id: string
      asker_id: string
      asker: User
      title: string
      description: string
      respondent: User

Given that I need to query questions per asker?

A: Assuming the asker field is a single subdocument (i.e. not an array of users or something), I'm pretty sure the difference in access rates will be nil. I suspect you'd need to be doing thousands of inserts / updates / reads a second before even noticing any difference, and even then I doubt it: if you create an index on the field (which you should), the index doesn't care how deep the source data is. It hashes the field with a similar structure. Theoretically, there may be a slight increase in the index creation time in a super-complex document structure, but even that is unlikely, and regardless, happens only once, asynchronously, during the write. After that, read speeds shouldn't be effected.
My evidence for this isn't exact, but I have several high volume queries (i.e. can burst to several hundred queries or inserts per sec) on a specific table, where some of the queries are on a field 1-level deep, and one of the queries is on a field 4-levels deep, and I see no difference in access times or throughput rates (all fields are indexed).
Unless you're planning for very high loads, I wouldn't worry about it. I think it's a classic case of premature optimization which will complicate your code (now you need to make sure asker_id and asker.asker_id are the same) for no performance benefit. Just index the field and be done with it.
If you are planning for very high loads and large tables, then it should be pretty easy to profile and time your queries.


text:
Q: When sorting an array of objects, is it possible to further group items that have been pushed to the bottom, using sort()? I'm doing this in JavaScript and I have to do it within a single sort() function as it's being sent as a param.
For example, I have objects that have I sort by category and then I further sort by sub category using:
return item1.category.localeCompare(item2.category) : item1.subCategory.localeCompare(item2.subCategory)

But for objects that have no category I push to the bottom using:
    if(item1.category == ''){
        res = 1
    }
    if(item2.category == ''){
        res = -1
    }

The problem with this is that all those items are all together at the bottom but they're all jumbled up and what I need is for them to be grouped together by subcategory.
Example of objects as I can sort them now:
[
  {'category':'cat1', 'subcategory':'subcat1'},
  {'category':'cat1', 'subcategory':'subcat2'},
  {'category':'cat2', 'subcategory':'subcat1'},
  {'category':'cat2', 'subcategory':'subcat2'}
  {'category':'', 'subcategory':'subcat1'},
  {'category':'', 'subcategory':'subcat2'},
  {'category':'', 'subcategory':'subcat1'},
  {'category':'', 'subcategory':'subcat2'}
]

Which I need to become:
[
  {'category':'cat1', 'subcategory':'subcat1'},
  {'category':'cat1', 'subcategory':'subcat2'},
  {'category':'cat2', 'subcategory':'subcat1'},
  {'category':'cat2', 'subcategory':'subcat2'}
  {'category':'', 'subcategory':'subcat1'},
  {'category':'', 'subcategory':'subcat1'},
  {'category':'', 'subcategory':'subcat2'},
  {'category':'', 'subcategory':'subcat2'}
]

A: You could sort first the empty parts to bottom and then with a compare the strings. Take both for category and subcategory.

var data = [{ category: 'cat2', subcategory: 'subcat1' }, { category: 'cat1', subcategory: 'subcat1' }, { category: 'cat2', subcategory: 'subcat2' }, { category: '', subcategory: '' }, { category: '', subcategory: 'subcat1' }, { category: '', subcategory: 'subcat2' }, { category: 'cat1', subcategory: 'subcat2' }, { category: 'cat1', subcategory: '' }, { category: 'cat2', subcategory: '' }];

data.sort(function (a, b) {
    return (
        !a.category - !b.category ||                 // move falsy values to bottom
        a.category.localeCompare(b.category) ||      // sort strings
        !a.subcategory - !b.subcategory ||
        a.subcategory.localeCompare(b.subcategory)
    );
});

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: You can even do this dynamically by using a helper function and sort in a nested fashion for as many properties as you like.

function getFakeObjects(n){  // helper function to get test objects
  return Array(n).fill()
                 .reduce(o => o.concat({p1 : String.fromCharCode(...Array(5).fill().map(_ => ~~(Math.random()*26)+97)),
                                        p2 : ~~(Math.random()*5)+1,
                                        p3 : ["Istanbul","Moscow","New York","Tokyo","Rio","Accra"][~~(Math.random()*6)],
                                        p4 : ~~(Math.random()*2+1)+String.fromCharCode(~~(Math.random()*3)+65)
                                       }),[]);
}

function multiLevelSorter(os,ps){
  return os.sort(function(a,b){
                   var p = ps.find(f => a[f] !== b[f]);
                   return a[p] < b[p] ? -1 : 1;
                 });
}

var fakes = getFakeObjects(50),
sortOrder = ["p3","p2","p4","p1"],
   sorted = multiLevelSorter(fakes,sortOrder);
sorted.forEach(o => console.log("{p1:", o.p1,"p2:",o.p2,"p3:",o.p3,"p4:",o.p4,"}"));
.as-console-wrapper { max-height: 100% !important; top: 0; }

So the above code sorts in the priorities of p3 -> p2 -> p4 -> p1.

A: You can also use the SortedArrayCategory. The code is follow
//arrTemp = Your actual array name.
                                self.sortedArrayCategory = arrTemp.sortedArrayUsingComparator {
                                    (obj1, obj2) -> NSComparisonResult in

                                    let p1 = obj1 as! String
                                    let p2 = obj2 as! String
                                    let result = p1.compare(p2)
                                    return result
                                }


text:
Q: showing results of object detection counting system on a dashboard Can you help me with this one.It's a project that should be done and I don't know how I put the data of counting objects on a web app.
Can someone please help me with the steps?


text:
Q: Two-way ANOVA or mixed models I wonder if two-way ANOVA or other mixed-models are to prefer for my analysis.
Short background: The effect of three different treatments on parasites on leaves was measured over time (7 sampling dates). Different leaves have been used every sampling so the subject should be independent. I wish to see the effect of treatment (fixed, 3 levels) and date(random, 7 levels) on the amount of parasites. I have 7 samples per date and treatment but use averaged values. I have troubles conducting the two-way ANOVA in R using both random and fixed effects. If anyone have suggestions for this I would love any help!
Very thankful for any help!

A: This is requires mixed model, because you have a between and a within-subject factor.


text:
Q: Type mismatch in lambda function - Kotlin I want the text to be taken from string resource, depends on item.route, which is specified before bellow code.
But whole "when" expression gives me the error:
"Type mismatch: inferred type is () -> Int but Int was expected."
I don't have idea how to resolve it.

Text(
        text = stringResource(id = {
            when (item.route) {
                "menu_screen" -> R.string.menu
                "orders_screen" -> R.string.orders
                else -> R.string.orders
            }
        }),
        textAlign = TextAlign.Center
    )

A: Just remove the extra curly brace ;)
Text(
    text = stringResource(id =
        when (item.route) {
            "menu_screen" -> R.string.menu
            "orders_screen" -> R.string.orders
            else -> R.string.orders
        }
    ),
    textAlign = TextAlign.Center
)

A: When you put bare brackets { } around something, it is interpreted as a lambda function. By "bare" I mean not after a class/fun/when/if/else, etc. You need to remove the extra brackets you put in there.
Text(
    text = stringResource(id =
        when (item.route) {
            "menu_screen" -> R.string.menu
            "orders_screen" -> R.string.orders
            else -> R.string.orders
        }
    ),
    textAlign = TextAlign.Center
)

Some other languages (such as Java) let you surround code with brackets to limit the scope of variables declared inside or to compute something that takes multiple expressions. To do this in Kotlin, you have to use a scope inline function such as run { }.


text:
Q: Hyperlinks not working I developeed my facebook app. In that i have added some some links to other pages but on clicking it doesn't redirect to other pages.
Amit Kumar Singh

After its failure as  am using heroku so i created a page over there and even try to redirect from there but it is not helping me.
Like i created page pokerfff.php there and try to redirect there
Amit Kumar Singh

and content of pokerfff.php is
<?php

   header( 'Location: https://www.facebook.com/pokerFFFFF' ) ;

?>

A: I should answer my own question.
My code is running under some frame so if i use target= _top in  will work like
Amit Kumar Singh


text:
Q: I'm getting error in "this.something" in all activity and mainfest, xml of android studio I just installed android studio because I reinstalled windows.
While opening my project, at first I got error in every where. Then I

*

*clean and rebuid the projects

*sync the project with gradle file

*invalidated caches/restart

*deleted .idea and .gradle files

*auto import

[UPDATE: I again invalidated caches/restart and it worked :)] But, how can I solve this warning?
I got this warinig while rebuilding the app, might this be reason of showing error?
error while rebuiding

My errors as compared to before are gone but I'm still getting the errors in xml, manifest, actvities.
error in xml

error in mainfest

error in activity

error in activity

error is DataAdapter

I think there might be issue of importing internal files from one to another but don't know to sove this. and, I don't know why I'm hiding package name, but I think that is good practice...?

A: Add ndkVersion to your module's build.gradle
android.ndkVersion  "your-installed-ndk-version"