Q: mysql query array counter Apologies if I have the terminology wrong.
I have a for loop in php which operates a mysql query...
for ($i = 0; $i <count($user_id_pc); $i++)
{
$query2 = " SELECT job_title, job_info FROM job_description WHERE  postcode_ss = '$user_id_pc[$i]'";

$job_data = mysqli_query($dbc, $query2);

$job_results = array();

    while ($row = mysqli_fetch_array($job_data))
        {
            array_push($job_results, $row);
        }

}

The results that are given when I insert a...
print_r ($job_results);

On screen -> Array()

If I change the query from $user_id_pc[$i] to $user_id_pc[14] for example I receive one set of results.
If I include this code after the query and inside the for loop
echo $i;
echo $user_id_pc[$i] . "
";

I receive the number the counter $i is on followed by the data inside the array for that counter position.
I am not sure why the array $job_results is empty from the query using the counter $i but not if I enter the number manually?
Is it a special character I need to escape?
The full code
        <?php
print_r ($user_id_pc);

  //Select all columns to see if user has a profile
     $query = "SELECT * FROM user_profile WHERE user_id = '" . $_SESSION['user_id'] . "'";

      //If the user has an empty profile direct them to the home page

  $data = mysqli_query($dbc, $query);

  if (mysqli_num_rows($data) == 0)
    {
        echo '

Your appear not to be logged on please visit the home page to log on or register. Thank you.

';
    }
//Select data from user and asign them to variables
    else
    {
          $data = mysqli_query($dbc, $query);
      if (mysqli_num_rows($data) == 1)
      {
          $row = mysqli_fetch_array($data);
          $cw_job_name = $row['job_description'];
          $cw_rate = $row['hourly_rate'];
          $job_mileage = $row['mileage'];
          $job_postcode = $row['postcode'];
          $response_id = $row['user_profile_id'];
      }
    }

    for ($i = 0; $i <count($user_id_pc); $i++)
        {
            $query2 = " SELECT job_title, job_info FROM job_description WHERE  postcode_ss = '{$user_id_pc[$i]}'";
    $job_data = mysqli_query($dbc, $query2);
    $job_results = array();
        while ($row = mysqli_fetch_array($job_data))
            {
                array_push($job_results, $row);
            }

    echo $i;
?>

<?php

}
print ($query2);
print $user_id_pc[$i];
         ?>

A: This is primarily a syntax error, the correct syntax should be:
$query2 = " SELECT job_title, job_info FROM job_description WHERE  postcode_ss = '{$user_id_pc[$i]}'";

Note that this is correct syntax but still wrong!! For two reasons the first is that it's almost always better (faster, more efficient, takes less resources) to do a join or a subquery or a simple IN(array) type query rather than to loop and query multiple times.
The second issue is that passing parameters in this manner leave your vulnerable to sql injection. You should use prepared statements.
The correct way
if(count($user_id_pc)) {
    $stmt = mysqli_stmt_prepare(" SELECT job_title, job_info FROM job_description WHERE  postcode_ss = ?");
    mysqli_stmt_bind_param($stmt, "s", "'" . implode("','",$user_id_pc) . "'");
    mysqli_stmt_execute($stmt);
}

Note that the for loop has been replaced by a simple if

A: You have to check the query variable, instead of:
$query2 = " SELECT job_title, job_info FROM job_description WHERE  postcode_ss = '$user_id_pc[$i]'"

have you tried this:
$query2 = " SELECT job_title, job_info FROM job_description WHERE  postcode_ss = '" . $user_id_pc[$i] . "' ";

And another thing, try something different like this:
while ($row = mysqli_fetch_array($job_data))
    {
        $job_results[] = array("job_title" => $row["job_title"], "job_info" => $row["job_info");
    }

Then try to print the values.

A: Sorry but I like foreach(), so your working code is:
<?php

 // To store the result
 $job_results = [];

 foreach($user_id_pc as $id ){
   // selecting matching rows
   $query2 ="SELECT job_title, job_info FROM job_description WHERE postcode_ss = '".$id."'";
   $job_data = mysqli_query($dbc, $query2);
   // checking if query fetch any result
   if(mysqli_num_rows($job_data)){
      // fetching the result
      while ($row = mysqli_fetch_array($job_data)){
        // storing resulting row
        $job_results[] = $row;
     }
   }
}
// to print the result
var_dump($job_results);


Q: Open file for Appending with is new indication I need to append data to a file, but if the file does not exist I need to add a header before appending.
If I open the file with FileMode.Append, I cannot see a way to work out if the file is new or not.
If I open the file with
FileStream file;
boolean isNew;
try
{
    file = File.Open(path, FileMode.CreateNew);
    isNew = true;
}
catch (IOException ex)
{
    file = File.Open(path, FileMode.Append);
    isNew = false;
}

I run into the risk of another process deleting the file between the the 2 open calls and not detecting the creation of the new file.
What is the recommended way of opening for appending and detecing if create or append?

A: Does this do what you need?
try
{
    var file = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);

    if (file.Length == 0)
    {
        // do header stuff
    }

    // do the rest
}
catch (IOException ex)
{
    // handle io ex.
}

A: Try something like this:
if (!File.Exists(path))
{
     file = File.Open(path, FileMode.CreateNew);
     isNew = true;
     return;
}
// otherwise append to existing file
file = File.Open(path, FileMode.Append);
isNew = false;


Q: Is there any way to return the element that does not pass a filter in stream? I have a list of string elements and I want to apply a filter to divide the list into two sub list, elements that start with "el" and others.
is there any way to divide the list using just one filter?
List elements = List.of("e1", "el2", "el3", "4 el", "5 el")

example:
elements.stream()
        .filter(s -> s.startWith("el))
        .collect( /* something that hold both the element that pass the filter and element that does not */ )

A: You can do it like so.

*

*use groupingBy and create a Map<String, List<String>>

*if the string starts with "el" group using the els key

*otherwise, use the others key

List<String> elements = List.of("e1", "el2", "el3", "4 el", "5 el");
Map<String, List<String>> map = elements.stream().collect(
        Collectors.groupingBy(str -> str.startsWith("el") ?
                "els" : "others"));

map.entrySet().forEach(System.out::println);

prints
els=[el2, el3]
others=[e1, 4 el, 5 el]

A: Since you have a threshold condition which determine if an item will go to group A, otherwise B, I suggest using partitioningBy for this.
For example:
    List<String> elements = List.of("e1", "el2", "el3", "4 el", "5 el");
    //create the partition map
    Map<Boolean,List<String>> partitionMap = elements.stream()
            .collect(Collectors.partitioningBy(s-> s.startsWith("el")));

    //getting the partitions
    List<String> startsWithEl = partitionMap.get(true);
    List<String> notStartingWilEl = partitionMap.get(false);

Now each list will hold its partition .


Q: IIS redirect rules to multiple 500 error page I need to return a different static page, for the 500 response type, depending on the language particle of the request (fr, es, pt, etc)
Is it possible to have one static page for each language (500-fr.aspx, 500-es.aspx, 500-pt.aspx) and somehow, depending on the language particle to return the necesary static page?
Eg:  mysite.com/fr/somepage is broken and returns a 500 response, and then IIS redirects the user to 500-fr.aspx page.
Thank you

A: There is a very simple and fast way, that does not even require you to manually write url rewriting rules.
In the Error Pages module, IIS has defined the same error to display different pages according to different languages.

You can see that it has checked "Try to return the error file in the client languag". And if you enter the file path.

Error pages of different languages already exist in different language folders.
So if you want to response custom page, just change these pages or create new error pages store into different folder and change the file name in file path.


Q: I am converting a python/kivy project to apk in google colab and some extension are not working so what extension I should use for audio/font file? I use jpg file for image but when I run my app in phone it won't open but it works for PNG file.
And also for audio file I use mp3, OGG file my app won't open but when I use wav file my app works but the sound doesn't come.
And for font file, both TTF and OTF extension won't work i.e. my app won't work

A: I solve my problem a bit, now the wav file is working correctly because I add the extension of wav file in the google colab file which  created after the compilation of my files (Buildozer.spec) but the problem with jpg is still there and for mp3 also


Q: Rails variables not working in JavaScript code In one of my Rails partials, in which I have access to the Folder model, some JavaScript is strangely enough not working. The Folder model has instances of the Submission model which belong to it. Example JSON for a folder instance looks like this:
{"created_at":"2013-09-24T18:55:54Z","id":2,"parent_id":null,"title":"Tumblr Drafts","updated_at":"2013-09-24T18:55:54Z","user_id":1,
"submissions":
[{"content":"This is a test.","created_at":"2013-09-30T23:00:00Z","folder_id":2,"id":93,"parent_id":null,"title":null,"updated_at":"2013-09-30T23:00:00Z","user_id":1}],"children":[]}

As you can see, the submissions are included in the JSON. The controller action looks like this:
    def show
        respond_to do |format|
            format.html
            format.js
            format.json {render :json => @folder.as_json( :include => [:submissions, :children])}
        end
    end

However, when I try to run this JavaScript, it doesn't return a console.log:
<script type="text/javascript">
      var wordCount = 0;
      <% @folder.submissions.each do |submission| %>
        var words = <%= submission.content %>.split(' ');
        wordCount += words.length;
      <% end %>
      console.log(wordCount);
    </script>

I use the @folder variable everywhere else in the partial in question, and it works. I can even output the titles of all the submissions into <p> tags. Is it may because the content field can be left empty, so sometimes it returns null?

A: Your problem is right here:
var words = <%= submission.content %>.split(' ');

That will dump your submission.content value into your JavaScript without any quoting so you'll end up saying things like:
var words = blah blah blah.split(' ');

and that's not valid JavaScript. You need to quote that string and properly escape it:
// You may or may not want submission.content HTML encoded so
// you might want submission.content.html_safe instead.
var words = '<%=j submission.content %>'.split(' ');

Or better, just do it all in Ruby rather than sending a bunch of throw-away text to the browser:
<script type="text/javascript">
  var wordCount = <% @folder.submissions.map { |s| submission.content.split.length }.sum %>
  console.log(wordCount);
</script>

That assumes that your JavaScript .split(' ') is really intended to split on /\s+/ rather than just single spaces of course.


Q: rebar3 doesnt compile erlydtl file I have a problem which my rebar3 does not compile the erlydtl files (.dtl) and I have looking around for a while but not solution. Previously it worked, but after I upgrade erlang to the newest version, the *.dtl file is not compiled and sync:on_sync does not work neight.
Anyone here have any idear on that?
Here is my rebar.conf file
{erl_opts, [debug_info]}.
{deps, [
    {sync, {git, "https://github.com/rustyio/sync.git" , {branch, "master"}}},
    {erlydtl, {git, "https://github.com/erlydtl/erlydtl.git", { branch, "master"}}},
    {jsx, {git, "https://github.com/talentdeficit/jsx.git", {branch, "main"}}},
    {epgsql, {git, "https://github.com/epgsql/epgsql.git"}},
    {gen_smtp, {git, "https://github.com/gen-smtp/gen_smtp.git", {branch, "master"}}},
    {cowboy, { git, "https://github.com/ninenines/cowboy.git", {branch, "master"}}},
    poolboy
]}.

{erlydtl_opts, [
    {doc_root, "src/templates"}
    %{outdir, "ebin"},
    %{compiler_options, [report, return, debug_info]},
    %{source_ext, ".dtl"}
    %% {module_ext, "_view"}
]}.

{provider_hooks, [
    {pre_hooks, [{compile, {erlydtl, compile}}]}
]}.

{relx, [
    {release, {core, "0.1.0"}, [
        core, poolboy, erlydtl,
        account, realestate, realestate_admin,
        sync, sasl, epgsql, jsx, gen_smtp
    ]},
    {mode, dev},

    %% automatically picked up if the files
    %% exist but can be set manually, which
    %% is required if the names aren't exactly
    %% sys.config and vm.args
    {sys_config, "./config/sys.config"},
    {vm_args, "./config/vm.args"}

    %% the .src form of the configuration files do
    %% not require setting RELX_REPLACE_OS_VARS
    %% {sys_config_src, "./config/sys.config.src"},
    %% {vm_args_src, "./config/vm.args.src"}
]}.

{profiles, [
    {prod, [
        {relx, [
            %% prod is the default mode when prod
            %% profile is used, so does not have
            %% to be explicitly included like this
            {mode, prod}

            %% use minimal mode to exclude ERTS
            %% {mode, minimal}
        ]}
    ]}
]}.

{dialyzer, [
    %% Warns the undefined type or unknown function
    {warnings, [ unknown ]}
]}.

{xref_checks, [
    %% enable most checks, but avoid 'unused calls' which is often
    %% very verbose
    undefined_function_calls, undefined_functions, locals_not_used,
    deprecated_function_calls, deprecated_functions
]}.

{plugins, [
    % {rebar3_auto, {git, "https://github.com/xuchaoqian/rebar3-auto.git", {branch, "master"}}}
]}.

Thanks,


Q: Converting .pb to coreml I'm new to coreml and I'm trying to convert my tiny-yolov3 model to a coreml model, but I keep getting this error.
[SSAConverter] [78/170] Converting op type: 'Conv2D', name: 'yolov3-tiny/convolutional1/Conv2D', output_shape: (-1, 16, 416, 416).
Traceback (most recent call last):
  File "/Users/ryanyang/Desktop/DW2TF/env/lib/python3.7/site-packages/coremltools/converters/tensorflow/_tf_converter.py", line 95, in convert
    optional_inputs=optional_inputs)
  File "/Users/ryanyang/Desktop/DW2TF/env/lib/python3.7/site-packages/coremltools/converters/nnssa/coreml/ssa_converter.py", line 149, in ssa_convert
    converter.convert()
  File "/Users/ryanyang/Desktop/DW2TF/env/lib/python3.7/site-packages/coremltools/converters/nnssa/coreml/ssa_converter.py", line 567, in convert
    convert_func(node)
  File "/Users/ryanyang/Desktop/DW2TF/env/lib/python3.7/site-packages/coremltools/converters/nnssa/coreml/ssa_converter.py", line 1493, in _convert_conv2d
    '[SSAConverter] Dynamic weights in convolution not implemented')
NotImplementedError: [SSAConverter] Dynamic weights in convolution not implemented

UPDATE: I have added minimum_ios_deployment_target="13" to the converter, but now it is giving me a different error.
My code is
import tfcoreml as tf_converter
tf_converter.convert(tf_model_path = 'data/yolov3-tiny-one-class.pb',
                     mlmodel_path = 'TinyYOLO.mlmodel',
                     output_feature_names = ['yolov3-tiny/convolutional13/BiasAdd'],
                     input_name_shape_dict = {'yolov3-tiny/net1' : [1, 416, 416, 3]},
                     image_input_names = ['yolov3-tiny/net1'],
                     image_scale = 1 / 255.0,
                     minimum_ios_deployment_target="13"
                     )

and my visualizer for my pb model from tf-coreml is
---------------------------------------------------------------------------------------------------------------------------------------------
0: op name = import/yolov3-tiny/net1, op type = ( Placeholder ), inputs = , outputs = import/yolov3-tiny/net1:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/net1:0 : (?, 416, 416, 3)
---------------------------------------------------------------------------------------------------------------------------------------------
1: op name = import/yolov3-tiny/convolutional1/kernel/Initializer/random_uniform/shape, op type = ( Const ), inputs = , outputs = import/yolov3-tiny/convolutional1/kernel/Initializer/random_uniform/shape:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional1/kernel/Initializer/random_uniform/shape:0 : (4,)
---------------------------------------------------------------------------------------------------------------------------------------------
2: op name = import/yolov3-tiny/convolutional1/kernel/Initializer/random_uniform/min, op type = ( Const ), inputs = , outputs = import/yolov3-tiny/convolutional1/kernel/Initializer/random_uniform/min:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional1/kernel/Initializer/random_uniform/min:0 : ()
---------------------------------------------------------------------------------------------------------------------------------------------
3: op name = import/yolov3-tiny/convolutional1/kernel/Initializer/random_uniform/max, op type = ( Const ), inputs = , outputs = import/yolov3-tiny/convolutional1/kernel/Initializer/random_uniform/max:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional1/kernel/Initializer/random_uniform/max:0 : ()
---------------------------------------------------------------------------------------------------------------------------------------------
4: op name = import/yolov3-tiny/convolutional1/kernel/Initializer/random_uniform/RandomUniform, op type = ( RandomUniform ), inputs = import/yolov3-tiny/convolutional1/kernel/Initializer/random_uniform/shape:0, outputs = import/yolov3-tiny/convolutional1/kernel/Initializer/random_uniform/RandomUniform:0
@input shapes:
name = import/yolov3-tiny/convolutional1/kernel/Initializer/random_uniform/shape:0 : (4,)
@output shapes:
name = import/yolov3-tiny/convolutional1/kernel/Initializer/random_uniform/RandomUniform:0 : (3, 3, 3, 16)
---------------------------------------------------------------------------------------------------------------------------------------------

......
......

358: op name = import/yolov3-tiny/convolutional12/dilation_rate, op type = ( Const ), inputs = , outputs = import/yolov3-tiny/convolutional12/dilation_rate:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional12/dilation_rate:0 : (2,)
---------------------------------------------------------------------------------------------------------------------------------------------
359: op name = import/yolov3-tiny/convolutional12/Conv2D, op type = ( Conv2D ), inputs = import/yolov3-tiny/route2:0, import/yolov3-tiny/convolutional12/kernel/read:0, outputs = import/yolov3-tiny/convolutional12/Conv2D:0
@input shapes:
name = import/yolov3-tiny/route2:0 : (?, 26, 26, 384)
name = import/yolov3-tiny/convolutional12/kernel/read:0 : (3, 3, 384, 256)
@output shapes:
name = import/yolov3-tiny/convolutional12/Conv2D:0 : (?, 26, 26, 256)
---------------------------------------------------------------------------------------------------------------------------------------------
360: op name = import/yolov3-tiny/convolutional12/BatchNorm/gamma/Initializer/ones, op type = ( Const ), inputs = , outputs = import/yolov3-tiny/convolutional12/BatchNorm/gamma/Initializer/ones:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/gamma/Initializer/ones:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
361: op name = import/yolov3-tiny/convolutional12/BatchNorm/gamma, op type = ( VariableV2 ), inputs = , outputs = import/yolov3-tiny/convolutional12/BatchNorm/gamma:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/gamma:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
362: op name = import/yolov3-tiny/convolutional12/BatchNorm/gamma/Assign, op type = ( Assign ), inputs = import/yolov3-tiny/convolutional12/BatchNorm/gamma:0, import/yolov3-tiny/convolutional12/BatchNorm/gamma/Initializer/ones:0, outputs = import/yolov3-tiny/convolutional12/BatchNorm/gamma/Assign:0
@input shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/gamma:0 : (256,)
name = import/yolov3-tiny/convolutional12/BatchNorm/gamma/Initializer/ones:0 : (256,)
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/gamma/Assign:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
363: op name = import/yolov3-tiny/convolutional12/BatchNorm/gamma/read, op type = ( Identity ), inputs = import/yolov3-tiny/convolutional12/BatchNorm/gamma:0, outputs = import/yolov3-tiny/convolutional12/BatchNorm/gamma/read:0
@input shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/gamma:0 : (256,)
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/gamma/read:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
364: op name = import/yolov3-tiny/convolutional12/BatchNorm/beta/Initializer/zeros, op type = ( Const ), inputs = , outputs = import/yolov3-tiny/convolutional12/BatchNorm/beta/Initializer/zeros:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/beta/Initializer/zeros:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
365: op name = import/yolov3-tiny/convolutional12/BatchNorm/beta, op type = ( VariableV2 ), inputs = , outputs = import/yolov3-tiny/convolutional12/BatchNorm/beta:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/beta:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
366: op name = import/yolov3-tiny/convolutional12/BatchNorm/beta/Assign, op type = ( Assign ), inputs = import/yolov3-tiny/convolutional12/BatchNorm/beta:0, import/yolov3-tiny/convolutional12/BatchNorm/beta/Initializer/zeros:0, outputs = import/yolov3-tiny/convolutional12/BatchNorm/beta/Assign:0
@input shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/beta:0 : (256,)
name = import/yolov3-tiny/convolutional12/BatchNorm/beta/Initializer/zeros:0 : (256,)
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/beta/Assign:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
367: op name = import/yolov3-tiny/convolutional12/BatchNorm/beta/read, op type = ( Identity ), inputs = import/yolov3-tiny/convolutional12/BatchNorm/beta:0, outputs = import/yolov3-tiny/convolutional12/BatchNorm/beta/read:0
@input shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/beta:0 : (256,)
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/beta/read:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
368: op name = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean/Initializer/zeros, op type = ( Const ), inputs = , outputs = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean/Initializer/zeros:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean/Initializer/zeros:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
369: op name = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean, op type = ( VariableV2 ), inputs = , outputs = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
370: op name = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean/Assign, op type = ( Assign ), inputs = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean:0, import/yolov3-tiny/convolutional12/BatchNorm/moving_mean/Initializer/zeros:0, outputs = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean/Assign:0
@input shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean:0 : (256,)
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean/Initializer/zeros:0 : (256,)
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean/Assign:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
371: op name = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean/read, op type = ( Identity ), inputs = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean:0, outputs = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean/read:0
@input shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean:0 : (256,)
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean/read:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
372: op name = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance/Initializer/ones, op type = ( Const ), inputs = , outputs = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance/Initializer/ones:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance/Initializer/ones:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
373: op name = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance, op type = ( VariableV2 ), inputs = , outputs = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
374: op name = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance/Assign, op type = ( Assign ), inputs = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance:0, import/yolov3-tiny/convolutional12/BatchNorm/moving_variance/Initializer/ones:0, outputs = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance/Assign:0
@input shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance:0 : (256,)
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance/Initializer/ones:0 : (256,)
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance/Assign:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
375: op name = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance/read, op type = ( Identity ), inputs = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance:0, outputs = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance/read:0
@input shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance:0 : (256,)
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance/read:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
376: op name = import/yolov3-tiny/convolutional12/BatchNorm/FusedBatchNorm, op type = ( FusedBatchNorm ), inputs = import/yolov3-tiny/convolutional12/Conv2D:0, import/yolov3-tiny/convolutional12/BatchNorm/gamma/read:0, import/yolov3-tiny/convolutional12/BatchNorm/beta/read:0, import/yolov3-tiny/convolutional12/BatchNorm/moving_mean/read:0, import/yolov3-tiny/convolutional12/BatchNorm/moving_variance/read:0, outputs = import/yolov3-tiny/convolutional12/BatchNorm/FusedBatchNorm:0, import/yolov3-tiny/convolutional12/BatchNorm/FusedBatchNorm:1, import/yolov3-tiny/convolutional12/BatchNorm/FusedBatchNorm:2, import/yolov3-tiny/convolutional12/BatchNorm/FusedBatchNorm:3, import/yolov3-tiny/convolutional12/BatchNorm/FusedBatchNorm:4
@input shapes:
name = import/yolov3-tiny/convolutional12/Conv2D:0 : (?, 26, 26, 256)
name = import/yolov3-tiny/convolutional12/BatchNorm/gamma/read:0 : (256,)
name = import/yolov3-tiny/convolutional12/BatchNorm/beta/read:0 : (256,)
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean/read:0 : (256,)
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance/read:0 : (256,)
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/FusedBatchNorm:0 : (?, 26, 26, 256)
name = import/yolov3-tiny/convolutional12/BatchNorm/FusedBatchNorm:1 : (256,)
name = import/yolov3-tiny/convolutional12/BatchNorm/FusedBatchNorm:2 : (256,)
name = import/yolov3-tiny/convolutional12/BatchNorm/FusedBatchNorm:3 : (256,)
name = import/yolov3-tiny/convolutional12/BatchNorm/FusedBatchNorm:4 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
377: op name = import/yolov3-tiny/convolutional12/BatchNorm/Const, op type = ( Const ), inputs = , outputs = import/yolov3-tiny/convolutional12/BatchNorm/Const:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/Const:0 : ()
---------------------------------------------------------------------------------------------------------------------------------------------
378: op name = import/yolov3-tiny/convolutional12/Activation, op type = ( LeakyRelu ), inputs = import/yolov3-tiny/convolutional12/BatchNorm/FusedBatchNorm:0, outputs = import/yolov3-tiny/convolutional12/Activation:0
@input shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/FusedBatchNorm:0 : (?, 26, 26, 256)
@output shapes:
name = import/yolov3-tiny/convolutional12/Activation:0 : (?, 26, 26, 256)
---------------------------------------------------------------------------------------------------------------------------------------------
379: op name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/shape, op type = ( Const ), inputs = , outputs = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/shape:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/shape:0 : (4,)
---------------------------------------------------------------------------------------------------------------------------------------------
380: op name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/min, op type = ( Const ), inputs = , outputs = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/min:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/min:0 : ()
---------------------------------------------------------------------------------------------------------------------------------------------
381: op name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/max, op type = ( Const ), inputs = , outputs = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/max:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/max:0 : ()
---------------------------------------------------------------------------------------------------------------------------------------------
382: op name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/RandomUniform, op type = ( RandomUniform ), inputs = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/shape:0, outputs = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/RandomUniform:0
@input shapes:
name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/shape:0 : (4,)
@output shapes:
name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/RandomUniform:0 : (1, 1, 256, 18)
---------------------------------------------------------------------------------------------------------------------------------------------
383: op name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/sub, op type = ( Sub ), inputs = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/max:0, import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/min:0, outputs = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/sub:0
@input shapes:
name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/max:0 : ()
name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/min:0 : ()
@output shapes:
name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/sub:0 : ()
---------------------------------------------------------------------------------------------------------------------------------------------
384: op name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/mul, op type = ( Mul ), inputs = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/RandomUniform:0, import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/sub:0, outputs = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/mul:0
@input shapes:
name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/RandomUniform:0 : (1, 1, 256, 18)
name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/sub:0 : ()
@output shapes:
name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/mul:0 : (1, 1, 256, 18)
---------------------------------------------------------------------------------------------------------------------------------------------
385: op name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform, op type = ( Add ), inputs = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/mul:0, import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/min:0, outputs = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform:0
@input shapes:
name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/mul:0 : (1, 1, 256, 18)
name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/min:0 : ()
@output shapes:
name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform:0 : (1, 1, 256, 18)
---------------------------------------------------------------------------------------------------------------------------------------------
386: op name = import/yolov3-tiny/convolutional13/kernel, op type = ( VariableV2 ), inputs = , outputs = import/yolov3-tiny/convolutional13/kernel:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional13/kernel:0 : (1, 1, 256, 18)
---------------------------------------------------------------------------------------------------------------------------------------------
387: op name = import/yolov3-tiny/convolutional13/kernel/Assign, op type = ( Assign ), inputs = import/yolov3-tiny/convolutional13/kernel:0, import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform:0, outputs = import/yolov3-tiny/convolutional13/kernel/Assign:0
@input shapes:
name = import/yolov3-tiny/convolutional13/kernel:0 : (1, 1, 256, 18)
name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform:0 : (1, 1, 256, 18)
@output shapes:
name = import/yolov3-tiny/convolutional13/kernel/Assign:0 : (1, 1, 256, 18)
---------------------------------------------------------------------------------------------------------------------------------------------
388: op name = import/yolov3-tiny/convolutional13/kernel/read, op type = ( Identity ), inputs = import/yolov3-tiny/convolutional13/kernel:0, outputs = import/yolov3-tiny/convolutional13/kernel/read:0
@input shapes:
name = import/yolov3-tiny/convolutional13/kernel:0 : (1, 1, 256, 18)
@output shapes:
name = import/yolov3-tiny/convolutional13/kernel/read:0 : (1, 1, 256, 18)
---------------------------------------------------------------------------------------------------------------------------------------------
389: op name = import/yolov3-tiny/convolutional13/bias/Initializer/zeros, op type = ( Const ), inputs = , outputs = import/yolov3-tiny/convolutional13/bias/Initializer/zeros:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional13/bias/Initializer/zeros:0 : (18,)
---------------------------------------------------------------------------------------------------------------------------------------------
390: op name = import/yolov3-tiny/convolutional13/bias, op type = ( VariableV2 ), inputs = , outputs = import/yolov3-tiny/convolutional13/bias:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional13/bias:0 : (18,)
---------------------------------------------------------------------------------------------------------------------------------------------
391: op name = import/yolov3-tiny/convolutional13/bias/Assign, op type = ( Assign ), inputs = import/yolov3-tiny/convolutional13/bias:0, import/yolov3-tiny/convolutional13/bias/Initializer/zeros:0, outputs = import/yolov3-tiny/convolutional13/bias/Assign:0
@input shapes:
name = import/yolov3-tiny/convolutional13/bias:0 : (18,)
name = import/yolov3-tiny/convolutional13/bias/Initializer/zeros:0 : (18,)
@output shapes:
name = import/yolov3-tiny/convolutional13/bias/Assign:0 : (18,)
---------------------------------------------------------------------------------------------------------------------------------------------
392: op name = import/yolov3-tiny/convolutional13/bias/read, op type = ( Identity ), inputs = import/yolov3-tiny/convolutional13/bias:0, outputs = import/yolov3-tiny/convolutional13/bias/read:0
@input shapes:
name = import/yolov3-tiny/convolutional13/bias:0 : (18,)
@output shapes:
name = import/yolov3-tiny/convolutional13/bias/read:0 : (18,)
---------------------------------------------------------------------------------------------------------------------------------------------
393: op name = import/yolov3-tiny/convolutional13/dilation_rate, op type = ( Const ), inputs = , outputs = import/yolov3-tiny/convolutional13/dilation_rate:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional13/dilation_rate:0 : (2,)
---------------------------------------------------------------------------------------------------------------------------------------------
394: op name = import/yolov3-tiny/convolutional13/Conv2D, op type = ( Conv2D ), inputs = import/yolov3-tiny/convolutional12/Activation:0, import/yolov3-tiny/convolutional13/kernel/read:0, outputs = import/yolov3-tiny/convolutional13/Conv2D:0
@input shapes:
name = import/yolov3-tiny/convolutional12/Activation:0 : (?, 26, 26, 256)
name = import/yolov3-tiny/convolutional13/kernel/read:0 : (1, 1, 256, 18)
@output shapes:
name = import/yolov3-tiny/convolutional13/Conv2D:0 : (?, 26, 26, 18)
---------------------------------------------------------------------------------------------------------------------------------------------
395: op name = import/yolov3-tiny/convolutional13/BiasAdd, op type = ( BiasAdd ), inputs = import/yolov3-tiny/convolutional13/Conv2D:0, import/yolov3-tiny/convolutional13/bias/read:0, outputs = import/yolov3-tiny/convolutional13/BiasAdd:0
@input shapes:
name = import/yolov3-tiny/convolutional13/Conv2D:0 : (?, 26, 26, 18)
name = import/yolov3-tiny/convolutional13/bias/read:0 : (18,)
@output shapes:
name = import/yolov3-tiny/convolutional13/BiasAdd:0 : (?, 26, 26, 18)
---------------------------------------------------------------------------------------------------------------------------------------------
OPS counts:
Placeholder : 1
ResizeNearestNeighbor : 1
ConcatV2 : 1
BiasAdd : 2
Fill : 4
MaxPool : 6
FusedBatchNorm : 11
LeakyRelu : 11
RandomUniform : 13
Sub : 13
Mul : 13
Add : 13
Conv2D : 13
VariableV2 : 59
Assign : 59
Identity : 60
Const : 116

Any help would be Greatly Appreciated !!!


Q: GoBack get called 3times uwp If i press the backbutton on my phone the GoBack method get called 3 times and i go to the start page insted of the previous page (but it works 1 time of 20). But on the PC it workes every time with only one call and Always get to the previous page.
This is the startMethod in the class:
 public DetailPageFavorites()
        {
       this.InitializeComponent();
        // If on a phone device that has hardware buttons then we hide the app's back button.
        if (ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
        {
            this.BackButton.Visibility = Visibility.Collapsed;
            this.button_like.Margin = new Thickness(0, 0, 0, 0);
        }
        SystemNavigationManager.GetForCurrentView().BackRequested += SystemNavigationManager_BackRequested;
}

Method used if hardwareButton is pressent:
   private void SystemNavigationManager_BackRequested(object sender, BackRequestedEventArgs e)
    {
        Frame frame = Window.Current.Content as Frame;
        e.Handled = true;
        if (frame.CanGoBack)
        {
            frame.GoBack();
        }

    }

Methods used on the PC:
 private void BackButton_Click(object sender, RoutedEventArgs e)
        {
            GoBack();
        }
        private void GoBack()
        {
            Frame frame = Window.Current.Content as Frame;
            if (frame == null)
            {
                return;
            }
            if (frame.CanGoBack)
            {
                frame.GoBack();
            }
        }

A: Make sure you remove SystemNavigationManager.GetForCurrentView().BackRequested event handler before navigate to other page.
Either atPage.Unloaded event or OnNavigatedFrom method.
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
            base.OnNavigatedFrom(e);
            SystemNavigationManager.GetForCurrentView().BackRequested -= SystemNavigationManager_BackRequested;
}


Q: R: Substitute multiple unwanted variables with NAs across multiple columns Having a tough time with some data wrangling. I am trying to keep only certain author institutional affiliations in a bibliographic data frame and replace the many unwanted affiliations with NAs. I need to do this across multiple columns since papers have multiple authors (up to 68).
reproducible code:
so <- data.frame(inst_1=c("FC1","FC2","Uni1","lab3","lab2"),
                 inst_2=c("FC1","FC5","college4","laboratory1","lab2"),
                 inst_3=c("FC2","FC2","University2","lab5","lab5"),
                 inst_4=c("FC3","FC6","dept2","lab3.2","lab1"),
                 inst_5=c("FC1","FC2","Uni3","labB","lab5"))

Example data frame:
 inst_1      inst_2      inst_3 inst_4 inst_5
1    FC1         FC1         FC2    FC3    FC1
2    FC2         FC5         FC2    FC6    FC2
3   Uni1    college4 University2  dept2   Uni3
4   lab3 laboratory1        lab5 lab3.2   labB
5   lab2        lab2        lab5   lab1   lab5

I want to select every column that has the prefix "inst" (likely using str_detect), and in those selected columns replace any institution that does not contain the characters "FC" with NAs. This is necessary because this sheet has 68 institution columns (inst prefix) and hundred of rows (individual scientific articles). I can't just select which institutions to replace with NAs because there are hundreds of different institutions, while I am just interested in keeping the institutions that contain "FC".

A: 1) dplyr Use mutate/across like this
library(dplyr)

so %>%
  mutate(across(starts_with("inst"), ~ replace(., !grepl("FC", .), NA)))

giving:
  inst_1 inst_2 inst_3 inst_4 inst_5
1    FC1    FC1    FC2    FC3    FC1
2    FC2    FC5    FC2    FC6    FC2
3   <NA>   <NA>   <NA>   <NA>   <NA>
4   <NA>   <NA>   <NA>   <NA>   <NA>
5   <NA>   <NA>   <NA>   <NA>   <NA>

2) Base R or using only base R:
ok <- startsWith(names(so), "inst")
repl <- function(x) replace(x, !grepl("FC", x), NA)
replace(so, ok, lapply(so[ok], repl))

3) collapse or using the collapse package with repl from (2)
library(collapse)

tfmv(so, startsWith(names(so), "inst"), repl)

4) data.table  With data.table we define a vector of inst names and use it with repl from (2).
library(data.table)

DT <- as.data.table(so)
inst <- grep("^inst", names(so))
DT[, (inst) := lapply(.SD, repl), .SDcols = inst]


Q: How to get part of the string? I have this string:
 var MapId ='Library://London/Maps/Main-Mobile.MapDefinition'

From string above I need to get this part:
 MapId ='Library://London/'

How can I do it with help of regex or jquery?

A: You can use split() and slice() operations:

var MapId ='Library://London/Maps/Main-Mobile.MapDefinition';
MapId = MapId.split(/\//).slice(0,3).join('/') + '/';
console.log(MapId);


Q: Android Studio illegal state exception: cannot find method (view) for android:onClick I'm using radio buttons to switch the colors in a project. When the user clicks one of the radio buttons, I want the associated theme to be saved to SharedPreferences. The necessary themes are set up, but upon clicking a radio button, this error is thrown:
    java.lang.IllegalStateException: Could not find method onThemeRadio(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.widget.RadioButton with id 'theme2'

The relevant XML and Java blocks are shown below.
Java:
    public void onThemeRadio(View view){
    SharedPreferences themeStorage = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor themeStorageEditor = themeStorage.edit();
    boolean checked = ((RadioButton)view).isChecked();
    int themeId = themeStorage.getInt("themeId",1);
    switch(view.getId()) {
        case R.id.theme1:
            if (checked)
                themeId = 1;
            break;
        case R.id.theme2:
            if (checked)
                themeId = 2;
            break;
        case R.id.theme3:
            if (checked)
                themeId = 3;
            break;
    }
    themeStorageEditor.putInt("themeId",themeId);
    themeStorageEditor.apply();
}

XML:
            <RadioGroup
        android:id="@+id/themeRadio"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:checkedButton="@+id/theme1"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/theme1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="onThemeRadio"
            android:text="Default Theme" />

        <RadioButton
            android:id="@+id/theme2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="onThemeRadio"
            android:text="Alternate Theme" />

        <RadioButton
            android:id="@+id/theme3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="onThemeRadio"
            android:text="Combined Theme" />
    </RadioGroup>

I've read a few similar issues, but none of the fixes worked or applied.
Thanks in advance!

A: It's difficult to tell based on the limited code you provided. But based on the error message, it would seem that you do not have the onThemeRadio(View) method in the right place. It needs to be a method on the Activity class that uses that XML layout. Use Android Studio to help figure it out. For example, does Android Studio highlight onThemeRadio(View) as an unused method? Or does the onclick attribute in XML get flagged that the method is missing or has the wrong signature? These are signs that the method is in the wrong place. You can also use the light bulb that pops up next to a highlighted onclick attribute to automatically create the method in the right place.


Q: How to make UITextView detect links for website, mail and phone number I have a UITextView object. The text in UIView has a phone number, mail link, a website link. I want to show them as links with following functionality.
When someone taps on URL - Safari should open the the website.
When someone taps on email link - Mail should open up with my address in to field
When someone taps on phone number - Phone application should call the number
Has anyone done this before or knows how to handle it?
Thanks,
AJ

A: Though the Question is super Old.
Still if anyone faces the same issue,
Also it can be used as a UILabel. Though
Below solution will do the job  : [There isn't a need for any library..]
So I've used MFMailcomposer() and UITexView [ Code is in Swift 3.0 - Xcode 8.3.2 ]
A 100% Crash Proof and Working Code Handles all the corner cases. =D
Step 1.
import MessageUI

Step 2. Add the delegate
class ViewController: UITextViewDelegate, MFMailComposeViewControllerDelegate{
Step 3. Add the textView IBOutlet From StoryBoard
@IBOutlet weak var infoTextView: UITextView!

Step 4. Call the below method in your viewDidload()
func addInfoToTextView()  {
    let attributedString = NSMutableAttributedString(string: "For further info call us on : \(phoneNumber)\nor mail us at : \(email)")
    attributedString.addAttribute(NSLinkAttributeName, value: "tel://", range: NSRange(location: 30, length: 10))
    attributedString.addAttribute(NSLinkAttributeName, value: "mailto:", range: NSRange(location: 57, length: 18))
    self.infoTextView.attributedText = attributedString
    self.infoTextView.linkTextAttributes = [NSForegroundColorAttributeName:UIColor.blue, NSUnderlineStyleAttributeName:NSNumber(value: 0)]
    self.infoTextView.textColor = .white
    self.infoTextView.textAlignment = .center
    self.infoTextView.isEditable = false
    self.infoTextView.dataDetectorTypes = UIDataDetectorTypes.all
    self.infoTextView.delegate = self
}

Step 5. Implement delegate methods for TextView
@available(iOS, deprecated: 10.0)
func textView(_ textView: UITextView, shouldInteractWith url: URL, in characterRange: NSRange) -> Bool {
    if (url.scheme?.contains("mailto"))! && characterRange.location > 55{
        openMFMail()
    }
    if (url.scheme?.contains("tel"))! && (characterRange.location > 29 && characterRange.location < 39){
        callNumber()
    }
    return false
}

//For iOS 10
@available(iOS 10.0, *)
func textView(_ textView: UITextView, shouldInteractWith url: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
    if (url.scheme?.contains("mailto"))! && characterRange.location > 55{
        openMFMail()
    }
    if (url.scheme?.contains("tel"))! && (characterRange.location > 29 && characterRange.location < 39){
        callNumber()
    }
    return false
}

Step 6. Write the helper Methods to open MailComposer and Call App
func callNumber() {
    if let phoneCallURL = URL(string: "tel://\(phoneNumber)")
    {
        let application:UIApplication = UIApplication.shared
        if (application.canOpenURL(phoneCallURL))
        {
            let alert = UIAlertController(title: "Call", message: "\(phoneNumber)", preferredStyle: UIAlertControllerStyle.alert)
            if #available(iOS 10.0, *)
            {
                alert.addAction(UIAlertAction(title: "Call", style: .cancel, handler: { (UIAlertAction) in
                    application.open(phoneCallURL, options: [:], completionHandler: nil)
                }))
            }
            else
            {
                alert.addAction(UIAlertAction(title: "Call", style: .cancel, handler: { (UIAlertAction) in
                    application.openURL(phoneCallURL)
                }))
            }

            alert.addAction(UIAlertAction(title: "cancel", style: .default, handler: nil))
            self.present(alert, animated: true, completion: nil)
        }
    }
    else
    {
        self.showAlert("Couldn't", message: "Call, cannot open Phone Screen")
    }
}
func openMFMail(){
    let mailComposer = MFMailComposeViewController()
    mailComposer.mailComposeDelegate = self
    mailComposer.setToRecipients(["\(email)"])
    mailComposer.setSubject("Subject..")
    mailComposer.setMessageBody("Please share your problem.", isHTML: false)
    present(mailComposer, animated: true, completion: nil)

}

Step 7. Write MFMailComposer's Delegate Method
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
    switch result {
    case .cancelled:
        print("Mail cancelled")
    case .saved:
        print("Mail saved")
    case .sent:
        print("Mail sent")
    case .failed:
        print("Mail sent failure: \(String(describing: error?.localizedDescription))")
    default:
        break
    }
    controller.dismiss(animated: true, completion: nil)
}

That's it you're Done... =D

Here is the swift file for the above code :
textViewWithEmailAndPhone.swift

Set the below properties to Use it as a UILabel

A: A note on detecting email addresses: The Mail app must be installed (it's not on the iOS Simulator) for email links to open a message compose screen.

A: Swift 3.0 +
As of swift 3.0, use the following code if you want to do it programmatically.
textview.isEditable = false
textview.dataDetectorTypes = .all

Or if you have a storyboard

A: If you are using OS3.0
you can do it like the following
textview.editable = NO;
textview.dataDetectorTypes = UIDataDetectorTypeAll;

A: Step 1. Create a subclass of UITextview and override the canBecomeFirstResponder function
KDTextView.h Code:
@interface KDTextView : UITextView

@end

KDTextView.m Code:
#import "KDTextView.h"

// Textview to disable the selection options

@implementation KDTextView

- (BOOL)canBecomeFirstResponder {
    return NO;
}

@end

Step 2. Create the Textview using subclass KDTextView
KDTextView*_textView = [[KDTextView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    [_textView setScrollEnabled:false];
    [_textView setEditable:false];
    _textView.delegate = self;
    [_textView setDataDetectorTypes:UIDataDetectorTypeAll];
    _textView.selectable = YES;
    _textView.delaysContentTouches = NO;
    _textView.userInteractionEnabled = YES;
    [self.view addSubview:_textView];

Step 3: Implement the delegate method
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
{
    return true;
}

A: I'm curious, do you have control over the text shown?  If so, you should probably just stick it in a UIWebView and throw some links in there to do it "the right way".

A: Swift 4.2 Xcode 10.1
func setupContactUsTextView() {
        let text = NSMutableAttributedString(string: "Love your App, but need more help? Text, Call (123) 456-1234 or email ")
        if let font = UIFont(name: "Calibri", size: 17) {
            text.addAttribute(NSAttributedStringKey.font,
                              value: font,
                              range: NSRange(location: 0, length: text.length))
        } else {
            text.addAttribute(NSAttributedStringKey.font,
                              value: UIFont.systemFont(ofSize: 17),
                              range: NSRange(location: 0, length: text.length))
        }
        text.addAttribute(NSAttributedStringKey.foregroundColor,
                          value: UIColor.init(red: 112/255, green: 112/255, blue: 112/255, alpha: 1.0),
                          range: NSRange(location: 0, length: text.length))
        text.addAttribute(NSAttributedStringKey.link, value: "tel://", range: NSRange(location: 49, length: 15))
        let interactableText = NSMutableAttributedString(string: "contact@abc.com")
        if let font = UIFont(name: "Calibri", size: 17) {
            interactableText.addAttribute(NSAttributedStringKey.font,
                                          value: font,
                                          range: NSRange(location: 0, length: interactableText.length))
        } else {
            interactableText.addAttribute(NSAttributedStringKey.font,
                                          value: UIFont.systemFont(ofSize: 17),
                                          range: NSRange(location: 0, length: interactableText.length))
        }
        interactableText.addAttribute(NSAttributedStringKey.link,
                                      value: "contact@abc.com",
                                      range: NSRange(location: 0, length: interactableText.length))
        interactableText.addAttribute(NSAttributedStringKey.underlineStyle,
                                      value: NSUnderlineStyle.styleSingle.rawValue,
                                      range: NSRange(location: 0, length: interactableText.length))
        text.append(interactableText)
        videoDescTextView.attributedText = text
        videoDescTextView.textAlignment = .center
        videoDescTextView.isEditable = false
        videoDescTextView.isSelectable = true
        videoDescTextView.delegate = self
    }

    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
        if (characterRange.location > 48 && characterRange.location < 65){
            print("open phone")
        }else{
            print("open gmail")
        }
        return false
    }

Steps -
1. Set the delegate to your text field and don't forget to implement UITextViewDelegate
2. Take the textView outlet - @IBOutlet weak var videoDescTextView: UITextView!
3. Add these two functions given above.
This function shows how to detect phone numbers, email from textView, how to underline your email id, how to give custom color to your text, custom font, how to call a function when tapping on phone or email, etc.
Hope this will help someone to save their valuable time. Happy Coding :)

A: If you want to auto detect links, email etc Please make sure "isSelectable" is set to true.
textview.isSelectable = true
textview.editable = false
textview.dataDetectorTypes = .all


Q: Why does Debug mode not guarantee the completion of a Task (.net core, C#) every one.
I am a newbie to here and the programming world.
MS docs is saying A task is a single work that is guaranteed to complete.
I found it is true in release build but not in debug build.
My testing code is very simple.
        static void Main(string[] args)
        {
            Console.WriteLine("1st Code executed");
            Task task = new Task(() =>
            {
                Console.WriteLine("2nd Code executed");
                Console.WriteLine("3rd Code executed");
            });
            task.Start();
            Console.WriteLine("4th Code executed");

            Console.ReadLine();
           }

In debug mode, it results in one of three below:
         /*Mostly
         * 1st Code executed
         * 4th Code executed

         * rarely
         * 1st Code executed
         * 4th Code executed
         * 2nd Code executed

         * rarely
         * 1st Code executed
         * 4th Code executed
         * 2nd Code executed
         * 3rd Code executed */

In release build, there is no exception that all four lines are shown before the app finishes, although lines in the task and 4th line comes in arbitrary order.
My question is what makes the app finish without completion of a task in debug mode and, in addition, how I can fix it thru debug options, if any.

A: Quick answer
Your Main method and your task run in parallel, and the Main method does not wait the task to finish.
In release mode, the task is "lucky". It finishes before Main. Not in debug mode. In both case the execution is random.
The fact they run in parallel explain why your can't predict the order of the printed lines.
Explanations
A Task is a thread that comes from the thread pool, so they are background threads.
The process running your code (which consist of all your threads) does not wait for background threads to finish in order to terminate. The process only wait that foreground threads have finished.
Then you may want to use the Thread class because they are foreground by default. But using Task is easier. So @John Wu's comment is totally relevant:

A task is not guaranteed to finish unless you await it or call Wait or
  Result or do something else to wait for it

You simply want to add at the end of your code:
task.Wait();

However you'll never be able to predict the order of the printed lines, because the threads run in parallel.


Q: BackgroundWorker's ProgressChanged not updating UI until end of work loop I am coding a WPF application that will grab email's off of an IMAP account, and then export them into a user-selected folder.
I use a BackgroundWorker to download the emails. However, my UI isn't being updated until the loop is over.
Any tips would be appreciated.
Class MainWindow
    Public MailRepo As MailRepository
    Private bw_Connect As New BackgroundWorker
    Private bw_Save As New BackgroundWorker

    Public Sub New()
        InitializeComponent()

        bw_Connect.WorkerReportsProgress = True
        bw_Connect.WorkerSupportsCancellation = True
        AddHandler bw_Connect.DoWork, AddressOf bw_Connect_DoWork

        bw_Save.WorkerReportsProgress = True
        bw_Save.WorkerSupportsCancellation = True
        AddHandler bw_Save.DoWork, AddressOf bw_Save_DoWork
        AddHandler bw_Save.ProgressChanged, AddressOf bw_Save_ProgressChanged

    End Sub

    Private Sub bw_Save_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
        Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)

        If bw_Connect.CancellationPending = True Then
            e.Cancel = True
        Else
            SaveEmails()
        End If
    End Sub

Private Sub SaveEmails()
    Dim allMails As IEnumerable(Of Message)
    'Get All Emails in Mailbox
    Try
        Dim mailBox As String
        Dispatcher.Invoke(DirectCast(Sub()
                                         mailBox = comboBoxEmailFolders.SelectedValue
                                     End Sub, Action))
        allMails = MailRepo.GetAllMails(mailBox)
    Catch i4e As Imap4Exception
        MsgBox("Error: Folder not found" & vbCrLf & i4e.Message)
        Return
    End Try
    Dim msg As Message
    Dim msgInt As Integer = 1
    'Save each message
    For Each msg In allMails
        bw_Save.ReportProgress(100 / allMails.Count * msgInt, Nothing)
        SaveMessage(msg)
        msgInt += 1
    Next
End Sub

Private Sub bw_Save_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs)
        Dim percentDone As String = e.ProgressPercentage.ToString() & "%"
        updateStatus("Saving Emails " & percentDone & " done.")
        progressBarStatus.Value = e.ProgressPercentage
    End Sub


Q: Nginx and Unicorn - (Connection refused) while connecting to upstream Trying to deploy my first rails app on a vps. I have followed the instructions in the following setup.
https://www.digitalocean.com/community/articles/how-to-1-click-install-ruby-on-rails-on-ubuntu-12-10-with-digitalocean
But my site gets a 504 Gateway Time-out.
In the nginx log I get the following:
2013/10/16 03:10:45 [error] 19627#0: *82 connect() failed (111: Connection refused) while connecting to upstream, client: 121.218.167.90, server: _, request: "GET / HTTP/1.1", upstream: "http://162.243.39.196:8080/", host: "162.243.39.196"

And when I try to run unicorn I get the following
E, [2013-10-16T04:26:28.530019 #30087] ERROR -- : adding listener failed addr=0.0.0.0:8080 (in use)

My nginx default file has the following
server {
        listen   80;
        root /home/rails/public;
        server_name _;
        index index.htm index.html;

        location / {
                try_files $uri/index.html $uri.html $uri @app;
        }

        location ~* ^.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|js|mp3|flv|mpeg|avi)$ {
                        try_files $uri @app;
                }

         location @app {
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $http_host;
                proxy_redirect off;
                proxy_pass http://app_server;
    }

}

My /home/unicorn/unicorn.conf has
listen "127.0.0.1:8080"
worker_processes 2
user "rails"
working_directory "/home/rails"
pid "/home/unicorn/pids/unicorn.pid"
stderr_path "/home/unicorn/log/unicorn.log"
stdout_path "/home/unicorn/log/unicorn.log"

Thanks for your help.

A: You are missing an upstream block where you refer to in proxy_pass http://app_server;. You can put it above the server block like this.
upstream app_server {
    server 127.0.0.1:8080 fail_timeout=0;
}

server {
    listen   80;
    root /home/rails/public;
    server_name _;
    index index.htm index.html;
    ...


Q: how do I order by the results of multiple union statements? I can't use a common table expression:
WITH    cte
          AS (SELECT    [StationID],
                        [LastDistribution]
              FROM      [DB1].[dbo].[ProcessingStations]
              UNION ALL
              SELECT    [StationID],
                        [LastDistribution]
              FROM      [DB2].[dbo].[ProcessingStations]
              UNION ALL
              SELECT    [StationID],
                        [LastDistribution]
              FROM      [DB3].[dbo].[ProcessingStations]
              UNION ALL
              SELECT    [StationID],
                        [LastDistribution]
              FROM      [DB4].[dbo].[ProcessingStations]
              UNION ALL
              SELECT    [StationID],
                        [LastDistribution]
              FROM      [DB5].[dbo].[ProcessingStations]
              ORDER BY  [StationID]
              UNION ALL
              SELECT    [StationID],
                        [LastDistribution]
              FROM      [DB6].[dbo].[ProcessingStations]
              UNION ALL
              SELECT    [StationID],
                        [LastDistribution]
              FROM      [DB7].[dbo].[ProcessingStations]
              UNION ALL
              SELECT    [StationID],
                        [LastDistribution]
              FROM      [DB8].[dbo].[ProcessingStations])
    SELECT  *
    FROM    cte
    ORDER BY StationID

How would I go about doing this?

A: Just put the ORDER BY at the end of your chain of SELECT ... FROM ... UNION ALL statements:
SELECT    [StationID],
          [LastDistribution]
          FROM      [DB1].[dbo].[ProcessingStations]
          UNION ALL
          SELECT    [StationID],
                    [LastDistribution]
          FROM      [DB2].[dbo].[ProcessingStations]
          UNION ALL
          SELECT    [StationID],
                    [LastDistribution]
          FROM      [DB3].[dbo].[ProcessingStations]
          UNION ALL
          SELECT    [StationID],
                    [LastDistribution]
          FROM      [DB4].[dbo].[ProcessingStations]
          UNION ALL
          SELECT    [StationID],
                    [LastDistribution]
          FROM      [DB5].[dbo].[ProcessingStations]
          ORDER BY  [StationID]
          UNION ALL
          SELECT    [StationID],
                    [LastDistribution]
          FROM      [DB6].[dbo].[ProcessingStations]
          UNION ALL
          SELECT    [StationID],
                    [LastDistribution]
          FROM      [DB7].[dbo].[ProcessingStations]
          UNION ALL
          SELECT    [StationID],
                    [LastDistribution]
          FROM      [DB8].[dbo].[ProcessingStations]
ORDER BY StationID

Here's a quick example I did in SSMS:
DECLARE @a table (x int)
DECLARE @b table (x int)
DECLARE @c table (x int)

insert into @a values (5)
insert into @a values (4)
insert into @a values (3)

insert into @b values (0)
insert into @b values (1)
insert into @b values (2)

insert into @c values (0)
insert into @c values (1)
insert into @c values (2)

select * from @a
union all
select * from @b
union all
select * from @c
order by x

And here's the output:
  x
-----
  0
  0
  1
  1
  2
  2
  3
  4
  5

As you can see, even though the SELECT * FROM @a came first, it still placed those last in the result set

A: Why can't you use a CTE?. Anyway, you still can do the same using a derived table:
SELECT *
FROM (  SELECT    [StationID],
                  [LastDistribution]
        FROM      [DB1].[dbo].[ProcessingStations]
        UNION ALL
        SELECT    [StationID],
                  [LastDistribution]
        FROM      [DB2].[dbo].[ProcessingStations]
        UNION ALL
        SELECT    [StationID],
                  [LastDistribution]
        FROM      [DB3].[dbo].[ProcessingStations]
        UNION ALL
        SELECT    [StationID],
                  [LastDistribution]
        FROM      [DB4].[dbo].[ProcessingStations]
        UNION ALL
        SELECT    [StationID],
                  [LastDistribution]
        FROM      [DB5].[dbo].[ProcessingStations]
        UNION ALL
        SELECT    [StationID],
                  [LastDistribution]
        FROM      [DB6].[dbo].[ProcessingStations]
        UNION ALL
        SELECT    [StationID],
                  [LastDistribution]
        FROM      [DB7].[dbo].[ProcessingStations]
        UNION ALL
        SELECT    [StationID],
                  [LastDistribution]
        FROM      [DB8].[dbo].[ProcessingStations]) A
ORDER BY StationID

A: See the fiddle, just put the ORDER BY on the last set to be "unioned". It achieves the same result without the overhead of the CTE.
The order will effect the entire unified set.
SELECT
        [StationID],
        [LastDistribution]
    FROM
        [dbo].[ProcessingStations]
UNION ALL
SELECT
        [StationID],
        [LastDistribution]
    FROM
        [dbo].[ProcessingStations]
UNION ALL
SELECT
        [StationID],
        [LastDistribution]
    FROM
        [dbo].[ProcessingStations]
    ORDER BY
        [StationID]


Q: Is there a way to get the resulting Makefile after includes? In a (GNU) Makefile, one can do:
include foo.mk

all:
    @echo "Hello, world!"

Is there a way to get make to spit out the Makefile after foo.mk has been included? Akin to after the C preprocessor has expanded macros etc.?
Update: a commenter below asked me to specify which problem I'm trying to solve. I wish to trigger a rebuild when/if there's changes to the Makefile and/or the underlying, included makefiles. I've found a recipe that goes something like:
.PHONY: bar

SHAFILE := foobar.sha256
$(SHAFILE): bar
    @sha256sum Makefile | cmp -s - $@ || sha256sum Makefile > $@

...

%.o: %.c $(SHAFILE)
$(CC) -c -o $@ $< $(CFLAGS)

(Obviously, the checksum should be of the Makefile including includes, but this is a start.)

A: Caveat: I haven't tried this, only read the manual.
After all your include lines (including the transitive set of nested includes, and even lines created by text substitution or built by functions), the Make variable MAKEFILE_LIST will reference all your makefiles.
So it should be sufficient to add a dependency to the end of your file such as
%.o: $(MAKEFILE_LIST)

You don't actually need the contents of the effective Makefile, just the list of files that comprise it.

A:
Is there a way to get make to spit out the Makefile after foo.mk has been included?

No.
There's gmake -d with a ton of debug output, some of which indicating which makefiles are being read:
$ gmake -d|grep Reading
Reading makefiles...
Reading makefile `GNUmakefile'...
Reading makefile `foo.mk' (search path) (no ~ expansion)...

This might be helpful if there are recursive include directives or those under conditionals.
Maybe you could tell us your actual problem you want to solve?


Q: Convert entire dom4j Element's namespace If I have an XML element as such:
<First id="" name="">
  <Second id="" name="">
  </Second>
</First>

How can I use dom4j to convert the namespace to something like below? Is there a simple way?
<test:First test:id="" test:name="">
  <test:Second test:id="" test:name="">
  </test:Second>
</test:First>

A: If you prefer a Java centric solution, DOM4J has support for traversing a document tree:
    Document doc = DocumentHelper.parseText(XML);
    final Namespace ns = Namespace.get("test", "urn:foo:bar");
    doc.accept(new VisitorSupport() {
        @Override
        public void visit(Element node) {
            node.setQName(QName.get(node.getName(), ns));
            // Attribute QNames are read-only, so need to create new
            List<Attribute> attributes = new ArrayList<Attribute>();
            while(node.attributes().size() > 0)
                attributes.add(node.attributes().remove(0));
            for(Attribute a: attributes) {
                node.addAttribute(QName.get(a.getName(), ns), a.getValue());
            }
        }
    });

A: You could run an XSLT transformation:
  <xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0">
    <xsl:template match="*">
      <xsl:element name="test:{local-name()}" namespace="http://test-namepace/ns">
        <xsl:apply-templates select="@* | node()"/>
      </xsl:element>
    </xsl:template>
    <xsl:template match="@*">
      <xsl:attribute name="test:{local-name()}" namespace="http://test-namepace/ns">
        <xsl:value-of select="."/>
      </xsl:element>
    </xsl:template>
  </xsl:transform>

I think DOM4J has methods to apply an XSLT 1.0 transformation directly, but you also have the option to use Saxon, which handles DOM4J as input and/or output alongside many other tree models.
Incidentally, (a) in your requirements example, the result document is ill-formed because it doesn't declare the namespace, and (b) it's not generally considered good practice to put all the attributes in the same namespace as the containing elements; I've given you a solution on the assumption that you have good reasons for this rather strange design.


Q: Interrrupt-able ScheduledExecutorService in Android Currently, I am designing a stock market app with the following requirement

*

*1) Scan stock price repeatedly, with a fixed sleep time.

*2) Able to interrupt the sleep any-time. This is because when user adds a new stock, we need to wake up from sleep, and scan immediately.

Previously, I'm using bare bone Thread, to full-fill the above 2 requirements.
private class StockMonitor extends Thread {
    @Override
    public void run() {
        final Thread thisThread = Thread.currentThread();

        while (thisThread == thread) {

            // Fetch stock prices...

            try {
                Thread.sleep(MIN_DELAY);
            } catch (java.lang.InterruptedException exp) {
                if (false == refreshed()) {
                    /* Exit the primary fail safe loop. */
                    thread = null;
                    break;
                }
            }
        }
    }

    public synchronized void refresh() {
        isRefresh = true;
        interrupt();
    }

    private synchronized boolean refreshed() {
        if (isRefresh) {
            isRefresh = false;
            // Interrupted status of the thread is cleared.
            interrupted();
            return true;
        }
        return false;
    }
}

When I want to perform requirement (2), I will call refresh. Thread will be waked up, and perform job immediately.
However, I feel it is difficult to maintain such bare bone Thread code, and can make mistake easily.
I prefer to use ScheduledExecutorService. However, it lack of ability for me to wake up the Thread from sleeping state, and perform job immediately.
I was wondering, is there any classes in Android, which enables me to perform periodically task as in ScheduledExecutorService? Yet has the ability to wake up the Thread from sleeping state, and perform job immediately.

A: Here is my solution with ScheduledThreadPoolExecutor. To cancel existing tasks, issue future.cancel() on Future object returned from scheduleAtFixedRate(). Then call scheduleAtFixedRate() again with initial delay set to 0.
class HiTask implements Runnable {
    @Override
    public void run() {
        System.out.println("Say Hi!");
    }
}

// periodically execute task in every 100 ms, without initial delay time

ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);

long initialDelay = 0;
long period = 100;

ScheduledFuture<?> future1 = exec.scheduleAtFixedRate(new HiTask(), initialDelay, period, TimeUnit.MILLISECONDS);

// to trigger task execution immediately

boolean success = future.cancel(true);    // mayInterruptIfRunning = true: interrupt thread even task has already started

ScheduledFuture<?> future2 = exec.scheduleAtFixedRate(new HiTask(), initialDelay, period, TimeUnit.MILLISECONDS);

A: Options you have with ScheduledExecutorService:

*

*submit() the same task again in the moment you need the data to be refreshed. If will be immediately executed (and only once). Possible drawback: If this happens very close to a scheduled execution, you have two scans with very little time in between.

*cancel() the Tasks in the moment you need the data to be refreshed, submit() it once for immediate execution and and schedule() for repeated execution.

Be aware that any exceptions that occur in the task that are unhandled cancel future executions. How to solve that is answered in How to reschedule a task using a ScheduledExecutorService?.
ExecutorService is not persistent (i.e. does not survive device reboot). I don't know if that's a problem for you. If it is there are libraries specialized on background task execution on Android:

*

*smart-scheduler-android

*android-priority-jobqueue

*android-job
You would have to apply the same workarounds mentioned above.


Q: get the child key for specific value when append table using Jquery i created a table and used Jquery to put all the user database from firebase info in it. The problem is: i have a button in the table that be should when you click the button console print the element key from database.
var userDataRef = firebase.database().ref("User/3N2f2rJSSAZmFOdZEeJdlsuEZam2").orderByKey();

userDataRef.on('child_added', function(childSnapshot) {
  var key = childSnapshot.key;
  var childData = childSnapshot.val();
  var title_val = childData.Title;
  var url_val = childData.Url;
    // Append data
    $("#data").append("
" + title_val + "	 <button class='box'>GO</button>	<button id='del' class='box'>Delete</button>	<
");

    $('#data').on('click', '#del', function(){
        console.log(key)
      });

                            Title
                            Link
                            Delete

when this function perform i gut all the keys not just the one from the exact raw
$('#data').on('click', '#del', function(){
        console.log(key)
      });

output :
-LkT_afLi9nfn65OS2QJ database.js:17:17
-LkTciKQVEa2bsbtSwkW database.js:17:17
-LkTclDO8dYSBfgiBjAZ

A: ID's should never be repeated, use the class of the buttons instead as a common attribute.

A: You are binding to all the elements and you are duplicating ids. Ids are singular.
You would be better off with either binding to the one button alone or event delegation with a data attribute.
userDataRef.on('child_added', function(childSnapshot) {
  /* cut out the vars */
  var myRow = $("
" + title_val + "	 <button class='box'>GO</button>	<button class='box'>Delete</button>
");
  myRow.find("button").on("click", function(){
    console.log(key)
  });
  $("#data").append(myRow);
});

or event delegation with a data attribute
$("#data").on("click", "button[data-key]", function(evt){
  var btn = $(this);
  console.log(btn.data("key"))
});

userDataRef.on('child_added', function(childSnapshot) {
  /* cut out the vars */
  var myRow = $("
" + title_val + "	 <button class='box'>GO</button>	<button class='box' data-key='" + key + "'>Delete</button>
");
  $("#data").append(myRow);
});


Q: How to query native html elements when testing a React application with Jest? When I render React elements, for example, a Button, then an equivalent HTML button element is created in the DOM.
But, when I query the DOM I'm still getting a wrapped element.
HTMLButtonElement {
      '__reactInternalInstance$gt1haeiqrhv': FiberNode {
        tag: 5,
        key: null,
        ...
}

Why don't I get the native element as if I rendered a normal div using JSDOM?
Is there a way to get it?

A: I suppose you have to query for getDOMNode:
const button = wrapper.find('button').getDOMNode();
// const button = wrapper.getDOMNode(); // <---if wrapper is button element

It will give you the lying dom element in the component.


Q: What is the best way to control a variable with radio buttons? I'm very new to Android programming, and I'm unable to find out what the accepted way to reach my goal is:
I have a variable in my main activity (sortOrder), which I want to set using radio buttons in a different activity. At the moment, I just change MainActivity.sortOrder from the other activity with a big switch case, so I'm wondering if there is a more elegant way.
Also, at the moment the radio buttons "forget" their choice when I return to MainActivity. Is is possible to save the selected radio button, and set the variable from that in MainActivity?
Here's some  code:
in MainActivity:
public static String sortOrder;
public static int checkedId;

These are given values in onCreate:
sortOrder = ShipContract.ShipEntry.COLUMN_NAME_NAME + " ASC";
checkedId = R.id.sort_name;

And here is OptionsSort, which is started from MainActivity:
public class OptionsSort extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_options_sort);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    RadioButton checkedButton = (RadioButton) findViewById(MainActivity.checkedId);
    checkedButton.setChecked(true);
}

public void onRadioButtonClicked(View view) {
    boolean checked = ((RadioButton) view).isChecked();

    switch(view.getId()) {
        case R.id.sort_name:
            if (checked)
                MainActivity.sortOrder = ShipContract.ShipEntry.COLUMN_NAME_NAME + " ASC";
            break;
        case R.id.sort_date:
            if (checked)
                MainActivity.sortOrder = ShipContract.ShipEntry.COLUMN_NAME_DATE + " ASC";
            break;
        case R.id.sort_capacity:
            if (checked)
                MainActivity.sortOrder = ShipContract.ShipEntry.COLUMN_NAME_CAPACITY + " ASC";
            break;
        case R.id.sort_line:
            if (checked)
                MainActivity.sortOrder = ShipContract.ShipEntry.COLUMN_NAME_LINE + " ASC";
            break;
        case R.id.sort_displacement:
            if (checked)
                MainActivity.sortOrder = ShipContract.ShipEntry.COLUMN_NAME_DISPLACEMENT + " ASC";
            break;
        case R.id.sort_speed:
            if (checked)
                MainActivity.sortOrder = ShipContract.ShipEntry.COLUMN_NAME_SPEED + " ASC";
            break;
        case R.id.sort_power:
            if (checked)
                MainActivity.sortOrder = ShipContract.ShipEntry.COLUMN_NAME_POWER + " ASC";
            break;
    }
    RadioGroup radiogroup = (RadioGroup) findViewById(R.id.sort_group);
    MainActivity.checkedId = radiogroup.getCheckedRadioButtonId();
    finish();
}

}

A: so far i understand your problem you want to take sortOder value from activity B and bring it to Activity A.This can be achieved if you startActivityForResult and there in activity B when you are done with everything just call setresult method and give it the resultant intent and finish this activity B.
In activity A you have to override onActivityResult and handle the result from activity B .
like
startActivityForResult(new Intent(this,ActivityB.class),123);
@Override
public void onActivityResult(int requestCode, int resultCode, Intentdata) {
        super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {

if (requestCode==123)
    {
      String sordData= data.getStringExtra("sortOrder","byName")
            sortYourDAta(sordData);
    }
}

}
and in activity b when sort order is selected
just store value in a variable sortOrder="byDate";
and onbackpressed or when ever you want to go back just call this
setResult(123,new Intent().putExtra("sortOrder",sortOrder));
finish();


Q: How to make flashlight Blink I am trying to make the camera flashlight blink. I already have written a code for switching the flashlight on and off. I am trying to create a method which could blink the flashlight on the click of a button.
How can i achieve this.
public void flash_effect() throws InterruptedException
{
    camera = Camera.open();
    params = camera.getParameters();
    params.setFlashMode(Parameters.FLASH_MODE_TORCH);

    Thread a = new Thread()
    {
        public void run()
        {
            for(int i =0; i < 10; i++)
            {
                camera.setParameters(params);
                camera.startPreview();
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                camera.stopPreview();
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }
    };
    a.start();
}

This code is not working.What am i doing wrong. Waiting for help.
EDITED
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testlight"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

        <uses-permission android:name="android.permission.CAMERA" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

LOGCAT
06-16 14:03:40.579: E/AndroidRuntime(20302): FATAL EXCEPTION: main
06-16 14:03:40.579: E/AndroidRuntime(20302): java.lang.IllegalStateException: Could not execute method of the activity
06-16 14:03:40.579: E/AndroidRuntime(20302):    at android.view.View$1.onClick(View.java:3626)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at android.view.View.performClick(View.java:4231)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at android.view.View$PerformClick.run(View.java:17537)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at android.os.Handler.handleCallback(Handler.java:725)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at android.os.Handler.dispatchMessage(Handler.java:92)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at android.os.Looper.loop(Looper.java:158)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at android.app.ActivityThread.main(ActivityThread.java:5751)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at java.lang.reflect.Method.invokeNative(Native Method)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at java.lang.reflect.Method.invoke(Method.java:511)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1083)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:850)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at dalvik.system.NativeStart.main(Native Method)
06-16 14:03:40.579: E/AndroidRuntime(20302): Caused by: java.lang.reflect.InvocationTargetException
06-16 14:03:40.579: E/AndroidRuntime(20302):    at java.lang.reflect.Method.invokeNative(Native Method)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at java.lang.reflect.Method.invoke(Method.java:511)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at android.view.View$1.onClick(View.java:3621)
06-16 14:03:40.579: E/AndroidRuntime(20302):    ... 11 more
06-16 14:03:40.579: E/AndroidRuntime(20302): Caused by: java.lang.RuntimeException: Fail to connect to camera service
06-16 14:03:40.579: E/AndroidRuntime(20302):    at android.hardware.Camera.native_setup(Native Method)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at android.hardware.Camera.(Camera.java:362)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at android.hardware.Camera.open(Camera.java:336)
06-16 14:03:40.579: E/AndroidRuntime(20302):    at com.example.testlight.MainActivity.flash_effect(MainActivity.java:185)

A: I've been working on your problem, and my solution can blink the flashlight. I used your same logic, except I used Handler instead of Thread to delay the blink.
public void flash_effect(View view)
{
    long delay = 50;
    camera = Camera.open();
    params = camera.getParameters();
    params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);

    camera.setParameters(params);
    camera.startPreview();

    handler.postDelayed(new Runnable() {
        @Override
        public void run() {

            params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
            camera.setParameters(params);
            camera.stopPreview();
            camera.release();

        }
    }, delay);

}

You have to initialise the handler before using it. Do it in the onCreate() method.
 Handler handler = new Handler();

This method is an onClick() of a button. I used a button to start a blink
 public void flash_effect(View view)


Q: Google Drive API IOS Permissions of GTLRDriveService I am playing around with the google drive API and trying to build a simple app that uploads a picture to my google drive. The app is supposed to upload a picture once the user is signed in, however it gives an error of

"2017-09-14 00:55:20.342237-0400 driveTest[6705:1647551] An error
  occurred: Error Domain=com.google.GTLRErrorObjectDomain Code=403
  "Insufficient Permission"
  UserInfo={GTLRStructuredError=GTLRErrorObject 0x1c4251d30:
  {message:"Insufficient Permission" errors:[1] code:403},
  NSLocalizedDescription=Insufficient Permission}"

I have tried to pass it the service which is of type GTLRDriveService to the initSetup() function of  the userSetUp class, but to no avail. Could someone please point me to the right track as to why my permissions are not working even though I have logged on correctly, and the part where I am passing in the GTLRDriveService is in the code that runs after a sucessful login.
I instantiate a userSetUp object and I
let setUpUser = userSetUp()
setUpUser.initSetup(service)
I have userSetUp written in objective c as such and it is bridged correctly as I am able to instantiate it in my viewcontroller file which is written in swift.
UserSetUp:::::::
#import "userSetUp.h"
#import <GoogleSignIn/GoogleSignIn.h>
@import GoogleAPIClientForREST;

@implementation userSetUp
- (void) initSetup:(GTLRDriveService *) driveService {

    printf("heloooooaiosuoiadoidauoalo");
    //GTLRDriveService *driveService = [GTLRDriveService new];
    //NSData *fileData = [[NSFileManager defaultManager] contentsAtPath:@"files/apple.jpg"];
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"apple" ofType:@"jpg"];
    NSData *fileData = [NSData dataWithContentsOfFile:filePath];
    GTLRDrive_File *metadata = [GTLRDrive_File object];
    metadata.name = @"apple.jpg";
    //metadata.mimeType = @"application/vnd.google-apps.document";

    GTLRUploadParameters *uploadParameters = [GTLRUploadParameters uploadParametersWithData:fileData
                                                                                MIMEType:@"image/jpeg"];
    uploadParameters.shouldUploadWithSingleRequest = TRUE;
    GTLRDriveQuery_FilesCreate *query = [GTLRDriveQuery_FilesCreate queryWithObject:metadata
                                                                   uploadParameters:uploadParameters];
    query.fields = @"id";
    [driveService executeQuery:query completionHandler:^(GTLRServiceTicket *ticket,
                                                         GTLRDrive_File *file,
                                                         NSError *error) {
        if (error == nil) {
            //NSLog(@"File ID %@", file.identifier);
            printf("it worked");
        } else {
            NSLog(@"An error occurred: %@", error);
        }
    }];

printf("upload complete!");

}
@end

And Viewcontroller. swift
     import GoogleAPIClientForREST
    import GoogleSignIn
    import UIKit
class ViewController: UIViewController, GIDSignInDelegate, GIDSignInUIDelegate     {

// If modifying these scopes, delete your previously saved credentials by
// resetting the iOS simulator or uninstall the app.
private let scopes = [kGTLRAuthScopeDriveReadonly]

let service = GTLRDriveService()
let signInButton = GIDSignInButton()
let output = UITextView()

override func viewDidLoad() {
    super.viewDidLoad()

    // Configure Google Sign-in.
    GIDSignIn.sharedInstance().delegate = self
    GIDSignIn.sharedInstance().uiDelegate = self
    GIDSignIn.sharedInstance().scopes = scopes

    GIDSignIn.sharedInstance().signInSilently()
    signInButton.frame = CGRect(x: view.frame.width/2 - signInButton.frame.width , y:  view.frame.height/2, width: signInButton.frame.width, height: signInButton.frame.height)
    // Add the sign-in button.
    view.addSubview(signInButton)

    // Add a UITextView to display output.
    output.frame = view.bounds
    output.isEditable = false
    output.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 20, right: 0)
    output.autoresizingMask = [.flexibleHeight, .flexibleWidth]
    output.isHidden = true
    view.addSubview(output);
    //let itsASetup()
}

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!,
          withError error: Error!) {
    if let error = error {
        showAlert(title: "Authentication Error", message: error.localizedDescription)
        self.service.authorizer = nil
    } else {
        self.signInButton.isHidden = true
        self.output.isHidden = false
        self.service.authorizer = user.authentication.fetcherAuthorizer()

        listFiles()
    }
}

// List up to 10 files in Drive
func listFiles() {
    let query = GTLRDriveQuery_FilesList.query()
    query.pageSize = 10
    service.executeQuery(query,
                         delegate: self,
                         didFinish: #selector(displayResultWithTicket(ticket:finishedWithObject:error:))
    )

}

// Process the response and display output
@objc func displayResultWithTicket(ticket: GTLRServiceTicket,
                             finishedWithObject result : GTLRDrive_FileList,
                             error : NSError?) {

    if let error = error {
        showAlert(title: "Error", message: error.localizedDescription)
        return
    }

    var text = "";
    if let files = result.files, !files.isEmpty {
        text += "Files:\n"
        for file in files {
            text += "\(file.name!) (\(file.identifier!))\n"
        }
    } else {
        text += "No files found."
    }
    output.text = text
    let setUpUser = userSetUp()
    setUpUser.initSetup(service)
}

// Helper for showing an alert
func showAlert(title : String, message: String) {
    let alert = UIAlertController(
        title: title,
        message: message,
        preferredStyle: UIAlertControllerStyle.alert
    )
    let ok = UIAlertAction(
        title: "OK",
        style: UIAlertActionStyle.default,
        handler: nil
    )
    alert.addAction(ok)
    present(alert, animated: true, completion: nil)
}
}

A: try to Change your scope like:
class ViewController: UIViewController, GIDSignInDelegate, GIDSignInUIDelegate
{
    // If modifying these scopes, delete your previously saved credentials by

    private let scopes = ["https://www.googleapis.com/auth/drive"]

    ...
}